Saturday, June 27, 2009

61. 23 OUT of 5

23 Out of 5

Your task is to write a program that can decide whether you can find an arithmetic expression consisting of five given numbers (1<=i<=5) that will yield the value 23.

For this problem we will only consider arithmetic expressions of the following from:

 
where : {1,2,3,4,5} -> {1,2,3,4,5} is a bijective function
and  {+,-,*} (1<=i<=4)

Input

The Input consists of 5-Tupels of positive Integers, each between 1 and 50.
Input is terminated by a line containing five zero's. This line should not be processed.

Output

For each 5-Tupel print "Possible" (without quotes) if their exists an arithmetic expression (as described above) that yields 23. Otherwise print "Impossible".

Sample Input

1 1 1 1 1
1 2 3 4 5
2 3 5 7 11
0 0 0 0 0

Sample Output

Impossible
Possible
Possible

1 comments:

Anurag said...

Sol in JAVA:
/* 23 out of 5 */

import java.util.Scanner;

class Main {

public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String line = in.nextLine();
while (!line.equals("0 0 0 0 0"))
{
Scanner s = new Scanner(line);
int a[] = new int[5];
for (int i = 0; i < 5; i++)
a[i] = s.nextInt();
boolean found = false;
for (int i=1;i<4 && !found;i++)
for (int j=1;j<4 && !found;j++)
for (int k=1;k<4 && !found;k++)
for (int h=1;h<4 && !found;h++)
for (int x1=0;x1<5 && !found;x1++)
for (int x2=0;x2<5 && !found;x2++)
{
if (x1 == x2) continue;
for (int x3=0;x3<5 && !found;x3++)
{
if ((x3 == x1) || (x3 == x2)) continue;
for (int x4=0;x4<5 && !found;x4++)
{
if ((x4 == x1) || (x4 == x2) || (x4 == x3))
continue;
for (int x5=0;x5<5 && !found;x5++)
{
if ((x5 == x1) || (x5 == x2) || (x5 == x3) || (x5
== x4)) continue;
long z = calc(a[x1],a[x2],i);
long x = calc(z,a[x3],j);
long v = calc(x,a[x4],k);
long n = calc(v,a[x5],h);
if (n == 23) found = true;
}}}}
if (found) System.out.println("Possible");
else System.out.println("Impossible");
line = in.nextLine();
}
}

static long calc(long a, long b, int i)
{
if (i==1) return a+b;
else if (i==2) return a-b;
else return a*b;
}
}

Post a Comment