Friday, 27 November 2015

How to configure and access Kafka via command line

Configuring Kafka with windows:

The commands for configuring kafka are same for both windows and linux, replace .bat with .sh for accessing in linux environment.

Step 1:
Download Apache Kafka binaries and unzip it under say D:/kafka<version>

Step 2:

Go to command prompt and run the kafka commands from windows folder under kafka<version>:

cd kafka<version>/bin/windows

Run Zookeper server:

zookeeper-server-start.bat ../../config/zookeeper.properties

Run Kafka server:

kafka-server-start.bat ../../config/server.properties

Accessing Kafka via command line utilities:

The commands for accessing kafka are same for both windows and linux, replace .bat with .sh for accessing in linux environment.

Create a topic:

kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test

List the topics created:

kafka-topics.bat --list --zookeeper localhost:2181

Send some message via producer program:

kafka-console-producer.bat --broker-list localhost:9092 --topic test

start a consumer program in a different cmd to see the messages sent from producer:

kafka-console-consumer.bat --zookeeper localhost:2181 --topic test --from-beginning


To publish/subscribe Kafka messages via Java API, please referUsing Java API for publish/consume Kafka messages





Saturday, 16 May 2015

Puzzle - measure 15 minutes using given hour glasses - Answer

The time difference between both the hour glasses is 4 minutes and we should make use of this time and add it to 11 minutes hour glass time to get 15 minutes.

At time 0 minutes:
hour glass1 - 0-11
hour glass2 - 0-7

At time 7 minutes:
hour glass1 - 7-4
hour glass2 - 7-0

Invert hour glass2.

At time 11 minutes:
hour glass1 - 11-0
hour glass2 - 4-3

Again invert hour glass2 to make use of the 4 minutes difference.

At 15 minutes:
hour glass1 - 11-0
hour glass2 - 0-7

When hour glass2 is emptied 15 minutes would pass.

Measure 15 minutes using given hour glasses

You have a 7 minutes hourglass and an 11 minutes hourglass with you.
You have to measure 15 minutes using them.

How will you do measure 15 minutes?

Click here to find the solution

Puzzle - Fruits and the lucky contest - Answer

There were 123 contestants.
When the boxes are opened,  it turns out that:
1. 43 people have guessed none of the fruits correctly
2. 39 people  have guessed one fruit correctly
3. 31 people have guessed two fruits  correctly.

So, there are 10 contestants left.

Total number of combinations possible initially was 4*3*2*1
But if 3 fruits are guessed correctly, there is only one possibility for the 4th fruit.
In other words, if 3 fruits are guessed correctly, 4th fruit cannot be guessed wrong.
That means all the remaining 10 people guessed all 4 fruits correctly.

Fruits and the lucky contest

There are four closed boxes kept for a lucky contest.
There are 4 fruits an apple, a banana, an orange, and a pear) that have been  placed in these four closed boxes.
Contestants will have to guess which fruit is  in which box.

There were 123 contestants.
When the boxes are opened,  it turns out that:
1. 43 people have guessed none of the fruits correctly
2. 39 people  have guessed one fruit correctly
3. 31 people have guessed two fruits  correctly.

How many people have guessed three fruits correctly?
How many people have guessed four fruits correctly?

Click here to find the solution

Thursday, 14 May 2015

Puzzle - 2 ropes to measure 45 minutes - Answer

You will light up both the ends of rope 1 and one end of rope 2.

When the rope 1 is finished burning, then you would light the other end of rope 2 as well.

So, rope 1 will finish burning exactly after 30 minutes and it will take 15 more minutes for rope 2 to finish burning.

2 ropes to measure 45 minutes

You are given 2 uneven ropes.
Each of these rope will burn in exactly one hour.

You are asked to measure 45 minutes using these 2 ropes.
There is no other means to know time.

Since the ropes burn unevenly, the rope might not be burn half at the time of 30 minutes.

How will you measure 45 minutes using these ropes?

Click here to find the solution

Wednesday, 13 May 2015

Puzzle - Find the poisoned wine barrel - Answer

There are 10 prisoners to be executed. So the emperor can make them taste wine from the barrels.

There are 2 possibilities associated with a prisoner when he tastes wine from a barrel - either he dies or he will not die.

So, in a 2 barrel scenario, using a single prisoner, we can identify whether the wine is poisoned or not.
i.e, he will taste bottle 1 and does not taste bottle 2. If he dies then bottle 1 is poisoned and if he survives bottle 2 is poisoned.

Now lets consider the scenario with 2 prisoners, the number of possible combinations would be 2*2 as there are 2 possibilities associated with them.
Barrel 1 -> Tasted by none
Barrel 2 -> Tasted by 1st prisoner
Barrel 3 -> Tasted by 2nd prisoner
Barrel 4 -> Tasted by both prisoners

