Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift String API Alternate for HackerRank

So I'm trying to prepare myself for coding interviews by doing HackerRank's test case samples. If you're familiar with the process, you usually take a standard input that has various lines of strings and you extract the information based on what the question is asking. I have come across numerous questions where they will give you a line (as a String) with n number of integers separated by a space (i.e. 1 2 3 4 5). In order to solve the problem I need to extrapolate an array of Int ([Int]) from a String. I came up with this nifty method:

func extractIntegers(_ s: String) -> [Int] {
    let splits = s.characters.split { [" "].contains(String($0)) }
    return splits.map { Int(String($0).trimmingCharacters(in: .whitespaces))! }
}

So I code it in my Playground and it works fantastic, I even run multiple test cases I make up, and they all pass with flying colors...then I copy the code to HackerRank and try running it for submission. And I get this:

solution.swift:16:29: error: value of type 'String' has no member 'trimmingCharacters'
return splits.map { Int(String($0).trimmingCharacters(in: .whitespaces))! }

So... okay maybe HR hasn't updated everything for Swift 3 yet. No big deal! I have an idea for an even cleaner solution! Here it is:

func extractIntegers(_ s: String) -> [Int] {
    return s.components(separatedBy: " ").map { Int($0)! }
}

....AAAAANDDD of course:

solution.swift:15:12: error: value of type 'String' has no member 'components'
return s.components(separatedBy: " ").map { Int($0)! }

So now I'm forced to use a really sloppy method where I loop through all the characters, check for spaces, append substrings from ranges between spaces into an array, and then map that array and return it.

Does anyone have any other clean ideas to work around HR's inadequacies with Swift? I would like any recommendations I can get!

Thanks in advance!

like image 831
Pierce Avatar asked Jan 17 '17 19:01

Pierce


1 Answers

The String methods

func trimmingCharacters(in set: CharacterSet) -> String
func components(separatedBy separator: String) -> [String]

are actually methods of the NSString class, defined in the Foundation framework, and "bridged" to Swift. Therefore, to make your code compile, you have go add

import Foundation

But a slightly simplified version of your first method compiles with pure Swift, without importing Foundation. I handles leading, trailing, and intermediate whitespace:

func extractIntegers(_ s: String) -> [Int] {
    let splits = s.characters.split(separator: " ").map(String.init)
    return splits.map { Int($0)! }
}

let a = extractIntegers("  12   234   -567 4  ")
print(a) // [12, 234, -567, 4]

Update for Swift 4 (and simplified):

func extractIntegers(_ s: String) -> [Int] {
    return s.split(separator: " ").compactMap { Int($0) }
}
like image 113
Martin R Avatar answered Oct 12 '22 23:10

Martin R