#JavaScript (ES6), 80
JavaScript (ES6), 80
f=(l,k=[1])=>l+l==k+k||l[k.length]&&f(l,k.concat(k))|f(l,k.concat(k.map(v=>-v)))
Recursively builds and check each list up to the length of the input list, starting with [1]
.
Return value is JS truthy or falsey, specifically 1
or true
if valid, 0
or false
or undefined
if not valid.
Test
f=(l,k=[1])=>l+l==k+k||l[k.length]&&f(l,k.concat(k))|f(l,k.concat(k.map(v=>-v)))
test=`[] -> False
[1] -> True
[-1] -> False
[1, 1] -> True
[1, -1] -> True
[1, 1, 1, 1] -> True
[1, 1, 1, 1, 1] -> False
[1, -1, -1, 1, -1, 1, 1, -1] -> True
[1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1] -> False
[1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1] -> False
[1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1] -> True`
.split('\n')
test.forEach(r=>{
input = r.match(/-?1/g)||[]
check = r.slice(-4) == 'True'
result = f(input)
console.log(result, check, '['+input+']')
})