So, if no one dies, bottle 1 is poisoned, if both of them dies bottle 4 is poisoned.
If prisoner 1 dies Barrel 2 is poisoned. If prisoner 2 dies Barrel 3 is poisoned.

Similarly, when you consider 10 prisoners, the number of possible combinations would be:
2*2*2*2*2*2*2*2*2*2 = 2^10 = 1024.

So, that is sufficient for testing 1000 barrels of wine.

Further you can eliminate the case in which every prisoner has to taste the wine, then 10 possibilities in which 9 of them has to taste the wine and few of the possibilities in which 8 of them has to taste the wine.
So, maximum number of prisoners that will die on tasting the wine is 8.

Tuesday, 12 May 2015

Find the poisoned wine barrel

The emperor of NoLand has 1000 slaves. He also have 10 prisoners to be executed.

There is a festival tomorrow and there are 1000 barrels of wine for the celebration to be given to each slave.

The emperor came to know that one of the barrel of wine is having deadly poison and the person who consumes even a minute amount of it would die in 10 hours. He brought a replacement barrel, but he does not know which one to replace.

There is only 12-15 hours left for tomorrow's festival.

He wants to celebrate the festival tomorrow and if any of the slaves die then everyone would be sad and no body would celebrate the festival.

How would he figure out the poisoned wine barrel and replace it so that no slaves die?

Click here to find the solution

Puzzle - 2 Eggs and a 100 storey building - Answer

You would be starting the thought process by thinking of a binary search, i.e, drop the first egg from 50th floor, if it does not break, then go to 25th floor etc. But if the first egg breaks on 50th floor, then you have to drop the second egg from 1 to 49th floor to figure out the answer.

Then you may be thinking of dropping the first egg at 25th floor, then at 50th, 75th etc, this will take 28 tries if the answer is 99th floor.

There is definitely a better answer.

The optimal number of drops would be such that if you do the first drop from nth floor, if the attempt fails, then do the drop by climbing (n-1) more floors, if it fails again, then do the drop after climbing (n-2) floors etc till (n-x) = 1. At this point you should have covered all the floors.
If the drop at any of these point breaks the egg, then start dropping from the last floor at which the breakage did not happen with the second egg and move up. In this way, n drops would be what you require the maximum to figure out the breaking point in any scenario.

So, in our case, to cover up 100 floors:

n + (n-1) + (n-2) + (n-3) + ......+ 2 + 1 >= 100

i.e, n*(n+1)/2 >= 100

=> n = 14

So, 14 is the answer.

2 Eggs and a 100 storey building

You are given 2 eggs and you have a 100 storey building in front of you.

Both the given eggs are identical and breaks if dropped from the same height.

You can drop these eggs multiple times from the building and it will not impact the condition of the eggs.

You have to figure out the highest floor number from which the egg can be dropped without breaking.

The puzzle is to figure out the minimum number of drops to figure out the highest floor at which the egg can be dropped without breaking.


Click here to find the solution

Sunday, 10 May 2015

Farmer and the river crossing puzzle - Answer


The farmer first carry goat to the other side of the river.
He then comes back and carry wolf to the other side and bring back the goat.
He then carries the basket of cabbage to the other side.
He would come back and carry the goat to the other side.

Farmer and the river crossing puzzle

A farmer wants to cross a river.
He has a wolf, a goat, and a basket of cabbage.

There is a boat that can carry him plus either the wolf, the goat, or the cabbage.

If the wolf and the goat are alone on one shore, the wolf will eat the goat.
If the goat and the cabbage are alone on the shore, the goat will eat the cabbage.

How can the farmer bring the wolf, the goat, and the cabbage across the river?

Click here to find the solution

Saturday, 9 May 2015

Puzzle - Cannibals and the hat puzzle 1 - Answer

C will give the answer as black.

If B and C were wearing white hats then A would have been able to give correct answer.
Since, A does not know the answer, B & C are either both wearing black hats or one black and one white hat.

If C was wearing a white hat, then B could have been sure that he would be wearing a black hat.
Since B was not able to find the correct answer, it means C is wearing a black hat.

Click here to find the solution

Puzzle - Pirates and sharing the gold coins - Answer

For understanding the solution, let us start with the scenario when there are only 2 pirates.
Then the answer is obvious in this case, the oldest pirate will take all 100 gold coins and will give nothing to the other guy and vote for himself to get the 50% majority.

Now, consider the scenario of 3 pirates.
The youngest pirate knows that if the oldest pirate dies, then he will get nothing.
So, if he gets anything, then he will vote for the oldest pirate.
The second pirate would oppose any proposal by the oldest pirate as he would get everything if he dies.
So, the answer in this scenario is 99-0-1 from oldest to youngest pirate.

