Friday, October 15, 2004

Magic Triangle java program

Problem: Compute a magic triangle with 4 nodes to a side. Fill the
nodes with integers from 1 to 10 such that the sum of the nodes on all
three sides is equal. Also, the sum of the node 2-5-9 and 3-5-8 and
4-5-6 are also equal, but they do not need to equal the sides.



// 1
// 2 3
// 4 5 6
// 7 8 9 10

import java.util.*;

public class MagicTriangle {
public static void main(String[] args ){
ArrayList numbers = new ArrayList();
int [] x = new int[10];
for( int i = 0; i < 10; ++ i ) {
numbers.add( new Integer(i + 1));
}

while( true ) {
Collections.shuffle( numbers );
for( int i =0; i < 10; ++i ) {
x[i] = ((Integer)numbers.get(i)).intValue();
}

int magic = x[0] + x[1] + x[3] + x[6];
if( magic == (x[0] + x[2] + x[5]+ x[9]) &&
magic == ( x[6] + x[7] + x[8] + x[9] )) {
int magic2 = x[1] + x[4] + x[8];
if( magic2 == (x[2] + x[4] + x[7] ) &&
magic2 == (x[3] + x[4] + x[5]) ) {
System.out.println("VVVVVV " + magic + " VVVVVVVVVVV");
System.out.println("\t\t\t" + x[0]);
System.out.println("\t\t" + x[1] + "\t\t" + x[2]);
System.out.println("\t" + x[3] + "\t\t" + x[4]+ "\t\t" + x[5]);
System.out.println(x[6] + "\t\t" + x[7]+ "\t\t" + x[8]+"\t\t" + x[9]);
System.out.println("^^^^^^^^^^^^^^^^^^^^");
}

}
}
}
}


0 Comments:

Post a Comment

<< Home