Tag Archive for programming

Project Euler Problem 14 Solution – Longest Collatz sequence

Longest Collatz sequence is a very cool problem which I first encountered (requiring different things, but method was the same) when I started learning C++. The problem states that for any set of positive integers you do the following:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

and that eventually, any number will end up at 1. the problem requires us to count how many numbers are in the chain between n and 1… the solution to this classic project Euler problem is below in Java.

 

/*
 * Author: Gal Appelbaum
 * www.galappelbaum.com
 */

public class p14 {

    public static void main(String[] args){
        int longestChain = 0;
        int finalNumber = 0;
        int count = 1;
        double currentNumber = 0;
        for(int i = 2; i < 1000000; i++){
            currentNumber = i;
            while(currentNumber != 1){
                if(currentNumber % 2 == 0)
                    currentNumber = currentNumber/2;
                else
                    currentNumber = 3*currentNumber + 1;
                count++;
            }
            if(count > longestChain){
                longestChain = count;
                finalNumber = i;
            }
            count = 0;
            System.out.println(i);
        }
        System.out.println(finalNumber);
    }
}

									

Project Euler Problem 4 Solution – Largest Palindrome Product

Largest Palindrome Product is a pretty cool problem (problem 4) that requires you to find the largest palindrome made of a product of two 3-digit numbers. a palindrome is a number that if inverted, it has the same value (ex. 9009, 1221, 69496, etc.). Unlike other programming websites, Project Euler doesn’t care too much about performance of your code, elegance, etc. but rather wants a final answer. Since I recently stumbled on some old code I wrote last year, I figured I’d share it… the solution to problem 4 is below and written in C++. it might take a moment or two to spit the final answer, but after all Project Euler is only interested in final answer.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;


int main(){
    string tempreverse;
    string temp;
    stringstream out;
    int tempnumber, tempnumber2; 
    int palindrome = 0;

    for(int i = 100; i < 1000; i++){
        for(int j = 100; j < 1000; j++){
            out.str("");
            tempnumber = i * j;
            out << tempnumber;
            temp = out.str();
            tempreverse = string (temp.rbegin(), temp.rend());
            tempnumber2 = atoi(tempreverse.c_str());
            if (tempnumber == tempnumber2){
                if(tempnumber > palindrome){
                    palindrome = tempnumber;
                }
            }
        }
    }
    std::cout << palindrome << "n";
    std::cout << "Press ENTER to continue...";
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );
    return 0;
}

									

TJU Problem 2955 Solution – Java

CETVRATA,  is a pretty straight forward question… some (like me) might not realize the extreme simplicity of it at first, but once you realize you’re over thinking it it’s a fairly easy programming problem.

While the question tries to make you think about which corners of the rectangle you have and maybe you’re thinking along that direction, the answer lies within the numbers and their order…  My solution to problem 2955 in java is below.

import java.util.Scanner;

public class p2955 {

    public static void main(String[] args){
        Scanner src = new Scanner(System.in);
        int a = src.nextInt(); // Left
        int b = src.nextInt(); // Right
        int c = src.nextInt(); // Left
        int d = src.nextInt(); // Right
        int e = src.nextInt(); // Left
        int f = src.nextInt(); // Right
        int answer1, answer2 = 0;
        if(a == c)
            answer1 = e;
        else if (a == e)
            answer1 = c;
        else
            answer1 = a;
        if(b == d)
            answer2 = f;
        else if(b == f)
            answer2 = d;
        else
            answer2 = b;
        System.out.printf("%d %dn", answer1, answer2);
    }
}

									

TJU Problem 2120 Solution – Java

Psuedo-Random Numbers is a fairly straight forward question but it has one main trick that even I didn’t notice initially… The last sentence of the explanation says “But be careful — the cycle might not begin with the seed!” and that’s the trick.

 

Essentially the example shows you how to solve this problem if the seed is the first number, but what should be assumed from the problem is that the random number sequence has “cycles” which will eventually restart. so the trick is to figure out if the new number you’ve generated has been generated before, and if it did, you’re done. All it is is a simple array that is as big as M (read the problem…), and every time a number is calculated and added to the array, backtrack to make sure it wasn’t there before. if it was, the arrays length from the point it was originally generated until now is your answer… here’s a simple solution in Java.

