String split and NumberFormatException
I was trying to convert a string with spaces into various subparts
So i used split method and then tried to convert the individual values into int
While parsing int values i was getting NumberFormatException
That seems very strange at first instance but yes i got it.
After careful notice i found that
19 String[] input = line.split("\\s+");
20 System.out.println(input[0]);
21 int withdrawl = Integer.parseInt("input[0]");
Line 21 already had " " quotes inserted in array generated by the split method
So just
19 String[] input = line.split("\\s+");
20 System.out.println(input[0]);
21 int withdrawl = Integer.parseInt(input[0]);
without quotes was enough to parse the value
The javadoc for split method explains more
The string "boo:and:foo", for example, yields the following results with these expressions:
Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }
read the program input from text file
Other day i was trying to take part in some online programming tests and generally we have to give our program which is compliant to certain guidelines.
One of them is that input has to be given from keyboard.
For testing locally i suggest that you can make one text file to give input all in one go
Some thing like
System.setIn(new FileInputStream(
"D:\\Development\\eclipse_workspace\\RandomInterview\\src\\1.txt"));
This will set the System.in to the text file specified and you can see the output in console.
Happy Programming
Useful link
http://stackoverflow.com/questions/188547/eclipse-reading-stdin-system-in-from-a-file
Use BufferedReader to read line by line
BufferedReader br = new BufferedReader(in);
String line ;
while ((line = br.readLine()) != null){
System.out.println(line);
}
Earlier i was doing one mistake
invoking readLine() both for checking null and for printing so as a effect the values were skipped and alternate values were being printed. This is due to fact that readLine was called two times and one value was being skipped
Useful resource
http://www.java2s.com/Code/Java/File-Input-Output/UseBufferedReadertoreadlinebyline.htm
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
This error comes when we give path
D:\Development\eclipse_workspace\
instead of
D:\\Development\\eclipse_workspace\\
We should escape the backslash with \
parrotTrouble
Programming problem at
http://codingbat.com/prob/p140449
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.
parrotTrouble(true, 6) → true
parrotTrouble(true, 7) → false
parrotTrouble(false, 6) → false
My Solution
First i wrote
public boolean parrotTrouble(boolean talking, int hour) {
if(!talking)
return false;
if((talking) && ( (hour<7)||(hour>20) ) )
return true;
}
I got error that
Error: public boolean parrotTrouble(boolean talking, int hour) {
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This method must return a result of type boolean
Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider using a final else {... to ensure that return is always called.
public boolean parrotTrouble(boolean talking, int hour) {
if(!talking)
return false;
else
return ((talking)&&( (hour<7)||(hour>20) ) );
}
The official solution was
public boolean parrotTrouble(boolean talking, int hour) {
return (talking && (hour < 7 || hour > 20));
// Need extra parenthesis around the || clause
// since && binds more tightly than ||
// && is like arithmetic *, || is like arithmetic +
}
Comparison and Lessons
I see that the official solution was too clean , i did extra smartness but straight away saying false if parrot is not talking. I was trying to avoid further checks. But yes official code looks good.
The main issue of missing return in first try.
We need to return always something as per function definition.
The else was missing from earlier code snippet
diff21
Programming problem at
http://codingbat.com/prob/p116624
Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
My Solution
First i wrote
public int diff21(int n) {
int absDiff = java.Math.abs(n-21);
if(n>21)
absDiff = 2*absDiff;
return absDiff;
}
It gave error that java.Math cannot be resolved to a type. Then i realized i should not use java build in packages
Then i modified correct the code as
public int diff21(int n) {
int absDiff = n-21;
if (absDiff < 0 )
absDiff = (-1)*absDiff;
if(n>21)
absDiff = 2*absDiff;
return absDiff;
}
After i read the coding rules ( see Comparison and Lessons below ) , i realized that packages are allowed to be imported
However my mistake was different , i wrote wrong java class package.
The revised correct code with build in function of abs is
public int diff21(int n) {
int absDiff = java.lang.Math.abs(n-21);
if(n>21)
absDiff = 2*absDiff;
return absDiff;
}
The official solution was
public int diff21(int n) {
if (n <= 21) {
return 21 - n;
} else {
return (n - 21) * 2;
}
}
Comparison and Lessons
I read the coding rules for CodingBat website (http://codingbat.com/help.html) The java.util package is included in all the problems
My second mistake was to use the wrong java.lang.Math package ( i used java.Math )
Other thing which i noticed specific to CodingBat is below
If the method takes a String or array argument, those arguments will not be passed in a null. However, the empty String or array is still a valid case unless the problem statement specifically says otherwise.
Lessons learnt to remember the java Math class package
sumDouble
Programming problem at
http://codingbat.com/prob/p154485
Given two int values, return their sum. Unless the two values are the same, then return double their sum.
sumDouble(1, 2) → 3
sumDouble(3, 2) → 5
sumDouble(2, 2) → 8
My Solution
public int sumDouble(int a, int b) {
if(a==b)
return 2*(a+b);
else
return(a+b);
}
The official solution was
public int sumDouble(int a, int b) {
// Store the sum in a local variable
int sum = a + b;
// Double it if a and b are the same
if (a == b) {
sum = sum * 2;
}
return sum;
}
Comparison and Lessons
Missed semi colons in first run , always check sytax errors
monkeyTrouble
Programming problem at
http://codingbat.com/prob/p181646
We have two monkeys, a and b, and the parameters aSmile and bSmile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return true if we are in trouble.
monkeyTrouble(true, true) → true
monkeyTrouble(false, false) → true
monkeyTrouble(true, false) → false
My Solution
Both smiling and both not smiling , that is both true and both false points my brain towards the XOR gate
First i wrote
return (aSmile ^ bSmile );
which gave result exatly opposite to what was required , so i read the problem again
i had to change the code with
return !(aSmile ^ bSmile );
The complete solution is
public class monkeyTrouble {
public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
return !(aSmile ^ bSmile);
}
}
The official solution was
public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
if (aSmile && bSmile) {
return true;
}
if (!aSmile && !bSmile) {
return true;
}
return false;
// The above can be shortened to:
// return ((aSmile && bSmile) || (!aSmile && !bSmile));
// Or this very short version (think about how this is the same as the above)
// return (aSmile == bSmile);
}
Comparison / Analysis
Lesson learnt is to read the problem carefully and to retest your solution with dry run for possible outputs. I am going to write unit tests for testing the programs in future
I found one website which explain all the logical operators in Java
http://www.sap-img.com/java/java-boolean-logical-operators.htm
SleepIn
Programming problem at
http://codingbat.com/prob/p187868
The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return true if we sleep in.
sleepIn(false, false) → true
sleepIn(true, false) → false
sleepIn(false, true) → true
My Solution
public class SleepIn {
public boolean sleepIn(boolean weekday, boolean vacation) {
if ((weekday == false) || (vacation == true))
return true;
else
return false;
}
}
The official solution was
public boolean sleepIn(boolean weekday, boolean vacation) {
if (!weekday || vacation) {
return true;
} else {
return false;
}
// This can be shortened to: return(!weekday || vacation);
}
Comparison
I tried to do it too childish way , comparing booleans :P
Websites for improving programming and algorithms skills
Bunch of resources for improving programming skills by practice and participating in online competitions
Online code practice which shows the right solution straight away. The best part which i like the most is that you can type your code into the text pad on website and see its output
http://livearchive.onlinejudge.org/
Here you will find hundreds of problems used in the ACM-ICPC Regional's and World Finals. You can submit your sources in a variety of languages, trying to solve any of the problems available in database.
New location is
http://uva.onlinejudge.org/index.php
SPOJ – Sphere Online Judge – is a problem set archive, online judge and contest hosting service accepting solutions in many languages.
This website has lots of programming contests
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
Participate in programming competitions , practice online questions , participate in online discussions
the USA Computing Olympiad, training pages and online contests.
The USACO 2011 December contest runs from December 9 through December 12. Click Here for further details.
2011-2012 Schedule
Nov 11-14: November Contest
Dec 9-12: December Contest
Jan 6-9: January Contest
Feb 3-6: February Contest
Mar 2-5: March Contest
April: US Open
June: Training Camp
September: IOI 2012 in Milan, Italy
http://www.bitwise.iitkgp.ernet.in/home
IITKGP Annual Algorithms and Programming contest
Bitwise 2011 was a great success with participation from 3200 teams from over 80 countries.
Any one around the world (except students of IITKGP CSE department) can participate in the contest
http://www.facebook.com/careers/puzzles.php?puzzle_id=7
Puzzles for solving posted by Facebook
Other Resources
A website having calendar which has dates for coding contests around the world
http://home.iitk.ac.in/~pankajj/programming_calender.html
http://www.algorithmist.com/index.php/Programming_Contest_Calendar
New line character / OS dependence
The new line character depends on your OS \n for Unix, \r\n for Windows and \r for old Macs
Always use
System.getProperty("line.separator")
To find out OS specific line separator instead of judging yourself and hard coding it.
This error can lead to many bugs in system
Katya karoon lyrics meaning
I was asked by my Non punjabi friends about meaning of Katya karoon , the famous song from Rockstar . Thought to translate full.
Kateya Karoon is an old punjabi folk song- The women in old days used to make cotton on the spinning feel . Still this is common time pass in villages but not in cities. Group of ladies join and sing , talk things of here and there.
Often they sing for for their husbands or lovers..
Following is the detailed analysis
Ting ling ling ling ting ling ling ling >>>> Punjabi rhyme sort of kids do this often
Ting ling ling ling ting ling ling
Kateya karoon kateya karoon >>>> I will spin the cotton wheel ,
Tera roon kateya karoon >>>> Girl is saying to his beloved i will spin your cotton >>> roon means cotton
Tera roon tera roon tera roon roon roon roon roooon >>>> tera means yours
Saari raati kateya karun >>> I spin your cotton all night >>>> literal means in your thoughts all night
Kateya karoon kateya karoon
Sari raati kateya karoon
Saara din sochhan vich langhda >>>>> The entire day is spent in this thought
Tere lai hun jiyun te marun >>>>> I shall live and die for you
Eh tan mera charkha hove >>>>> My body will be the spinning wheel
Hove ulfat yaar di chittaa roon >>>>>> And let the love of my beloved be pure cotton
Nachdi phiroon tapdi phiroon >>>>> Let me dance let me fly jumping all around
Keeli mai napdi phiroon >>> Let me be in ecstasy , full speed no stop :P >>>>> keeli napdi phiroon is often used in punjabi to do things fast
Hadh karoon, hadh karoon >>>> Crossing all boundaries all barriers
Hadh karoon roon roon roon rooooon
Yaara bulle luteya karoon >>>>> I will enjoy full
Mainu darr hun naiyo jag da >>>>>> Now I dont fear this world
Tere lai hun jiyun te maroon >>>>> I shall live and die for you
Mai saari raat kateya kateya karoon....
Update
The one more thing which you might be interested
In song Nadaan parindey there are few lines written by Sheik farid who was
a 12th-century Sufi preacher and saint of the Chishti Order of South Asia.
IF you listen song below from time 4.06 min
You can listen following lines
The original lines are as follows ( In Punjabi with english translation)
English transliteration
kaga karang dhandolya sagla khaya maas
eh do naina mat chuho pir dekhan ki aas
The image below says all about feelings behind these original lines.
http://www.sikhiwiki.org/index.php/Sheikh_Farid
Although film people have copied and modified the lines to make suitable for the film but
i just wanted to share the original person behind those lovely lines
The bani ( text ) written by Sheik farid has been incorporated into Guru Granth Sahib ( the holy book of Sikhs)