Showing posts with label puzzle. Show all posts
Showing posts with label puzzle. Show all posts

21 December 2010

15 game in Flash Actionscript3

Having implemented the 15-game in Java, I thought I would attempt the same with Flash + AS3. And the same was done swiftly and I have presented the output and the code here. This is the same as the applet version, you will have to use your arrow keys to play.




The Layout grid file which I wrote on my own to simulate an exact Grid Layout similar to the one in Java.

Cheers!!
Braga

20 December 2010

CAT Brain Teaser

Well, this can be considered off-topic. A brain teaser in CAT. Only 2% students were able to solve this in the CAT Exam. They should have been really sick :) Enough build up, lets see what the problem is.

Given,

5+3+2 = 151022
9+2+4 = 183652
8+6+3 = 482466
5+4+5 = 202541

Then, 7+2+5 = ???


Solution:

5+3+2 = (5*3)(5*2)(5*3 + 5*2 - 3)
9+2+4 = (9*2)(9*4)(9*2 + 9*4 - 2)
8+6+3 = (8*6)(8*3)(8*6 + 8*3 - 6)
5+4+5 = (5*4)(5*5)(5*4 + 5*5 - 4)

Hence,

7+2+5 = (7*2)(7*5)(7*2 + 7*5 - 2) = 143547

Cheers!!
Jack

16 December 2010

How to find angle between hour and minute hands in an analog clock?

Given a simple clock, we have to find the angle between the hour and minute hands. Since this is a deliberate question, we should obviously be ignoring the thickness of the hands in the clock.


We need to understand the following things before we arrive at our solution.
  • The hour hand moves at the rate of 0.5 degrees per minute.
  • The minute hand moves at the rate of 6 degrees per minute.
The reason for the above statements are obvious if you think a layer deep. Now, for the code (works both for C++ and Java)


Cheers!!
Jack.

14 October 2010

Interview Puzzle - Equal heads

Puzzle:

There are 50 coins on the table out of which 43 are tail-face up and 7 are head face up. You are blind folded and there is no way to determine which side is up by rubbing, etc. You have to divide the 50 coins in two sets (not necessarily equal) such that both have equal number of coins with heads face up.

Solution:

Divide the 50 coins into two sets - once set with 43 coins and the other set with 7 coins. Thus, the first set will contain 'x' heads and '43-x' tails and the second set will contain '7-x' heads and 'x' tails. The possibilities can be tabulated as shown in the left table.

Now, flip the coins in the second set, so that both will contain 'x' heads. The result after flipping can be seen on the right table. You can see that both sets have equal number of heads whatever be the distribution.


Cheers!!
Jack

07 October 2010

Print a Matrix in diagonal zig zag order

Problem:
Given a square matrix, write a program to print the items in zig zag diagonal order.

Following is an example,

So the output expected for the above example is,

1 -> 2 -> 6 -> 3 -> 7 -> 11 -> 4 -> 8 -> 12 -> 16 -> 5 -> 9 -> 13 -> 17 -> 21 -> 10 -> 14 -> 18 -> 22 -> 15 -> 19 -> 23 -> 20 -> 24 -> 25

Solution:

This program is a bit tricky and is very hard to solve immediately when asked in an interview. People who try to attack problems involving matrices always think they need at least two loops to arrive at the solution. But the surprise here is the problem can be solved in just a single loop with a very simple logic. I have provided the solution in C++ below, you may also try to solve the same in the language of your choice!!


Cheers!!
Jack

25 September 2010

A Free game in Java

I wanted to play this game so badly as I use to be very good at it. I was not knowing the proper keyword to find it online. So, what the heck, I went ahead and created one! The front end used was Swing.
The objective of this game is to arrange from numbers 1 through 24 (or depending on the size) in proper order and you have one square free. You can move to that empty sqaure by pressing either of the four arrow keys UP/DOWN/LEFT/RIGHT. All the puzzles formed will have a solution. You can use this code anywhere you want.

If you have Java installed in your browser, you should be able to see the Applet. Just click anywhere inside the applet and start playing using the arrow keys! Have fun!


Screenshot Applet




Cheers,
Bragaadeesh.

28 April 2010

Find the last person seated around in a circle program/puzzle

This is a programming question asked at one of the class companies. Following is the question

“n” people are seated around in a circle. At each step, the “m”th person is eliminated from the circle. The next iteration continues from the person next to the eliminated person. In the end, there will be only one person remaining. Given “n” and “m”, write a program to find out the person who will be remaining at the end.
int FindWinner(int n, int m)


Me and my roommate both implemented a solution for the above problem one in Java and the other in C++ respectively. Please see the code and the ouput for the above problem below.

