Jump to content
BrainDen.com - Brain Teasers
  • 0

Numbers 25


Billabolla
 Share

Question

1 answer to this question

Recommended Posts

  • 0

Very nice puzzle...

5u0oyp.jpg


public class Main {

public static void main(String[] args) {

  int[][] connections = { { 1 }, { 0, 2, 3, 9 }, { 1, 6 }, { 1, 4, 5 },

    { 3, 5, 10 }, { 3, 4, 9, 10 }, { 2, 7, 8, 9 }, { 6, 8 },

    { 6, 7, 9, 11 }, { 1, 5, 6, 8, 10, 11 }, { 4, 5, 9, 11 },

    { 8, 9, 10 } };

  int[] values = new int[connections.length];

  int[] sums = { 26, 31, 13, 19, 19, 25, 20, 19, 6, 6, 7, 8 };

  for (int i = 0; i < values.length; i++) {

   values[i] = -1;

  }

  tryValues(connections, values, sums, 0);

}

private static void tryValues(int[][] connections, int[] values,

   int[] sums, int index) {

  if (index >= values.length) {

   System.out.println(java.util.Arrays.toString(values));

   return;

  }

  for (int i = 0; i < values.length; i++) {

   if (!contains(values, i)) {

    values[index] = i;

    if (isLegal(connections, values, sums)) {

	 tryValues(connections, values, sums, index + 1);

    }

    values[index] = -1;

   }

  }

}

private static boolean isLegal(int[][] connections, int[] values, int[] sums) {

  for (int i = 0; i < values.length; i++) {

   if (values[i] >= 0) {

    int sum = 0;

    boolean incomplete = false;

    for (int con : connections[i]) {

	 if (values[con] < 0) {

	  incomplete = true;

	  break;

	 }

	 sum += values[con];

    }

    if (!incomplete) {

	 if (sum != sums[values[i]]) {

	  return false;

	 }

    }

   }

  }

  return true;

}

private static boolean contains(int[] arr, int num) {

  for (int a : arr) {

   if (a == num) {

    return true;

   }

  }

  return false;

}

}

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...