Bulls and Cows Java code explanation -


i've been searching source code of game , found one. however, didn't understand hasdupes method @ end of code.

could explain me?

source code - here

public static boolean hasdupes(int num){     boolean[] digs = new boolean[10];     while(num > 0){         if(digs[num%10]) return true;         digs[num%10] = true;         num/= 10;     }     return false; 

so let's step through it:

boolean[] digs = new boolean[10]; 

in java, items in array declaration given default value. in case of boolean, false. creates array of 10 elements each element false

while(num > 0){     if(digs[num%10]) return true;     digs[num%10] = true;     num/= 10; } 

modding number 10 (num % 10) , dividing 10 (num/= 10) common way "pop" off last digit number. example,

int somenum = "1357"; int lastdigit = mod % 10; // lastdigit 7 somenum /= 10; // somenum 135 

as can see, 7 gets removed. while loop popping of each digit of num until digits processed. now, each digit being removed, digs[num%10] = true; keeping track of digits removed. keeping track of these, if(digs[num%10]) return true; return true method if digit has been processed.

so, in simpler words, method checks see if number contains more 1 of same digit.

12345 return false 12341 return true 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -