42
\$\begingroup\$

Background

Inspired by Octave's (and, by extension, MATL's) very convenient interpretation of truthy/falsy matrices, Jelly got the Ȧ (Octave-style all) atom.

Ȧ takes an array as input and returns 1 if the array is non-empty and does not contain the number 0 (integer, float, or complex) anywhere in the tree structure; otherwise, it returns 0.

For example, the array [[]] is truthy because it is non-empty and contains no zeroes, but [[0]] is falsy because it contains a 0 at the innermost level.

Task

In a programming language of your choice, write a full program or a function that takes a possibly empty, possibly jagged array of integers as input and prints or returns a truthy or falsy value that indicates if Ȧ would return 1 or 0, respectively.

Your submission must abide to the following rules.

  • The truthy and falsy values must be consistent for all inputs, i.e, all arrays for which Ȧ returns 1 must map to the same truthy value, and all arrays for which Ȧ returns 0 must map to the same falsy value.

  • Since full programs can only take string representations of arrays as input, this is allowed. However, you must use the canocical representation of your language, as returned by repr or similar.

    In particular you cannot assume that the first element of the array will be preceded by a space.

  • If (and only if) your language cannot represent jagged arrays natively, you may take a string representation of the input, using the canonical syntax of any pre-existing programming language.

  • If your language has several ways of representing jagged arrays (e.g., lists and tuples), you only have to support one of them.

  • If your language has a built-in that is itself a valid submission to this challenge, you may not use it in your answer. All other built-ins are allowed.

  • You are encouraged to post answers using both array and string manipulation, even if one is significantly shorter than the other.

  • All standard rules apply.

May the shortest code in bytes win!

Truthy test cases

[1]
[10]
[[]]
[[[[1]]]]
[[], [1], [1, 2]]
[[1], [1, [2]], [1, [2, [3]]]]
[[8], [8, [9]], [8, [9, [10]]]]

Falsy test cases

[]
[0]
[0, -1]
[-1, 0]
[[[[0]]]]
[[0], [1, 2], [3, 4, 5]]
[[8], [8, [9]], [8, [9, [1, 0]]]]
[-1, 0, 0, 0]
\$\endgroup\$
19
  • \$\begingroup\$ Based on the test cases, do you mean "contain the number 0" to mean anywhere in the tree structure? That's not what I have guessed it meant. \$\endgroup\$
    – xnor
    Commented Mar 18, 2017 at 17:35
  • \$\begingroup\$ Yes, anywhere. I'll try to clarify that. \$\endgroup\$
    – Dennis
    Commented Mar 18, 2017 at 17:36
  • \$\begingroup\$ What exactly do you mean "you cannot assume that the string representation will have a particular format"? \$\endgroup\$
    – Dada
    Commented Mar 18, 2017 at 17:40
  • 4
    \$\begingroup\$ These are not jagged arrays - jagged arrays would have all numbers at the same depth, because only sizes vary, not element types. \$\endgroup\$ Commented Mar 18, 2017 at 18:41
  • 4
    \$\begingroup\$ @Qwertiy Right, "most" languages where "everything" is an Object... my favorite is Haskell, where it isn't. Nor in C, at least not in a way that allows you to mix arrays and ints safely. Both of those languages are perfectly capable of jagged arrays, but still cannot use them for this problem. \$\endgroup\$ Commented Mar 18, 2017 at 23:41

48 Answers 48

1
2
1
\$\begingroup\$

Zsh, 19 bytes

egrep '\b0\b|^\[]$'

Try it online!

zsh doesn't have any support for nested arrays, so there is no "canonical" representation. I've used Python-style square bracket notation, but this could fairly trivially be modified for most other syntaxes.

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

R, 35 bytes

function(x)all(unlist(x))&length(x)

Try it online!

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

05AB1E, 4 bytes

gªĀß

Try it online or verify all test cases.

Explanation:

g     # Push the length of the (implicit) input-list
 ª    # Append this length to the (implicit) input-list
  Ā   # Check for each inner-most integer that it's NOT 0 (0 if 0; 1 otherwise)
   ß  # Pop and push the flattened minimum of the list
      # (after which it is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

Vyxal r, 3 bytes

fpA

Try it Online!

I don't think there's a flagless 3-byter. Tons of 4-byters though.

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

Fig, \$4\log_{256}(96)\approx\$ 3.292 bytes

AfJL

Try it online!

-3 thanks to Steffan

AfJL
  JL # Prepend the length of the input
 f   # Flatten
A    # All truthy?
\$\endgroup\$
9
  • \$\begingroup\$ This doesn't work for many test cases. You need to check all, not any. \$\endgroup\$
    – naffetS
    Commented Oct 10, 2022 at 18:03
  • \$\begingroup\$ @Steffan this outputs using inverted logic \$\endgroup\$
    – Seggan
    Commented Oct 10, 2022 at 18:04
  • \$\begingroup\$ I know. It doesn't work correctly, for example try [0, -1] which should return 1 with inverted logic. \$\endgroup\$
    – naffetS
    Commented Oct 10, 2022 at 18:05
  • \$\begingroup\$ @Steffan then the testcases are wrong? the challenge says "does not contain the number 0 (integer, float, or complex) anywhere in the tree structure;" \$\endgroup\$
    – Seggan
    Commented Oct 10, 2022 at 18:07
  • \$\begingroup\$ Sorry, [0, -1] produces correct output. [0] and [] do not, though. \$\endgroup\$
    – naffetS
    Commented Oct 10, 2022 at 18:08
1
\$\begingroup\$

CJam, 10 9 bytes

-1 byte by replacing #) with &

_,\e_0&!&

Try it online!

Link includes all test cases

Explanation

_,\e_0&!& # function
_,        # dup and push the length of the input array
  \e_     # flatten the input array
     0&   # AND the array with 0, essentially check if 0 in list
       !  # logical negate (0 IS in list => returns 0, 0 is NOT in list => returns 1
        & # bitwise AND (of the length and the 0 check)
\$\endgroup\$
0
\$\begingroup\$

PHP, 63 54 bytes

9 bytes saved by @user63956

function a($a){return$a&&!strpos(print_r($a,1)," 0");}

takes an array as input; returns true or false: If $a is not empty,
check if print_r output contains a 0 value.

array solution, 83 bytes

function b($a,$r=0){$r|=$a;foreach($a as$v)$r|=is_array($v)?b($v,1):!!$v;return$r;}

recursive function returns 1 or 0.

breakdown

function b($a,$r=0)
{
    $r|=$a;         # if $a is not empty, set $r (no effect in recursion)
    foreach($a as$v)    # loop through elements:    
        $r&=is_array($v)    # 2. if test failed, clear $r
            ?b($v,1)        # 1. if array, recurse
            :!!$v;          #    else test element <>0
    return$r;           # return $r
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You can save a few bytes with strpos(print_r($a,1)," 0") instead of preg_match(...). \$\endgroup\$
    – user63956
    Commented Mar 19, 2017 at 12:03
  • \$\begingroup\$ @user63956 ... and it also solves the 0-index problem. I wasn´t aware of the second print_r parameter. Great! \$\endgroup\$
    – Titus
    Commented Mar 20, 2017 at 12:06
0
\$\begingroup\$

CJam, 12 bytes

l~a_e_+:e&!!

Try it online! or verify all test cases

Explanation

l~            e# Read and eval a line of input
  a           e# Wrap the array in an array
   _          e# Duplicate it
    e_        e# Flatten it
      +       e# Concatenate; results in adding the input array to the beginning of itself
       :e&    e# Reduce the array using logical AND: if any element of the array is falsy,
              e#   the result will be that falsy element, otherwise a truthy element
          !!  e# Double negation (coerce to boolean)
\$\endgroup\$
0
\$\begingroup\$

QBIC, 41 bytes

;?-(_lA|<3)+instr(A,@[0`)+instr(A,@,0`)=0

Maybe it's time to put instr on the to-do list... Explanation:

;                   Get a string from the cmd line
 -(_lA|<3)          Check the length ( _lA| ) and yield 0 for 
                    strings longer than 2, 1 for shorter ones;
                    this checks for the empty array []
 +instr(A,@[0`)     Then check if the string "[0" is present,
 +instr(A,@,0`)     or the string ",0"
                    If any of the above is true, these statements give a 1.
                    Those are summed: invalid arrays have a sum > 0
?              =0   Print a -1 for 'true' arrays, and '0' for false.

QBIC cannot do a list-based version of this challenge.

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

Pyth, 9 Bytes

!|/.nQ0!l

Takes an array and outputs True or False.

The double ! (Not) is needed so that the output is consistently true or false.

Explanation:

!|/.nQ0!l
        l     - The length of the input array (input implicit on the right)
       !l     - Negate it: True if 0 else False
     Q        - Evaluate the input string to a array
   .nQ        - flatten the array
  /   0       - How often does 0 appear?
 |            - logical OR: If zero does appear return True else the length of the array
!             - Negate the result

Try it online!

more boring same length alternative:

!|}0.nQqY
\$\endgroup\$
0
\$\begingroup\$

Scala, 53 47 44 bytes

A lambda (assign to a variable or value of type String=>Boolean, and call that variable/value).

x=> !(x=="[]"|x.split("\\D+") contains "0")

I collapsed the filtering logic by splitting the input string at any non-digit character, and then checking if the resulting sequence has a 0 anywhere. We do this via string manipulation because Scala (or Java) cannot represent arbitrarily jagged arrays uniformly at the type level.

I do not handle the case of an empty string "" as that is an illegal representation for a jagged list, the legal empty jagged list would be "[]", which has to be special-cased.

The input format is exactly the OP's input format.

\$\endgroup\$
4
  • \$\begingroup\$ I think you can leave off the parameter type: codegolf.meta.stackexchange.com/questions/11223/… \$\endgroup\$ Commented Mar 21, 2017 at 15:49
  • \$\begingroup\$ @BrianMcCutchon You can't, because it doesn't otherwise work in my REPL. \$\endgroup\$ Commented Mar 21, 2017 at 18:01
  • \$\begingroup\$ You don't need it to be a standalone REPL line. Assign it to a variable, with the type specified in the variable declaration. \$\endgroup\$ Commented Mar 21, 2017 at 21:01
  • \$\begingroup\$ You can remove the parens around the parameter two save two bytes, and by using operator notation (dropping the dot before contains and the parens around "0") al least two more. \$\endgroup\$
    – corvus_192
    Commented Mar 22, 2017 at 20:52
0
\$\begingroup\$

Prolog, 23 bytes

\(0^_).
\(A^B):- \A;\B.

Takes a list with ^/2 as the pair constructor, terminated by anything and nested if necessary. Succeeds if it contains 0 and fails if it doesn't.

Invocation

SWISH it online!

?- \(5^4^3^2^1^end).
false.
?- \(5^4^3^2^1^0^end).
true.
?- \(5^4^(1^0^ -1^end)^2^1^end).
true.
\$\endgroup\$
0
\$\begingroup\$

Pyth, 5 bytes

.Aa.n

Test suite

Uses the same approach as hvd's Jelly answer, which is fairly different from the existing Pyth answer.

Explanation:
.Aa.n   | Full program
.Aa.nQQ | with implicit variables
--------+-----------------------------------------------------------------
.A      | print whether all the elements of the following list are truthy:
  a   Q |  append the input to 
   .nQ  |  the flattened input
\$\endgroup\$
0
\$\begingroup\$

Haskell + free, 8 bytes

In order to represent a ragged list in Haskell we use a free monad of lists. We use the free library to get these free monads.

all(/=0)

Try it online!

Luckily the library implements an instance of Foldable for the new type so all from the base library works. We just check that all the elements are not equal to zero.

If the input array were of booleans, the actual truthy type of Haskell this could be and.

This is neat but what if we didn't have this instance?

Haskell + free, 18 bytes

(/=0).iter product

Try it online!

Here we use iter to tear down the array. We call it with product so that we get the product of the entire thing in the end. If there were any zeros then the result is 0, so to convert to a boolean we just check if it is equal to zero.

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

Japt, 6 bytes

ÊmUc e

Try it

I think there's probably a way to not need the explicit U. There might also be a shorter way to handle the empty list case, c e alone is right for all other cases.

ÊmUc e #
 m     # Get the minimum of:
Ê      #  The length of the input
       # and:
  U    #  The input
   c   #  flattened
     e #  all elements are truthy
\$\endgroup\$
0
\$\begingroup\$

Raku, 45 bytes

{?$_&&!$_».List.flat».List.flat.grep: *==0}

Try it online!

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

Nibbles, 6.5 bytes

^0?`=@\$D"0"

Attempt This Online!

Nibbles doesn't support heterogenous arrays, so this takes the input as a string in any reasonable format.

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

Nekomata + -e, 2 bytes

NZ

Attempt This Online!

NZ
N   Check that the list is not empty
 Z  Check that it does not contain any zeros
\$\endgroup\$
1
2

Your Answer

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

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