Puzzle: Two Bullet Russian Roulette

Puzzle

A Russian gangster kidnaps you. He puts two bullets in consecutive order in an empty standardd six-round revolver, spins it, points it at your head and shoots. …click… You are still alive. He then asks you, “do you want me to spin it again and fire or pull the trigger again right away?” For each option, what is the probability that you’ll be shot?

Solution

With 2 bullets arranged consecutively in a six round revolver, there is only 6 ways to arrange the bullets in the revolver. Here are the six possible ways to arrange two bullets consecutively in a six round revolver. 

Figure 1: Arrangements of 2 consecutive bullets in a 6 chamber revolver
Figure 1: Arrangements of 2 consecutive bullets in a 6 chamber revolver

Additional insight, if you are familiar with Mathematical Probability: There is 6C1 i.e. 6 ways to arrange 2 bullets consecutively. If you wonder why it is not 6C2, here is why: since the two bullets are arranged one right next to the other, the moment you choose a slot for a bullet, the slot for the next is chosen implicitly. 

The probability of getting shot in the first round is when the revolver was in arrangement #1 or #4 from the above picture. In other words, there is a 2 out of 6 i.e. 33% chances that you get killed by the gangster when the revolver is spin and fired; in other words, 100% – 33% = 67% chance of surviving.

Once you survive the first round, we can eliminate the arrangements #1 and #4 from the possibilities. Now, there are four ways the revolver could be arranged, and out of those four ways, one way is with a bullet in the current chamber where the revolver’s firing pin is pointing. In other words, once you survive the first firing, there is a 25% chance that you could be killed by the gangster if he pulls the trigger again right away without spinning the cylinder of the revolver; in other words, 100% – 25% = 75% chance of surviving.

Figure 2: Arrangements of 2 consecutive bullets in a 6 chamber revolver when the first chamber is empty
Conclusion

The optimal choice to increase your probability of surviving is to let the gangster fire right away. You have a 67% chance of surviving if you spin the revolver, and a 75% chance if you fire right away without spinning. Dare the gangster to fire right away! 😉

Lucy – how did she meet him!

Lucy.. it was not he who found her; she was the one who found him..!

To steal away her childhood, to push-away a few weeks old baby from her mother, is our society heartless, I wonder!

It is 5AM in India. A young man in his early 30s is on his vacation. He is slowly getting used to the new time zone. Where he is from, it is twelve and a half hours to 5AM! He got ready and head out for his morning walk. He rides his motorcycle 5 minutes to a well-lit street where he leaves the motorcycle and do his morning walk. He followed his routine as usual that day, little did he know what the future had for him!

Sun is not here yet! He locked his motorcycle, put on his headphones, started playing the podcast on Advaita Vendanta from where he left last day, turned on his steps-counter and started jogging . After a few minutes, he slowed down to speed-walk. He walked around 3 kilometers after which he was about to turn around.

As if she was waiting for him for ever, she spotted him and ran to him! He noticed when she was close enough to touch him. He was overwhelmed by the cuteness of that a few weeks old puppy – Lucy! He picked Lucy up with both hands and played with her for some time.

Figure 1: Lucy excited to have a friend

There were 3 people nearby talking to each other and staring at him occassionally. Are they watching Lucy and me playing or is Lucy with them, he wondered. He thought Lucy accompanined them for a morning walk. So, he decided to part with her. It was a struggle for both of them. He asked Lucy to go the other way towards the three men, but how much can a few weeks old puppy understand! He would then try to walk away and Lucy would try to catch up with him. After a few tries, he managed to leave Lucy towards the men and continue his walk back to his motorcycle.

He made it back to his motorcycle, but he found himself still with Lucy in his thoughts. He wondered if the men knew Lucy at all! What if Lucy lost her way back home somehow! What if Lucy was abandoned! What if Lucy lost her mom and is alone! Worst! What if Lucy gets into an accident; she was on the roadside when he left her; she is neither old enough to stay away from the road nor fast enough to run away from a speeding vehicle! He was overwhelmed with thoughts, he started his motorcycle and rode it to where he found Lucy. She is not there!

This is exactly where he found her, and yet she is not there. May be, she actually was with one of the men and went home with them. When he was about to turn, he saw her, at a distance, staring at him from behind a coconut tree. The moment she confirmed it was him, she ran to him with those cute little legs. She rounded his motorcycle a couple of times in an effort to get as close to him as possible.With one hand, he leaned and picked her up.

Figure 2: Lucy on her first day; tired

He was overwhelmed with happiness. She was shivering in that cold. He patted and massaged her gently to keep her warm. After a few minutes, he kept her on his motorcycle and kick-started it. Alas! She fell down! As he slowly rolled his motorcycle forward, she tried to walk on the motorcycle and fell down!

Figure 3: Lucy wants to stay as close as possible

He suddenly took his hands off the clutch without changing the gear to neutral. Usually, this would result in a strong lurch forward and loss of control. But, Gods were with him. The motorcycle just turned off. He was worried Lucy was hurt from the fall. He leaned down and picked her up again. He inspected her legs one by one. He held and massaged each leg to see if she is in pain. She seems ok. She looked at him as if the fall was nothing compared to what she has been through in past days!

Figure 4: Lucy survived the fall

This time, he was more careful. He changed the gear to neutral and kick-start the bike all while holding Lucy with one hand. She is a quick learner. Instead of trying to walk on the motorcycle, this time, she moved close to him and held him with her tiny little paws. He didn’t want to take chances though. He slowly changed the gear to first and rode the motorcycle at a low speed all the way back to his home. All the while, she held on to him.

Figure 5: Lucy on the way home

It took days for her to get accustomed to the new environment. It took weeks for her to forget that traumatizing experience of abandonment. She had a good sleep after how many days who knows!

Figure 6: Lucy having a good sleep after coming home

Now, she has a partner – Tiger. Although they fight with each other and don’t like to share food, they like each other’s company. Tiger is the naughtier one. He keeps Lucy on her toes steeling her toys and making her run after him.

Figure 7: Lucy and Tiger taking rest after running around
Figure 8: Lucy and Tiger acting innocent when they saw the camera!

They both have their routine play-time during when they learn new commands and play fetch.

Figure 9: Lucy going for the ball
Figure 10: Lucy’s touch down!

What would have happened if he didn’t go back to check on her!
What would have happened if she didn’t find him!
Some questions are better left unanswered..!

Figure 11: Lucy likes to pose for the camera!
Figure 12: Lucy’s favorite sitting posture
Figure 13: Lucy and Tiger planning a mischief – attack the rooster which is twice their size!

We all are Artists – A business student’s encounter with ART-111

A few months back, I wondered how art would help a business student! How do canvas, pencils, charcoal, and eraser help an International Business student? I asked myself. I still signed up for Art 111 in North Seattle Community (NSC) College. Now, when I look back, that decision to learn art was one of the best decisions I made in the recent past.

The journey was not easy. In fact, it was a bit frustrating when I couldn’t make both ends of my ellipses meet. Ellipse is one of the very basic building blocks of art. But my ellipses were anything but it. I kept drawing again and again and again in hope that the ends will meet some day. Then, I learned a better way to hold pencil to draw beautiful ellipses – drawing with your shoulder letting your hand flow on the canvas. A simple and elegant approach and yet I didn’t know that for the last 3 decades. If you are struggling to make both ends of your metaphorical ellipses meet, ask yourself if you are holding the pencil right.

Figure 1: Struggle with ellipses

How many of you believe in the power of dreams? Not the ones we dream while asleep, the ones we consciously dream of becoming/having. When we dream and act on those dreams, we realize them, don’t we? Some call it vision. It’s the result of someone’s dream/vision of every household having a computer that I am using a laptop to write this article. The ability to see things in mind and act in a way to manifest is art. Below is my drawing I made blindfolded. Can you make out what I meant to draw? Each of those drawing is a single line.

Figure 2: Blind contour drawings

Now see the same drawing with my eyes open. Is it better? Again, each of these drawings is a single line. Art taught me the full potential of a line and that learning was a humbling experience. By continuously analyzing my progress with my eyes open, I could course correct before it was too late. You might hear this as Agile methodology, scrum, sprint, etc. This part of my art class reinforced my belief in those methodologies.

Figure 3: Contour drawing with eyes open

Knowing what you don’t see makes you more successful in life and business. The successful businesses we see around today, from multinational companies to mom and pop stores, are a result of a lot of hard work behind the scene. When we see an object, our limited vision is missing out on the other side. Art is a skill to see all sides and to overcome the limitations of our eyeballs. See in below drawing how art helped me see all sides of objects. Normally the back side of these objects are not visible. But it is visible to an artist – a 365-degree vision.

Figure 4: X-ray vision

Knowing all sides helped me expand my mind and improve my art.

Figure 5: bottle

Real world is not a bunch of lines. It is not just black or white. There are infinite shades. An artist is someone who understands the infinity of this world. They observe the subtle variations of shades. They know the marriage of an object to its shadow in presence of light. In short, they see what many of us fail to even notice even when it is right in front of us. It’s a quality every business student must possess. They should see the opportunity in the market. They should perceive the subtle variations in their business environment. This would help them make the right strategic decisions. I kept drawing in hope that I will get there one day.

Figure 6: 3-D Forms

Figure 7: 3-D sphere

Figure 8: Cup and saucer

Figure 9: Bedroom

A wise teacher knows a student has to face the world themselves one day. Prof. Kelly knew this; she taught us the skills to face the world and pushed us to explore the world ourselves. The result was, in a way, self-realization for me. See it yourself in my below drawings of objects from my little world – a hand sanitizer (symbolizes the struggle our world faces today) and my bed lamp.

Figure 10: Still life from direct observation – 1

Figure 11: Still life from direct observation – 2

The one who keeps drawing their metaphorical ellipses never losing the hope that the ends will meet one day, the one who expands their vision beyond what they see with their naked eyes, the one who uses the tools without fear, the one who is not afraid to make mistakes, the one who is willing to erase their metaphorical drawing to make it better, they get to draw the future and put a ding in the universe.

Thank you, Prof. Kelly.

Judge not, a book by its cover!

We rely on our brain for everything – opinions, decisions, perception, vision, trust, love are all coming from your brain. We use our sensory organs to learn our environment and people around us. Learning impacts our character. We form opinions about people from our personal experience with them as well as hearsay. But how often do you confirm the accuracy of the information you have! Your opinions about a person can change when a different information about them reach you. This is what happened in case of Ram, a village boy from South India.

Ram’s village was a close knit society with every one knowing each other by their name and their whole family. The elders of that village hung out at a coffee shop right next to Ram’s home every morning. They shared stories and opinions on current topics. This coffee shop was also known among villagers as “origin of rumors”. People at coffee shop could easily overhear every loud conversation at Ram’s home. They often heard Ram’s mom scolding Ram. News about Ram’s frequent scolding spread in the village in no time. Consequently, an ill opinion formed in that village about Ram. They started questioning every aspect of Ram. Whenever they saw him roaming around with his friends, they thought he was up to something bad. However, that opinion didn’t last long as they came to know about who Ram really was and how he helped his classmate to pass 10th grade exam. This story happens in a different part of the world. For that same reason, I need to tell you first, about India and the small state in India where this story happened.

In India, 10th grade exam is one of the main deciding factors of a kid’s future. This is the first time in their school life where teachers outside their school evaluate answer-sheets. This is to avoid any favoritism. This is also a time for schools to prove their value when they compete with each other to have better results. Schools open early to cover the syllabus and prepare students for the 10th final exam. For a state-sponsored school, the evaluation will be within the state. For other schools that follow the Central Board of Secondary Education syllabus (CBSE) or Indian Certificate of Secondary Education (ICSE) syllabus, answer sheets are evaluated outside the state. Parents send their kids to CBSE and ICSE schools to give their kids a better future overlooking the high cost. When a state-sponsored school costs less than a couple of bucks for an entire year, these schools cost a fortune every month. Competition is relatively more in CBSE and ICSE schools, and often they stop low performing students from taking the final exam to improve the schools’ pass rate. Kids undergo tremendous pressure from society, school and family during this time.

In a village in Kerala, one of the southernmost states in India, there was a school that followed CBSE syllabus. With more amenities and dedicated teachers, the school attracted many students from that society. Over time, the school moved from a small building to multistory campus. One year after another school strived in having all their students pass the 10th final exam. In 2005, a new batch of students entered their first “test of life” in that school. That bunch of students had a mix of characters – poor and rich, naughty and obedient, quiet and loud, troublemaker and peacemaker. For 10th class students, school reduces the play time with more focus on studies. Teachers covered the syllabus at twice the pace than usual. Time went by so fast there were only a couple of months left for the final exams. During this time, the school disperses the class to let the students revise the lessons themselves. The only thing that stands between the students and the final exam at this point are the mock exams; the school conducts them to give a taste of what’s coming. Remo Mathew and Ram Ridwani were attending their finals from that school that year.

Remo was a single child to his parents and was a bookworm. He liked fictional novels and Harry Potter was his favorite. He carried around his favorite novel in his small, red school bag. Ram lived with his mom who was a homemaker and his father was abroad. He commuted to school on school bus. He managed to score good marks in all subjects except Mathematics. Ram used to say: “It was not my cup of tea” about it and often failed in that subject.

Ram lived near to the school. He was from a middle-class family. Ram’s father worked for the Indian government and often got deputed to different parts of the country. During Ram’s 9th class, his father was working in a neighboring state of Kerala. His father was an entrepreneur and created a small business in home town. Ram’s mom was an undergraduate in Mathematics. She wanted to become a school teacher, but Ram’s father didn’t let her. It was considered shameful for the family to let women work at that time. By the time Ram’s father realized his mistake they had two kids to take care. So he made her manager of his small business. She managed the business when Ram’s father was out of town.  Ram didn’t like to help his mom with the shop. He would rather play games on his computer or watch movies. But when the time calls, Ram had no other choice but to attend to customers. He didn’t get any special allowance for his time. Ram described it as “child labor” while his father’s reply was: “You are having free living space, free food, free education! If I start charging you for that, you will owe me five times of the allowance you are asking for”. Ram couldn’t beat his dad on this argument. So he worked in the shop unwillingly. The shop had a telephone booth in the corner and was the only one for that entire locality. People waited in line to talk to their dear ones and paid in cash.

One day, Ram’s classmate Arjun brought an expensive bicycle to school. It had gears unlike any other bicycle Ram had ever seen. Ram went home and asked for a similar bike. The reply from his mom was no different from the one she usually gives to any of Ram’s similar asks. Ram had no other choice other than convincing his dad. He went to the shop and dialed his father. Dad scolded him for making an expensive call for such an “impossible” ask. Ram cried over the phone, and soon dad played his card. He asked Ram to wait until dad’s next visit. Ram’s dad used to come home once a month at that time. During his next visit, Ram got a gearless bicycle. Ram was happy that he got at least a bike although he wished for one with gear. Ram roamed around on his bike and explored roads he couldn’t go before. He often skipped school to ride to lakes and visit places. During such a ride, Ram bumped into one of his dad’s friends. The news reached Ram’s home in no time and restrictions were put in place for Ram and his bicycle.

Remo and Ram were classmates. The school decided to split the whole class into two divisions – A and B, as Remo and Ram moved to 10th. Remo and Ram went to division B. Anna Mary was another student who ended up in division B. Anna was Remo’s family friend, and their families knew each other. During the division, Shafeeq and Minnu who were more than friends to each other ended up in separate classrooms. That started conflicts in their relationship and soon began to fall off. Anna was Minnu’s close friend, and Anna approached Ram for help. Although they couldn’t save their relation, it soon resulted in something new. Ram and Anna became friends. When they were spending time together Anna told him “I am going for extra Mathematics and Science lessons from tomorrow. I wish you could join me”. Ram couldn’t give her a reply at that time. He went to his mom that evening and convinced her that his 10th final exam is at stake. That poor soul wanted the best for her kid and sent Ram for lessons. Little did she know at that point what Ram was up to! Ram had to bicycle around 3 miles every day after school for his new adventure. Ram was good in Mathematics like his mom and used this time to be with Anna. Anna was “a beautiful cute angel” to Ram.

Remo was taking the same lessons too. Ram saw Remo’s struggle with Mathematics and offered him help. But Ram had to give up one of his tutoring for this. Ram decided to give up his science lessons as the tutor was strict and didn’t allow talking to Anna. Soon Ram started going to Remo’s home instead of Science tutoring. Remo’s mom, Mary, made snacks and juice for Ram every time. Ram didn’t disclose this arrangement to his mom. Days went by without any problem. One day, when Ram reached home, Ram’s mom asked about the lessons he learned from his Science tutor that day. Ram started giving a long list of areas he “learned”. Soon Ram’s uncle came by and burst into laughter overhearing this conversation. Ram got nervous but decided to stick with his story. Ram’s uncle revealed the phone call from the Science tutor. Ram had no choice but to disclose his arrangement with Remo. Ram had been in so many troubles in the past; his mom and uncle didn’t believe his new revelation. “It was too good to be true” for them. Ram’s mom called Remo’s home and confirmed the story. She was still angry for bunking classes that Ram mentioned as a necessity for the final exam. She was also happy for Ram’s good deed, but she successfully hid it from Ram. Ram was allowed to continue helping Remo during weekends from then on the condition that Ram will focus on his lessons too.

After the mock exams, the school decided not to let Remo attend the final exam based on his results. The school was not confident in Remo. Remo’s mom begged to let him take the finals. At last the school gave up. The final exams happen in designated schools, and the students from the rest of the nearby schools attend their exams in the selected school. Ram’s and Remo’s school was the chosen one for the 2005 final exam. On his first day of the exams, Ram’s parents took him to temple and prayed for him. Ram’s dad dropped him at the school after that. For the remaining days, Ram bicycled to school. On the final day of exams, Ram came out of the exam hall with relief that he can play with his friends. He didn’t want to think about the results. Ram didn’t see Remo during the exams or the following days.

Will he pass? It was the day before the results come out. Ram’s mom was worried. She was more concerned about what her relatives would say about her son if he fails. She could eat well and has a migraine. Ram’s father kept calling home every other hour to check on Ram and mother. Results are published on CBSE website. Ram’s father has noted down Ram’s exam ID during one of those calls to check the results from his office. To everyone’s surprise, Ram passed with flying colors. He scored more than many class toppers. Ram’s mom was happy and called every one of her relatives to share this news. Ram’s relatives came by to congratulate him. He became a “brilliant kid” from “naughty one” in a day. Ram could feel a sense of respect from everyone at that point.

Two days later, it was a Sunday morning. Ram was watching TV with his legs on top of coffee table, TV remote in his right hand and a cup of tea in his other hand. Ram’s mother was in the backyard taking care of her kitchen garden. They were not expecting anyone at that time. The house was disorganized – dried clothes on a couch in the living room, chairs not in their proper place, newspaper on the floor. Ram felt like he heard a knock on the front door. He muted the TV and waited for a second knock before he got up. He peeped through the window to see the person. It was Remo’s mother, Mary. Ram rushed to his room to change clothes and ran back to open the door. He welcomed her with a smile. They exchanged pleasantries. Ram shouted to his mom to come see who came to their house. Ram left out the details to surprise his mom. Ram’s mother came to the living room after washing her hands. She was surprised to see Mary. She enquired about Remo. “Remo is out of town and he would have been here otherwise” told Mary. Ram’s mom made tea for everyone and had a long chat with Mary. They sat together on the couch after moving the clothes to bedroom and relived the last one year. They exchanged stories one after another and laughed at all tense moments they went through for their kids. Ram carried on with his program on TV while they lost themselves in each other. As the sun set, Remo’s mom realized how late it was. She wished she could stay longer and talked but she had to take two buses to reach home. As she was about to leave, Ram stood up and said “Bye aunty. Tell Remo that I asked about him”. Mary walked to Ram, held him close and looked at his eyes like she had something to say. But instead of saying anything, she hugged him. Mary told Ram: “I wish you were my son. You have a good heart. God bless you my kid.” while she held him tightly. As she turned around to leave, Ram saw on Mary’s face the same happiness his mom had when his 10th grade results came out. Ram and his mom stood there, in front of the house watching Mary walk away.

 

Puzzle : Count possible combinations of coins

Q. Given a sum of value S and infinite supply of coins each of value C = { C1, C2, .. , Cn}, how many ways can you make the change? The order of coins doesn’t matter.

For example, for S = 5 and S = {1,2}, there are three solutions:  (1, 1, 1, 1, 1), (1, 1, 1, 2), (1, 2, 2) . So output should be 3. For S = 10 and C = {2, 5, 3, 6}, there are five solutions: (2,2,2,2,2), (2,2,3,3), (2,2,6), (2,3,5) and (5,5). So the output should be 5.

Yes, I agree; this question is hard. But can we simplify it to come up with a solution that will solve this tough one!

What if C was { 1 } and S was 10? Number of combinations possible is 1; Ten times 1 is the only way to form the sum 10. That was quick and easy, right? 😀

Lets take it to next level. This time, lets try with more coins: 1 and 2 and same sum: 10. Yes, many combinations flashed my mind too. Lets cross this bridge one step at a time. Lets first list out all the combinations

1464_1

How do I convert this to a program!!! Lets walk through the process that happened in my brain when I wrote down those combinations.

  1. I took zero 2 and tried to form the remaining sum with all 1. I could use ten 1 to form the sum.
  2. I took one 2 and tried to form the rest of the sum with all 1.
  3. Took three 2 and got six 1
  4. Took four 2 and got four 1
  5. Took five 2 and got two 1
  6. Took six 2 and got zero 1

Good question (if this already came up in your mind)! what if I tried to find the count of 2 by giving values to number of 1. Lets work it out.

1464_2

Both cases, I did nothing but iterate from 0 till a number which when multiplied with the chosen coin (2 in first case and 1 in second case) is larger than sum. In every step, I tried to form the remaining “sum” with rest of the denominations.

We encountered more steps than in the previous one but at the end it turned out to be the same number of combinations. Obvious! Trying out both ways helped us discover an optimization: Larger Denominations First. Lets shorten it to LDF 😉

So lets transform our knowledge to algorithm now. For that, lets set some terminologies.

Terminologies:

  1. D : All denominations(coins) in ascending order. Why sorting? Sorting is just to implement LDF (Larger Denominations First) and is optional.
  2. D[i] : value of i-th coin . Assume that index starts with 1.
  3. S : sum to be formed.
  4. F(i, S) : Returns the maximum combinations possible with first ‘i’ denominations to form sum ‘S’
  5. F(i, n, S) : Returns the maximum combinations possible with first ‘i’ denominations using i-th denomination ‘n’ times. This function is to find the maximum combinations possible with remaining denominations while keeping the count of i-th denomination to a particular value.