Similarly, for 4 pirate scenario, the answer would be 99-0-1-0

And hence the answer for 5 pirate situation is 98-0-1-0-1

Pirates and sharing the gold coins

There were 5 greedy and cunning pirates.
They got 100 gold coins and wanted to divide it amongst themselves.
Only the oldest pirate has the right to propose how to share the gold coins.
If he gets the majority that is 50% or more vote for his proposal (including his vote), then the coins will be shared according to his proposal, but if he does not get 50% votes, then the other pirates would kill him and the process gets repeated with next oldest pirate.

Assuming that the pirates are very intelligent and very greedy, how would the oldest pirate make the proposal so that he gets maximum number of gold coins and escapes death?

Click here to find the solution

Cannibals and the hat puzzle 1

Three explorers A, B, C were caught by cannibals of an island.
The cannibals gave them a possible chance to escape.

A, B and C are lined up in order, so that A can see B and C, and B can see C only, while C cannot see anyone.

A  ->  B  -> C


The cannibals take out 5 hats, of which 3 were black and 2 were white, and show these to them.

The hats were then placed on each of their head (one hat per head), without them knowing what color of their own hat is. They would be allowed to escape if at least one of them can guess the color of their hats and they are allowed only one guess.

A looks at the hats of the people in front of him and says "I do not know".
B looks at the hats of the people in front of him and says "I do not know".

Will C be able to save the explorers from the island?

Puzzle - Identify coins in the chest - Answer

You should pick up a coin from chest C.

If you get a gold coin, that means Chest C contains only gold coins because the chest is mislabelled.
That means chest A labelled gold coins contains only silver coins and chest C labelled silver coins contains 50 silver and 50 gold coins.

Similarly, if you get a silver coin, that means Chest C contains only silver coins.because the chest is mislabelled. This means chest B labelled silver coins contains only gold coins and the chest A labelled silver coins contains 50 silver and 50 gold coins.

Identify coins in the chest

You have got 3 chests of coins.

Chest A has been labelled as "100 gold coins"
Chest B has been labelled as "100 silver coins"
Chest C has been labelled as "50 gold coins and 50 silver coins"

All the chests are labelled incorrectly but one of the label suits them.
You will be given one random coin from any of these chests that you choose to.
You need to identify the contents of each chest based on this one coin.

Which chest should you pick a coin from and why?

Click here to find the solution

Puzzle - Find Cheryl's birthday - Answer

Given dates are:

May 15
May 16
May 19

June 17
June 18

July 14
July 16

August 14
August 15
August 17

18 and 19 are the distinct numbers in the given list and these days are in May and June respectively.

If Albert was told one of these month, then there is a possibility that Bernard might know the answer straight away. But he was told a month other than May and June, so he knows that Bernard also does not know the answer.

So, Bernard understands that the month is either July or August.
The day is distinct so that Bernard gets the answer, so it is not July 14 or August 14.

That leaves us with July 16, August 15, August 17
Now, from above dates if Albert can get the correct answer only if the month is distinct. If it is August there are 2 possibilities.
So, the answer is July 16

Find Cheryl's birthday


Albert and Bernard became friends with Cheryl.
They wanted to know her birthday.
Cheryl gave them a list of 10 possible dates.

May 15
May 16
May 19

June 17
June 18

July 14
July 16

August 14
August 15
August 17

Cheryl then tells Albert and Bernard separately the month and the day of her birthday respectively.

Albert: I don't know when Cheryl's birthday is, but I know that Bernard also does not know.
Bernard: At first I don't know when Cheryl's birthday is, but I know now.
Albert: Then I also know when Cheryl's birthday is.

So, when is Cheryl's birthday?


Click here to find the solution

Puzzle - Three kids - find their ages - Answer

Three kids - find their ages


Solution:
Since the product of their ages is 72 and its sum has to be less than 31 (date of a month), the possible combinations are as follows:
3,3,8
3,6,4
6,6,2
12,3,2
9,2,4
24,3,1
12,6,1
9,8,1
18,4,1

Since, Jack was not able to understand their ages after knowing that the sum of their ages is same as his birth date, that means the the combination has more than one matching sum. So, you need to check for the combinations only till you find combinations having matching sum.

The only such combination is 3,3,8 and 6,6,2 which adds up to 14.

From Jill's statement that the eldest son started going for piano classes, it is clear that there is an eldest son. This rules out the combination of 6,6,2.

So, the answer is 3,3,8

Three kids - find their ages


Jack and Jill were childhood friends. They meets after several years.

