Monday, May 5, 2008

Day 7 - Who Won?

You are given an array of strings containing a 3 letter country name followed by a hyphen (-) and A 3 digit number. These strings represent the number of points earned by the students of the respective country in a programming competition.
NOTE: There are only 3 countries participating, India, China and USA. The 3 letter code for the countries are IND, CHI and USA respectively.

Write a function that calculates the total number of points scored by the students of IND, CHI and USA and returns a string in the same format with the country code followed by a hyphen followed by the total points scored by the country which has the highest points.

eg
INPUT -> ["IND-32","CHI-33","USA-29","USA-30","IND-12","CHI-34"]
OUTPUT -> "CHI-67"

NOTE: It is guaranteed that the sum of the scores won't be equal.

Day 6 - Solution

The problem here is to break the string into corresponding numbers.

There are 2 general ways of going about it.

1. Using String Streams.
String Streams are a mechanism of converting a string to a stream. So you can do things like write to the stream and read from the stream, very similar to how you use cout and the << operator to write to Standard Output Stream and cin and >> operator to read from the Standard Input Stream.

So we initialize a String Stream with our string - namely DOB.
We then read the day, the '/' character, the month, the '/' character and the year from it.

Check the Program.


Click on the image for a clearer view.


2. The 2nd way is using sscanf()
The syntax of sscanf is very similar to scanf, only that you need to specify the string that it needs to scan as the first argument. Note that sscanf() is a C compatible function so our string object (dob) won't work with it. We will have to convert it to a C compatible string. That is attained by using the c_str() functionality built in the string class.
eg string obj -> "12/3/00"
obj.c_str() => char * => "12/3/00\0"

You'll understand better by having a look at the program.



Click on the image for a clearer view.


The result of both the program is the same:-



If you know of any other ways, please bring it to my notice :)

Day 6 - Question : Breaking Strings

You are given a string containing a string Date of Birth in DD/MM/YYYY format. Eg "15/08/1947". Write a function that takes the string as an input and returns a vector containing 3 elements:
v[0] = Day as an integer
v[1] = Month as an integer
v[2] = Year as an integer

eg:
INPUT : "15/08/1947"
Output: [15, 8, 1947]