Problem:
Given 4 number a, b, c, and d; output the sequence of a, b and c along with arithmetic
operators such that the result is d. The arithmetic operations allowed are
“+,-,/,*”.
I/p: a,b,c,d
O/p: <expression>
Eg.:
I/p: 4 3 2 10
O/p: 4+3*2=10
Solution: (in Scala)
object Aha {
def main(args: Array[String]) {
val (a, b, c, d) = (readInt, readInt, readInt, readInt)
val operations = List[((Int, Int) => Int, Int, String)](
({_+_}, 1, "+"), ({_-_}, 1, "-"), ({_*_}, 2, "*"), ({_/_}, 2, "/")
)
for {
(i, pi, si) <- operations
(j, pj, sj) <- operations
if((pi >= pj && j(i(a, b), c) == d) || (pi < pj && i(a, j(b, c)) == d))
} println(a + si + b + sj + c + "=" + d)
}
}
Same thing in C++ (with Boost):
#include <iostream>
#include <string>
#include <functional>
#include <boost/tuple/tuple.hpp>
#include <boost/function.hpp>
#include <boost/foreach.hpp>
using namespace std;
using namespace boost;
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
tuple<function<int(int, int)>, int, string> operations[] = {
make_tuple(plus<int>(), 1, "+"),
make_tuple(minus<int>(), 1, "-"),
make_tuple(multiplies<int>(), 2, "*"),
make_tuple(divides<int>(), 2, "/")
};
function<int(int, int)> i, j;
int pi, pj;
string si, sj;
BOOST_FOREACH(tie(i, pi, si), operations) {
BOOST_FOREACH(tie(j, pj, sj), operations) {
if((pi >= pj && j(i(a, b), c) == d) || (pi < pj && i(a, j(b, c)) == d)) {
cout << a << si << b << sj << c << "=" << d << endl;
}
}
}
}