Re: 10344 - 23 Out of 5
Posted: Wed Aug 07, 2013 3:09 am
I tried a lot with this and no luck so far,
this is the last version of my code, I'm using recursion to generate all possible permutation and test if it evaluates into 23
is my logic wrong ? or is my implementation wrong? or maybe both are wrong
please help.
this is the last version of my code, I'm using recursion to generate all possible permutation and test if it evaluates into 23
is my logic wrong ? or is my implementation wrong? or maybe both are wrong

please help.
Code: Select all
#include <iostream>
using namespace std;
bool fun (int num[] , int vis[], int acc = 0 ,int n = 0)
{
if ( n == 4)
return acc == 23;
bool res = false;
for (int i = 0; i < 5 ; i++)
{
if (!vis[i])
{
vis[i] = 1;
res = fun (num, vis, acc * num[i] , n+1) ||
fun (num, vis, acc + num[i] , n+1) ||
fun (num, vis, acc - num[i] , n+1);
if (res)
return true;
}
vis[i] = 0;
}
return false;
}
int main ()
{
int num [5];
int vis [5] = {0};
while (true)
{
for (int i = 0; i < 5 ; i++)
vis[i]= 0;
cin>>num[0]>>num[1]>>num[2]>>num[3]>>num[4];
if (num[0]+num[1]+num[2]+num[3]+num[4] == 0)
break;
cout<<( fun(num,vis)? "Possible": "Impossible")<<endl;
}
}