#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/24_game/Solve
#

var formats = [
    '((%d %s %d) %s %d) %s %d',
    '(%d %s (%d %s %d)) %s %d',
    '(%d %s %d) %s (%d %s %d)',
    '%d %s ((%d %s %d) %s %d)',
    '%d %s (%d %s (%d %s %d))',
];

var op = %w( + - * / );
var operators = op.map { |a| op.map {|b| op.map {|c| "#{a} #{b} #{c}" } } }.flatten;

loop {
    var input = Sys.scanln("Enter four integers or 'q' to exit: ") \\ break;
    input == 'q' && break;

    input ~~ /^\h*[1-9]\h+[1-9]\h+[1-9]\h+[1-9]\h*$/ || (
        say "Invalid input!"; next;
    );

    var n = input.split.map{.to_i};
    var numbers = n.permutations;

    formats.each { |format|
        numbers.each { |n|
            operators.each { |operator|
                var o = operator.split;
                var str = (format % (n[0],o[0],n[1],o[1],n[2],o[2],n[3]));
                Sidef.new.execute_code(str) == 24 && say str;
            }
        }
    }
}
