| Bytes | Lang | Time | Link |
|---|---|---|---|
| 084 | Setanta | 250807T193300Z | bb94 |
| 013 | AWK | 250807T153754Z | xrs |
| 009 | APLDyalog Unicode | 231111T104848Z | Kamila S |
| 008 | Uiua | 231110T215219Z | chunes |
| 013 | Raku | 230710T050553Z | Jo King |
| 010 | Wolfram Language Mathematica | 230710T031419Z | att |
| 003 | Nekomata + e | 230710T021504Z | alephalp |
| 004 | Thunno 2 | 230709T133922Z | The Thon |
| nan | Fig | 230220T174730Z | Seggan |
| 004 | Pyt | 230220T144557Z | Kip the |
| 003 | Vyxal | 230220T143259Z | pacman25 |
| 009 | Zsh | 230220T101006Z | roblogic |
| 004 | Japt ! | 170519T103747Z | Shaggy |
| 019 | Arturo | 230219T220453Z | chunes |
| 090 | Kotlin | 170827T182110Z | jrtapsel |
| 004 | Jelly | 170827T152316Z | clapp |
| 064 | Common Lisp | 170827T082006Z | Renzo |
| 006 | Pyth | 170827T083541Z | Mr. Xcod |
| 027 | Java 8 | 170516T075533Z | Kevin Cr |
| 006 | MY | 170826T165747Z | Adalynn |
| 030 | TXR Lisp | 170826T143711Z | Kaz |
| 026 | Perl 5 | 170825T230607Z | Xcali |
| 019 | Ruby 1.9+ | 170825T161801Z | histocra |
| 003 | Jelly | 170825T154350Z | Dennis |
| 022 | JavaScript ES6 | 170513T075123Z | Shaggy |
| 021 | Ruby | 170516T080808Z | G B |
| 225 | Ruby | 170513T081113Z | ymbirtt |
| 010 | Actually | 170515T211333Z | user4594 |
| 028 | R | 170515T093645Z | JAD |
| 007 | 05AB1E | 170515T140531Z | Riley |
| 006 | Pyth | 170515T014442Z | Esolangi |
| 007 | CJam | 170515T011936Z | Esolangi |
| 280 | Axiom | 170514T175529Z | user5898 |
| 029 | PHP<7.0 | 170513T192609Z | Jör |
| 046 | PHP | 170514T135418Z | user6395 |
| 006 | Ohm | 170514T104100Z | Linnea G |
| 038 | Python 2 | 170513T193052Z | xnor |
| 036 | Haskell | 170513T185150Z | Ørj |
| 040 | Python 2 | 170513T075845Z | ovs |
| 048 | JavaScript ES6 | 170513T074245Z | Arjun |
| 2125 | Clojure | 170513T104927Z | NikoNyrh |
| 033 | Prolog SWI | 170513T082650Z | Adnan |
| 004 | 05AB1E | 170513T092440Z | Emigna |
| 010 | Retina | 170513T075621Z | Martin E |
| 004 | 05AB1E | 170513T081236Z | Erik the |
| 011 | Retina | 170513T074935Z | user4180 |
| 004 | Jelly | 170513T085345Z | Erik the |
| 013 | Octave | 170513T075645Z | Stewie G |
| 042 | Python 2 | 170513T074538Z | Wheat Wi |
| 015 | Mathematica | 170513T081157Z | alephalp |
| 003 | MATL | 170513T080527Z | DJMcMayh |
| 024 | Mathematica | 170513T075347Z | Greg Mar |
| 004 | MATL | 170513T080606Z | Stewie G |
| 026 | JavaScript ES6 | 170513T075654Z | Arnauld |
| 005 | APL Dyalog | 170513T075507Z | user4180 |
| 028 | Mathics | 170513T074508Z | Pavel |
| 055 | Python 3 | 170513T074812Z | Leaky Nu |
| 004 | Jelly | 170513T074226Z | Leaky 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}
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.
Uiua, 8 bytes
/×⬚1/×=2
/×⬚1/×=2
=2 # where are elements equal to two?
⬚1/× # multiply columns, filling missing elements with one
/× # product
Thunno 2, 4 bytes
Ḟ2=p
Explanation
Ḟ2=p # Implicit input
Ḟ # Flatten the list
2= # Check for == 2
p # All are true?
# Implicit output
Pyt, 4 bytes
Ƒ2=Π
Ƒ implicit input; Ƒlatten array
2= is each element equal to 2?
Π product (returns 1 for empty array); implicit print
Zsh, 9 bytes
<<<${@/2}
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Í
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]
$=>[ ; 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
Common Lisp, 68 64 bytes
(defun n(l)(or(and(consp l)(n(car l))(n(cdr l)))(not l)(= l 2)))
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.
MY, 6 bytes
⎕ḟ2=Π←
How?
⎕evaluated inputḟflatten2=element-wise equality with twoΠproduct←output with no newline
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
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ṁ⁼
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
}
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
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));
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)
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(:)[]
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 are2.
Python 2, 43 40 bytes
f=lambda l:l>=[]and all(map(f,l))or l==2
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)
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
Explanation
˜ # flatten list
YQ # check each element for equality to 2
P # product of list
Jelly, 4 bytes
F=2Ạ
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)
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))
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.
MATL, 3 bytes
2=p
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~
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=∊
Explanation
∧/ Only
2= 2s are equal to
∊ any of the elements in the enlisted form of the right argument
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)