import java.util.Scanner;

public class p2120 {

    public static void main(String[] args){
        boolean run = true;
        boolean done = false;
        int Z, I, M, L = 0;
        int caseNumber = 1; 
        int answer = 0;
        Scanner src = new Scanner(System.in);
        while(run){
            Z = src.nextInt();
            I = src.nextInt();
            M = src.nextInt();
            L = src.nextInt();
            if(Z == 0 && I == 0 && M == 0 && L == 0)
                break;
            int[] results = new int[M];
            for(int i = 0; i <= M; i++){
                results[i] = (Z*L+I) % M;
                L = results[i];
                if(i > 0){
                    for(int j = i-1; j >= 0; j--){
                        if(results[j] == results[i]){
                            answer = i - j;
                            done = true;
                            break;
                        }  
                    }
                }
                if(done)
                    break;
            }
            System.out.printf("Case %d: %dn", caseNumber, answer);
            caseNumber++;
            answer = 0;
            done = false;
        }
    }
}

									

Facebook Hacker Cup 2013 Qualifying round

Facebooks yearly Hacker Cup started last weekend with its qualifying round running through the weekend… 3 questions, nothing TOO complicated, solve one and you’re in for round 1 which is February 2nd. I managed to squeeze my way into the 1st round by solving only the 1st question… unfortunately I didn’t read the instructions and downloaded the test file for the 2nd question which then triggered a timer of 6 minutes to submit the source code and answers… and I had neither… The third question was a pain, didn’t bother with it too much (2 tests to study for). So here’s the 1st question AND my code for it… I actually ranked 6915 out of 10169… lol.

Question 1: Beautiful Strings

When John was a little kid he didn’t have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could… he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.

Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it.

The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn’t care about whether letters are uppercase or lowercase, so that doesn’t affect the beauty of a letter. (Uppercase ‘F’ is exactly as beautiful as lowercase ‘f’, for example.)

You’re a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?

Input

The input file consists of a single integer m followed by m lines.

Output

Your output should consist of, for each test case, a line containing the string “Case #xy” where x is the case number (with 1 being the first case in the input file, 2 being the second, etc.) and y is the maximum beauty for that test case.

Example Input:

5
ABbCcc
Good luck in the Facebook Hacker Cup this year!
Ignore punctuation, please :)
Sometimes test cases are hard to make up.
So I just go consult Professor Dalves

Example Output:

Case #1: 152
Case #2: 754
Case #3: 491
Case #4: 729
Case #5: 646

My solution… again, can be cleaned up, save a couple of lines… but meh.

import java.util.Scanner;

public class BeautifulStrings {

    public static void main(String args[]) {
        Scanner scn = new Scanner(System.in);
        final int[] chars = new int[26];
        int tempMax = 0;
        int tempMaxIndex = 0;
        int finalAnswer = 0;
        final int cases = Integer.parseInt(scn.nextLine());
        for (int i = 0; i <= cases; i++) {
            int HighestValueAvailable = 26;
            final String tempS = scn.nextLine().toLowerCase(); //temporary string converted into lower case only
            final char[] temp = tempS.toCharArray();
            for (int j = 0; j < tempS.length(); j++) {
                final int currentChar = (int) temp[j];
                if (currentChar >= 97 && currentChar <= 122) { // ensure the characters are letters.
                    chars[currentChar - 97]++;
                }
            }
            for (int a = 0; a < tempS.length(); a++) {
                for (int b = 0; b < chars.length; b++) {
                    if (chars[b] > tempMax) { // find the number that re-appears the most.
                        tempMax = chars[b]; //keep the value, and index of the value.
                        tempMaxIndex = b;
                    }
                }
                finalAnswer = finalAnswer + (HighestValueAvailable * tempMax); // calculate answer and restart variables.
                chars[tempMaxIndex] = 0;
                HighestValueAvailable--;
                tempMax = 0;
            }
            System.out.printf("Case #%d: %dn", i + 1, finalAnswer);
            finalAnswer = 0;
        }
    }
}