22
\$\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!

asked May 13, 2017 at 7:40
\$\endgroup\$
19
  • \$\begingroup\$ Can we take in a string representing the array? \$\endgroup\$ Commented May 13, 2017 at 7:42
  • \$\begingroup\$ Will there be objects other than numbers and other arrays in the arrays \$\endgroup\$ Commented May 13, 2017 at 7:43
  • 2
    \$\begingroup\$ What kind of numbers? Compex int, compex float, float int, int , not negative? \$\endgroup\$ 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\$ Commented Feb 20, 2023 at 21:46

58 Answers 58

1
2
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.

answered May 13, 2017 at 7:45
\$\endgroup\$
6
  • \$\begingroup\$ lambda x:set(x)==set("[], 2")? \$\endgroup\$ Commented May 13, 2017 at 7:48
  • \$\begingroup\$ Fails for [22] \$\endgroup\$ Commented May 13, 2017 at 7:51
  • \$\begingroup\$ @LeakyNun Fixed \$\endgroup\$ Commented May 13, 2017 at 8:00
  • \$\begingroup\$ @LeakyNun Your suggestion fails for [] \$\endgroup\$ Commented May 13, 2017 at 8:10
  • \$\begingroup\$ lambda x:set(x)<=set("[],2"*-~-("22"in x)) for -1 \$\endgroup\$ Commented May 13, 2017 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
answered May 14, 2017 at 10:41
\$\endgroup\$
1
\$\begingroup\$

PHP, 46 bytes

<?=!preg_match('/:"(?!2")/',serialize($_GET));
answered May 14, 2017 at 13:54
\$\endgroup\$
2
  • \$\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\$ Commented May 14, 2017 at 16:00
  • \$\begingroup\$ <?=!preg_match('/:"(?!2")/',$argn); and input is a string representation of the serialized array - 11 Bytes \$\endgroup\$ Commented May 14, 2017 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!

answered May 13, 2017 at 19:26
\$\endgroup\$
1
  • 2
    \$\begingroup\$ You don't need the $r variable: <?array_walk_recursive($_GET,function($i){$i-2&&die;})?>1. \$\endgroup\$ Commented May 14, 2017 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
answered May 15, 2017 at 1:44
\$\endgroup\$
1
\$\begingroup\$

Ruby 1.9+, 19 bytes

->x{x*$/!~/^2?+.$/}

Form is stolen from G B's answer. The main difference is that I join on a newline (the default value of $/), which lets me write a shorter regex by using the ^.$ special characters that have specific interactions with newlines.

The trick that makes this version-specific (1.9 and higher) is the use of the "possessive" quantifier 2?+. Like 2?, it'll match zero or one instances of a 2, but this form will hold onto that 2 forever and prevent it from being matched by the ., so a 2 on its own line won't match the overall regexp.

answered Aug 25, 2017 at 16:18
\$\endgroup\$
1
\$\begingroup\$

Kotlin, 90 bytes

Submission

fun r(i:String):Any{return i.replace(Regex("[\\[\\]2,]+"),"")==""&&!i.contains("22")}

TryItOnline

TryItOnline

answered Aug 27, 2017 at 18:21
\$\endgroup\$
1
\$\begingroup\$

Japt -!, (削除) 6 (削除ここまで) (削除) 5 (削除ここまで) 4 bytes

c dÍ

Try it

c dÍ :Implicit output of array
c :Flatten
 d :Any truthy (non-zero) when
 Í :Subtracted from 2
 :Implicit output of negation of result
answered May 19, 2017 at 10:37
\$\endgroup\$
1
\$\begingroup\$

Vyxal, 3 bytes

2J≈

Try it Online!

Append a 2, check if everything is equal

answered Feb 20, 2023 at 14:32
\$\endgroup\$
1
\$\begingroup\$

Raku, 13 bytes

*.flat.all==2

Try it online!

answered Jul 10, 2023 at 5:05
\$\endgroup\$
1
\$\begingroup\$

Uiua, 8 bytes

×ばつ=2

Try it!

×ばつ=2
 =2 # where are elements equal to two?
 ×ばつ # multiply columns, filling missing elements with one×ばつ # product
answered Nov 10, 2023 at 21:52
\$\endgroup\$
1
\$\begingroup\$

Setanta, 84 bytes

gniomh f(l){ma go_teacs(l)<"[" toradh l==2t:=1le i idir(0,fad@l)t=t&f(l[i])toradh t}

try-setanta.ie link

Alternate text substitution-based solution, 93 bytes

gniomh(l){l=go_teacs(l)le i idir(0,5)l=athchuir@l(["[2",", 2","[","]",","][i],"")toradh"!">l}

Turns out to be longer than the recursion-based solution, but I think this is neat.

try-setanta.ie link

answered Aug 7 at 19:33
\$\endgroup\$
0
\$\begingroup\$

Clojure, 21 or 25 bytes

#(every?(set"[]2 ")%)
#(every? #{2}(flatten %))

The first one takes the argument as string, second one as an actual nested list.

#{2} is the set with one element 2, calling it with an existing element returns it and for a non-existing it returns nil (falsy).

answered May 13, 2017 at 10:49
\$\endgroup\$
0
\$\begingroup\$

Axiom, 280 bytes

w(x:Union(List(Any),NNI)):Boolean==(x case List(Any)=>(g:List(Any):=x;leaf? g=>return true;for i in g repeat(q:=w(i);q=false=>return false);return true);r:NNI:=x;r=2=>true;false)
m(b:List Any):Boolean==(for i in b repeat(q:=w(i::Union(List(Any),NNI));q=false=>return false);true)

ungolfed and test

f(x:Union(List(Any),NNI)):Boolean==
 x case List(Any)=>
 g:List(Any):=x
 leaf? g =>return true
 for i in g repeat 
 q:=f(i)
 q=false => return false
 return true
 r:NNI:=x
 r=2=>true
 false
h(b:List Any):Boolean==
 for i in b repeat
 q:=f(i::Union(List(Any),NNI))
 q=false=> return false
 true
(5) -> [[i, m(i)] for i in [ [2],[2,2],[[2],[2,2],2],[],[[],[]] ] ]
 (5)
 [[[2],true],[[2,2],true],[[[2],[2,2],2],true],[[],true],[[[],[]],true]]
 Type: List List Any
(6) -> [[i, m(i)] for i in [ [1],[22],[2,2,2,1], [[1,2],2] ] ]
 (6) [[[1],false],[[22],false],[[2,2,2,1],false],[[[1,2],2],false]]
 Type: List List Any
answered May 14, 2017 at 17:55
\$\endgroup\$
0
\$\begingroup\$

CJam, 7 bytes

Input is in the form of a CJam array literal.

q~e_2-!

Explanation:

q e# Read input: | "[[1 2] 2]"
~ e# Eval: | [[1 2] 2]
e_ e# Flatten: | [1 2 2]
2- e# Remove 2s: | [1]
! e# Not: | 0
answered May 15, 2017 at 1:19
\$\endgroup\$
0
\$\begingroup\$

Actually, 10 bytes

⌠♂i⌡Y2#@-b

Try it online!

Explanation:

⌠♂i⌡Y2#@-b
⌠♂i⌡Y call the function until the result stops changing (fixed-point combinator):
 ♂i for each item: flatten
 2#@- set difference: all items that are not 2s
 b cast to boolean (1 if list is not empty, else 0)
answered May 15, 2017 at 21:13
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 26 bytes

25 bytes of code + 1 for -n

map$.&=$_==2,/\d+/g;say$.

Try it online!

answered Aug 25, 2017 at 23:06
\$\endgroup\$
0
\$\begingroup\$

TXR Lisp, 30 bytes

(opip flatten(all @1(op = 2)))

Run:

1> (opip flatten(all @1(op = 2)))
#<intrinsic fun: 0 param + variadic>
2> [*1 '()]
t
3> [*1 '(2)]
t
4> [*1 '(2 2 ())]
t
5> [*1 '(() ())]
t
6> [*1 '(() (1))]
nil
7> [*1 '((2) 1 ())]
nil
answered Aug 26, 2017 at 14:37
\$\endgroup\$
0
\$\begingroup\$

MY, 6 bytes

⎕ḟ2=Π←

Try it online!

How?

  • evaluated input
  • flatten
  • 2= element-wise equality with two
  • Π product
  • output with no newline
answered Aug 26, 2017 at 16:57
\$\endgroup\$
0
\$\begingroup\$

Pyth, 6 bytes

q]2{.n

Try it here!

answered Aug 27, 2017 at 8:35
\$\endgroup\$
0
\$\begingroup\$

Common Lisp, (削除) 68 (削除ここまで) 64 bytes

(defun n(l)(or(and(consp l)(n(car l))(n(cdr l)))(not l)(= l 2)))

Try it online!

answered Aug 27, 2017 at 8:20
\$\endgroup\$
0
\$\begingroup\$

Jelly, (削除) 3 (削除ここまで) 4 bytes

F=2Ạ

Gained a byte because of a failed test case.

Try it online!

answered Aug 27, 2017 at 15:23
\$\endgroup\$
3
  • \$\begingroup\$ This fails on the [[1,2],2] test case. \$\endgroup\$ Commented Aug 27, 2017 at 17:31
  • \$\begingroup\$ @ØrjanJohansen Fixed at the cost of one byte. \$\endgroup\$ Commented Aug 27, 2017 at 17:33
  • 1
    \$\begingroup\$ It is now a dupe of this: codegolf.stackexchange.com/a/120371/44874 \$\endgroup\$ Commented Aug 30, 2017 at 13:42
0
\$\begingroup\$

Arturo, 19 bytes

$=>[[]=--flatten&2]

Try it

$=>[ ; a function
 []= ; is the empty block equal to...
 --flatten&2 ; the input, flattened, with 2s removed?
] ; end function
answered Feb 19, 2023 at 22:04
\$\endgroup\$
0
\$\begingroup\$

Zsh, 9 bytes

<<<${@/2}

Try it online!

Falsey: output contains a number. Truthy: anything else (spaces or empty string). Link includes a test harness that prints T or F

answered Feb 20, 2023 at 10:10
\$\endgroup\$
2
  • \$\begingroup\$ This doesn't really do nested lists does it? It just seems to be space separated numbers \$\endgroup\$ Commented Jul 10, 2023 at 5:04
  • \$\begingroup\$ True, Zsh only does 1-dimensional arrays/lists \$\endgroup\$ Commented Jul 10, 2023 at 10:18
0
\$\begingroup\$

Pyt, 4 bytes

Ƒ2=Π

Try it online!

Ƒ implicit input; Ƒlatten array
 2= is each element equal to 2?
 Π product (returns 1 for empty array); implicit print
answered Feb 20, 2023 at 14:45
\$\endgroup\$
0
\$\begingroup\$

Fig, \3ドル\log_{256}(96)\approx\$ 2.469 bytes

r=2

Try it online!

r=2
 =2 # Is each element equal to 2?
r # Product
answered Feb 20, 2023 at 17:47
\$\endgroup\$
0
\$\begingroup\$

APL(Dyalog Unicode), (削除) (削除ここまで)9 bytes SBCS

(⊢≡2⍴⍨≢)∊

Try it on APLgolf!

Alternatively, another 9-byte solution:

∧/'2 '∊⍨⍕

Try it on APLgolf!

answered Nov 11, 2023 at 10:48
\$\endgroup\$
0
\$\begingroup\$

AWK, 13 bytes

!/[013-9]|22/

Attempt This Online!

Will print line back to you for truthy, or nothing for falsey.

answered Aug 7 at 15:37
\$\endgroup\$
1
2

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.