Determine if an Array contains something other than 2

Take an array which consists of numbers or arrays, output if it only contains 2s.

Output should be a truthy or falsey value (Sorry if this destroys answers)


[2,2]
[,[2,2],2]
[]
[[],[]]

Falsey Test Cases



[2,2,2,1]
[[1,2],2]

Standard Loopholes Are forbidden.

Default IO rules apply.

Code-golf, Fewest bytes wins!

• Can we take in a string representing the array? May 13 '17 at 7:42
• Will there be objects other than numbers and other arrays in the arrays May 13 '17 at 7:43
• There will only be arrays and numbers, and a string representing the array is fine. May 13 '17 at 7:44
• What kind of numbers? Compex int, compex float, float int, int , not negative?
– user58988
May 14 '17 at 13:53
• FTR and in the name of proper mathematical thinking: the array [] does not contain a two. May 15 '17 at 11:08

Python 2, 43 40 bytes

f=lambda l:l>=[]and all(map(f,l))or l==2

Try it online!

At time of posting this answer, it was still allowed per this meta consensus to output via throwing an error / not throwing an error. Therefore this answer at 26 bytes was valid:

f=lambda l:l==2or map(f,l)

Try it online!

• That's a neat way to check whether an element is a list. May 13 '17 at 8:09
• This is why I don't like that consensus. It really ruins python golfing. May 13 '17 at 8:36
• However since you are going by exit code you don't need the all, anything other than an error is truthy. May 13 '17 at 8:39

Prolog (SWI), 43 33 bytes

I smell... recursion.

Thanks to Emigna and Leaky Nun for saving 10 bytes!

Code

a([]).
a([X|T]):-(X=2;a(X)),a(T).

Explanation:

For non-Prolog users, a list is formatted in the following way: [Head | Tail].

The Head is the first element of the list, and tail is the remaining list. Test it here!. An important case here is that the tail of a list with 1 element is equal to []. You can test that here.

% State that an empty array is truthy.
a([]).

% If the list is not empty (covered by the previous line), we need to check
% whether the Head is equal to 2 or whether the head is truthy.
% After that, we only need to check if the remaining list is truthy.

Jelly, 4 bytes

F;2E

Try it online!

How it works

F;2E
F    flatten
;2  append 2
E all elements are equal

Octave, 13 bytes

@(x)~any(x-2)

Verify all test cases.

This is an anonymous function taking one input argument, x. It subtracts 2 from all elements, checks if there are any non-zero elements. It negates the output to get true for cases where all values are zero.

This works because x-2 works for matrices of all sizes, including the empty matrix, [].

x-2 would be sufficient if there couldn't be empty matrices in the input.

MATL, 3 bytes

2=p

Try it online!

Technically, this could just be

2=

Since an array containing any zero elements is falsy, but this seems cheap.

• A list containing 0 is falsy? Oh man. May 13 '17 at 8:18
• I don't think the 2-byte version is valid, since in the comments ATaco said that a unique output pair is valid. May 13 '17 at 8:22
• I believe 2= fails for empty matrices, or? May 13 '17 at 8:34
• @stewiegriffin That seems like a strange edge case to need to handle, but conveniently it does work: Try it online! May 13 '17 at 8:36
• Yes, 2=p works fine. The shorter version in the end, 2=, doesn't. Also, "the strange edge cases" are two of the test cases. :-) May 13 '17 at 8:38

Mathics, 28 bytes

Select[Flatten@#,#!=2&]=={}&

Try it online!

• I think that the input {0} is allowed; that would result in a false positive. May 13 '17 at 7:48

Retina, 13 10 bytes

Thanks to Kritixi Lithos for saving 3 bytes.

\W|\b2

^$Try it online! 05AB1E, 4 bytes ˜YQP Try it online! Explanation ˜ # flatten list YQ # check each element for equality to 2 P # product of list • Why wouldn't 2 work instead of Y? May 13 '17 at 9:26 • @EriktheOutgolfer: 2 works as well. I just like the fact that there are no numbers in it :) May 13 '17 at 9:26 JavaScript (ES6), 221923 22 bytes a=>!/[^2,]|22/.test(a) Test it f= a=>!/[^2,]|22/.test(a) console.log(" "+f()+": "+JSON.stringify()) console.log(" "+f([2,2])+": "+JSON.stringify([2,2])) console.log(" "+f([,[2,2],2])+": "+JSON.stringify([,[2,2],2])) console.log(" "+f([])+": "+JSON.stringify([])) console.log(" "+f([[],[]])+": "+JSON.stringify([[],[]])) console.log(f()+": "+JSON.stringify()) console.log(f()+": "+JSON.stringify()) console.log(f([2,2,2,1])+": "+JSON.stringify([2,2,2,1])) console.log(f([[1,2],2])+": "+JSON.stringify([[1,2],2])) • Nice one! I wonder if it could be shortened some more, but I doubt it. May 13 '17 at 8:33 • Thanks, @Arnauld; still haven't figured out a way to improve on it. May 13 '17 at 18:23 Mathematica, 15 bytes FreeQ[x_/;x!=2] It also works in Mathics. Try it online! APL (Dyalog), 5 bytes ∧/2=∊ Try it online! Explanation ∧/ Only 2= 2s are equal to ∊ any of the elements in the enlisted form of the right argument Mathematica, 24 bytes Cases[t=Flatten@#,2]==t& Pure function returning True or False. After Flattening the nested array and calling it t, Cases[t,2] returns the list of elements that match the "pattern" 2, and ==t checks whether that's the whole list. Mathematica, 29 bytes (#//.{2->{},{{}..}->{}})=={}& Not as short, but more fun. Starting from the input #, two replacement rules are applied until the result stops changing (//.): first, all 2s are replaced by {}s; and then any list whose entries are all empty sets ({{}..}) are replaced (repeatedly) by empty sets. If the rest is an empty set (=={}), we win. • Outgolfed, but I still really want to know what is being done here. May 13 '17 at 7:55 Haskell, 36 bytes An anonymous function, takes a String and returns a Bool. Use as (all((==2).fst).(reads=<<).scanr(:)[]) "[2,2,2,1]" all((==2).fst).(reads=<<).scanr(:)[] Try it online! How it works • Haskell doesn't have builtin mixed-type lists, so we take a string as argument. • scanr(:)[] generates a list of all suffixes of the string. • (reads=<<) tries to parse a number at the beginning of each suffix, combining the successes into a list of tuples (n,restOfString). • all((==2).fst) checks if all the parsed numbers are 2. • How about just not.all(elem"2,[]")? – zbw May 14 '17 at 19:42 • @zbw That fails because of numbers like 22. May 14 '17 at 22:37 Python 2, 38 bytes lambda l:l.strip('[],2')==l*('22'in l) Try it online! Takes in a string without spaces, outputs a bool. Checks if removing all the characters '[],2' of l gives the empty string. Also checks that 22 is not a substring -- if it is, the input l is used in place of the empty string to compare to the result of removal, and that always fails. Ruby, 2823 22 bytes - 5 bytes saved by G B ->x{x.flatten-==[]} Despite "flatten" being really long, it's still shorter than regex based solutions or recursive stuff that has to rescue errors in the base case. Ruby's built-in conflation of sets and arrays, however, is amazingly useful sometimes. • x.flatten.uniq== May 14 '17 at 14:04 • @NickM - that won't work on test cases like [] or [[],[]]. [2,*x].flatten.uniq== is slightly longer May 14 '17 at 15:04 • x.flatten|== would be shorter. – G B May 16 '17 at 8:11 • @GB and x.flatten-==[] is shorter still. Thanks for the tip! May 16 '17 at 13:19 • And yet regex wins: codegolf.stackexchange.com/a/120781/18535 :-) – G B May 16 '17 at 13:24 JavaScript (ES6), 26 bytes f=a=>a.map?a.every(f):a==2 Test cases f=a=>a.map?a.every(f):a==2 console.log(f()) console.log(f([2,2])) console.log(f([,[2,2],2])) console.log(f([])) console.log(f([[],[]])) console.log(f()) console.log(f()) console.log(f([2,2,2,1])) console.log(f([[1,2],2])) • You need to count f= because you referred to it. May 13 '17 at 7:58 • @LeakyNun Indeed. Fixed. May 13 '17 at 8:00 MATL, 4 bytes 2-a~ Try it online! Breakdown: % Implicit input 2- % Push 2 to the stack, and subtract from input a % Any non-zero elements? ~ % Negate to get true for cases where all elements are zero. Well, outgolfed. But I'm keeping this, since I'm quite happy I managed this all on my own (even though the task is super simple). R, 28 bytes function(x)!any(unlist(x)-2) unlist(x) turns a (nested) list into a vector. Then 2 is subtracted from that vector. any converts (with a warning) numeric to logical and checks if there are any TRUEs. This is inverted with ! and output. This works with nested lists because unlist by default works recursively to unlist all list entries of the initial list. This also works with empty lists, because unlist(list()) becomes numeric(), an empty numerical vector. Coercion by any makes it logical(), which is interpreted as FALSE by any, and then reversed to TRUE by !. • pryr::f(!any(unlist(x)-2)) saves a couple of bytes. – BLT May 15 '17 at 14:36 • this is the same length as all(unlist(x)==2) as well. May 15 '17 at 15:29 • or you could also say any(unlist(x)-2) which returns a consistent TRUE if there is a non-2 value in the flattened array and a consistent FALSE if all the values are 2... May 15 '17 at 16:41 • @Giuseppe Not sure if TRUE counts as falsey though :/ – JAD May 15 '17 at 18:53 • well, there's still not a consensus on meta, but codegolf.meta.stackexchange.com/a/2192/67312 May 15 '17 at 19:48 Python 3, 55 bytes No cheating. Uses nested list as input. f=lambda a:all(type(x)!=int and f(x)for x in a if x!=2) Try it online! • -1 byte: int!=type(x)and – user45941 May 17 '17 at 22:14 Jelly, 4 bytes F=2Ạ Try it online! Slightly different than Leaky's algorithm. Explanation: F=2Ạ F Flatten =2 Check if equal to 2 (vectorizes) Ạ Check if there isn't any falsey value Retina, 14 11 bytes ^(\W|2\b)+$

Try it online!

• \W doesn't seem such a good criteria : 2.2 is a number that isn't 2, yet I suppose it would match May 15 '17 at 14:12
• @Aaron I have just asked the OP on whether the array can containing decimal numbers. If they state that floating-point numbers will be present in the array, I will change my submission. May 15 '17 at 14:15
• Yeah, I see RosLup asked the same question yesterday and hasn't got an answer yet. I hope OP will come soon to clarify ! May 15 '17 at 14:16

05AB1E, 4 bytes

2‚˜Ë

Try it online!

JavaScript (ES6), 5350 48 bytes

_=>(_+"").split,.map(c=>!c?2:c).every(c=>c==2)

Saved 5 bytes, thanks to @Shaggy!

Test Cases :

let f =

_=>(_+"").split,.map(c=>!c?2:c).every(c=>c==2)

console.log(f())
console.log(f([2,2]))
console.log(f([,[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))

console.log(f())
console.log(f())
console.log(f([2,2,2,1]))
console.log(f([[1,2],2]))

• f([]) and f([[],[]]) should be truthy May 13 '17 at 7:46
• @Arnauld Is it correct now? May 13 '17 at 7:53
• I think so. :-) May 13 '17 at 7:55
• Think you can save a couple of bytes with !c instead of c=="". May 13 '17 at 8:03
• @Arnauld Thanks for pointing that out. This challenge was actually posted as a CMC in the Nineteenth byte. That CMC did not have anything to say regarding [[],[]] etc kind of test cases. When the challenge got posted on the main site, I quickly added my solution (It even asked me CAPTCHA!) without looking at rules! Thanks once again! :) May 13 '17 at 8:05

05AB1E, 7 bytes

˜DOsg·Q
˜D      # Flatten and duplicate
O     # Sum one copy
sg·  # Get double the length of the other copy
Q # Check if they are equal

Java 8, 12655 27 bytes

s->s.matches("(\\W|2\\b)+")

Port of @KritixiLithos's amazing Retina answer, excluding the ^...$, since String#matches always matches the entire String and adds the ^...$ implicitly.

-2 bytes thanks to @Jakob for reminding me of ^...$isn't necessary for String#matches. Try it here. • I hate to nullify all your work on the list solution, but couldn't you coerce to a string and use the string solution? Aug 25 '17 at 15:45 • @Jakob You mean in the explanation? I am using a regex String solution at the moment. I've just kept my original List answer and it's explanation, because the String solution is a port. Are you asking to just remove the List solution? Or add an explanation for the String solution? Aug 26 '17 at 16:36 • I mean that as long as you have a list solution you might as well shorten it by using the string solution in it. Like boolean c(java.util.List l){return(l+"").matches("^(\\W|2\\b)+$");} would work, right? Just wanted to point that out in case you were planning to further golf the list solution. Aug 26 '17 at 18:39
• Oh and you can lose 2 bytes by removing ^ and $in the regex, since String.matches only tests against the whole string. Aug 26 '17 at 18:46 • @Jakob Removed the List answer entirely, converted to Java 8, and removed the ^...$. Forgot about that, even though I've used it quite a lot of times in the past.. Aug 26 '17 at 19:52

Python 2, 4443 42 bytes

Takes x as the string representation of the list. This also assumes like in the example the representations have no spaces.

lambda x:set(x)<=set("[],2"*0**("22"in x))

Try it online!

Explanation

Both of these take the characters in the string representation of the input and determine if any characters other than [], 2 are in it. They do this by casting to a set and comparing to the set of just those characters. However this fails if we have a number other than 2 which has only digits of 2 (e.g. 22 or 222), in order to patch this case we multiply the string used to create the set by the negation of whether or not x contains "22". If it contains it this will be the empty set, otherwise it will be the same as before.

• May 13 '17 at 7:48
• Fails for  May 13 '17 at 7:51
• @LeakyNun Fixed May 13 '17 at 8:00
• @LeakyNun Your suggestion fails for [] May 13 '17 at 8:10
• lambda x:set(x)<=set("[],2"*-~-("22"in x)) for -1
– ovs
May 13 '17 at 8:31

Ohm, 6 bytes

∙e]Å2N

Uses CP-437 encoding.

Explanation:

∙e]Å2E
∙e           ■Evaluate the input to form an array
Å         ■any(              ,             )
]          ■    flatten(input)
2N       ■                   lambda x:x!=2
■implict end of any and print

PHP, 46 bytes

<?=!preg_match('/:"(?!2")/',serialize($_GET)); • @JörgHülsermann Could you please give an example? All the test cases seem to work. If you test it not through a browser, do you pass scalar values of$_GET as strings? May 14 '17 at 16:00

PHP<7.0, 42 Bytes

use the deprecated function ereg

<?=!ereg("22|[013-9]",json_encode($_GET)); PHP, 50 Bytes prints 1 for true and nothing for false -1 Byte for other wise remove ! or + 1 Byte for true 1, false 0 add + before ! <?=!preg_match('#22|[013-9]#',json_encode($_GET));

Try it online!

• You don't need the $r variable: <?array_walk_recursive($_GET,function($i){$i-2&&die;})?>1. May 14 '17 at 13:48

Pyth, 6 bytes

!-.nQ2

Very similar to my CJam answer. I'm still new to Pyth, so please tell me if there's anything I can golf off.

Explanation:

Q   Input:     [[[], ], ]
.n    Flatten:   [2, 1]
-   2  Remove 2s: 
!       Not:       False