20
\$\begingroup\$

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)

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\$
  • \$\begingroup\$ Can we take in a string representing the array? \$\endgroup\$ – Sriotchilism O'Zaic May 13 '17 at 7:42
  • \$\begingroup\$ Will there be objects other than numbers and other arrays in the arrays \$\endgroup\$ – Sriotchilism O'Zaic May 13 '17 at 7:43
  • \$\begingroup\$ There will only be arrays and numbers, and a string representing the array is fine. \$\endgroup\$ – ATaco May 13 '17 at 7:44
  • 2
    \$\begingroup\$ What kind of numbers? Compex int, compex float, float int, int , not negative? \$\endgroup\$ – RosLuP May 14 '17 at 13:53
  • 1
    \$\begingroup\$ FTR and in the name of proper mathematical thinking: the array [[2]] does not contain a two. \$\endgroup\$ – ceased to turn counterclockwis May 15 '17 at 11:08

45 Answers 45

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\$
  • \$\begingroup\$ A list containing 0 is falsy? Oh man. \$\endgroup\$ – Erik the Outgolfer May 13 '17 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\$ – Erik the Outgolfer May 13 '17 at 8:22
  • \$\begingroup\$ I believe 2= fails for empty matrices, or? \$\endgroup\$ – Stewie Griffin May 13 '17 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 May 13 '17 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\$ – Stewie Griffin May 13 '17 at 8:38
15
\$\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\$
  • 1
    \$\begingroup\$ That's a neat way to check whether an element is a list. \$\endgroup\$ – Adnan May 13 '17 at 8:09
  • \$\begingroup\$ This is why I don't like that consensus. It really ruins python golfing. \$\endgroup\$ – Sriotchilism O'Zaic May 13 '17 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\$ – Sriotchilism O'Zaic May 13 '17 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\$
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\$
7
\$\begingroup\$

Mathics, 28 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I think that the input {0} is allowed; that would result in a false positive. \$\endgroup\$ – Greg Martin May 13 '17 at 7:48
6
\$\begingroup\$

Retina, 13 10 bytes

Thanks to Kritixi Lithos for saving 3 bytes.

\W|\b2

^$

Try it online!

\$\endgroup\$
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\$
  • \$\begingroup\$ Why wouldn't 2 work instead of Y? \$\endgroup\$ – Erik the Outgolfer May 13 '17 at 9:26
  • \$\begingroup\$ @EriktheOutgolfer: 2 works as well. I just like the fact that there are no numbers in it :) \$\endgroup\$ – Emigna May 13 '17 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\$
  • \$\begingroup\$ Nice one! I wonder if it could be shortened some more, but I doubt it. \$\endgroup\$ – Arnauld May 13 '17 at 8:33
  • \$\begingroup\$ Thanks, @Arnauld; still haven't figured out a way to improve on it. \$\endgroup\$ – Shaggy May 13 '17 at 18:23
5
\$\begingroup\$

Mathematica, 15 bytes

FreeQ[x_/;x!=2]

It also works in Mathics. Try it online!

\$\endgroup\$
4
\$\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\$
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\$
  • \$\begingroup\$ Outgolfed, but I still really want to know what is being done here. \$\endgroup\$ – Pavel May 13 '17 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\$
  • \$\begingroup\$ How about just not.all(`elem`"2,[]")? \$\endgroup\$ – zbw May 14 '17 at 19:42
  • \$\begingroup\$ @zbw That fails because of numbers like 22. \$\endgroup\$ – Ørjan Johansen May 14 '17 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\$
  • 1
    \$\begingroup\$ x.flatten.uniq==[2] \$\endgroup\$ – Nick M May 14 '17 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 May 14 '17 at 15:04
  • 1
    \$\begingroup\$ x.flatten|[2]==[2] would be shorter. \$\endgroup\$ – G B May 16 '17 at 8:11
  • \$\begingroup\$ @GB and x.flatten-[2]==[] is shorter still. Thanks for the tip! \$\endgroup\$ – ymbirtt May 16 '17 at 13:19
  • 1
    \$\begingroup\$ And yet regex wins: codegolf.stackexchange.com/a/120781/18535 :-) \$\endgroup\$ – G B May 16 '17 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\$
  • \$\begingroup\$ You need to count f= because you referred to it. \$\endgroup\$ – Leaky Nun May 13 '17 at 7:58
  • \$\begingroup\$ @LeakyNun Indeed. Fixed. \$\endgroup\$ – Arnauld May 13 '17 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\$
  • 1
    \$\begingroup\$ pryr::f(!any(unlist(x)-2)) saves a couple of bytes. \$\endgroup\$ – BLT May 15 '17 at 14:36
  • \$\begingroup\$ this is the same length as all(unlist(x)==2) as well. \$\endgroup\$ – Giuseppe May 15 '17 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 May 15 '17 at 16:41
  • 1
    \$\begingroup\$ @Giuseppe Not sure if TRUE counts as falsey though :/ \$\endgroup\$ – JAD May 15 '17 at 18:53
  • 1
    \$\begingroup\$ well, there's still not a consensus on meta, but codegolf.meta.stackexchange.com/a/2192/67312 \$\endgroup\$ – Giuseppe May 15 '17 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\$
  • \$\begingroup\$ -1 byte: int!=type(x)and \$\endgroup\$ – Mego May 17 '17 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\$
  • \$\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 May 15 '17 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\$ – Cows quack May 15 '17 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 May 15 '17 at 14:16
2
\$\begingroup\$

05AB1E, 4 bytes

2‚˜Ë

Try it online!

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

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\$
  • \$\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 Aug 25 '17 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\$ – Kevin Cruijssen Aug 26 '17 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 Aug 26 '17 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 Aug 26 '17 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\$ – Kevin Cruijssen Aug 26 '17 at 19:52
1
\$\begingroup\$

Python 2, 44 43 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.

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

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

PHP, 46 bytes

<?=!preg_match('/:"(?!2")/',serialize($_GET));
\$\endgroup\$
  • \$\begingroup\$ @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? \$\endgroup\$ – user63956 May 14 '17 at 16:00
  • \$\begingroup\$ <?=!preg_match('/:"(?!2")/',$argn); and input is a string representation of the serialized array - 11 Bytes \$\endgroup\$ – Jörg Hülsermann May 14 '17 at 16:35
1
\$\begingroup\$

PHP<7.0, 29 Bytes

Input as as string array JSON encoded

<?=!ereg("22|[013-9]",$argn);

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!

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

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:     [[[], [2]], [1]]
  .n    Flatten:   [2, 1]
 -   2  Remove 2s: [1]
!       Not:       False
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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