Setup
A number (n) of lamps are placed in a line, some are switched on and some are off. Write a function that will return the smallest number of lamps that need to be switched on or off so that the line of lamps alternate.
You are given an array of 0s and 1s as input. 1 means on, 0 means off. Return the minimum number of switches needed.
Example
For a = [1, 0, 0, 1, 1, 1, 0]
, the result should be 3
.
1 0 0 1 1 1 0 --> 0 1 0 1 0 1 0
Tests
lamps([1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1]) lamps( [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) lamps([1, 0, 1]) lamps([1, 0, 1, 0]) lamps([0, 1, 0, 1, 0]) lamps([1, 0, 1, 0, 0, 1, 0, 1]) lamps([1,0,0,1,1,0,0,0,0,1,0])
Good luck, have fun!
This challenge comes from myjinxin2015 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (12)
A Common Lisp implementation 😊.
Correct solution:
This solution is wrong, I'll change it and put the new corrected one of the top. I misunderstood the problem statement the first time.
the first test shouldn't be 6?
1 0 0 1 0 1 0 0 1 0 1
0 1 0 1 0 1 0 1 0 1 0
(alternated)x x - - - - - x x x x
What I've understood from the problem statement is that both converting everything to 0s and converting everything to 1s are valid answers, and you need to choose the fastest one (less changes needed).
For the
1 0 0 1 0 1 0 0 1 0 1
Maybe I understood it wrong :( Definetely, I understood it wrong. I'll change it :D.
I don't know, i think that you understood it right your solution makes sense, the way that i imagine there is no way to get the "less changes needed" because i'll switch everything to see if it it's alternated
I though the solution was to count the number of changes to light everything on or off. But the idea is to find out the number of changes for alternate lights, so the solution there is wrong :(.
I just changed the original post to add the new solution.
Now that I read the comments, I think Kevin is right, but I understood it from the point of view of Rafael. But it makes sense since they need to alternate, not to start with 0 (switched off) everytime.
Rust:
Javascript
Python:
A variation on the javascript solution. Opted for a bit more verbosity for ease of understanding. Would love feedback as I get my coding skills back into shape.
Elm
Demo.
Standard ML of New Jersey