Implementation in Java

package brainteasers;

public class FindWinner {
 public static void main(String[] args) {
  FindWinner finder = new FindWinner();
  char winner = finder.findWinner(10,3);
  System.out.println("\nAnd the winner is "+(char)(winner-32)+"!!");
 }
 
 private char findWinner(int n, int m){
  char[] people = getPeople(n);
  boolean[] eliminated = new boolean[n];
  //always start from 1st person
  int remainingGuys = n;
  int current = 0;
  
  while(remainingGuys>1){
   int inkiPinki=0;
   
   while( eliminated[current] || ++inkiPinki != m )
       current = (current+1) % n;
   
   eliminated[current] = true;
   printStatus( eliminated, people );
   remainingGuys--;
   
   while(eliminated[(current+1)%n]){
    current++;
   }
   
   current = (current+1)%n;
  }
  
  System.out.println();
  return people[current];
 }

 private void printStatus(boolean[] eliminated, char[] people) {
  System.out.println();
  for(int i=0;i<eliminated.length;i++){
   char output;
   if(eliminated[i]){
    output = people[i];
   }else{
    output = (char)(people[i] - 32);
   }
   System.out.print(output+" ");
  }
 }

 private char[] getPeople(int n) {
  char[] people = new char[n];
  System.out.println("Participants are...");
  for(int i=0;i<n;i++){
   people[i] = (char)(i+97);
   System.out.print((char)(people[i]-32)+" ");
  }
  System.out.println();
  return people;
 }
}
/*
Participants are...
A B C D E F G H I J 

A B c D E F G H I J 
A B c D E f G H I J 
A B c D E f G H i J 
A b c D E f G H i J 
A b c D E f g H i J 
a b c D E f g H i J 
a b c D E f g h i J 
a b c D e f g h i J 
a b c D e f g h i j 

And the winner is D!!
*/

Implementation in C++

//============================================================================
// Name        : puzzle.cpp
// Author      : Prabhu Jayaraman
// Version     : 0.1
// Copyright   : Free
// Description : Find Last man stand
//============================================================================

#include <iostream>
using namespace std;

int FindWinner(int n, int m)
{
 int a[n];
 for(int i=0;i<n;i++)
 {
  a[i] = 1;
 }
 int e = 0;
 int c = 0;
 for(int i=0;;i++)
 {
  if(e == (n-1))
   break;
  if(a[i%n] == 1)
   c++;
  if(c == m)
  {
   a[i%n] = 0;
   e++;
   c = 0;
  }
 }
 for(int i=0;i<n;i++)
 {
  if(a[i] == 1)
   return i+1;
 }
 return -1;
}

int main()
{
 int x = FindWinner(20,19);
 cout << x << endl;
 return 0;
}

Cheers,
Bragaadeesh

06 February 2010

Find common sequence that is out of order between two given strings in Java

Hi,
Recently i faced this question from Amazon. Given two strings, find the longest common sequence that is out of order. Initially it was royally confusing to me what the question meant, but I was able to come up with a solution. Please see the following program implemented in Java. The sample inputs and outputs have been provided at the end.
package dsa.stringmanipulation;

import java.util.LinkedHashMap;
import java.util.Map;

public class Sequence {
 public static void main(String[] args) {
  Sequence seq = new Sequence();
  String str1 = "a111b3455yy";
  String str2 = "byy115789";
  System.out.println("Input1: "+str1);
  System.out.println("Input2: "+str2);
  String solution = seq.findCommonSequnce(str1, str2);
  System.out.println("Output: "+solution);
 }
 
 public String findCommonSequnce(String str1, String str2){
  if(str1==null || str2==null){
   return "";
  }
  if(str1.length() == 0 || str2.length() == 0){
   return "";
  }
  //parse first String store the frequency of characters
  //in a hashmap
  Map<Character,Integer> firstStringMap = frequencyMap(str1);
  
  StringBuilder output = new StringBuilder();
  
  for(int i=0;i<str2.length();i++){
   int count = 0;
   if(firstStringMap.containsKey(str2.charAt(i)) && (count=firstStringMap.get(str2.charAt(i)))>0){
    output.append(str2.charAt(i));
    firstStringMap.put(str2.charAt(i), --count);
   }
  }
  
  return output.toString();
 }

 /**
  * Returns a map with character as the key and its occurence as the value
  * @param str
  * @return
  */
 private Map<Character,Integer> frequencyMap(String str) {
  Map<Character, Integer> freqMap = new LinkedHashMap<Character,Integer>();
  for(int i=0;i<str.length();i++){
   Integer count = freqMap.get(str.charAt(i));
   if(count==null){//means the frequency is yet to stored
    freqMap.put(str.charAt(i), 1);
   }else{
    freqMap.put(str.charAt(i), ++count);
   }
  }
  return freqMap;
 }
}

//SAMPLE OUTPUTS
//Input1: a111b3455yy
//Input2: byy115789
//Output: byy115
//
//Input1: lsjfa9fjdsajf
//Input2: dsklajfdkl99
//Output: dslajf9

Cheers,
Bragaadeesh.

17 January 2010

Merge Sort in Java

Now that we've examined one of the most simplest and inefficient sorting algorithms (Bubble Sort), lets have a look at O(nlogn) sorts. To start with, we shall look into Merge Sort.
Merge Sort follows divide and conquer technique. The following is a simple pictorial illustration of the same.

There will be two parts in this sort. One would be halving the input numbers O(logn) and the other would be merging them back O(n) which results in a comprehensive O(nlogn) time. Wait till you see the running version of this sort technique and the time taken to sort a million entries.

First for the code part,
package dsa.sorting;

public class MergeSortOptimized
{

    public static int SIZE = 1000000;

    public static void main(String args[])
    {
        int[] a = new int[SIZE];
        for (int i = 0; i < SIZE; i++) {
            a[i] = (int) (Math.random() * SIZE);
        }
        long start = System.currentTimeMillis();
        MergeSortOptimized mNew = new MergeSortOptimized();
        mNew.sort(a);
        long end = System.currentTimeMillis();
        System.out.println("Time taken to sort a million elements : "
                + (end - start) + " milliseconds");
    }

    public int[] sort(int[] input)
    {
        int[] temp = new int[input.length];
        mergeSort(input, temp, 0, input.length - 1);
        return input;
    }

    public void mergeSort(int[] fromArray, int[] toArray, int left, int right)
    {
        if (left < right) {
            int center = (left + right) / 2;
            mergeSort(fromArray, toArray, left, center);
            mergeSort(fromArray, toArray, center + 1, right);
            merge(fromArray, toArray, left, center + 1, right);
        }
    }

    public void merge(int[] fromArray, int[] toArray, int leftPos,
            int rightPos, int rightEnd)
    {
        int leftEnd = rightPos - 1;
        int tempPos = leftPos;

        int numElements = rightEnd - leftPos + 1;

        while (leftPos <= leftEnd && rightPos <= rightEnd) {
            if (fromArray[leftPos] < fromArray[rightPos]) {
                toArray[tempPos++] = fromArray[leftPos++];
            }
            else {
                toArray[tempPos++] = fromArray[rightPos++];
            }
        }

        while (leftPos <= leftEnd) {
            toArray[tempPos++] = fromArray[leftPos++];
        }
        while (rightPos <= rightEnd) {
            toArray[tempPos++] = fromArray[rightPos++];
        }

        for (int i = 0; i < numElements; i++, rightEnd--) {
            fromArray[rightEnd] = toArray[rightEnd];
        }

    }

}
// Time taken to sort a million elements : 247 milliseconds

As you may observe, the above technique just took 247 milliseconds to sort a million elements whereas the bubble sort tooks almost 28 seconds to sort a hundred thousand elements!!!!! This is due to the logarithmic order of the sort.

Pros:
1) Works in O(nlogn) time.
2) Worst case of merge sort is equal to best case of a quick sort! (We shall discuss more about in the coming sections).

Cons:
1) Consumes extra space.
2) Due to the recursive nature of the algorithm, may eat up stack.

Thanks for reading my post. We shall explore more sorting techniques in the coming days. Till then, bye for now from,
Bragaadeesh.

16 January 2010

Find Loops in a Singly Linked List in Java

This is a very simple yet efficient program written in Java to find whether a Singly Linked List has loops or not. If you need the SingleLinkedList class, please click this link.
The logic is simple, there will be two pointers one traversing once and the other traversing twice. If at all we get a NullPointerException in the process we can be very sure that there are no loops. In the other case, there is definitely a loop. You may play with it. Dont forget to copy this class.
package dsa.linkedlist;

public class FindLoopsInLinkedList {
 public static void main(String args[]){
  FindLoopsInLinkedList finder = new FindLoopsInLinkedList();
  SinglyLinkedList<Integer> randomList = finder.giveMeALoopedList();
  System.out.println("Loop Existence : "+finder.doesLoopExist(randomList));
 }
 
 public boolean doesLoopExist(SinglyLinkedList<Integer> listToCheck){
  Node<Integer> singleJump = listToCheck.start;
  Node<Integer> doubleJump = listToCheck.start;
  
  try{
   while(true){
    singleJump = singleJump.next;
    doubleJump = doubleJump.next.next;
    if(singleJump == doubleJump){
     return true;
    }
   }
  }catch(NullPointerException ne){
   return false;
  }
 }
 
 private SinglyLinkedList<Integer> giveMeALoopedList(){
  SinglyLinkedList<Integer> sampleList = new SinglyLinkedList<Integer>();
  //First Insert randomly ten elements in a linked list
  for(int i=0;i<9;i++){
   sampleList.add(i);
  }
  //Force the list to have a loop in this fashion
  Node<Integer> lastNode = sampleList.getLast();
  lastNode.next = sampleList.getNodeAt(3);
  return sampleList;
 }
}
//-------OUTPUT--------
//Loop Existence : true

Cheers!
Bragaadeesh.

Java Program to reverse a Singly Linked List

Hi folks,

I have written an efficient way to reverse a Singly Linked List using three pointers/nodes for traversal/temporary purposes. I have given a pictorial representation of what happens with near, mid and far pointer. The program is mostly self explanatory. Remember, we are using our implementation of Singly Linked List. You may visit this link if you need that class.



Note : You may click on the above image to get a clearer picture.

Now, for the source code.


Cheers,
Bragaadeesh.

15 January 2010

Java/C++ Program to reverse words in a sentence but still maintain the space position

This is a slight modification to the previous program. Here we should maintain the space as well. For doing that, I am simultaneously tracking the spaces and the words. I have made an assumption that there wont be any trailing or leading spaces in the sentence as such. Even if its there, a slight tweak of the following code would give me the output i desire.

package dsa.stringmanipulation;

import java.util.ArrayList;
import java.util.List;

public class RevWordWhiteSpace {

public static final String SPACE = " ";

private List<Integer> spaceTracker = new ArrayList<Integer>();
private List<String> wordTracker = new ArrayList<String>();

public static void main(String args[]){
RevWordWhiteSpace rev = new RevWordWhiteSpace();
System.out.println(rev.getRevWithWhiteSpace("This     should  maintain the space in place"));
}

/*
* Lets assume that our input text will not have any spaces before and after
*/
public String getRevWithWhiteSpace(String inputText){
if(inputText!=null && inputText.length()>0){
int lenOfText = inputText.length();
if(lenOfText==1){
return inputText;
}else{
constructLists(inputText);
StringBuilder output = new StringBuilder();
for(int i=wordTracker.size()-1,j=0; i>0; i--,j++){
output.append(wordTracker.get(i));
output.append(constructSpace(spaceTracker.get(j)));
}
output.append(wordTracker.get(0));
return output.toString();
}
}else{
System.out.println("Invalid Sentence");
return null;
}
}

private CharSequence constructSpace(Integer integer) {
String op="";
for(int i=0;i<integer;i++){
op+=" ";
}
return op;
}

private void constructLists(String inputText) {
int tempBufSpace = 0;
String bufWord = "";
for(int i=0;i<inputText.length();i++){
if(inputText.charAt(i)!=' '){
if(tempBufSpace>0){
spaceTracker.add(tempBufSpace);
tempBufSpace=0;
}
bufWord+=inputText.charAt(i);
}else{
if(bufWord.length()>0){
wordTracker.add(bufWord);
bufWord = "";
}
tempBufSpace++;
}
}
if(bufWord.length()>0){
wordTracker.add(bufWord);
}
}
}

//The output produced would be
//place     in  space the maintain should This

Also code in C++,

#include <iostream>
#include <string.h>

using namespace std;

void str_rev(char s[], int start, int end)
{
    int len = end - start;
    for(int i=0;i<len/2;i++)
    {
        char t = s[i+start];
        s[i+start] = s[end-i-1];
        s[end-i-1] = t;
    }
}

int main()
{
    char a[] = "my     name is prabhu";
    cout << "[" << a << "] ==> ";
    str_rev(a,0,strlen(a));

    cout << "[" << a << "] ==> ";

    int start_index = 0;
    for(size_t i=0;i<=strlen(a);i++)
    {
      if(a[i] == ' ' || a[i] == '\0')
      {
         str_rev(a,start_index,i);
         start_index = i+1;
      }
    }
    cout << "[" << a << "] ==> ";
    char b[strlen(a)+1];
    int i=0, k=0, j=strlen(a)-1;
    while(a[i] != '\0')
    {
        if(a[i] != ' ')
            b[k++] = a[i];
        else
        {
            while(a[j] != ' ' && j>=0)
                j--;
            while(a[j--] == ' ' && j>=0)
                b[k++] = ' ';
        }
        i++;
    }
    b[k] = '\0';
    cout << "[" << b << "]" << endl;
  
    return 0;
}


Cheers,
Bragaadeesh.