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!
58 Answers 58
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)
-
1\$\begingroup\$ That's a neat way to check whether an element is a list. \$\endgroup\$Adnan– Adnan2017年05月13日 08:09:45 +00:00Commented May 13, 2017 at 8:09
-
\$\begingroup\$ This is why I don't like that consensus. It really ruins python golfing. \$\endgroup\$2017年05月13日 08:36:34 +00:00Commented May 13, 2017 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\$2017年05月13日 08:39:50 +00:00Commented May 13, 2017 at 8:39
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).
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.
MATL, 3 bytes
2=p
Technically, this could just be
2=
Since an array containing any zero elements is falsy, but this seems cheap.
-
\$\begingroup\$ A list containing 0 is falsy? Oh man. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年05月13日 08:18:59 +00:00Commented May 13, 2017 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– Erik the Outgolfer2017年05月13日 08:22:57 +00:00Commented May 13, 2017 at 8:22
-
\$\begingroup\$ I believe
2=fails for empty matrices, or? \$\endgroup\$Stewie Griffin– Stewie Griffin2017年05月13日 08:34:40 +00:00Commented May 13, 2017 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– DJMcMayhem2017年05月13日 08:36:15 +00:00Commented May 13, 2017 at 8:36
-
\$\begingroup\$ Yes,
2=pworks fine. The shorter version in the end,2=, doesn't. Also, "the strange edge cases" are two of the test cases. :-) \$\endgroup\$Stewie Griffin– Stewie Griffin2017年05月13日 08:38:58 +00:00Commented May 13, 2017 at 8:38
-
\$\begingroup\$ I think that the input
{0}is allowed; that would result in a false positive. \$\endgroup\$Greg Martin– Greg Martin2017年05月13日 07:48:11 +00:00Commented May 13, 2017 at 7:48
-
\$\begingroup\$ Seems to fail for lists that contain
-2. \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2023年02月20日 15:57:58 +00:00Commented Feb 20, 2023 at 15:57
05AB1E, 4 bytes
̃YQP
Explanation
̃ # flatten list
YQ # check each element for equality to 2
P # product of list
-
\$\begingroup\$ Why wouldn't
2work instead ofY? \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年05月13日 09:26:21 +00:00Commented May 13, 2017 at 9:26 -
\$\begingroup\$ @EriktheOutgolfer:
2works as well. I just like the fact that there are no numbers in it :) \$\endgroup\$Emigna– Emigna2017年05月13日 09:26:58 +00:00Commented May 13, 2017 at 9:26
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]))
-
\$\begingroup\$ Nice one! I wonder if it could be shortened some more, but I doubt it. \$\endgroup\$Arnauld– Arnauld2017年05月13日 08:33:45 +00:00Commented May 13, 2017 at 8:33
-
\$\begingroup\$ Thanks, @Arnauld; still haven't figured out a way to improve on it. \$\endgroup\$Shaggy– Shaggy2017年05月13日 18:23:49 +00:00Commented May 13, 2017 at 18:23
APL (Dyalog), 5 bytes
∧/2=∊
Explanation
∧/ Only
2= 2s are equal to
∊ any of the elements in the enlisted form of the right argument
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.
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.
-
\$\begingroup\$ How about just
not.all(`elem`"2,[]")? \$\endgroup\$zbw– zbw2017年05月14日 19:42:12 +00:00Commented May 14, 2017 at 19:42 -
\$\begingroup\$ @zbw That fails because of numbers like
22. \$\endgroup\$Ørjan Johansen– Ørjan Johansen2017年05月14日 22:37:06 +00:00Commented May 14, 2017 at 22:37
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.
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.
-
1\$\begingroup\$ x.flatten.uniq==[2] \$\endgroup\$Nick M– Nick M2017年05月14日 14:04:03 +00:00Commented May 14, 2017 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– ymbirtt2017年05月14日 15:04:31 +00:00Commented May 14, 2017 at 15:04 -
1\$\begingroup\$ x.flatten|[2]==[2] would be shorter. \$\endgroup\$G B– G B2017年05月16日 08:11:58 +00:00Commented May 16, 2017 at 8:11
-
\$\begingroup\$ @GB and
x.flatten-[2]==[]is shorter still. Thanks for the tip! \$\endgroup\$ymbirtt– ymbirtt2017年05月16日 13:19:36 +00:00Commented May 16, 2017 at 13:19 -
1\$\begingroup\$ And yet regex wins: codegolf.stackexchange.com/a/120781/18535 :-) \$\endgroup\$G B– G B2017年05月16日 13:24:45 +00:00Commented May 16, 2017 at 13:24
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]))
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).
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 !.
-
1\$\begingroup\$
pryr::f(!any(unlist(x)-2))saves a couple of bytes. \$\endgroup\$BLT– BLT2017年05月15日 14:36:22 +00:00Commented May 15, 2017 at 14:36 -
\$\begingroup\$ this is the same length as
all(unlist(x)==2)as well. \$\endgroup\$Giuseppe– Giuseppe2017年05月15日 15:29:07 +00:00Commented May 15, 2017 at 15:29 -
\$\begingroup\$ or you could also say
any(unlist(x)-2)which returns a consistentTRUEif there is a non-2 value in the flattened array and a consistentFALSEif all the values are2... \$\endgroup\$Giuseppe– Giuseppe2017年05月15日 16:41:25 +00:00Commented May 15, 2017 at 16:41 -
1\$\begingroup\$ @Giuseppe Not sure if
TRUEcounts as falsey though :/ \$\endgroup\$JAD– JAD2017年05月15日 18:53:30 +00:00Commented May 15, 2017 at 18:53 -
1\$\begingroup\$ well, there's still not a consensus on meta, but codegolf.meta.stackexchange.com/a/2192/67312 \$\endgroup\$Giuseppe– Giuseppe2017年05月15日 19:48:49 +00:00Commented May 15, 2017 at 19:48
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)
-
\$\begingroup\$ -1 byte:
int!=type(x)and\$\endgroup\$user45941– user459412017年05月17日 22:14:59 +00:00Commented May 17, 2017 at 22:14
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
-
\$\begingroup\$
\Wdoesn't seem such a good criteria :2.2is a number that isn't2, yet I suppose it would match \$\endgroup\$Aaron– Aaron2017年05月15日 14:12:30 +00:00Commented May 15, 2017 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\$user41805– user418052017年05月15日 14:15:00 +00:00Commented May 15, 2017 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– Aaron2017年05月15日 14:16:38 +00:00Commented May 15, 2017 at 14:16
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]))
-
\$\begingroup\$
f([])andf([[],[]])should be truthy \$\endgroup\$Arnauld– Arnauld2017年05月13日 07:46:06 +00:00Commented May 13, 2017 at 7:46 -
\$\begingroup\$ @Arnauld Is it correct now? \$\endgroup\$Arjun– Arjun2017年05月13日 07:53:25 +00:00Commented May 13, 2017 at 7:53
-
\$\begingroup\$ I think so. :-) \$\endgroup\$Arnauld– Arnauld2017年05月13日 07:55:02 +00:00Commented May 13, 2017 at 7:55
-
\$\begingroup\$ Think you can save a couple of bytes with
!cinstead ofc=="". \$\endgroup\$Shaggy– Shaggy2017年05月13日 08:03:09 +00:00Commented May 13, 2017 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– Arjun2017年05月13日 08:05:08 +00:00Commented May 13, 2017 at 8:05
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
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
}
-
\$\begingroup\$ Curses! Nice work. What's this
x*?!!~construct? \$\endgroup\$ymbirtt– ymbirtt2017年05月16日 13:28:36 +00:00Commented May 16, 2017 at 13:28
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.
-
\$\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– Jakob2017年08月25日 15:45:06 +00:00Commented Aug 25, 2017 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– Kevin Cruijssen2017年08月26日 16:36:27 +00:00Commented Aug 26, 2017 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– Jakob2017年08月26日 18:39:58 +00:00Commented Aug 26, 2017 at 18:39 -
1\$\begingroup\$ Oh and you can lose 2 bytes by removing
^and$in the regex, sinceString.matchesonly tests against the whole string. \$\endgroup\$Jakob– Jakob2017年08月26日 18:46:13 +00:00Commented Aug 26, 2017 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– Kevin Cruijssen2017年08月26日 19:52:30 +00:00Commented Aug 26, 2017 at 19:52
Thunno 2, 4 bytes
Ḟ2=p
Explanation
Ḟ2=p # Implicit input
Ḟ # Flatten the list
2= # Check for == 2
p # All are true?
# Implicit output
[[2]]does not contain a two. \$\endgroup\$