swift - How to transpose an array of strings -


i've txt includes datas following format.

ayga:gka:goroka:goroka:papua new guinea:06:04:54:s:145:23:30:e:5282 ayla:lae::lae:papua new guinea:00:00:00:u:00:00:00:u:0000 aymd:mag:madang:madang:papua new guinea:05:12:25:s:145:47:19:e:0020 

how disintegrate each line colons(":") , load each section arrays in example.

var array1 = ["ayga", "ayla", "aymd"] var array2 = ["gka", "lae", "mag"] var array3 = ["goroka", "", "madang"] var array4 = ["goroka", "lae", "madang"] var array5 = ["papua new guinea", "papua new guinea", "papua new guinea"] var array6 = ["06", "00", "05"] var array7 = ["04", "00", "12"] var array8 = ["54", "00", "25"] var array9 = ["s", "u", "s"] var array10 = ["145", "00", "145"] var array11 = ["23", "00", "47"] var array12 = ["30", "00", "19"] var array13 = ["e", "u", "e"] var array14 = ["5282", "0000", "0020"] 

what trying called transposition. turning array looks like:

[[1, 2, 3], [4, 5, 6]] 

into array looks like:

[[1, 4], [2, 5], [3, 6]] 

to this, let's define generic function transposition , apply problem

// import text file bundle  guard     let inputurl = nsbundle.mainbundle().urlforresource("input", withextension: "txt"),     let input = try? string(contentsofurl: inputurl)     else { fatalerror("unable data") }  // convert input string [[string]] let strings = input.componentsseparatedbystring("\n").map { (string) -> [string] in     string.componentsseparatedbystring(":") }  // define generic transpose function. // key solution.  public func transpose<t>(input: [[t]]) -> [[t]] {     if input.isempty { return [[t]]() }     let count = input[0].count     var out = [[t]](count: count, repeatedvalue: [t]())     outer in input {         (index, inner) in outer.enumerate() {             out[index].append(inner)         }     }      return out }  // transpose strings let results = transpose(strings) 

you can see results of transposition with

for result in results {     print("\(result)") } 

which generates (for example)

["ayga", "ayla", "aymd"] ["gka", "lae", "mag"] ["goroka", "", "madang"] ["goroka", "lae", "madang"] ["papua new guinea", "papua new guinea", "papua new guinea"] ["06", "00", "05"] ["04", "00", "12"] ["54", "00", "25"] ["s", "u", "s"] ["145", "00", "145"] ["23", "00", "47"] ["30", "00", "19"] ["e", "u", "e"] ["5282", "0000", "0020"] 

this has advantage of not depending on number of arrays have, , number of subarrays taken count of first array.

you can download example playground this, has input file in playground's resources.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -