Skip to content

Instantly share code, notes, and snippets.

@Sophie1214
Created June 22, 2017 19:37
Show Gist options
  • Save Sophie1214/b851a16029c1f14a893a9cea1bdf7abe to your computer and use it in GitHub Desktop.
Save Sophie1214/b851a16029c1f14a893a9cea1bdf7abe to your computer and use it in GitHub Desktop.
A way to reorder a string in a specific manner
//The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
//
//P A H N
//A P L S I I G
//Y I R
//And then read line by line: "PAHNAPLSIIGYIR"
//Write the code that will take a string and make this conversion given a number of rows:
//
//string convert(string text, int nRows);
//convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"
//The way I understand it : convert("ABCDEFGHIJKLMNOPQRST", 4) will transform the string into:
//A G M S
//B E H K N Q T
//C F I L O R
//D J P
//
//and it will return: "AGMBEHKNCFILDJ"
import Foundation
func convert(_ s: String, _ numRows: Int) -> String {
var mainArray = [[String]]()
for _ in 1...numRows{
let singleArray = [String]()
mainArray.append(singleArray)
}
let theString = Array(s.characters)
var count = numRows
var arrayCounter = 0
if numRows <= 2 {
for char in theString{
if arrayCounter%numRows != 0{
mainArray[numRows - 1].append("\(char)")
}
else{
mainArray[0].append("\(char)")
}
arrayCounter += 1
}
var newString = ""
for array in mainArray {
newString += array.joined()
}
return newString
}else {
arrayCounter = 0
var charCounter = 0
while charCounter < theString.count {
if count == numRows || count == 2*numRows {
arrayCounter = 0
}
if count == 2*numRows {
// mainArray[0].append(" ")
count = 0
}
else if count == (numRows - 1) {
// mainArray[numRows - 1].append(" ")
}
else {
mainArray[arrayCounter].append("\(theString[charCounter])")
charCounter += 1
}
count += 1
arrayCounter += 1
}
var newString = ""
for array in mainArray {
newString += array.joined()
}
return newString
}
}
let string = "ABCDEFGHIJKLMN"
print(convert(string, 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment