21
\$\begingroup\$

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,2],2]
[]
[[],[]]

Falsey Test Cases

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

Standard Loopholes Are forbidden.

Default IO rules apply.

Code-golf, Fewest bytes wins!

\$\endgroup\$
19
  • \$\begingroup\$ Can we take in a string representing the array? \$\endgroup\$
    – Wheat Wizard
    Commented May 13, 2017 at 7:42
  • \$\begingroup\$ Will there be objects other than numbers and other arrays in the arrays \$\endgroup\$
    – Wheat Wizard
    Commented May 13, 2017 at 7:43
  • 2
    \$\begingroup\$ What kind of numbers? Compex int, compex float, float int, int , not negative? \$\endgroup\$
    – user58988
    Commented May 14, 2017 at 13:53
  • 2
    \$\begingroup\$ FTR and in the name of proper mathematical thinking: the array [[2]] does not contain a two. \$\endgroup\$ Commented May 15, 2017 at 11:08
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – ATaco
    Commented Feb 20, 2023 at 21:46

56 Answers 56

16
\$\begingroup\$

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!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ That's a neat way to check whether an element is a list. \$\endgroup\$
    – Adnan
    Commented May 13, 2017 at 8:09
  • \$\begingroup\$ This is why I don't like that consensus. It really ruins python golfing. \$\endgroup\$
    – Wheat Wizard
    Commented May 13, 2017 at 8:36
  • \$\begingroup\$ However since you are going by exit code you don't need the all, anything other than an error is truthy. \$\endgroup\$
    – Wheat Wizard
    Commented May 13, 2017 at 8:39
11
\$\begingroup\$

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).

Try it online! or Verify all test cases!

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.
a([Head | Tail]) :- (Head = 2; a(Head)), a(Tail).
\$\endgroup\$
0
10
\$\begingroup\$

Jelly, 4 bytes

F;2E

Try it online!

How it works

F;2E
F    flatten
 ;2  append 2
   E all elements are equal
\$\endgroup\$
9
\$\begingroup\$

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.

\$\endgroup\$
0
8
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ A list containing 0 is falsy? Oh man. \$\endgroup\$ Commented May 13, 2017 at 8:18
  • \$\begingroup\$ I don't think the 2-byte version is valid, since in the comments ATaco said that a unique output pair is valid. \$\endgroup\$ Commented May 13, 2017 at 8:22
  • \$\begingroup\$ I believe 2= fails for empty matrices, or? \$\endgroup\$ Commented May 13, 2017 at 8:34
  • \$\begingroup\$ @stewiegriffin That seems like a strange edge case to need to handle, but conveniently it does work: Try it online! \$\endgroup\$
    – DJMcMayhem
    Commented May 13, 2017 at 8:36
  • \$\begingroup\$ 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. :-) \$\endgroup\$ Commented May 13, 2017 at 8:38
7
\$\begingroup\$

Mathics, 28 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ I think that the input {0} is allowed; that would result in a false positive. \$\endgroup\$ Commented May 13, 2017 at 7:48
6
\$\begingroup\$

Retina, 13 10 bytes

Thanks to Kritixi Lithos for saving 3 bytes.

\W|\b2

^$

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Seems to fail for lists that contain -2. \$\endgroup\$ Commented Feb 20, 2023 at 15:57
6
\$\begingroup\$

05AB1E, 4 bytes

˜YQP

Try it online!

Explanation

˜      # flatten list
 YQ    # check each element for equality to 2
   P   # product of list
\$\endgroup\$
2
  • \$\begingroup\$ Why wouldn't 2 work instead of Y? \$\endgroup\$ Commented May 13, 2017 at 9:26
  • \$\begingroup\$ @EriktheOutgolfer: 2 works as well. I just like the fact that there are no numbers in it :) \$\endgroup\$
    – Emigna
    Commented May 13, 2017 at 9:26
6
\$\begingroup\$

