Tag Archive for code

TJU Problem 2123 Solution – Java

Head or Tail is a simple counting problem… count 0s or 1s and output the final counts… code’s below.

/*
 * Author: Gal Appelbaum
 * www.galappelbaum.com
 */
import java.util.*;

public class p2123 {

    public static void main(String args[]){
        Scanner scn = new Scanner(System.in);
        int games = scn.nextInt();
        int currentGame;
        while(games != 0){
            int Mary = 0;
            int John = 0;
            while(games != 0 ){
                currentGame = scn.nextInt();
                if(currentGame == 0)
                    Mary++;
                else
                    John++;
                games--;
            }
            System.out.printf("Mary won %d times and John won %d timesn", Mary, John);
            games = scn.nextInt();
        }
    }
}

									

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);
    }
}

									

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;
        }
    }
}

									

C++: Finding Prime Numbers

Finding a prime number is a big part of computing. Tons of homework assignments, programming exercises, contests, etc, have questions that require figuring out if a number is prime or print a list of primes in a certain range, etc… figured I’d post a simple way to figure out if a number is prime. This might not be the most “optimal” code but then again I wrote this first year in college and been reusing it ever since… enjoy.

This specific version was part of a loop and returned only the prime numbers.

int isPrime(int number){
    int count=0;
    for(int a = 1; a<=number ;a++)
    {
        if(number % a == 0)
            count++;
    }
    if(count == 2)
        return number; 
    return 0; 
} 
									

Lambert W Subroutine

I recently had an interesting assignment in which I had to create a LambertW solution in Fortran95. While it isn’t the hardest thing to code once you understand how to do it, it still took a little to figure this one out. Here’s a piece of code in Fortran and this is newtons method. There are links below describing exactly how it works, and an example of Newtons method in Python as well. enjoy.

subroutine Lambert(n,a,finalp)
  implicit none
    real :: n, a, y, z, firstW, lastW, CurrentW, expW
    real :: eps = 0.00000000001
    integer :: finalp
    firstW=1
    LastW=FirstW
    CurrentW=0
    
    loop:do
        expW = exp(lastW)
        z = (-a)*(exp(-a))
        CurrentW = LastW - ((LastW * expW - z) / ((expW * (LastW + 1)) - ((LastW + 2) * (LastW * expW) / (2 * LastW + 2 -z))))
        if(lastW - CurrentW < eps) exit loop
        lastW = CurrentW
        end do loop
 end subroutine Lambert
									

and here are some useful Links:

Lambert W Function Explained with solutions

Python Solution