Jack: How many kids have you got?
Jill: Three kids. Product of their ages is 72 and sum of their ages is same as your birth date.
Jack: I still did not get their ages.
Jill: My eldest son started going for piano classes.
Jack: Now I got their ages.

What are the ages of Jill's kids?


Click here to find the solution

Monday, 26 January 2015

Find next greatest number from digits of a given number

Find the smallest number that has same set of digits as n and is greater than n. 
If n is the greatest possible number with its set of digits, then print "not possible".

Examples:

Input:  n = "1234"
Output: "1243"

Input:  n = "1243"
Output: "1324"

Input:  n = "1324"
Output: "1342"

Input:  n = "1342"
Output: "1423"

Input: n = "4321"

Output: "Not Possible"

Input:  n = "5349762"
Output: "5362479"

Input: n = "53497766"
Output: "53646779"


Algorithm:

From the first few examples, we can see that the algorithm is to traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. Then replace this small number with the next highest traversed number. Then pick remaining traversed number plus the small number, sort them from smallest to largest and append them to the end. 
For a more complex level, handle duplicate numbers in the set. For handling duplicate numbers that needs to be sorted, we requires a set that accept duplicate numbers. Refer to blog on How to add duplicate entries to a Set for creating a set that accepts duplicate entries.


package com.prasune.coding;

import java.util.Set;
import java.util.TreeSet;

public class NextGreatestNumber {

      public static void main(String[] args) {
            printNextGreaterNumber(4321);
      }

      private static void printNextGreaterNumber(Integer number) {
            String nextGreaterNumber = null;
            String numberAsString = number.toString();
            Integer prevValue = 0;
            Set<Integer> numbersToSort =
                  new TreeSet<Integer>(new CustomComparator());        
           
            for (int i = numberAsString.length() - 1; 0 <= i; i--) {
                  Integer digit =                   Integer.parseInt(""+numberAsString.charAt(i));             
                  if(digit < prevValue){
                        Integer replacement = 
                                   getReplacementNumber(digit, numbersToSort);

                        nextGreaterNumber = numberAsString.substring(0, i)
                                          + replacement;
                        numbersToSort.add(digit);
                        nextGreaterNumber = appendSortedNumbers(
                                              nextGreaterNumber,                                                              numbersToSort,                                                                  replacement);
                        break;
                  } else{
                        prevValue = digit;
                  }    
                  numbersToSort.add(digit);
            }
            if(nextGreaterNumber != null){
                  System.out.println("Next greater number: " 
                                     + nextGreaterNumber);
            }else{
                  System.out.println("Not Possible");
            }          
      }

      private static Integer getReplacementNumber(Integer digit,                                                                  Set<Integer> numbersToSort) {
            Integer replacementNumber = 0;
            for (Integer number : numbersToSort) {
                  if(number > digit){
                        replacementNumber = number;
                        break;
                  }
            }
            return replacementNumber;
      }

      private static String appendSortedNumbers(String nextGreaterNumber,
                                                Set<Integer> numbersToSort,
                                                Integer replacement) {
            boolean isReplacementExcluded = false;
            StringBuilder greaterNumberString =
                                      new StringBuilder(nextGreaterNumber);
            for (Integer number : numbersToSort) {
                  if(!isReplacementExcluded && number == replacement){
                        isReplacementExcluded = true;                  
                  }else {
                        greaterNumberString.append(number);
                  }
            }
            return greaterNumberString.toString();
      }    
}




Sunday, 11 January 2015

How to add duplicate entries to a Set

There could be use cases in programming where you would require to store duplicate values in addition to sorting them. A Set implementation would do sorting for you but then the duplicate entries get eliminated.

A hack for countering this is to return false when the values are equal. A sample implementation of Set to allow duplicate entries are as follows:

Create a custom comparator as follows that does not return 0 when the entries are equal.

package com.prasune.coding;

import java.util.Comparator;

public class CustomComparator implements Comparator<Integer>
{
    @Override
    public int compare(Integer i1, Integer i2)
    {
        if(i1.compareTo(i2) == 0){
            return 1;
        }
        else{
            return i1.compareTo(i2);
        }
    }
}




Create a Set implementation using the above comparator and add numbers to the Set:

package com.prasune.coding;

import java.util.Set;
import java.util.TreeSet;

public class SetWithDuplicates {

      public static void main(String[] args) {
            Set<Integer> numbersToSort = new TreeSet<Integer>(new CustomComparator());
            numbersToSort.add(10);
            numbersToSort.add(12);
            numbersToSort.add(15);
            numbersToSort.add(11);
            numbersToSort.add(12);
            for (Integer number : numbersToSort) {
                  System.out.print(number);
                  System.out.print(" ");
            }
      }
}

You will get the output as:
10 11 12 12 15