Monday 29 August 2016

Project Euler Problem 26: Reciprocal cycles

Problem


A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/20.5
1/30.(3)
1/40.25
1/50.2
1/60.1(6)
1/70.(142857)
1/80.125
1/90.(1)
1/100.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

Solution

Use array to store the index of occurred digits is very efficient. Take 7 as example, each mod is 1,3,2,6,4,5, they are saved as arr[1]=1, arr[3]=2, arr[2]=3, arr[6]=4, arr[4]=5, arr[5]=6. Once you find an arr[i] such that arr[i] != 0, you immediately know the length.


      private static final int LIMIT = 1000;  
      public static void main(String[] args) {  
           int result = 0;  
           int longest = 0;  
           for (int i=2; i<LIMIT; i++){  
                int recurringNum = recurringNum(i);   
                if (recurringNum > longest){  
                     longest = recurringNum;  
                     result = i;  
                }  
           }  
           System.out.println(result);  
      }  
      public static int recurringNum(int num) {  
           int[] arr = new int[num+1];  
           int index = 1;  
           int mod = 1;  
           while(mod != 0 && arr[mod] == 0){  
                arr[mod]=index++;  
                mod = mod * 10 % num;  
           }  
           if (mod == 0){  
                return 0;  
           }  
           return index-arr[mod];  
   }  

Sunday 28 August 2016

Project Euler Problem 23: Non-abundant sums

Problem

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

Solution

Initially I was using a Set to store all the abundant sum number. The performance was OK. But once I changed Set to List, the performance degraded badly. It prompted me to change the use of collection to a boolean array. I am pretty happy about the performance gain. 

      private static final int LIMIT = 28123;  
      private static final List<Integer> abundant = new ArrayList<>();  
      private static final boolean[] isAbundantSum = new boolean[LIMIT+1];  
      public static void main(String[] args) {  
           for (int i=1; i<=LIMIT; i++){  
                if (isAbundant(i)){  
                     abundant.add(i);  
                     for (int j : abundant){  
                          if (i+j <= LIMIT){  
                               isAbundantSum[i+j] = true;  
                          }  
                     }  
                }  
           }  
           int sum = 0;  
           for (int i = 1; i < isAbundantSum.length; i++){  
                if (!isAbundantSum[i]){  
                     sum += i;  
                }  
           }  
           System.out.println(sum);  
      }  
      private static int d(int number){  
           int sum = 1;  
           int sqrt = (int)Math.sqrt(number);  
           for (int i=2; i<=sqrt; i++){  
                if (number % i == 0){  
                     sum += (i + number / i);  
                }  
           }  
           if (sqrt * sqrt == number){  
                sum -= sqrt;  
           }  
           return sum;  
      }  
      private static boolean isAbundant(int number){  
           return d(number) > number;  
      }  

Saturday 27 August 2016

Project Euler Problem 19: Counting Sundays

Problem

You are given the following information, but you may prefer to do some research for yourself.
  • 1 Jan 1900 was a Monday.
  • Thirty days has September,
    April, June and November.
    All the rest have thirty-one,
    Saving February alone,
    Which has twenty-eight, rain or shine.
    And on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

Solution

