Peter Parker Peter Parker - 1 year ago 577
Swift Question

How to get multiple lines of stdin Swift HackerRank?

I just tried out a HackerRank challenge, and if a question gives you x lines of input, putting x lines of let someVariable = readLine() simply doesn't cut it, because there are lot's of test cases that shoot way more input to the code we write, so hard coded readLine() for each line of input won't fly.

Is there some way to get multiple lines of input into one variable?

Answer Source

For anyone else out there who's trying a HackerRank challenge for the first time, you might need to know a couple of things that you may have never come across. I only recently learned about this piece of magic called the readLine() command, which is a native function in Swift.

When the HackerRank system executes your code, it passes your code lines of input and this is a way of retrieving that input.

let line1 = readLine()
let line2 = readLine()
let line3 = readLine()

line1 is now given the value of the first line of input mentioned in the question (or delivered to your code by one of the test cases), with line2 being the second and so on.

Your code may work just great but may fail on a bunch of other test cases. These test cases don't send your code the same number of lines of input. Here's food for thought:

var string = ""

while let thing = readLine() {
string += thing + " "


Now the string variable contains all the input there was to receive (as a String, in this case).

Hope that helps someone


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download