Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. //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)
  2. //
  3. //P A H N
  4. //A P L S I I G
  5. //Y I R
  6. //And then read line by line: "PAHNAPLSIIGYIR"
  7. //Write the code that will take a string and make this conversion given a number of rows:
  8. //
  9. //string convert(string text, int nRows);
  10. //convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"
  11.  
  12. //The way I understand it : convert("ABCDEFGHIJKLMNOPQRST", 4) will transform the string into:
  13. //A G M S
  14. //B E H K N Q T
  15. //C F I L O R
  16. //D J P
  17. //
  18. //and it will return: "AGMBEHKNCFILDJ"
  19.  
  20.  
  21.  
  22.  
  23.  
  24. import Foundation
  25.  
  26. func convert(_ s: String, _ numRows: Int) -> String {
  27. var mainArray = [[String]]()
  28.  
  29. for _ in 1...numRows{
  30. let singleArray = [String]()
  31. mainArray.append(singleArray)
  32. }
  33.  
  34.  
  35. let theString = Array(s.characters)
  36. var count = numRows
  37. var arrayCounter = 0
  38.  
  39. if numRows <= 2 {
  40. for char in theString{
  41. if arrayCounter%numRows != 0{
  42. mainArray[numRows - 1].append("\(char)")
  43. }
  44. else{
  45. mainArray[0].append("\(char)")
  46. }
  47. arrayCounter += 1
  48. }
  49. var newString = ""
  50. for array in mainArray {
  51. newString += array.joined()
  52. }
  53. return newString
  54. }else {
  55. arrayCounter = 0
  56. var charCounter = 0
  57. while charCounter < theString.count {
  58. if count == numRows || count == 2*numRows {
  59. arrayCounter = 0
  60. }
  61. if count == 2*numRows {
  62. // mainArray[0].append(" ")
  63. count = 0
  64. }
  65. else if count == (numRows - 1) {
  66. // mainArray[numRows - 1].append(" ")
  67. }
  68. else {
  69. mainArray[arrayCounter].append("\(theString[charCounter])")
  70. charCounter += 1
  71. }
  72. count += 1
  73. arrayCounter += 1
  74. }
  75. var newString = ""
  76. for array in mainArray {
  77. newString += array.joined()
  78. }
  79. return newString
  80. }
  81. }
  82.  
  83. let string = "ABCDEFGHIJKLMN"
  84.  
  85. print(convert(string, 4))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement