Guest User

Untitled

a guest
Jan 26th, 2020
98
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Cocoa
  2.  
  3. class Solution {
  4. func canWinNim(_ n: Int) -> Bool {
  5. return canWinNim(n, myTurn: true)
  6. }
  7.  
  8. func canWinNim(_ n: Int, myTurn: Bool) -> Bool {
  9. print("Turn: \(myTurn ? "Mine" : "Enemy"). Number of stones remaining: \(n)")
  10. if myTurn && n <= 3 {
  11. return true
  12. } else if !myTurn && n <= 3 {
  13. return false;
  14. }
  15.  
  16. let one = canWinNim(n-1, myTurn: !myTurn)
  17. let two = canWinNim(n-2, myTurn: !myTurn)
  18. let three = canWinNim(n-3, myTurn: !myTurn)
  19.  
  20. if myTurn {
  21. if one {
  22. return canWinNim(n-1, myTurn: !myTurn)
  23. } else if two {
  24. return canWinNim(n-2, myTurn: !myTurn)
  25. } else if three {
  26. return canWinNim(n-3, myTurn: !myTurn)
  27. } else {
  28. print("Turn: \(myTurn ? "Mine" : "Enemy"), failed to win with 1,2,3. Returning false.")
  29. return false;
  30. }
  31. } else {
  32. if !one {
  33. return canWinNim(n-1, myTurn: !myTurn)
  34. } else if !two {
  35. return canWinNim(n-2, myTurn: !myTurn)
  36. } else if !three {
  37. return canWinNim(n-3, myTurn: !myTurn)
  38. } else {
  39. print("Turn: \(myTurn ? "Mine" : "Enemy"), failed to win with 1,2,3. Returning true.")
  40. return true;
  41. }
  42. }
  43. }
  44. }
  45.  
  46. let solution = Solution()
  47. print(solution.canWinNim(8))
RAW Paste Data