JavaScript (ES6), 22 19 23 22 bytes

a=>!/[^2,]|22/.test(a)

Test it

f=
a=>!/[^2,]|22/.test(a)
console.log(" "+f([2])+": "+JSON.stringify([2]))
console.log(" "+f([2,2])+": "+JSON.stringify([2,2]))
console.log(" "+f([[2],[2,2],2])+": "+JSON.stringify([[2],[2,2],2]))
console.log(" "+f([])+": "+JSON.stringify([]))
console.log(" "+f([[],[]])+": "+JSON.stringify([[],[]]))
console.log(f([1])+": "+JSON.stringify([1]))
console.log(f([22])+": "+JSON.stringify([22]))
console.log(f([2,2,2,1])+": "+JSON.stringify([2,2,2,1]))
console.log(f([[1,2],2])+": "+JSON.stringify([[1,2],2]))

\$\endgroup\$
2
  • \$\begingroup\$ Nice one! I wonder if it could be shortened some more, but I doubt it. \$\endgroup\$
    – Arnauld
    Commented May 13, 2017 at 8:33
  • \$\begingroup\$ Thanks, @Arnauld; still haven't figured out a way to improve on it. \$\endgroup\$
    – Shaggy
    Commented May 13, 2017 at 18:23
5
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

Mathematica, 15 bytes

FreeQ[x_/;x!=2]

It also works in Mathics. Try it online!

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Outgolfed, but I still really want to know what is being done here. \$\endgroup\$
    – Pavel
    Commented May 13, 2017 at 7:55
4
\$\begingroup\$

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.
\$\endgroup\$
2
  • \$\begingroup\$ How about just not.all(`elem`"2,[]")? \$\endgroup\$
    – zbw
    Commented May 14, 2017 at 19:42
  • \$\begingroup\$ @zbw That fails because of numbers like 22. \$\endgroup\$ Commented May 14, 2017 at 22:37
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

Ruby, 28 23 22 bytes - 5 bytes saved by G B

->x{x.flatten-[2]==[]}

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.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ x.flatten.uniq==[2] \$\endgroup\$
    – Nick M
    Commented May 14, 2017 at 14:04
  • 1
    \$\begingroup\$ @NickM - that won't work on test cases like [] or [[],[]]. [2,*x].flatten.uniq==[2] is slightly longer \$\endgroup\$
    – ymbirtt
    Commented May 14, 2017 at 15:04
  • 1
    \$\begingroup\$ x.flatten|[2]==[2] would be shorter. \$\endgroup\$
    – G B
    Commented May 16, 2017 at 8:11
  • \$\begingroup\$ @GB and x.flatten-[2]==[] is shorter still. Thanks for the tip! \$\endgroup\$
    – ymbirtt
    Commented May 16, 2017 at 13:19
  • 1
    \$\begingroup\$ And yet regex wins: codegolf.stackexchange.com/a/120781/18535 :-) \$\endgroup\$
    – G B
    Commented May 16, 2017 at 13:24
3
\$\begingroup\$

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([2]))
console.log(f([2,2]))
console.log(f([[2],[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))

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

\$\endgroup\$
2
  • \$\begingroup\$ You need to count f= because you referred to it. \$\endgroup\$
    – Leaky Nun
    Commented May 13, 2017 at 7:58
  • \$\begingroup\$ @LeakyNun Indeed. Fixed. \$\endgroup\$
    – Arnauld
    Commented May 13, 2017 at 8:00
3
\$\begingroup\$

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).

\$\endgroup\$
3
\$\begingroup\$

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 !.

\$\endgroup\$
11
  • 1
    \$\begingroup\$ pryr::f(!any(unlist(x)-2)) saves a couple of bytes. \$\endgroup\$
    – BLT
    Commented May 15, 2017 at 14:36
  • \$\begingroup\$ this is the same length as all(unlist(x)==2) as well. \$\endgroup\$
    – Giuseppe
    Commented May 15, 2017 at 15:29
  • \$\begingroup\$ 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... \$\endgroup\$
    – Giuseppe
    Commented May 15, 2017 at 16:41
  • 1
    \$\begingroup\$ @Giuseppe Not sure if TRUE counts as falsey though :/ \$\endgroup\$
    – JAD
    Commented May 15, 2017 at 18:53
  • 1
    \$\begingroup\$ well, there's still not a consensus on meta, but codegolf.meta.stackexchange.com/a/2192/67312 \$\endgroup\$
    – Giuseppe
    Commented May 15, 2017 at 19:48
2
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ -1 byte: int!=type(x)and \$\endgroup\$
    – user45941
    Commented May 17, 2017 at 22:14
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Retina, 14 11 bytes

^(\W|2\b)+$

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ \W doesn't seem such a good criteria : 2.2 is a number that isn't 2, yet I suppose it would match \$\endgroup\$
    – Aaron
    Commented May 15, 2017 at 14:12
  • \$\begingroup\$ @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. \$\endgroup\$
    – user41805
    Commented May 15, 2017 at 14:15
  • \$\begingroup\$ Yeah, I see RosLup asked the same question yesterday and hasn't got an answer yet. I hope OP will come soon to clarify ! \$\endgroup\$
    – Aaron
    Commented May 15, 2017 at 14:16
2
\$\begingroup\$

05AB1E, 4 bytes

2‚˜Ë

Try it online!

\$\endgroup\$
0
2
\$\begingroup\$

JavaScript (ES6), 53 50 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([2]))
console.log(f([2,2]))
console.log(f([[2],[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))

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

\$\endgroup\$
10
  • \$\begingroup\$ f([]) and f([[],[]]) should be truthy \$\endgroup\$
    – Arnauld
    Commented May 13, 2017 at 7:46
  • \$\begingroup\$ @Arnauld Is it correct now? \$\endgroup\$
    – Arjun
    Commented May 13, 2017 at 7:53
  • \$\begingroup\$ I think so. :-) \$\endgroup\$
    – Arnauld
    Commented May 13, 2017 at 7:55
  • \$\begingroup\$ Think you can save a couple of bytes with !c instead of c=="". \$\endgroup\$
    – Shaggy
    Commented May 13, 2017 at 8:03
  • \$\begingroup\$ @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! :) \$\endgroup\$
    – Arjun
    Commented May 13, 2017 at 8:05
2
\$\begingroup\$

05AB1E, 7 bytes

˜DOsg·Q

Try it online! or Try All Tests!

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

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!

\$\endgroup\$
1
  • \$\begingroup\$ Curses! Nice work. What's this x*?!!~ construct? \$\endgroup\$
    – ymbirtt
    Commented May 16, 2017 at 13:28
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

Java 8, 126 55 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.

\$\endgroup\$
5
  • \$\begingroup\$ I hate to nullify all your work on the list solution, but couldn't you coerce to a string and use the string solution? \$\endgroup\$
    – Jakob
    Commented Aug 25, 2017 at 15:45
  • \$\begingroup\$ @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? \$\endgroup\$ Commented Aug 26, 2017 at 16:36
  • \$\begingroup\$ 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. \$\endgroup\$
    – Jakob
    Commented Aug 26, 2017 at 18:39
  • 1
    \$\begingroup\$ Oh and you can lose 2 bytes by removing ^ and $ in the regex, since String.matches only tests against the whole string. \$\endgroup\$
    – Jakob
    Commented Aug 26, 2017 at 18:46
  • \$\begingroup\$ @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.. \$\endgroup\$ Commented Aug 26, 2017 at 19:52
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Nekomata + -e, 3 bytes

2-ž

Attempt This Online!

2-      Minus 2
  ž     Check if all elements are zero
\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 13 10 bytes

2#2&

Try it online!

is \[VectorLessEqual].

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.