Last active
March 25, 2019 13:06
-
-
Save vibinnair/3911b220dffaffaffed6c3037b34b9ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://www.hackerrank.com/challenges/fp-list-replication/problem | |
import Foundation | |
func printElements(_ numberOfTimes: Int, _ list: [Int]) -> [Int] { | |
if list.count <= 0 { | |
return list | |
} | |
let appendedArray = addToList(numberOfTimes, list.first!) | |
let newArray = Array(list.dropFirst()) | |
return appendedArray + printElements(numberOfTimes, newArray) | |
} | |
func addToList(_ numberOfTimes: Int, _ number: Int) -> [Int] { | |
if numberOfTimes <= 0 { | |
return [] | |
} | |
let list = [number] | |
return list + addToList(numberOfTimes - 1, number) | |
} | |
print("\(printElements(5, [3, 1, 2, 4]))") | |
--------------------------------------------------------------------------------------- | |
REFACTORED / UPDATED to reduce variable names | |
--------------------------------------------------------------------------------------- | |
import Foundation | |
func printElements(_ numberOfTimes: Int, _ list: [Int]) -> [Int] { | |
if list.count <= 0 { | |
return list | |
} | |
let appendedArray = addToList(numberOfTimes, list.first!) | |
let newArray = Array(list.dropFirst()) | |
return appendedArray + printElements(numberOfTimes, newArray) | |
} | |
func addToList(_ numberOfTimes: Int, _ number: Int) -> [Int] { | |
if numberOfTimes <= 0 { | |
return [] | |
} | |
return [number] + addToList(numberOfTimes - 1, number) | |
} | |
print("\(printElements(5, [3, 1, 2, 4]))") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment