# Determine if an Array contains something other than 2

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

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

## Truthy Test Cases


[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, 2017 at 7:42
• Will there be objects other than numbers and other arrays in the arrays May 13, 2017 at 7:43
• What kind of numbers? Compex int, compex float, float int, int , not negative?
– user58988
May 14, 2017 at 13:53
• FTR and in the name of proper mathematical thinking: the array [] does not contain a two. May 15, 2017 at 11:08
• @KevinCruijssen Given the sheer number of answers that ignore the commented restriction (And the age of the challenge), I'd rather now state that answers needn't worry about numbers other than positive integers. I'll adjust the challenge description to specify this. Feb 20 at 21:46

# 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, 2017 at 8:09
• This is why I don't like that consensus. It really ruins python golfing. May 13, 2017 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, 2017 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, 2017 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, 2017 at 8:22
• I believe 2= fails for empty matrices, or? May 13, 2017 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, 2017 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, 2017 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, 2017 at 7:48

## Retina, 13 10 bytes

Thanks to Kritixi Lithos for saving 3 bytes.

\W|\b2

^$ Try it online! • Seems to fail for lists that contain -2. Feb 20 at 15:57 # 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, 2017 at 9:26 • @EriktheOutgolfer: 2 works as well. I just like the fact that there are no numbers in it :) May 13, 2017 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, 2017 at 8:33 • Thanks, @Arnauld; still haven't figured out a way to improve on it. May 13, 2017 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, 2017 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, 2017 at 19:42 • @zbw That fails because of numbers like 22. May 14, 2017 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, 2017 at 14:04 • @NickM - that won't work on test cases like [] or [[],[]]. [2,*x].flatten.uniq== is slightly longer May 14, 2017 at 15:04 • x.flatten|== would be shorter. – G B May 16, 2017 at 8:11 • @GB and x.flatten-==[] is shorter still. Thanks for the tip! May 16, 2017 at 13:19 • And yet regex wins: codegolf.stackexchange.com/a/120781/18535 :-) – G B May 16, 2017 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, 2017 at 7:58 • @LeakyNun Indeed. Fixed. May 13, 2017 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, 2017 at 14:36 • this is the same length as all(unlist(x)==2) as well. May 15, 2017 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, 2017 at 16:41 • @Giuseppe Not sure if TRUE counts as falsey though :/ – JAD May 15, 2017 at 18:53 • well, there's still not a consensus on meta, but codegolf.meta.stackexchange.com/a/2192/67312 May 15, 2017 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, 2017 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, 2017 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, 2017 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, 2017 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, 2017 at 7:46
• @Arnauld Is it correct now? May 13, 2017 at 7:53
• I think so. :-) May 13, 2017 at 7:55
• Think you can save a couple of bytes with !c instead of c=="". May 13, 2017 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, 2017 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


# Ruby, 21 bytes

->x{x*?!!~/[^2!]|22/}


Using a regex is actually shorter, because joining an array also flattens it.

## How it works

->x{
x*?!                -> Join array using an exclamation mark
!~              -> String does not contain
/[^2!]        -> characters different from '2' or '!'
|       -> or
22/    -> '2' repeated at least twice
}


Try it online!

• Curses! Nice work. What's this x*?!!~ construct? May 16, 2017 at 13:28

# Jelly, 3 bytes

2ṁ⁼


Try it online!

### How it works

2ṁ⁼  Main link. Argument: A (array)

2ṁ   Mold 2 like A. This replaces each number in A by 2.
⁼  Test if the result is equal to A.


# 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, 2017 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, 2017 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, 2017 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, 2017 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, 2017 at 19:52

# Thunno 2, 4 bytes

Ḟ2=p


Try it online!

#### Explanation

Ḟ2=p  # Implicit input
Ḟ     # Flatten the list
2=   # Check for == 2
p  # All are true?
# Implicit output


# Nekomata + -e, 3 bytes

2-ž


Attempt This Online!

2-      Minus 2
ž     Check if all elements are zero


# Wolfram Language (Mathematica), 13 10 bytes

2#2&


Try it online!

 is \[VectorLessEqual].