g | x | w | all
Bytes Lang Time Link
084Setanta250807T193300Zbb94
013AWK250807T153754Zxrs
009APLDyalog Unicode231111T104848ZKamila S
008Uiua231110T215219Zchunes
013Raku230710T050553ZJo King
010Wolfram Language Mathematica230710T031419Zatt
003Nekomata + e230710T021504Zalephalp
004Thunno 2230709T133922ZThe Thon
nanFig230220T174730ZSeggan
004Pyt230220T144557ZKip the
003Vyxal230220T143259Zpacman25
009Zsh230220T101006Zroblogic
004Japt !170519T103747ZShaggy
019Arturo230219T220453Zchunes
090Kotlin170827T182110Zjrtapsel
004Jelly170827T152316Zclapp
064Common Lisp170827T082006ZRenzo
006Pyth170827T083541ZMr. Xcod
027Java 8170516T075533ZKevin Cr
006MY170826T165747ZAdalynn
030TXR Lisp170826T143711ZKaz
026Perl 5170825T230607ZXcali
019Ruby 1.9+170825T161801Zhistocra
003Jelly170825T154350ZDennis
022JavaScript ES6170513T075123ZShaggy
021Ruby170516T080808ZG B
225Ruby170513T081113Zymbirtt
010Actually170515T211333Zuser4594
028R170515T093645ZJAD
00705AB1E170515T140531ZRiley
006Pyth170515T014442ZEsolangi
007CJam170515T011936ZEsolangi
280Axiom170514T175529Zuser5898
029PHP<7.0170513T192609ZJör
046PHP170514T135418Zuser6395
006Ohm170514T104100ZLinnea G
038Python 2170513T193052Zxnor
036Haskell170513T185150ZØrj
040Python 2170513T075845Zovs
048JavaScript ES6170513T074245ZArjun
2125Clojure170513T104927ZNikoNyrh
033Prolog SWI170513T082650ZAdnan
00405AB1E170513T092440ZEmigna
010Retina170513T075621ZMartin E
00405AB1E170513T081236ZErik the
011Retina170513T074935Zuser4180
004Jelly170513T085345ZErik the
013Octave170513T075645ZStewie G
042Python 2170513T074538ZWheat Wi
015Mathematica170513T081157Zalephalp
003MATL170513T080527ZDJMcMayh
024Mathematica170513T075347ZGreg Mar
004MATL170513T080606ZStewie G
026JavaScript ES6170513T075654ZArnauld
005APL Dyalog170513T075507Zuser4180
028Mathics170513T074508ZPavel
055Python 3170513T074812ZLeaky Nu
004Jelly170513T074226ZLeaky Nu

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

AWK, 13 bytes

!/[013-9]|22/

Attempt This Online!

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

APL(Dyalog Unicode), 9 bytes SBCS

(⊢≡2⍴⍨≢)∊

Try it on APLgolf!

Alternatively, another 9-byte solution:

∧/'2 '∊⍨⍕

Try it on APLgolf!

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

Raku, 13 bytes

*.flat.all==2

Try it online!

Wolfram Language (Mathematica), 13 10 bytes

2#2&

Try it online!

is \[VectorLessEqual].

Nekomata + -e, 3 bytes

2-ž

Attempt This Online!

2-      Minus 2
  ž     Check if all elements are zero

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

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

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

Vyxal, 3 bytes

2J≈

Try it Online!

Append a 2, check if everything is equal

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

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

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

Kotlin, 90 bytes

Submission

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

TryItOnline

TryItOnline

Jelly, 3 4 bytes

F=2Ạ

Gained a byte because of a failed test case.

Try it online!

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!

Pyth, 6 bytes

q]2{.n

Try it here!

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.

MY, 6 bytes

⎕ḟ2=Π←

Try it online!

How?

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

Perl 5, 26 bytes

25 bytes of code + 1 for -n

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

Try it online!

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.

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.

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

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!

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.

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)

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

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

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

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

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

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!

PHP, 46 bytes

<?=!preg_match('/:"(?!2")/',serialize($_GET));

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

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.

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

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!

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

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

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

05AB1E, 4 bytes

˜YQP

Try it online!

Explanation

˜      # flatten list
 YQ    # check each element for equality to 2
   P   # product of list

Retina, 13 10 bytes

Thanks to Kritixi Lithos for saving 3 bytes.

\W|\b2

^$

Try it online!

05AB1E, 4 bytes

2‚˜Ë

Try it online!

Retina, 14 11 bytes

^(\W|2\b)+$

Try it online!

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

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.

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.

Mathematica, 15 bytes

FreeQ[x_/;x!=2]

It also works in Mathics. Try it online!

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.

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.

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

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

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

Mathics, 28 bytes

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

Try it online!

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!

Jelly, 4 bytes

F;2E

Try it online!

How it works

F;2E
F    flatten
 ;2  append 2
   E all elements are equal