Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. import kotlin.random.Random
  2.  
  3. fun main() {
  4. for (size in 1..100){
  5. val train = Train(size)
  6. //Switch of the light at position, where we woke up
  7. train.setSwitchState(false)
  8. val calculatedSize=calculateTrainSize(train)
  9. println("$calculatedSize==$size")
  10. }
  11. }
  12.  
  13. fun calculateTrainSize(train: Train, steps: Int = 1): Int {
  14. //Move left by the indicated value of steps and switch off the light
  15. repeat(steps) {train.moveLeft()}
  16. train.setSwitchState(false)
  17. //Move backward to the initial position and move right by the indicated values of steps and switch off the light
  18. repeat(steps*2) {train.moveRight()}
  19. train.setSwitchState(false)
  20. //Move left to the position where we previously switched off the light and switch on it is
  21. repeat(steps*2) {train.moveLeft()}
  22. train.setSwitchState(true)
  23. //Move right to the position where we previously switched off the light and checking if it was switched on
  24. repeat(steps * 2) {
  25. train.moveRight()
  26. //We can be sure that we switched off it earlier and if it is turned on then we walk in a circle
  27. if (train.getSwitchState())
  28. return it+1;
  29. }
  30. //Move back to switched on light and switch off it for next iteration
  31. repeat(steps * 2) { train.moveLeft() }
  32. train.setSwitchState(false)
  33. //Move to the position where we woke up
  34. repeat(steps) { train.moveRight() }
  35. //Try to move on one more step
  36. return calculateTrainSize(train, steps + 1)
  37. }
  38.  
  39. class Train(private val size: Int) {
  40. init {
  41. if (size<1)
  42. throw IllegalArgumentException("Argument size must be >=1, otherwise the task doesn't make sense")
  43. }
  44.  
  45. //Array of train switches with random initial state
  46. private val trainSwitches = BooleanArray(size).map { Random.nextBoolean() }.toMutableList()
  47. // Current position in the train, initial value generated randomly
  48. var position: Int = (0 until size).random()
  49.  
  50. fun setSwitchState(isOn: Boolean) {
  51. trainSwitches[position] = isOn
  52. }
  53.  
  54. fun getSwitchState(): Boolean {
  55. return trainSwitches[position]
  56. }
  57.  
  58. fun moveLeft(): Int {
  59. if (--position < 0)
  60. position = size-1
  61. return position
  62. }
  63.  
  64. fun moveRight(): Int {
  65. if (++position >= size)
  66. position = 0
  67. return position
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement