algorithm - Arrange eight consecutive number in a matrix so that no two number are adjacent -


need number 1 8 in following diagram such no 2 number in neighbor cell consecutive each other pattern :

     *     ***     ***      * 

where each * contain number between 1 8 , no 2 neighbor * consucutive number.

assuming neighbours horizontally , vertically (not diagonally), greedy solution reshuffle till find solution. array small enough, need bit more 24 retries on average find match.

import java.util.random;  public class eightpattern {     private static random rnd = new random();      /*      * -0-      * 123      * 456      * -7-      */     private static boolean isok(int[] array) {         if (       math.abs(array[0] - array[2]) == 1                 || math.abs(array[1] - array[2]) == 1                 || math.abs(array[2] - array[3]) == 1                 || math.abs(array[1] - array[4]) == 1                 || math.abs(array[2] - array[5]) == 1                 || math.abs(array[3] - array[6]) == 1                 || math.abs(array[4] - array[5]) == 1                 || math.abs(array[5] - array[6]) == 1                 || math.abs(array[5] - array[7]) == 1) {             return false;         }         return true;     }      //shuffle until find isok solution     public static void patternshuffle(int[] array) {         {             shufflearray(array);         }while(!isok(array));     }       //fisher–yates shuffle     static void shufflearray(int[] ar) {         (int = ar.length - 1; > 0; i--) {             int index = rnd.nextint(i + 1);             int = ar[index];             ar[index] = ar[i];             ar[i] = a;         }     }      private static void printpattern(int[] array) {         system.out.println(" " + array[0]);         system.out.println("" + array[1] + array[2] + array[3]);         system.out.println("" + array[4] + array[5] + array[6]);         system.out.println(" " + array[7]);     }      public static void main(string args[]) {         int[] = new int[]{1,2,3,4,5,6,7,8};         patternshuffle(a);         printpattern(a);     }    } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -