Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, July 13, 2013

Problem 42


The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?

/**
 *
 @author Umang 
 * started at : 13/07/2013 09:01 PM 
 * completed at : 9:26 PM
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Problem42
{

    private static HashMap<Integer, Long> triangleValues;
    private static int countedTill = 0;

    static
    {
        triangleValues = new HashMap<>();
    }

    private static long calcuateTriangleNumber(int no)
    {
        return no * (no + 12;
    }

    public static long getTriangleNumber(int no)
    {
        long triangleNumber = 0;
        if (no >= countedTill)
        {
            
            int i = 0;
            for (i = countedTill; i <= no; i++)
            {
                triangleNumber = calcuateTriangleNumber(no);
                triangleValues.put(no, triangleNumber);
            }
            countedTill = i;
        }
        else
        {
            triangleNumber = triangleValues.get(no);
        }
        return triangleNumber;
    }

    private static boolean isTriangleNumber(long no)
    {
        boolean isTriangleNumber = false;
        long triangleNumber = 0;
        int i = 0;
        do
        {
            triangleNumber = getTriangleNumber(i);
            if (triangleNumber == no)
            {
                isTriangleNumber = true;
                break;
            }
            i++;
        }
        while (no >= triangleNumber);
        return isTriangleNumber;
    }

    private static String getFileContent()
    {
        StringBuilder content = new StringBuilder("");

        File aFile = new File("D:/words.txt");
        Scanner aScanner = null;
        try
        {
            aScanner = new Scanner(aFile);
        }
        catch (FileNotFoundException ex)
        {
            System.out.println("File could not be readed");
            ex.printStackTrace();
            System.exit(0);
        }
        while (aScanner.hasNextLine())
        {
            content = content.append(aScanner.nextLine());
        }
        return content.toString();
    }

    private static LinkedList<String> getWordList()
    {
        LinkedList<String> result = new LinkedList<>();

        String content = getFileContent();
        StringTokenizer lineTokenizer = new StringTokenizer(content, ",\"");
        while (lineTokenizer.hasMoreTokens())
        {
            result.add(lineTokenizer.nextToken());
        }
        return result;
    }

    private static int getCharNo(char character)
    {
        int charNo = 0;
        char capitalized = Character.toUpperCase(character);
        charNo = ((intcapitalized64;
        return charNo;
    }

    private static long getValueFromString(String str)
    {
        long count = 0;
        for (int i = 0; i < str.length(); i++)
        {
            count += getCharNo(str.charAt(i));
        }

        return count;
    }

    public static void main(String args[])
    {
        int triangleNumberCount = 0;
        LinkedList<String> wordList = getWordList();
        for (String word : wordList)
        {
            if (isTriangleNumber(getValueFromString(word)))
            {
                triangleNumberCount++;
            }
        }
        System.out.println("There are " + triangleNumberCount + " triangle numbers");
    }
}

Thursday, January 10, 2013

Amicable Number

import java.util.ArrayList;

/**
 @author Umang
 */
/**
 * Let d(n) be defined as the sum of proper divisors of n 
 * (numbers less than n which divide evenly into n).
 
 * If d(a) = b and d(b) = a, where a  b, then a and b are an amicable pair 
 * and each of a and b are called amicable numbers.
 
 * For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 
 * 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 
 * 71 and 142; so d(284) = 220.
 
 * Evaluate the sum of all the amicable numbers under 10000.
 */
public class Problem21
{

    private static boolean isAmicable(int no)
    {
        long sum = sum(getEvenDivisors(no));
        long no2 = sum(getEvenDivisors(sum));
        return no == no2 && sum != no;
    }

    private static long sum(ArrayList<Long> numbers)
    {
        long ans = 0;
        for (Long number : numbers)
        {
            ans += number;
        }
        return ans;
    }

    private static ArrayList<Long> getEvenDivisors(long n)
    {
        long root = Math.round(Math.sqrt(n)) 1;

        ArrayList<Long> test = new ArrayList<Long>();
        test.add(1L);
        for (long i = 2; i <= root; i++)
        {
            if (n % i == 0)
            {
                test.add(i);
                test.add(n / i);
            }
        }
        return test;
    }

    public static void main(String[] args)
    {
        long sum = 0;
        for (int i = 0; i < 10000; i++)
        {
            if (isAmicable(i))
            {
                sum = sum + i;
            }
        }
        System.out.println("Sum = " + sum);
    }
}

Circular Primes

package javaapplication3;

import java.util.ArrayList;

/**
 * The number, 197, is called a circular prime because all rotations of the
 * digits: 197, 971, and 719, are themselves prime.
 *
 * There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71,
 * 73, 79, and 97.
 *
 * How many circular primes are there below one million?
 */
/**
 @author Umang
 */
public class Problem35
{

    public static ArrayList<Long> getDigits(long no)
    {
        ArrayList<Long> numbers = new ArrayList<Long>();
        long temp = no;
        while (temp > 0)
        {
            numbers.add(temp % 10);
            temp /= 10;
        }
        return numbers;
    }

    private static int getCount(long no)
    {
        ArrayList<Long> numbers = getDigits(no);
        return numbers.size();
    }

    public static long sumOfFactorialOfEach(ArrayList<Integer> numbers)
    {
        long sum = 0;

        for (int no : numbers)
        {
            sum += factorial(no);
        }
        return sum;
    }

    static boolean isPrime(long n)
    {
        //check if n is a multiple of 2
        if (n % == 0)
        {
            return false;
        }
        //check the odds
        for (long i = 3; i * i <= n; i += 2)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
        return true;
    }

    static String rotate(String number)
    {
        return number.subSequence(1, number.length()) "" + number.charAt(0);
    }

    private static long factorial(long no)
    {
        return no == : no * factorial(no - 1);
    }

    static boolean checkRotationsAndPrime(long no)
    {
        boolean allPrimes = true;
        String strNo = new Long(no).toString();
        int rotations = getCount(no);
        for (int i = 0; i < rotations; i++)
        {
            if (!isPrime(new Long(strNo)))
            {
                allPrimes = false;
            }
            strNo = rotate(strNo);
        }
        return allPrimes;
    }

    public static void main(String[] args)
    {
        long count = 0;
        for (int i = 1; i <= 1000000; i++)
        {
            if (checkRotationsAndPrime(i))
            {
                count++;
            }
        }
        System.out.println("\nCount is " + count);
    }
}

Problem 18

package javaapplication3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringTokenizer;

/**
 * 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
 *  2 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
 *
 * NOTE: As there are only 16384 routes, it is possible to solve this problem by
 * trying every route. However, Problem 67, is the same challenge with a
 * triangle containing one-hundred rows; it cannot be solved by brute force, and
 * requires a clever method! ;o)
 */
/**
 *
 @author Umang
 */
public class Problem18
{

    /**
     * get the file content from given location
     @return file content in string format
     */
    private static String getFileContent()
    {
        StringBuilder content = new StringBuilder("");

        File aFile = new File("D:/input.txt");
        Scanner aScanner = null;
        try
        {
            aScanner = new Scanner(aFile);
        
        catch (FileNotFoundException ex)
        {
            System.out.println("File could not be readed");
            ex.printStackTrace();;
            System.exit(0);
        }
        while (aScanner.hasNextLine())
        {
            content = content.append(aScanner.nextLine() "\n");
        }
        return content.toString();
    }

    /**
     * gets the numbers in format of  LinkedList<LinkedList<Integer>>
     @return  LinkedList<LinkedList<Integer>> from the ifile
     */
    private static LinkedList<LinkedList<Integer>> getList()
    {
        LinkedList<LinkedList<Integer>> result = new LinkedList< LinkedList< Integer>>();

        String content = getFileContent();
        StringTokenizer lineTokenizer = new StringTokenizer(content, "\n\r");
        while (lineTokenizer.hasMoreTokens())
        {
            LinkedList<Integer> row = new LinkedList<Integer>();

            StringTokenizer numberTokenizer = new StringTokenizer(lineTokenizer.nextToken()" ");
            while (numberTokenizer.hasMoreTokens())
            {
                Integer no = new Integer(numberTokenizer.nextToken());
                row.add(no);
            }

            result.add(row);

        }
        return result;
    }

    /**
     
     @param rows is the LinkedList<LinkedList<Integer>> where everything is stored
     @param row_no is the row number
     @param col_no is the column number
     @return the actual number at given row and column from LinkedList<LinkedList<Integer>>
     @throws Exception if no number is found in the list (assuming that the 
     * number is never 0 in the list)
     */
    public static int get_item_at(LinkedList<LinkedList<Integer>> rows, int row_no, int col_nothrows Exception
    {
        int no = 0;

        int row_count = 0;
        int col_count = 0;

        for (LinkedList<Integer> row : rows)
        {
            col_count = 0;
            for (Integer number : row)
            {
                if (row_no == row_count && col_count == col_no)
                {
                    no = number;
                    break;
                }
                col_count++;
            }
            row_count++;
        }
        if (no == 0)
        {
            throw new Exception("No such item");
        }
        return no;
    }

    public static void main(String[] argsthrows Exception
    {
        LinkedList<LinkedList<Integer>> numbers = getList();
        System.out.println("Ans is " + getHighestSumFromList(numbers, 00));
    }

    private static int getHighestSumFromList(LinkedList<LinkedList<Integer>> rows, int row, int colthrows Exception
    {
        int currunt_no = get_item_at(rows, row, col);
        int mul_left = 0;
        int mul_right = 0;
        try
        {
            mul_left = getHighestSumFromList(rows, row + 1, col)  + currunt_no;
            mul_right = getHighestSumFromList(rows, row + 1, col + 1)  + currunt_no;
        
        catch (Exception e)
        {
            // if at the end of the list then return the currunt value 
            return get_item_at(rows, row, col);
        }
        int bigger_number =  mul_left > mul_right ? mul_left : mul_right;
        return bigger_number;

    }
}

Wednesday, January 9, 2013

Problem 92

package javaapplication3;

import java.util.ArrayList;

/**
 * A number chain is created by continuously adding the square of the digits 
 * in a number to form a new number until it has been seen before.
 *  
 * For example,
 * 44 -> 32 ->  13 ->  10 ->  1 ->  1
 * 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89
 
 * Therefore any chain that arrives at 1 or 89 will become stuck in an 
 * endless loop. What is most amazing is that EVERY starting number will 
 * eventually arrive at 1 or 89.
 
 * How many starting numbers below ten million will arrive at 89?
 */
/**
 @author Umang
 */
public class Problem92
{

    public static ArrayList<Long> getDigits(long no)
    {
        ArrayList<Long> numbers = new ArrayList<Long>();
        long temp = no;
        while (temp > 0)
        {
            numbers.add(temp % 10);
            temp /= 10;
        }
        return numbers;
    }

    public static long sumSquaresOfNo(long no)
    {
        ArrayList<Long> numbers = getDigits(no);
        long sum = 0;

        for (long curunt_no : numbers)
        {
            sum += (curunt_no * curunt_no);
        }
        return sum;
    }

    static boolean doesArrivesAt89(long no)
    {
        boolean return_val = false;
        long squares = sumSquaresOfNo(no);
        if (squares == || squares == 89)
        {
            if (squares == 1)
            {
                return_val = false;
            
            else if (squares == 89)
            {
                return_val = true;

            }
        else
        {
            return_val = doesArrivesAt89(squares);
        }
        return return_val;
    }

    public static void main(String[] args)
    {
        int count = 0;
        for (long l = 1; l <= 10000000; l++)
        {
            if (doesArrivesAt89(l))
            {
                count++;
            }
        }
        System.out.println("count is " + count);
    }
}