Editorial for WC '15 Contest 2 J1 - A New Hope


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

The first junior problem is always meant to test the bare basics of interpretation and implementation – i.e. can you understand what the problem is asking and use your language on a rudimentary level to do basic input/output accordingly? In this case, we just have to input a number N and output the sentence with N number of fars. The hardest part is following the output format exactly. Two ways to approach this are as follows.

The first way follows simple intuition – output the first part of the phrase, loop N times to output far, and finally output the last part of the phrase. However, this raises a common problem with loops – we actually want the first and last iterations of the loop to do different things (the first far should be followed by a comma, but the last far should not). The typical ways to handle this are: doing a check within the loop for the border case, or just doing the border case outside of the loop and only loop N-1 times. The last option is usually easier because it removes the need for an extra if-statement.

Another possible solution comes from simply observing that the number of fars can only be as big as 5, which tells us that it's quite feasible to "hardcode" the answer. In other words, we can use 5 if/else-statements to check what N is equal to, and then go on to copy and paste the line of code which outputs the phrase for each of the 5 conditions, except with the number of fars manually modified in each case.

if (N == 1)
 cout << "A long time ago in a galaxy far away..." << endl;
else if (N == 2)
 cout << "A long time ago in a galaxy far, far away..." << endl;
else if (N == 3)
 cout << "A long time ago in a galaxy far, far, far away..." << endl;
...

This is also a perfectly fair solution, because some of you may be able to hardcode faster than obtaining a generic version using loops (which works for any sized N, and not just for N not exceeding 5). Although contests encourage taking advantage of small input sizes to speed up coding, just know that you should eventually be acquainted with writing generic solutions for harder problems that must scale.


Comments

There are no comments at the moment.