Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import kotlin.random.Random
- fun main() {
- for (size in 1..100){
- val train = Train(size)
- //Switch of the light at position, where we woke up
- train.setSwitchState(false)
- val calculatedSize=calculateTrainSize(train)
- println("$calculatedSize==$size")
- }
- }
- fun calculateTrainSize(train: Train, steps: Int = 1): Int {
- //Move left by the indicated value of steps and switch off the light
- repeat(steps) {train.moveLeft()}
- train.setSwitchState(false)
- //Move backward to the initial position and move right by the indicated values of steps and switch off the light
- repeat(steps*2) {train.moveRight()}
- train.setSwitchState(false)
- //Move left to the position where we previously switched off the light and switch on it is
- repeat(steps*2) {train.moveLeft()}
- train.setSwitchState(true)
- //Move right to the position where we previously switched off the light and checking if it was switched on
- repeat(steps * 2) {
- train.moveRight()
- //We can be sure that we switched off it earlier and if it is turned on then we walk in a circle
- if (train.getSwitchState())
- return it+1;
- }
- //Move back to switched on light and switch off it for next iteration
- repeat(steps * 2) { train.moveLeft() }
- train.setSwitchState(false)
- //Move to the position where we woke up
- repeat(steps) { train.moveRight() }
- //Try to move on one more step
- return calculateTrainSize(train, steps + 1)
- }
- class Train(private val size: Int) {
- init {
- if (size<1)
- throw IllegalArgumentException("Argument size must be >=1, otherwise the task doesn't make sense")
- }
- //Array of train switches with random initial state
- private val trainSwitches = BooleanArray(size).map { Random.nextBoolean() }.toMutableList()
- // Current position in the train, initial value generated randomly
- var position: Int = (0 until size).random()
- fun setSwitchState(isOn: Boolean) {
- trainSwitches[position] = isOn
- }
- fun getSwitchState(): Boolean {
- return trainSwitches[position]
- }
- fun moveLeft(): Int {
- if (--position < 0)
- position = size-1
- return position
- }
- fun moveRight(): Int {
- if (++position >= size)
- position = 0
- return position
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement