20
\$\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
    May 13, 2017 at 7:42
  • \$\begingroup\$ Will there be objects other than numbers and other arrays in the arrays \$\endgroup\$
    – Wheat Wizard
    May 13, 2017 at 7:43
  • 2
    \$\begingroup\$ What kind of numbers? Compex int, compex float, float int, int , not negative? \$\endgroup\$
    – user58988
    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\$ 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
    Feb 20 at 21:46

56 Answers 56

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.

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

PHP, 46 bytes

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

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You don't need the $r variable: <?array_walk_recursive($_GET,function($i){$i-2&&die;})?>1. \$\endgroup\$
    – user63956
    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
\$\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.

\$\endgroup\$
1
\$\begingroup\$

Kotlin, 90 bytes

Submission

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

TryItOnline

TryItOnline

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

Vyxal, 3 bytes

2J≈

Try it Online!

Append a 2, check if everything is equal

\$\endgroup\$
1
\$\begingroup\$

Raku, 13 bytes

*.flat.all==2

Try it online!

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

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

Perl 5, 26 bytes

25 bytes of code + 1 for -n

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

Try it online!

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

Pyth, 6 bytes

q]2{.n

Try it here!

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

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

Jelly, 3 4 bytes

F=2Ạ

Gained a byte because of a failed test case.

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ This fails on the [[1,2],2] test case. \$\endgroup\$ Aug 27, 2017 at 17:31
  • \$\begingroup\$ @ØrjanJohansen Fixed at the cost of one byte. \$\endgroup\$
    – clapp
    Aug 27, 2017 at 17:33
  • 1
    \$\begingroup\$ It is now a dupe of this: codegolf.stackexchange.com/a/120371/44874 \$\endgroup\$
    – steenbergh
    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
\$\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

\$\endgroup\$
2
  • \$\begingroup\$ This doesn't really do nested lists does it? It just seems to be space separated numbers \$\endgroup\$
    – Jo King
    Jul 10 at 5:04
  • \$\begingroup\$ True, Zsh only does 1-dimensional arrays/lists \$\endgroup\$
    – roblogic
    Jul 10 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
\$\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
\$\endgroup\$
0
\$\begingroup\$

Uiua, 8 bytes

/×⬚1/×=2

Try it!

/×⬚1/×=2
      =2  # where are elements equal to two?
  ⬚1/×    # multiply columns, filling missing elements with one
/×        # product
\$\endgroup\$
0
\$\begingroup\$

APL(Dyalog Unicode), 9 bytes SBCS

(⊢≡2⍴⍨≢)∊

Try it on APLgolf!

Alternatively, another 9-byte solution:

∧/'2 '∊⍨⍕

Try it on APLgolf!

\$\endgroup\$
1
2

Your Answer

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

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