For our case where D = { 1, 2 } and S = 10:

  • F(2, 10) should give us 6 since there are 6 different ways to form a sum of 10 with 1 and 2
  • F(1, 10) should give 1.
  • F(2, 0, 10) should give 1
  • F(2, 1, 10) should give 1
  • F(2, 2, 10) should give 1
  • F(2, 3, 10) should give 1
  • F(2, 4, 10) should give 1
  • F(2, 5, 10) should give 1
  • F(2, 6, 10) should give 0
  • F(2, 7, 10) should give 0

Lets try to define F(i, S) in terms of F(i, n, S).

1464_3

This is nothing but mathematical representation of a for-loop with variable x iterating from 0 to (S/D[i]),  beyond which the x*D[i] will be greater than S.

Now we should define F(i, n, S). As stated before, F(i, n, S) is the maximum number of combinations possible with D[i] used ‘n’ times. With the number of D[i] fixed to n, we just need to iterate through the rest of the coins. So it can be defined as

1464_4

It is a recursive function which reduces the sum by D[i]*n and finds the maximum combinations with rest of the coins. But what should it do when it reaches the last denomination? It should be able to divide the sum without any remainder; if not, there is no possible combination with the chosen numbers. Simple!

1464_5

Now, lets try to apply our new algorithm.

F(2, 10) = F(2, 0, 10) +
           F(2, 1, 10) +
           F(2, 2, 10) +
           F(2, 3, 10) +
           F(2, 4, 10) +
           F(2, 5, 10)
         = F(1, 0, 10) + F(1, 2, 10) + F(1, 3, 10) + F(1, 4, 10) + F(1, 5, 10) + F(1, 6, 10) + F(1, 7, 10) ++ F(1, 8, 10) + F(1, 9, 10) + F(1, 10, 10) +           F(1, 0, 8) + F(1, 1, 8) + F(1, 2, 8) + F(1, 3, 8) + F(1, 4, 8) + F(1, 5, 8) + F(1, 6, 8) + F(1, 7, 8) ++ F(1, 8, 8) + 
           F(1, 0, 8) + F(1, 1, 8) + F(1, 2, 8) + F(1, 3, 8) + F(1, 4, 8) + F(1, 5, 8) + F(1, 6, 8) + F(1, 7, 8) ++ F(1, 8, 8) + 
           F(1, 0, 6) + F(1, 1, 6) + F(1, 2, 6) + F(1, 3, 6) + F(1, 4, 6) + F(1, 5, 6) + F(1, 6, 6) +
           F(1, 0, 4) + F(1, 1, 4) + F(1, 2, 4) + F(1, 3, 4) + F(1, 4, 4) + 
           F(1, 0, 2) + F(1, 1, 2) + F(1, 2, 2) + 
           F(1, 0, 0)
         = 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 +
           0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 +
           0 + 0 + 0 + 0 + 0 + 1 +
           0 + 0 + 0 + 1 +
           0 + 1 +
           1 
         = 6

That worked!

Lets write some Java now..

package fun.puzzles;

import java.util.Arrays;
import java.util.List;

public class CoinCombinationsPuzzle {
    
    private final List<Integer> coins; 
    
    public CoinCombinationsPuzzle(List<Integer> coins) {
        this.coins = coins;    
    }
    
    public int maximumPossibleCombinations(int numOfCoins, Integer sum) {
        coins.sort(null);
        int maxIteration = sum/coins.get(numOfCoins);
        int maxPossibleCombinations = 0;
        for (int i = 0; i <= maxIteration; i++) {
            maxPossibleCombinations += maximumPossibleCombinations(numOfCoins, i, sum);
        }
        return maxPossibleCombinations;
    }
    
    public int maximumPossibleCombinations(int numOfCoins, int count, Integer sum) {
        // safety check
        if (numOfCoins < 0) { return 0;    }
        if (numOfCoins < 1) {
            if (count * coins.get(numOfCoins) == sum) {
                return 1;
            }
            else {
                return 0;
            }
        }
        // Reduce the fixed denomination from sum
        sum -= (count * coins.get(numOfCoins));
        int maxIteration = sum/coins.get(numOfCoins-1);
        int maxPossibleCombinations = 0;
        for (int i = 0; i <= maxIteration; i++) {
            maxPossibleCombinations += maximumPossibleCombinations(numOfCoins-1, i, sum);
        }
        return maxPossibleCombinations;
    }
    
    public int maximumPossibleCombinations(Integer sum) {
        return maximumPossibleCombinations(coins.size()-1, sum);
    }
    
    public void printMaximumPossibleCombinations(Integer sum) {
        System.out.printf("Coins: %-50s Sum: %-5d MaximumPossibleCombinations: %-5d\n", 
                coins, sum, maximumPossibleCombinations(coins.size()-1, sum));
    }
    
    public static void main(String[] args) {
        List<Integer> coins;
        CoinCombinationsPuzzle ccp;
        
        coins = Arrays.asList(1, 2);
        ccp = new CoinCombinationsPuzzle(coins);
        ccp.printMaximumPossibleCombinations(5);
        
        coins = Arrays.asList(1, 2);
        ccp = new CoinCombinationsPuzzle(coins);
        ccp.printMaximumPossibleCombinations(10);
        
        coins = Arrays.asList(1, 2, 3);
        ccp = new CoinCombinationsPuzzle(coins);
        ccp.printMaximumPossibleCombinations(100);
        
        coins = Arrays.asList(1, 2, 5, 10);
        ccp = new CoinCombinationsPuzzle(coins);
        ccp.printMaximumPossibleCombinations(1074);
    }
}

Output:

1464_6

This solution can still be optimized by caching the results of recursive method: maximumPossibleCombinations(int numOfCoins, int count, Integer sum)

 

docker run hello-world

Virtualization is the latest Trend and it’s happening everywhere. We started with virtualising hardware and soon realised its over-kill. Realisation is the starting of change. It resulted in a light weight version of virtualization: Linux-Containers or LXC . They are getting adopted Industry wide.

LXC is the solution but what is the tool!!!

One of the most accepted tool is Docker

LXC makes use of the kernel functionalities of cgroup and kernel-namespace. It virtualises at the operating system level and makes it less costlier than its predecessor.

So let’s try setting-up docker and run hello-world, our very old custom..

fyi: Docker makes use of virtualbox. For OSX you may download the package (.pkg) from boot2docker/osx-installer and double-clicking it installs both virtualbox and docker. For other OS/platforms, you may follow instructions from docker-installation-guide.

Once the installation is complete, use splotligt (⌘-Space bar) to open boot2docker.

It opens terminal and runs the initialisation steps and generates encryption keys.

Screen Shot 2015-07-15 at 10.21.51 pm

The terminal is left to you after that.

Lets spin up the VM now.

boot2docker start

Display the docker environment variables to see if the certificate path are set right.

boot2docker shellinit

