41
2
Alternating Arrays
An alternating array is a list of any length in which two (not necessarily different) values are alternating. That is to say, all even-indexed items are equal, and all odd-indexed items are equal.
Your task is to write a program or function which, when given a list of positive integers, outputs/returns truthy
if it is alternating and falsy
otherwise.
This is code-golf, so the shortest code (in bytes) wins!
Edge Cases:
[] -> True
[1] -> True
[1,1] -> True
[1,2,1] -> True
Other Test Cases:
[1,2,1,2] -> True
[3,4,3] -> True
[10,5,10,5,10] -> True
[10,11] -> True
[9,9,9,9,9] -> True
[5,4,3,5,4,3] -> False
[3,2,1,2,1,2] -> False
[1,2,1,2,1,1,2] -> False
[2,2,3,3] -> False
[2,3,3,2] -> False
Example
Here is an example you can test your solution against, written in Python 3 (not golfed):
def is_alternating(array):
for i in range(len(array)):
if array[i] != array[i%2]:
return False
return True
What are the possible values of the elements of the array? – Robert Hickman – 2016-12-19T21:06:31.787
@RobertHickman a list of positive integers, within your language's standard int size – FlipTack – 2016-12-19T21:12:16.943
oh I see that in the question now. Oops and thanks. – Robert Hickman – 2016-12-19T21:12:54.620