#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Sum_and_Product_Puzzle
#

func grep_unique(a, by) { a.group_by{ .(by) }.values.grep{.len == 1}.map{_[0]} }
func sums       (n)     { 2 .. n//2 -> map {|i| [i, n-i] } }

var all_pairs = (2..97 -> map {|i| ([i] ~X (i+1 .. 98))... })

var p_unique = Hash()
p_unique{grep_unique(all_pairs, :prod).map { .join(' ') }...} = ()

var s_pairs     = all_pairs.grep {|p| sums(p.sum).all { !p_unique.contains(.join(' ')) } }
var p_pairs     = grep_unique(s_pairs, :prod)
var final_pairs = grep_unique(p_pairs, :sum)

final_pairs.each { |p| printf("X = %d, Y = %d\n", p...) }

assert_eq(final_pairs, [[4, 13]])
