#!/usr/bin/ruby

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

var formats = [
    {|a,b,c|
        Hash.new(
            func   => {|d,e,f,g| ((d.$a(e)).$b(f)).$c(g) },
            format => "((%d #{a} %d) #{b} %d) #{c} %d"
        )
    },
    {|a,b,c|
        Hash.new(
            func   => {|d,e,f,g| (d.$a((e.$b(f)))).$c(g) },
            format => "(%d #{a} (%d #{b} %d)) #{c} %d",
        )
    },
    {|a,b,c|
        Hash.new(
            func   => {|d,e,f,g| (d.$a(e)).$b(f.$c(g)) },
            format => "(%d #{a} %d) #{b} (%d #{c} %d)",
        )
    },
    {|a,b,c|
        Hash.new(
            func   => {|d,e,f,g| (d.$a(e)).$b(f.$c(g)) },
            format => "(%d #{a} %d) #{b} (%d #{c} %d)",
        )
    },
    {|a,b,c|
        Hash.new(
            func   => {|d,e,f,g| d.$a(e.$b(f.$c(g))) },
            format => "%d #{a} (%d #{b} (%d #{c} %d))",
        )
    },
];

var op = %w( + - * / );
var blocks = op.map { |a| op.map { |b| op.map { |c| formats.map { |format|
    format(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_num};
    var numbers = n.permutations;

    blocks.each { |block|
        numbers.each { |n|
            if (block{:func}.call(n...) == 24) {
                say (block{:format} % (n...));
            }
        }
    }
}
