Skip to content

Instantly share code, notes, and snippets.

@yossan
Last active September 18, 2017 03:53
Show Gist options
  • Select an option

  • Save yossan/bf1b83418334319fd0a5c2fd0c72c3ef to your computer and use it in GitHub Desktop.

Select an option

Save yossan/bf1b83418334319fd0a5c2fd0c72c3ef to your computer and use it in GitHub Desktop.
Hanoi Tower
/*
Hanoi Tower
Calucuating How many moves in Swift
result is 2^n - 1
*/
func hanoi(_ n: Int, from: String="from", target: String="target", other: String="other") -> Int {
guard n != 0 else { return 0 }
// move top of n-1 disks on from to other
var count = hanoi(n-1, from: from, target: other, other: target)
// move the last disk to target
count += 1
// move n-1 disks on other to target
count += hanoi(n-1, from: other, target: target, other: from)
return count
}
print(hanoi(3)) // 7
print(hanoi(4)) // 15
print(hanoi(5)) // 31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment