Determine if an Array contains something other than 2

20

3

Take an array which consists of numbers 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!

ATaco

Posted 2017-05-13T07:40:01.063

Reputation: 7 898

Can we take in a string representing the array? – Post Rock Garf Hunter – 2017-05-13T07:42:40.043

Will there be objects other than numbers and other arrays in the arrays – Post Rock Garf Hunter – 2017-05-13T07:43:26.997

There will only be arrays and numbers, and a string representing the array is fine. – ATaco – 2017-05-13T07:44:11.983

Is it okay if we output 0 for truthy testcases, and some positive integer for falsey ones? – user41805 – 2017-05-13T07:46:04.923

Can we assume input numbers are positive? – Pavel – 2017-05-13T07:46:50.003

Input numbers will not be non-negative, and any unique output pair is acceptable... – ATaco – 2017-05-13T07:47:21.633

@ATaco Does "unique output pair" mean that "a positive integer for falsey" is not allowed? – Leaky Nun – 2017-05-13T07:56:44.833

I'll allow it, as it's still clearly distinguishable from a truthy result. – ATaco – 2017-05-13T07:57:49.740

@ATaco so what exactly do you allow, and why would a cat program be invalid? – Leaky Nun – 2017-05-13T08:04:13.580

Is it OK to return true` in one case and raise an error in the other? I assume no, but I can shave a byte off if the answer's yes. – ymbirtt – 2017-05-13T08:12:37.597

Atleast one output should be uniquely consistent. And yes, error is fine. – ATaco – 2017-05-13T08:17:35.137

You should clarify exactly what outputs are expected. Default IO would imply Truthy-falsy, but the comments say that at least one output should be consistent. https://codegolf.meta.stackexchange.com/q/12305/31716

– James – 2017-05-13T08:29:17.700

Alright, I'm going to be specific in the challenge, as this comment section is getting too much. – ATaco – 2017-05-13T08:30:35.207

2What kind of numbers? Compex int, compex float, float int, int , not negative? – RosLuP – 2017-05-14T13:53:20.840

What about:" Take an array void or contain integers or contain arrays of integers or array voids, output if it only contains 2s." – RosLuP – 2017-05-14T14:08:31.557

1FTR and in the name of proper mathematical thinking: the array [[2]] does not contain a two. – ceased to turn counterclockwis – 2017-05-15T11:08:02.237

Can the array contain floating point numbers like 2.2? – user41805 – 2017-05-15T14:13:19.200

Answers

8

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.

James

Posted 2017-05-13T07:40:01.063

Reputation: 54 537

A list containing 0 is falsy? Oh man. – Erik the Outgolfer – 2017-05-13T08:18:59.927

I don't think the 2-byte version is valid, since in the comments ATaco said that a unique output pair is valid. – Erik the Outgolfer – 2017-05-13T08:22:57.200

I believe 2= fails for empty matrices, or? – Stewie Griffin – 2017-05-13T08:34:40.463

@stewiegriffin That seems like a strange edge case to need to handle, but conveniently it does work: Try it online!

– James – 2017-05-13T08:36:15.893

Yes, 2=p works fine. The shorter version in the end, 2=, doesn't. Also, "the strange edge cases" are two of the test cases. :-) – Stewie Griffin – 2017-05-13T08:38:58.797

15

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!

ovs

Posted 2017-05-13T07:40:01.063

Reputation: 21 408

1That's a neat way to check whether an element is a list. – Adnan – 2017-05-13T08:09:45.823

This is why I don't like that consensus. It really ruins python golfing. – Post Rock Garf Hunter – 2017-05-13T08:36:34.647

However since you are going by exit code you don't need the all, anything other than an error is truthy. – Post Rock Garf Hunter – 2017-05-13T08:39:50.973

11

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

Adnan

Posted 2017-05-13T07:40:01.063

Reputation: 41 965

10

Jelly, 4 bytes

F;2E

Try it online!

How it works

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

Leaky Nun

Posted 2017-05-13T07:40:01.063

Reputation: 45 011

9

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.

Stewie Griffin

Posted 2017-05-13T07:40:01.063

Reputation: 43 471

7

Mathics, 28 bytes

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

Try it online!

Pavel

Posted 2017-05-13T07:40:01.063

Reputation: 8 585

I think that the input {0} is allowed; that would result in a false positive. – Greg Martin – 2017-05-13T07:48:11.437

6

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

Shaggy

Posted 2017-05-13T07:40:01.063

Reputation: 24 623

Nice one! I wonder if it could be shortened some more, but I doubt it. – Arnauld – 2017-05-13T08:33:45.270

Thanks, @Arnauld; still haven't figured out a way to improve on it. – Shaggy – 2017-05-13T18:23:49.277

6

Retina, 13 10 bytes

Thanks to Kritixi Lithos for saving 3 bytes.

\W|\b2

^$

Try it online!

Martin Ender

Posted 2017-05-13T07:40:01.063

Reputation: 184 808

6

05AB1E, 4 bytes

˜YQP

Try it online!

Explanation

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

Emigna

Posted 2017-05-13T07:40:01.063

Reputation: 50 798

Why wouldn't 2 work instead of Y? – Erik the Outgolfer – 2017-05-13T09:26:21.330

@EriktheOutgolfer: 2 works as well. I just like the fact that there are no numbers in it :) – Emigna – 2017-05-13T09:26:58.573

5

Mathematica, 15 bytes

FreeQ[x_/;x!=2]

It also works in Mathics. Try it online!

alephalpha

Posted 2017-05-13T07:40:01.063

Reputation: 23 988

4

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.

Greg Martin

Posted 2017-05-13T07:40:01.063

Reputation: 13 940

Outgolfed, but I still really want to know what is being done here. – Pavel – 2017-05-13T07:55:07.010

4

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

user41805

Posted 2017-05-13T07:40:01.063

Reputation: 16 320

4

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.

ymbirtt

Posted 2017-05-13T07:40:01.063

Reputation: 1 792

1x.flatten.uniq==[2] – Nick M – 2017-05-14T14:04:03.927

1@NickM - that won't work on test cases like [] or [[],[]]. [2,*x].flatten.uniq==[2] is slightly longer – ymbirtt – 2017-05-14T15:04:31.597

1x.flatten|[2]==[2] would be shorter. – G B – 2017-05-16T08:11:58.390

@GB and x.flatten-[2]==[] is shorter still. Thanks for the tip! – ymbirtt – 2017-05-16T13:19:36.880

1

And yet regex wins: https://codegolf.stackexchange.com/a/120781/18535 :-)

– G B – 2017-05-16T13:24:45.930

4

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

  • 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 are 2.

Ørjan Johansen

Posted 2017-05-13T07:40:01.063

Reputation: 6 914

How about just not.all(\elem`"2,[]")`? – zbw – 2017-05-14T19:42:12.100

@zbw That fails because of numbers like 22. – Ørjan Johansen – 2017-05-14T22:37:06.970

4

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.

xnor

Posted 2017-05-13T07:40:01.063

Reputation: 115 687

3

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

Arnauld

Posted 2017-05-13T07:40:01.063

Reputation: 111 334

You need to count f= because you referred to it. – Leaky Nun – 2017-05-13T07:58:34.213

@LeakyNun Indeed. Fixed. – Arnauld – 2017-05-13T08:00:12.900

3

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

Stewie Griffin

Posted 2017-05-13T07:40:01.063

Reputation: 43 471

3

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

JAD

Posted 2017-05-13T07:40:01.063

Reputation: 2 898

1pryr::f(!any(unlist(x)-2)) saves a couple of bytes. – BLT – 2017-05-15T14:36:22.100

this is the same length as all(unlist(x)==2) as well. – Giuseppe – 2017-05-15T15:29:07.060

or you could also say any(unlist(x)-2) which returns a consistent TRUE if there is a non-2 value in the flattened array and a consistent FALSE if all the values are 2... – Giuseppe – 2017-05-15T16:41:25.530

1@Giuseppe Not sure if TRUE counts as falsey though :/ – JAD – 2017-05-15T18:53:30.200

@BLT that's codegolf magic, imma check that out. – JAD – 2017-05-15T18:53:53.253

@JarkoDubbeldam it tends to get confused for more complex functions but for simple ones, it infers the arguments so you don't have to declare them (or write function). If only the package name were shorter... – BLT – 2017-05-15T19:03:20.887

@BLT, still very nice. Makes any answer using apply with an anonymous function that bit shorter. – JAD – 2017-05-15T19:04:37.890

@BLT maybe add it here: https://codegolf.stackexchange.com/questions/4024/tips-for-golfing-in-r?s=1%7C1.4077 ;)

– JAD – 2017-05-15T19:05:26.153

@JarkoDubbeldam I did a few months ago: https://codegolf.stackexchange.com/a/111578/62105

– BLT – 2017-05-15T19:06:34.720

1

well, there's still not a consensus on meta, but https://codegolf.meta.stackexchange.com/a/2192/67312

– Giuseppe – 2017-05-15T19:48:49.373

@Giuseppe I think this answer is pretty clear, and has a lot more upvotes than the other answers: https://codegolf.meta.stackexchange.com/a/2194/59530

– JAD – 2017-05-16T06:53:09.197

2

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

Arjun

Posted 2017-05-13T07:40:01.063

Reputation: 4 544

f([]) and f([[],[]]) should be truthy – Arnauld – 2017-05-13T07:46:06.023

@Arnauld Is it correct now? – Arjun – 2017-05-13T07:53:25.837

I think so. :-) – Arnauld – 2017-05-13T07:55:02.403

Think you can save a couple of bytes with !c instead of c=="". – Shaggy – 2017-05-13T08:03:09.877

@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! :) – Arjun – 2017-05-13T08:05:08.787

Save more with ("'+a) instead of a.join(). – Shaggy – 2017-05-13T08:21:55.280

@Shaggy Won't that fail for [[][]] and similar cases? – Arjun – 2017-05-13T15:21:55.313

Nope, it'll still return true properly. – Shaggy – 2017-05-13T16:19:14.073

@Shaggy Thanks! – Arjun – 2017-05-13T16:28:43.527

One more: replace !c?2:c with c||2 or maybe even just c|2 - you'll need to double check that against the test cases . – Shaggy – 2017-05-13T16:42:33.633

Actually, you might even be able to use c^2 thus allowing you to replace c==2 with !c. Again, you'd need to run a full set of tests to double check it works. – Shaggy – 2017-05-13T16:46:43.717

2

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!

Leaky Nun

Posted 2017-05-13T07:40:01.063

Reputation: 45 011

-1 byte: int!=type(x)and – Mego – 2017-05-17T22:14:59.507

2

Retina, 14 11 bytes

^(\W|2\b)+$

Try it online!

user41805

Posted 2017-05-13T07:40:01.063

Reputation: 16 320

\W doesn't seem such a good criteria : 2.2 is a number that isn't 2, yet I suppose it would match – Aaron – 2017-05-15T14:12:30.443

@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. – user41805 – 2017-05-15T14:15:00.937

Yeah, I see RosLup asked the same question yesterday and hasn't got an answer yet. I hope OP will come soon to clarify ! – Aaron – 2017-05-15T14:16:38.663

2

05AB1E, 4 bytes

2‚˜Ë

Try it online!

Erik the Outgolfer

Posted 2017-05-13T07:40:01.063

Reputation: 38 134

2

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

Erik the Outgolfer

Posted 2017-05-13T07:40:01.063

Reputation: 38 134

2

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

Riley

Posted 2017-05-13T07:40:01.063

Reputation: 11 345

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.

Try it here.

Kevin Cruijssen

Posted 2017-05-13T07:40:01.063

Reputation: 67 575

I hate to nullify all your work on the list solution, but couldn't you coerce to a string and use the string solution? – Jakob – 2017-08-25T15:45:06.167

@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? – Kevin Cruijssen – 2017-08-26T16:36:27.373

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. – Jakob – 2017-08-26T18:39:58.587

1Oh and you can lose 2 bytes by removing ^ and $ in the regex, since String.matches only tests against the whole string. – Jakob – 2017-08-26T18:46:13.103

@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.. – Kevin Cruijssen – 2017-08-26T19:52:30.973

1

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.

Post Rock Garf Hunter

Posted 2017-05-13T07:40:01.063

Reputation: 55 382

lambda x:set(x)==set("[], 2")? – Leaky Nun – 2017-05-13T07:48:56.653

Fails for [22] – Leaky Nun – 2017-05-13T07:51:31.427

@LeakyNun Fixed – Post Rock Garf Hunter – 2017-05-13T08:00:22.337

@LeakyNun Your suggestion fails for [] – Post Rock Garf Hunter – 2017-05-13T08:10:27.123

lambda x:set(x)<=set("[],2"*-~-("22"in x)) for -1 – ovs – 2017-05-13T08:31:34.053

@ovs Already took that byte off a slightly different way, thanks though! – Post Rock Garf Hunter – 2017-05-13T08:33:22.867

1

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!

Jörg Hülsermann

Posted 2017-05-13T07:40:01.063

Reputation: 13 026

2You don't need the $r variable: <?array_walk_recursive($_GET,function($i){$i-2&&die;})?>1. – user63956 – 2017-05-14T13:48:05.177

1

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

Roman Gräf

Posted 2017-05-13T07:40:01.063

Reputation: 2 915

1

PHP, 46 bytes

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

user63956

Posted 2017-05-13T07:40:01.063

Reputation: 1 571

@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? – user63956 – 2017-05-14T16:00:34.390

<?=!preg_match('/:"(?!2")/',$argn); and input is a string representation of the serialized array - 11 Bytes – Jörg Hülsermann – 2017-05-14T16:35:54.560

1

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

Esolanging Fruit

Posted 2017-05-13T07:40:01.063

Reputation: 13 542

1

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!

G B

Posted 2017-05-13T07:40:01.063

Reputation: 11 099

Curses! Nice work. What's this x*?!!~ construct? – ymbirtt – 2017-05-16T13:28:36.917

1

Japt, 6 5 bytes

c e¶2

Try it online


Explanation

    :Implicit input of array U
c   :Flattens U
e   :Check if every element ...
¶2  :... is strictly equal (===) to 2

Shaggy

Posted 2017-05-13T07:40:01.063

Reputation: 24 623

1

Kotlin, 90 bytes

Submission

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

TryItOnline

TryItOnline

jrtapsell

Posted 2017-05-13T07:40:01.063

Reputation: 915

0

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

NikoNyrh

Posted 2017-05-13T07:40:01.063

Reputation: 2 361

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

RosLuP

Posted 2017-05-13T07:40:01.063

Reputation: 3 036

0

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

Esolanging Fruit

Posted 2017-05-13T07:40:01.063

Reputation: 13 542

0

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)

Mego

Posted 2017-05-13T07:40:01.063

Reputation: 32 998

0

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.

Dennis

Posted 2017-05-13T07:40:01.063

Reputation: 196 637

0

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.

histocrat

Posted 2017-05-13T07:40:01.063

Reputation: 20 600

0

Perl 5, 26 bytes

25 bytes of code + 1 for -n

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

Try it online!

Xcali

Posted 2017-05-13T07:40:01.063

Reputation: 7 671

0

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

Kaz

Posted 2017-05-13T07:40:01.063

Reputation: 372

0

MY, 6 bytes

⎕ḟ2=Π←

Try it online!

How?

  • evaluated input
  • flatten
  • 2= element-wise equality with two
  • Π product
  • output with no newline

Zacharý

Posted 2017-05-13T07:40:01.063

Reputation: 5 710

0

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!

Renzo

Posted 2017-05-13T07:40:01.063

Reputation: 2 260

0

Pyth, 6 bytes

q]2{.n

Try it here!

Mr. Xcoder

Posted 2017-05-13T07:40:01.063

Reputation: 39 774

0

Jelly, 3 4 bytes

F=2Ạ

Gained a byte because of a failed test case.

Try it online!

clap

Posted 2017-05-13T07:40:01.063

Reputation: 834

This fails on the [[1,2],2] test case. – Ørjan Johansen – 2017-08-27T17:31:55.267

@ØrjanJohansen Fixed at the cost of one byte. – clap – 2017-08-27T17:33:11.100

It is now a dupe of this: https://codegolf.stackexchange.com/a/120371/44874

– steenbergh – 2017-08-30T13:42:55.540