`To set the environment variables displayed with the above command, run the above command with ‘eval’

eval "$(boot2docker shellinit)" 
or 
$(boot2docker shellinit)

We are ready for the final run..

boot2docker run hello-world

You should now be seeing the output of hello-world.

Screen Shot 2015-07-15 at 10.45.51 pm

 

If things didn’t go well and you want to start again deleting the current vm, run the below set of commands in order.

boot2docker delete
boot2docker init
boot2docker start
$(boot2docker shellinit)
boot2docker run hello-world

Python CGI in Apache httpd server

Pre-requisite: Working Apache Server.

 

In httpd-vhosts.conf:

Add below content inside <VirtualHost …>

ScriptAlias /cgi-bin/ "/cgi-bin/" 
<directory "<httpd-installed-path="">/cgi-bin/">
         Options Indexes FollowSymLinks ExecCGI
         AddHandler cgi-script .cgi .py
         AllowOverride None
         Require all granted 

Now create a new file ‘test.py’ in /cgi-bin/  with content:

#!/usr/bin/env python

import cgi
cgi.test()

Make sure the below line is not commented in httpd.conf

LoadModule cgi_module modules/mod_cgi.so

Start/Restart apache server.

You can verify the loaded cgi module using the command:

sudo [path/]apachectl -M | grep cgi

Try below url in web-browser:

http://<ip/hostname>:/cgi-bin/test.py

eg:
http://localhost:1025/cgi-bin/test.py
http://localhost:80/cgi-bin/test.py

You will get a page with details on current working directory, command line arguments, etc..

Configure VMs which talk to each other.

Hi,

This blog will walk you through setting up three different fedora VMs : ram, daisy and rincy; who will be talking to each other and also with the host machine; very soon…

Pre-requirements:

  • 3VMs already setup inVirtualBox.
    • See mine below. Name doesn’t matter much. You may use your own. My VMs run fedora OS. Depending on your OS, you may have to Google a little more on how to set different configurations. I am sure, Google will be happy to help you.

Screen Shot 2015-03-15 at 9.29.44 pm

 

A little help with my vocabulary:

host machine : machine which runs VirtualBox
VM           : Virtual Machine

First we need a Host-Only Adapter. This needs to be created in the Virtual Box and not in any particular VMs. So lets do that first.

Go to the preference of VirtualBox. Mine is a Mac. Don’t confuse with the screenshots if you are using another host OS.

Screen Shot 2015-03-15 at 8.49.51 pmGo to the “Network” tab and choose “Host-only Networks” sub-tab and create a new Adapter by clicking on the green plus sign you see on the right side of the window. There comes the new adapter “vboxnet0”

Screen Shot 2015-03-15 at 8.50.23 pm

Double-click “vboxnet0” or click on the screw-driver icon on the right side of the window after highlighting “vboxnet0”  to see it’s settings. Below are the default values and we are fine with it unless you really want to change it. You can see the “Lower Address Bound and “Upper Address Bound”. We can choose IP from this range for our machines.

Screen Shot 2015-03-15 at 8.51.04 pm

Press “OK” if you made some change else “OK” or “Cancel” as you like and we have a working “Host-only Adapter” now.

Now we should connect it to all three VMs.

Highlight a VM and click “Settings” (on the top of the window between “New” and “Show”)

Screen Shot 2015-03-15 at 8.51.41 pm

Select the “Network” tab from the window which appeared. Leave “Adapter 1” as we need it to be Attached to “NAT” for accessing internet via host machine. Select “Adapter 2” and select “Host-only Adapter” option from the drop down menu of “Attached to:”. Ofcourse the value for “Name:” is our newly created “vboxnet0”.

Screen Shot 2015-03-15 at 8.52.14 pm

Set “Promiscuous Mode:” to “Allow All” or “Allow VMs”. Putting it to “Deny” will stop any communication via this Adapter. Hope you too don’t want that as our intention is otherwise.

Screen Shot 2015-03-15 at 8.52.39 pm

Now we need to boot into the VMs and assign a static-IP for each.

I will start will “ram” VM.

In RedHat/Fedora we can use “system-config-network” for this purpose.

Install it using the below command. You should have root privilege or sudo privilege for this.Screen Shot 2015-03-15 at 9.18.47 pmOnce installed, run “system-config-network” command to start assigning the static IP.

Screen Shot 2015-03-15 at 9.19.24 pmThat will take you to something like this:

Screen Shot 2015-03-15 at 9.19.34 pm

Highlight “Device Configuration” from it using arrow keys and press “Enter/Return” key.

Screen Shot 2015-03-15 at 9.19.53 pmWe need to edit “vboxnet0”, so highlight it. If you don’t see that, you may highlight “” and press Enter.

Make sure your settings match the below ones. You may choose any IP from the range we saw earlier. I go for 192.168.56.[101-103]. Need not be adjacent ones.

Use tab and arrow keys to highlight the “OK” button and press Enter after the changes.

Screen Shot 2015-03-15 at 9.20.03 pmClick “Save”.

Screen Shot 2015-03-15 at 9.20.26 pm

Then “Save&Quit”

Screen Shot 2015-03-15 at 9.20.37 pm

With this, we have assigned static-IP 192.168.56.101 to VM: ram.

Now lets do a small trick to ease our path ahead; a small DNS resolution.

Lets use the names ram, daisy and rincy instead of the IPs.

For that, open the /etc/hosts file.

Screen Shot 2015-03-15 at 9.21.30 pmAnd add below lines to it.Screen Shot 2015-03-15 at 9.21.51 pm

Like wise, assign 192.168.56.102 to daisy and 192.168.56.103 to rincy and update the /etc/hosts file.

Now reboot all the VMs to be on the safer side. and try the below commands in all three VMs and host machine.

ping -c 3 ram
ping -c 3 daisy
ping -c 3 rincy

You will get the below output which means rincy, ram and daisy started talking to each other..

Screen Shot 2015-03-15 at 9.23.12 pmTry from the host machine and you will see Big-Daddy can talk to his children now..

Screen Shot 2015-03-15 at 9.24.52 pmSo there comes an end to this blog..

LDAP_CONTROL_RELAX undeclared while installing python-ldap

ERROR:

Modules/constants.c: In function ‘LDAPinit_constants’:
Modules/constants.c:158: error: ‘LDAP_OPT_DIAGNOSTIC_MESSAGE’ undeclared (first use in this function)
Modules/constants.c:158: error: (Each undeclared identifier is reported only once
Modules/constants.c:158: error: for each function it appears in.)
Modules/constants.c:380: error: ‘LDAP_CONTROL_RELAX’ undeclared (first use in this function)
error: command ‘gcc’ failed with exit status 1

 

Solution:
Install openldap24-libs & openldap24-libs-devel :
sudo yum install openldap24-libs-devel
sudo yum install openldap24-libs

Run the below commands and get the unique list of directories from the output:
Add those folders to setup.cfg file in the below section:
[_ldap]
library_dirs = /opt/openldap-RE24/lib /usr/lib
include_dirs = /opt/openldap-RE24/include /usr/include/sasl /usr/include

Now run the installation command:
python setup.py install