How to Get Multiple Lines of Stdin Swift Hackerrank

How to get multiple lines of stdin Swift HackerRank?

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 + " "
}

print(string)

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

Hope that helps someone

:)

Hackerrank stdin only gives me the first line from multiple lines

If you need the 3 lines, call it 3 times :)

The documentation is explicit

Returns Characters read from standard input through the end of the
current line
or until EOF is reached, or nil if EOF has already been
reached.

But it seems they forgot to indicate that reading a line will change the current line

Swift two readLine/scanf/stdin input in Single line

You can easily split what is read into an Array.

let values = readLine()?.components(separatedBy: CharacterSet.whitespacesAndNewlines) ?? []

You can then store those in multiple variables in different ways. Here is an example:

let valueOne = values.count > 0 ? Int(values[0]) : nil
let valueTwo = values.count > 1 ? Int(values[1]) : nil

Swift: HackerRank readLine an array of Int


let line = readLine()!

print(line)

//To Array, should work. Wrote it real quick
let array = readLine()!.characters.split(" ").map( { String($0)! } )

Difficulty getting readLine() to work as desired on HackerRank

readLine() reads a single line from standard input, which
means that your inputString contains only the first line from
the input data. You have to call readLine() in a loop to get
the remaining input data.

So your program could look like this:

func tweakString(string: String) -> String {
// For a single input string, compute the output string according to the challenge rules ...
return result
}

let N = Int(readLine()!)! // Number of test cases

// For each test case:
for _ in 1...N {
let input = readLine()!
let output = tweakString(string: input)
print(output)
}

(The forced unwraps are acceptable here because the format of
the input data is documented in the challenge description.)

HackerRank says ~ no response on stdout ~ Swift

I have run into this before, the way I solved it was saving my code somewhere and resetting to the boilerplate code. So just reset to the boilerplate and copy your function back in. On many swift hackerrank problems they have something like the following:

func myFunc(param: [Int]) -> [Int] {
/*
* Write your code here.
*/
}

// The following is an example of your function being written to stdout

let fileName = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: fileName, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: fileName)!

let result = myFunc(param: input)

fileHandle.write(result.map{ String($0) }.joined(separator: "\n").data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

The code after the function is what writes to stdout

Reading unknown number of lines from console

Try something like this

a_lst = []          # Start with empty list
while True:
a_str = input('Enter item (empty str to exit): ')
if not a_str: # Exit on empty string.
break
a_lst.append(a_str)
print(a_lst)

Can swift while loops use functions as parameters?

This code calls readLine() at the start of every iteration. The result of that function is a String? (a.k.a. Optional<String>). If there is really a String there, it'll be bound to the variable line, and the block will be called once. This process is repeated until the binding isn't possible, that is, until readLine() returns nil.



Related Topics



Leave a reply



Submit