Given the first day of the year and whether it's a leap year, the number of Sundays can be found quickly through a lookup.

      private static final int[] LEAP_YEAR_DAY = new int[7];  
      private static final int[] NONE_LEAP_YEAR_DAY = new int[7];  
      private static final int[] DAYS_IN_MONTH = {31,28,31,30,31,30,31,31,30,31,30}; //Jan - Nov   
      public static void main(String[] args) {  
           pattern(1900, NONE_LEAP_YEAR_DAY);  
           pattern(2000, LEAP_YEAR_DAY);  
           int firstDayOfYear = 1;  
           int totalSundays = 0;  
           for (int year=1901; year<=2000; year++){  
                firstDayOfYear = firstDayOfYear(firstDayOfYear, year-1);  
                totalSundays += numberSundays(firstDayOfYear, year);  
           }  
           System.out.print(totalSundays);  
      }  
      private static int firstDayOfYear(int previousYearFirstDay, int previousYear){  
           if (isLeapYear(previousYear)){  
                return (previousYearFirstDay + 366 % 7) % 7;  
           }  
           return (previousYearFirstDay + 365 % 7) % 7;  
      }  
      private static int numberSundays(int firstDay, int year){  
           int sundayIndex = (7 - firstDay) % 7;  
           return isLeapYear(year) ? LEAP_YEAR_DAY[sundayIndex] : NONE_LEAP_YEAR_DAY[sundayIndex];  
      }  
      private static void pattern(int year, int[] days) {  
           int nthDayInYear = 1; //1st Jan is the 1st day of the year  
           int firstDayOfMonth = 0; //1 is Monday, 0 being Sunday  
           days[firstDayOfMonth]++;   
           for (int i=0; i<DAYS_IN_MONTH.length; i++){  
                nthDayInYear += daysInMonth(i, year);  
                firstDayOfMonth = (nthDayInYear - 1) % 7;  
                days[firstDayOfMonth]++;  
           }  
      }  
      private static int daysInMonth(int i, int year) {  
           if (i != 1) { //Not Feb  
                return DAYS_IN_MONTH[i];  
           }  
           return isLeapYear(year) ? DAYS_IN_MONTH[i] + 1: DAYS_IN_MONTH[i];  
      }  
      private static boolean isLeapYear(int year) {  
           return (year % 100 != 0 && year % 4 ==0) || year % 400 == 0;  
      }  

Project Euler Problem 18 and 67: Maximum path sum

Problem

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

Solution

Once again, don't use recursive prematurely!

This one requires working from bottom to top.

 private static final int ROW = 15;  
      private static final int[][] M = new int[ROW][ROW];  
      public static void main(String[] args) {  
           readFile();  
           for (int i=ROW-2; i >= 0; i--){  
                for (int j=0; j <= i; j++){  
                     M[i][j] = Math.max(M[i+1][j], M[i+1][j+1]) + M[i][j];  
                }  
           }  
           System.out.println(M[0][0]);       
      }  
      private static void readFile() {  
           File file = new File("Q18.txt");  
           try {  
                Scanner sc = new Scanner(file);  
                int i = 0;  
                while (sc.hasNextLine()) {  
                     int j = 0;  
                     Scanner lineSc = new Scanner(sc.nextLine());  
                     while (lineSc.hasNextInt()){  
                          M[i][j++]=lineSc.nextInt();       
                     }  
                     i++;  
                }  
                sc.close();  
           } catch (FileNotFoundException e) {  
                e.printStackTrace();  
           }  
      }  

Thursday 25 August 2016

Project Euler Problem 16: Power digit sum

Problem

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

Solution

Nothing fancy here. Just implement my own multiply by 2 algorithm.

 private static final int N = 1000;  
      public static void main(String[] args) {  
           String result = "1";  
           for (int i = 1; i<=N; i++){  
                result = times2(result);  
           }  
           System.out.println(sumDigits(result));  
      }  
      private static String times2(String num){  
           String result = "";  
           int carryOver = 0;  
           for (int i = num.length()-1; i>=0; i--){  
                int temp = Integer.parseInt(num.charAt(i)+"") * 2 + carryOver;  
                result = String.valueOf(temp % 10) + result;  
                carryOver = temp >= 10 ? 1 : 0;  
           }  
           if (carryOver == 1){  
                result = "1"+result;  
           }  
           return result;  
      }  
      private static int sumDigits(String num){  
           int result = 0;  
           for (int i = 0; i<num.length(); i++){  
                result += Integer.parseInt(num.charAt(i)+"");  
           }  
           return result;  
      }  

Project Euler Problem 15: Lattice paths

Problem

Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?

Solution

The lesson learnt is avoid recursive as it hurts your performance badly!

 private static final int NUMBER = 20;  
      private static final long[][] grid = new long[NUMBER+1][NUMBER+1];  
      public static void main(String[] args) {  
           grid[0][0] = 0;  
           for (int i=1; i <= NUMBER; i++){  
                grid[i][0] = 1;  
                grid[0][i] = 1;  
           }  
           for (int i=1; i <= NUMBER; i++){  
                for (int j=1; j <=i; j++){  
                     grid[i][j] = grid[j][i] = grid[j-1][i] + grid[j][i-1];  
                }  
           }  
           System.out.println(grid[NUMBER][NUMBER]);  
      }  

Project Euler Problem 14: Longest Collatz sequence

Problem


The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.

Solution

There are two tricks
  • Use long instead of int
  • Save the result for each number along the way to an array
      private static final int NUMBER = 1000000;  
      private static final int[] TERMS = new int[NUMBER];  
      public static void main(String[] args) {  
           long largest = 0;  
           int num = 0;  
           for (int i=1; i<NUMBER; i++){  
                long terms =terms(i);   
                if (terms > largest){  
                     largest = terms;  
                     num = i;  
                }  
           }  
           System.out.println(num+" "+largest);  
      }  
      private static long next(long n){  
           if (n % 2 == 0){  
                return n / 2;  
           }else{  
                return 3*n+1;  
           }  
      }  
      private static int terms(long n){  
           long temp = n;  
           int count = 1;  
           while (temp > 1){  
                temp = next(temp);  
                if (temp < NUMBER && TERMS[(int)temp] != 0){  
                     count += TERMS[(int)temp];  
                     break;  
                }  
                count++;  
           }  
           TERMS[(int)n] = count;  
           return count;  
      }  

Project Euler Problem 13: Large sum

Problem
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690
Solution

Here is my analysis posted on projecteuler































Initially I was using type long to store the result before I realize it wouldn't work for the counter example mentioned above. It prompted me to think hard and I finally came up with this working solution. Admittedly, it's still not flexible enough -- while it can handle virtually any length of number, the total size of numbers is restricted to 100. My algorithm breaks when it exceeds 100. It shouldn't be hard to fix though but I figure I already spent too much time on this problem, and it's time to move on.

      private static final String[] NUMBERS = new String[100];  
      private static final int DIGIT = 10;  
      public static void main(String[] args) {  
           readFile();  
           String result = "";  
           String unConfirmedDigits = String.valueOf(sumAt(0));  
           for (int i=1; i<NUMBERS[0].length(); i++){  
                String toCheck = assembleDigitisToCheck(unConfirmedDigits, i);  
                String confirmedDigits = confirmedDigits(toCheck);  
                result += confirmedDigits;  
                if (result.length() >= DIGIT){  
                     break;  
                }  
                unConfirmedDigits = String.valueOf(toCheck).substring(confirmedDigits.length());  
           }  
           if (result.length() >= DIGIT){  
                result = result.substring(0,DIGIT);  
           }else{  
                result = (result+unConfirmedDigits).substring(0,DIGIT);  
           }  
           System.out.println(result);  
      }  
      private static String assembleDigitisToCheck(String unConfirmedDigits, int i) {  
           UnconfirmedDigits unconfirmed = new UnconfirmedDigits(unConfirmedDigits);  
           int previousSum = unconfirmed.lastTwoUnconfirmedDigit*10+sumAt(i);  
           String toCheck;  
           if (previousSum >= 1000){  
                toCheck = String.valueOf(unconfirmed.firstUnConfirmedDigit+1);  
                for (int j=0; j<unconfirmed.nines.length(); j++){  
                     toCheck += "0";  
                }  
                toCheck += String.valueOf(previousSum-1000);  
           }else{  
                String previousSumStr = previousSum < 100 ? "0"+previousSum : String.valueOf(previousSum);   
                toCheck = String.valueOf(unconfirmed.firstUnConfirmedDigit)+unconfirmed.nines+String.valueOf(previousSumStr);  
           }  
           return toCheck;  
      }  
      private static class UnconfirmedDigits{  
           private int firstUnConfirmedDigit;   
           private String nines;  
           private int lastTwoUnconfirmedDigit;  
           private UnconfirmedDigits(String unConfirmedDigits){  
                firstUnConfirmedDigit = Integer.parseInt(unConfirmedDigits.substring(0,1)); //2 as in 29999956  
                nines = unConfirmedDigits.substring(1, unConfirmedDigits.length()-2); // 99999 as the number of 9s in 29999956 is 5  
                lastTwoUnconfirmedDigit = Integer.parseInt(unConfirmedDigits.substring(unConfirmedDigits.length()-2)); //56 as in 29999956  
           }  
      }  
      private static int sumAt(int index){  
           int sum=0;  
           for (String s : NUMBERS){  
                sum+=Integer.valueOf(s.charAt(index)+"");  
           }  
           return sum;  
      }  
      private static String confirmedDigits(String num){  
           if (num.length() <= 3){  
                return "";  
           }  
           for (int i = num.length() - 3; i>=0; i--){  
                if (Integer.valueOf(num.charAt(i)+"") < 9){  
                     return num.substring(0, i);  
                }  
           }  
           return "";  
      }  
      private static void readFile() {  
           File file = new File("Q13.txt");  
           try {  
                Scanner sc = new Scanner(file);  
                int i = 0;  
                while (sc.hasNextLine()) {  
                     NUMBERS[i++]=sc.nextLine();  
                }  
                sc.close();  
           } catch (FileNotFoundException e) {  
                e.printStackTrace();  
           }  
      }  

Tuesday 23 August 2016

Project Euler Problem 12: Highly divisible triangular number

Problem

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?

Solution

First attempt

The trick of counting the divisors is only check up to the square root of the number, and each time add 2 to the count. It didn't cross my mind the first time, and I checked up to half the number and each time add 1 to the count. It took forever....

      private static final int DIVISOR_NUMBER = 500;  
      public static void main(String[] args) {  
           int triangleNumber = 1;  
           int natualNumber = 2;  
           int divisorNumber = 1;  
           while (divisorNumber <= DIVISOR_NUMBER){  
                triangleNumber += natualNumber;  
                divisorNumber = divisorNumber(triangleNumber);  
                natualNumber++;  
           }  
           System.out.println(triangleNumber);  
      }  
      private static int divisorNumber(int number){  
           int count = 2;  
           int sqrt = (int)Math.sqrt(number);  
           for (int i=2; i<=sqrt; i++){  
                if (number % i == 0){  
                     count+=2;  
                }  
           }  
           if (sqrt * sqrt == number){  
                count--;  
           }  
           return count;  
      }  

Second attempt

This is really brilliant.

Kudos to kpsychas who came up with it. https://projecteuler.net/thread=12;page=3#5370

It is a bit difficult to understand the original post. So I have expanded it to make it more clear.



      private static final int DIVISOR_NUMBER = 500;  
      public static void main(String[] args) {  
           int k = 2;  
           int divisorNumberOdd = 0;  
           int divisorNumberEven = 0;  
           do{  
                k++;  
                divisorNumberOdd = divisorNumber(k) * divisorNumber(2*k-1);  
                divisorNumberEven = divisorNumber(k) * divisorNumber(2*k+1);  
           }while(divisorNumberOdd <= DIVISOR_NUMBER && divisorNumberEven <= DIVISOR_NUMBER);  
           if (divisorNumberOdd > DIVISOR_NUMBER){  
                System.out.println(k*(2*k-1));  
           }else{  
                System.out.println(k*(2*k+1));  
           }  
      }  
      private static int divisorNumber(int number){  
           int count = 2;  
           int sqrt = (int)Math.sqrt(number);  
           for (int i=2; i<=sqrt; i++){  
                if (number % i == 0){  
                     count+=2;  
                }  
           }  
           if (sqrt * sqrt == number){  
                count--;  
           }  
           return count;  
      }  

Project Euler Problem 11: Largest product in a grid

Problem

In the 20×20 grid below, four numbers along a diagonal line have been marked in red.

08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48

The product of these numbers is 26 × 63 × 78 × 14 = 1788696.

What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?

Solution

It is worth mentioning that the algorithm to calculate adjacent product for horizontal, vertical and diagonal direction can be consolidated.
      private static final int SIZE = 20;  
      private static final int[][] m = new int[SIZE][SIZE];  
      private static final int K = 4;  
      public static void main(String[] args) {  
           readFile();  
           int greatestProduct = 0;  
           for (int i=0; i<SIZE; i++){  
                for (int j=0; j<SIZE; j++){  
                     int rowProduct = adjacentProduct(i, j, 1, 0);  
                     int colProduct = adjacentProduct(i, j, 0, 1);  
                     int diagProductRight = adjacentProduct(i, j, 1, 1);  
                     int diagProductLeft = adjacentProduct(i,j, 1, -1);  
                     int tempGreatest = Math.max(Math.max(rowProduct, colProduct),   
                               Math.max(diagProductLeft, diagProductRight));  
                     greatestProduct = Math.max(greatestProduct, tempGreatest);  
                }  
           }  
           System.out.println(greatestProduct);  
      }  
      private static int adjacentProduct(int i, int j, int iStep, int jStep){  
           int iK = i+iStep*(K-1);  
           int jK = j+jStep*(K-1);  
           if (!withinBoundary(iK) || !withinBoundary(jK)){  
                return 0;  
           }  
           int product = 1;  
           for (int x=i,y=j,count=0; count<K; x+=iStep,y+=jStep, count++){  
                product *= m[x][y];  
           }  
           return product;  
      }  
      private static boolean withinBoundary(int i) {  
           return 0 <= i && i < SIZE;  
      }  
      private static void readFile() {  
           File file = new File("Q11.txt");  
           try {  
                Scanner sc = new Scanner(file);  
                int row = 0;  
                int col = 0;  
                while (sc.hasNextLine()) {  
                     int i = sc.nextInt();  
                     m[row][col] = i;  
                     col++;  
                     if (col == SIZE){  
                          col = 0;  
                          row++;  
                     }  
                }  
                sc.close();  
           } catch (FileNotFoundException e) {  
                e.printStackTrace();  
           }  
      }  

Monday 22 August 2016

Project Euler Problem 8: Largest product in a series

Problem

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

Solution

Two optimizations I made to make the program quicker are
  • Keep the previous product value, when it is not 0, divide the previous product value by the number at index-1, and multiply the result by the number at index+12. 
  • Check if the current sequence of numbers contains any 0s, if it does, move on to the next index. (I use bit operation to determine this. It's probably overkill, but I was so obsessed with the idea of 'going through the array only once') 
To explain the logic of determining whether a sequence of digits contains any 0s using bit operation, let's assume the length is sequence is 4, and here is a sample sequence 2708209487.

Firstly, we are checking 2708. Iterate from left to right, when we see a 0 we push a 1 to a queue, when we see a none 0, we push a 0 to the queue. The result is 0100 (decimal number 4).  The code to achieve this is

 if (numAt(i) == 0){   
   zeros |= 1 << j;    
 }   

When the result > 0, it means the sequence contains a 0.

The next sequence to check is 7082. We could repeat the previous step, but we don't have to. We can simply get rid of the right most digit of the previous result and left pad with new digit, in this case, 2.

Here is the relevant code.

 int result = previousZeros >> 1;   //Get rid of the right most digit
 if (numAt(index+NUMBER-1)==0){   
   result |= 1 << (NUMBER - 1);  //Left pad a 0 or 1 for the new digit 
 }  

Complete code

      private static final int NUMBER = 13;  
      private static final String STR =   
      "73167176531330624919225119674426574742355349194934"+  
      "96983520312774506326239578318016984801869478851843"+  
      "85861560789112949495459501737958331952853208805511"+  
      "12540698747158523863050715693290963295227443043557"+  
      "66896648950445244523161731856403098711121722383113"+  
      "62229893423380308135336276614282806444486645238749"+  
      "30358907296290491560440772390713810515859307960866"+  
      "70172427121883998797908792274921901699720888093776"+  
      "65727333001053367881220235421809751254540594752243"+  
      "52584907711670556013604839586446706324415722155397"+  
      "53697817977846174064955149290862569321978468622482"+  
      "83972241375657056057490261407972968652414535100474"+  
      "82166370484403199890008895243450658541227588666881"+  
      "16427171479924442928230863465674813919123162824586"+  
      "17866458359124566529476545682848912883142607690042"+  
      "24219022671055626321111109370544217506941658960408"+  
      "07198403850962455444362981230987879927244284909188"+  
      "84580156166097919133875499200524063689912560717606"+  
      "05886116467109405077541002256983155200055935729725"+  
      "71636269561882670428252483600823257530420752963450";  
      public static void main(String[] args) {  
           long previousProduct = calulateProduct(0, 0);  
           long greatestProduct = previousProduct;  
           int zeros = zeros(0);  
           for (int i=1; i<STR.length()-NUMBER; i++){  
                zeros = zeros(i, zeros);  
                if (zeros == 0){  
                     long product = calulateProduct(i, previousProduct);  
                     previousProduct = product;  
                     if (product > greatestProduct){  
                          greatestProduct = product;  
                     }       
                }else{  
                     previousProduct = 0;  
                }  
           }  
           System.out.println(greatestProduct);  
      }  
      private static long calulateProduct(int index, long previousProduct) {  
           if (previousProduct > 0){  
                return previousProduct / numAt(index-1) * numAt(index+NUMBER-1);   
           }  
           long product = 1;  
           for (int i=index; i<index+NUMBER; i++){  
                product *= (long)numAt(i);  
           }  
           return product;  
      }  
      private static int zeros(int index){  
           int zeros = 0;  
           for (int i=index, j=0; i<index+NUMBER; i++,j++){  
                if (numAt(i) == 0){  
                     zeros |= 1 << j;   
                }  
           }  
           return zeros;  
      }  
      private static int zeros(int index, int previousZeros){  
           if (previousZeros == -1){  
                return zeros(index);  
           }  
           int result = previousZeros >> 1;  
           if (numAt(index+NUMBER-1)==0){  
                result |= 1 << (NUMBER - 1);  
           }  
           return result;  
      }  
      private static long numAt(int index){  
           return Long.valueOf(STR.charAt(index)+"");  
      }  

Project Euler Problem 7: 10001st prime

Problem

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

Solution

Some optimization includes

  • Use an array to store found prime numbers to check future prime number candidate
  • Only check numbers 6k+1 and 6k-1, because we know other number can either be divided by 2 or 3.

      private static final int NUMBER = 10001;  
      private static final long[] primeNumbers = new long[NUMBER-1];  
      public static void main(String[] args) {  
           primeNumbers[0]=3L;  
           int index = 1;  
           for (int i=6; index < NUMBER - 1; i+=6){ //Because we start at 3 instead of 2  
                for (int j=-1; j <= 1; j+=2){ //Only test 6K+1 and 6k-1  
                     if (isPrimeNumber(i+j, index)){  
                          primeNumbers[index]=i+j;  
                          index++;  
                     }  
                     if (index >= NUMBER - 1){  
                          break;  
                     }  
                }  
           }       
           System.out.println(primeNumbers[index-1]);  
      }  
      private static boolean isPrimeNumber(long number, int index){  
           double sqrt = Math.sqrt(number);  
           for (int i = 0; primeNumbers[i] <= sqrt; i++){  
                if (number % primeNumbers[i] == 0){  
                     return false;  
                }  
           }  
           return true;  
      }  

Sunday 21 August 2016

Project Euler Problem 5: Smallest multiple

Problem

 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

 What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Solution

Attempt 1: Count the occurrences of the prime factor for each number, and multiply them all.

      private static Map<Integer, Integer> primeNumberOccurrence = new HashMap<>();  
      public static void main(String[] args) {  
           for (int i=2; i<=20; i++){  
                updatePrimeNumberOccurrence(i);  
           }  
           int total = 1;  
           for (int key : primeNumberOccurrence.keySet()){  
                int occurrence = primeNumberOccurrence.get(key);  
                total *= Math.pow(key, occurrence);  
           }  
           System.out.println(total);  
      }  
      private static void updatePrimeNumberOccurrence(int number){  
           int divisor = 2;  
           int divisorCount = 0;  
           while(number > 1){  
                if(number % divisor == 0){  
                     number = number / divisor;  
                     divisorCount++;  
                }else{  
                     update(divisor, divisorCount);  
                     divisor++;  
                     divisorCount = 0;  
                }  
           }  
           update(divisor, divisorCount);  
      }  
      private static void update(int divisor, int divisorCount){  
           if (divisorCount != 0){  
                int oldCount = primeNumberOccurrence.get(divisor) != null ? primeNumberOccurrence.get(divisor) : 0;  
                if (divisorCount > oldCount){  
                     primeNumberOccurrence.put(divisor, divisorCount);  
                }  
           }  
      }  

Attempt 2: Use greatest common factor

      private static final int NUMBER = 20;  
      public static void main(String[] args) {  
           int total = NUMBER;  
           for (int i = NUMBER-1; i >= 2; i--){  
                //greatest common factor  
                total *= i / BigInteger.valueOf(total).gcd(BigInteger.valueOf(i)).intValue();  
           }  
           System.out.println(total);  
      }  

Project Euler Problem 4: Largest palindrome product

Problem

A palindromic number reads the same both ways.

The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.

Solution

The efficiency of checking if a number is palindrome can certainly be improved, but I am more focused on optimization on two for loops.

  • Start from 999 backwards, and start j=i instead of 999
  • Check product > current largest palindrome first instead of checking product is palindrome first
  • break inner loop when we know the rest product cannot be larger than the current largest palindrome

      public static void main(String[] args) {  
           long largestPalindrome = 0;  
           for (int i = 999; i >= 100; i--){  
                for (int j = i; j >= 100; j--){  
                     long product = i * j;  
                     if (product > largestPalindrome){  
                          if (isPalindrome(product)){  
                               largestPalindrome = product;  
                               break;  
                          }  
                     }else{  
                          break;  
                     }  
                }  
           }  
           System.out.println(largestPalindrome);  
      }  
      private static boolean isPalindrome(long product) {  
           String s = String.valueOf(product);  
           return reverse(s).equals(s);  
      }  
      private static String reverse(String s) {  
           String r = "";  
           for (int i=s.length()-1; i>=0; i--){  
                r += s.charAt(i);  
           }  
           return r;  
      }  

Project Euler Problem 3: Largest prime factor

Problem

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143?

Solution


If the while loop condition changes to divisor < number, it will be extremely slow for number like 600851475145


      public static void main(String[] args) {            
           long number = 600851475143L;  
           long divisor = 2;  
           while((divisor * divisor) <= number){  
                if(number%divisor==0){  
                     number = number/divisor ;  
                }  
                divisor++;  
           }  
           System.out.println(number);  
      }  

Wednesday 17 August 2016

Blackjack house edge

Statistically speaking, Blackjack is probably the only casino game where you can win money in the long run.

Inspired by the movie <21>, I decided to write a Java program (https://github.com/sunmingtao/blackjack) to find out the house edge for the following two scenarios:
  1. The player employs the basic strategy.
  2. The player counts the card and bets only when the situation favours him.
What is basic strategy?

Basic strategy, simply put, is the strategy that enables you to lose the least money to the casino in the long run. Given a hand against a specific dealer’s face up card, the strategy chart will tell you which action to take. If you decide to disobey the strategy chart, it will cause you to lose more money.

Since  Blackjack’s rules vary from casino to casino, there is a basic strategy for each set of rules.

My program assumes the use of American rules (with hole card), as opposed to European/Australian rules (without hole card). Also assumed is the following variation of rules, which is quite common in America.

  • Hole card games — dealer peeks for blackjack on 10s and Ace upcards.
  • The dealer must stand on Soft-17.
  • Blackjack payout is 3 to 2 odds.
  • 21 on split Aces cannot count as a player blackjack.
  • We can double down on any hand total.
  • We can double down after splitting.
  • We can split hands up to three times, making four total hands.
  • We can split Aces only once, and only take one card to split Aces.
  • Unlike 10-valued cards can be split; 10-card and Jack, etc.
  • Late surrender is allowed.

Here is the basic strategy chart corresponding to the above rules.














































S = Stand
H = Hit
Dh = Double (if not allowed, then hit)
Ds = Double (if not allowed, then stand)
SP = Split
SU = Surrender (if not allowed, then hit)

How do I work out the house edge?

First off, I don’t know how to calculate the precise odds mathematically. There are so many combinations that I think it’s only theoretically possible to do the precise calculation. But precision doesn’t really matter here. Knowing a range is more than sufficient to help us make a decision. If we know the house edge of Baccarat falls between 0.5% and 0.6% while Baccarat is 1%-1.2%, we want to stay a bit away from Baccarat table.

The approach I take is Monte Carlo method, which is to simulate the game played between player and dealer for a large number of times.

Number of hands simulated House edge
89412575 0.36
89411293 0.38
89409262 0.35

We see a house edge between 0.35% and 0.38%. This means if we bet $100 every time, after 100 hands, we are expected to lose 35-38 dollars on average.

Now let’s see how card counting reverses the house edge.

How does card counting work?

The more big cards (10-A) remain in the deck, the more advantage shifts to the player’s side.  The rationale behind this system is that with more big cards remaining, the player is more likely to hit a natural blackjack, which pays 3 to 2. And the dealer is more likely to bust because he is obliged to hit on 4 or 5 while the player can choose to stand. 

To count card is simple, start the counter as 0, when you see 2-6, add 1 to the counter. When you see 10-A, subtract 1 from the counter. Do nothing when you see 7-9. 

We call the value of this counter as ‘running count’. The casino normally uses 6-8 decks of cards, so we need to translate our information into ‘true count’, which means the ‘running count’ per remaining deck. 

For example, the ‘running count’ is 5, and there are about 5 decks of cards remaining. The ‘true count’ would be 1. 

So when can you start betting? When ‘true count’ >= 1. At least it’s what the online article says. However, my program actually proves using ‘running count’ is almost as effective as ‘true count’.

Let's compare the result between true count and running count.

When true count > 1

Number of hands simulated Number of hands bet House edge per hand bet House edge per hand dealt
89413874 28600935 -1.10 -0.35
89411394 28576145 -1.07 -0.34
89409522 28573179 -1.08 -0.35

When running count > 1

Number of hands simulated Number of hands bet House edge per hand bet House edge per hand dealt
89409623 39847047 -0.73 -0.32
89412203 39847047 -0.77 -0.34
89412267 39816672 -0.79 -0.35

We see a player advantage in both cases. While it is undeniable that true count's edge is significantly higher than running count's in terms of 'per hand bet' (1.08 vs 0.77), it doesn't mean you can make significantly more money using true count. We must take the opportunity cost into consideration.

While using true count, there is only roughly 30% of the time when you can bet. The rest of time you have to sit out. It's highly unlikely you can tap into this idle period to make any money because you still need to be preoccupied with keeping track of the count. Consequently the real house edge that will reflect in your hourly earning rate is based on the total hands dealt, whether you play or not. And when we compare the house edge per hand dealt, the difference can hardly be said to have any statistical significance.

Finally let's do some rough estimate for a card counting pro's hourly rate. Suppose a dealer deals 100 hands an hour and the pro bets $100 every time, he's then earning $35 an hour on average. Double the stake, he will be earning $70 an hour. To stay under the radar, his stake probably can't go higher than that. Otherwise the casino will soon catch on and ban him. Upping the stake will also face the bankroll issue. We must bear in mind that the $35 or the $70 hourly rate doesn't mean you will be constantly earning this amount hour by hour like ordinary office workers do. You could win $500 this hour and lose $300 next hour. If you don't have a bankroll large enough, chances are you will go broke before you get a chance to win it back.

Monday 1 August 2016

List all possible combinations

First attempt:
      public static <T> List<List<T>> allCombination(List<T> list, int n){  
           List<List<T>> result = new ArrayList<>();  
           if (n > 0){  
                for (int i=0; i<list.size(); i++){  
                     List<T> sublist = list.subList(i+1, list.size());  
                     if (sublist.size() >= n-1){  
                          List<List<T>> subAllCombination = allCombination(sublist, n-1);  
                          if (subAllCombination.size() > 0){  
                               for (List<T> strList : subAllCombination){  
                                    List<T> entry = new ArrayList<>();  
                                    entry.add(list.get(i));  
                                    entry.addAll(strList);  
                                    result.add(entry);  
                               }       
                          }else{  
                               List<T> entry = new ArrayList<>();  
                               entry.add(list.get(i));  
                               result.add(entry);  
                          }       
                     }  
                }  
           }  
           return result;  
      }  

Second attempt:
      public static <T> List<List<T>> allCombo(List<T> list, int n){  
           List<List<T>> result = new ArrayList<>();  
           push(list, n, new ArrayList<T>(), result);  
           return result;  
      }  
      private static <T> void push(List<T> list, int n, List<T> items, List<List<T>> result) {  
           if (n == 0){  
                result.add(new ArrayList<>(items));  
                return;  
           }  
           for (int i=0; i<list.size(); i++){  
                items.add(list.get(i));  
                push(list.subList(i+1, list.size()), n-1, items, result);       
                items.remove(items.size()-1);  
           }       
      }  

Testing code:
      public static void main(String[] args){  
           List<String> list = Arrays.asList("A","B","C","D","E");  
           for (List<String> str : allCombo(list, 3)){  
                System.out.println(str);  
           }  
      }  

Result:

[A, B, C]
[A, B, D]
[A, B, E]
[A, C, D]
[A, C, E]
[A, D, E]
[B, C, D]
[B, C, E]
[B, D, E]
[C, D, E]