title: Count repetitions of an array

text:
# Question
Title: Count repetitions of an array
You will receive an array and must return the number of integers that occur more than once.

```
[234, 2, 12, 234, 5, 10, 1000, 2, 99, 234]

```

This will return 2, since each of `234` and `2` appear more than once.

```
[234, 2, 12, 234]
[2, 12, 234, 5, 10, 1000, 2]

```

The list will never be more than 100k integers long, and the integers inside the list will always be in between -100k and 100k.

Integers should be counted if they occur more than once, so if an integer occurs 3 times then it will still only count as one repeated integer.

**Test cases**

```
[1, 10, 16, 4, 8, 10, 9, 19, 2, 15, 18, 19, 10, 9, 17, 15, 19, 5, 13, 20]  = 4
[11, 8, 6, 15, 9, 19, 2, 2, 4, 19, 14, 19, 13, 12, 16, 13, 0, 5, 0, 8]     = 5
[9, 7, 8, 16, 3, 9, 20, 19, 15, 6, 8, 4, 18, 14, 19, 12, 12, 16, 11, 19]   = 5
[10, 17, 17, 7, 2, 18, 7, 13, 3, 10, 1, 5, 15, 4, 6, 0, 19, 4, 17, 0]      = 5
[12, 7, 17, 13, 5, 3, 4, 15, 20, 15, 5, 18, 18, 18, 4, 8, 15, 13, 11, 13]  = 5
[0, 3, 6, 1, 5, 2, 16, 1, 6, 3, 12, 1, 16, 5, 4, 5, 6, 17, 4, 8]           = 6
[11, 19, 2, 3, 11, 15, 19, 8, 2, 12, 12, 20, 13, 18, 1, 11, 19, 7, 11, 2]  = 4
[6, 4, 11, 14, 17, 3, 17, 11, 2, 16, 14, 1, 2, 1, 15, 15, 12, 10, 11, 13]  = 6
[0, 19, 2, 0, 10, 10, 16, 9, 19, 9, 15, 0, 10, 18, 0, 17, 18, 18, 0, 9]    = 5
[1, 19, 17, 17, 0, 2, 14, 10, 10, 12, 5, 14, 16, 7, 15, 15, 18, 11, 17, 7] = 5

```

# Answer
# , 20 bytes

Is this what you are after? Uses `table` to count the occurrences of each of the `scan` input values. Tests if count is \> 1 and sums the trues.

```
sum(table(scan())>1)

```

Try it online!
> 16 votes

# Answer
# Bash \+ coreutils, 18

```
sort|uniq -d|wc -l

```

Try it online!
> 9 votes

# Answer
# Haskell, 42 bytes

```
f s=sum[1|x<-[-9^6..9^6],filter(==x)s>[x]]

```

Try it online! Abuses the fact the the integers in the list are guaranteed to be within -100k and 100k.
> 9 votes

# Answer
# APL (Dyalog Unicode), ~~9~~ 8 bytesSBCS

-1 thanks to ngn

Anonymous tacit prefix function.

```
+/1<⊢∘≢⌸

```

Try it online!

`+/` sum of

`1<` whether 1 is less than

for each unique element:

`⊢∘` ignoring the actual unique element,

the count of its occurrences
> 7 votes

# Answer
# C# (Visual C# Interactive Compiler), 40 bytes

```
n=>n.GroupBy(c=>c).Count(c=>c.Count()>1)

```

The first draft of the spec was unclear, and I thought it mean return all the elements that appear more than once. This is the updated version.

Somehow I didn't notice that my code returned the number of elements that appeared once. Thanks to Paul Karam for catching that!

Try it online!
> 5 votes

# Answer
# C (clang) ~~175~~ ~~117~~ 95 bytes

```
c(*a,*b){return*a-*b;}r(*l,m){qsort(l,m,4,c);return((!m||l[1]-*l)&l[-1]==*l)+(m?r(l+1,m-1):0);}

```

Try it online!

This is the first time I've submitted one of these, so let me know if there are any issues with formatting or anything.

Updates from the comments:

* -58 to 117 bytes from Jo King
* -80 to 95 bytes from ASCII-only

original submission
> 5 votes

# Answer
# , ~~11~~ 9 bytes

-2 bytes thanks to Jonah!

```
1#.1<1#.=

```

Try it online!

## Original solution:

```
1#.(1<#)/.~

```

Try it online!

Explanation:

```
        /.~   group the list by itself
   (   )      for each group
    1<#       is the length greater than 1
1#.           sum by base-1 conversion

```
> 4 votes

# Answer
# 05AB1E, 4 bytes

```
Ù¢≠O

```

Try it online! or as a Test Suite

**Explanation**

```
   O  # sum
  ≠   # the false values
 ¢    # in the count
Ù     # of each unique digit in input

```
> 4 votes

# Answer
# Python 3, 38 bytes

```
lambda a:sum(a.count(x)>1for x in{*a})

```

Try it online!
> 4 votes

# Answer
# Jelly, 4 bytes

```
ĠITL

```

**Try it online!**

...Or `ĠIƇL`

### How?

```
ĠITL - Link: list of integers   e.g. [234, 2, 12, 234, 5, 10, 1000, 2, 99, 234]
Ġ    - group indices by value        [[2,8],5,6,3,9,[1,4,10],7]
 I   - incremental differences       [[6],[],[],[],[],[3,6],[]]
  T  - truthy indices                [1,6]
   L - length                        2

```

would filter to keep only truthy results of `I` (`[[6],[3,6]]`) which also has the desired length.
> 4 votes

# Answer
# Java 8, ~~74~~ 73 bytes

```
L->L.stream().filter(i->L.indexOf(i)<L.lastIndexOf(i)).distinct().count()

```

Try it online.

**Explanation:**

```
L->                      // Method with ArrayList parameter and integer return-type
  L.stream()             //  Create a stream of the input-list
   .filter(i->           //  Filter it by:
     L.indexOf(i)        //   Where the first index of a value
     <L.lastIndexOf(i))  //   is smaller than the last index of a value
   .distinct()           //  Deduplicate this filtered list
   .count()              //  And return the count of the remaining values

```
> 4 votes

# Answer
# Uiua, 7 bytes

```
/+>1⍘⊚⊛

```

Try it!

```
/+>1⍘⊚⊛
      ⊛  # classify (i.e. map integers -> naturals)
    ⍘⊚   # inverse where (occurrences)
  >1     # where are they greater than one?
/+       # sum

```
> 4 votes

# Answer
# Ruby, 34 bytes

```
->a{a.uniq.count{|x|a.count(x)>1}}

```

Try it online!
> 3 votes

# Answer
# Perl 6, 15 bytes

```
+*.repeated.Set

```

Try it online!

Pretty self explanatory. An anonymous code block that gets the count (`+`) of the `Set` of elements among the `repeated` elements of the input (`*`).

I've realised I've posted almost the exact same solution for a related question.
> 3 votes

# Answer
# Python 3, 63 bytes

```
lambda l:len(C(l)-C({*l}))
from collections import Counter as C

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Extended), ~~8~~ 7 bytesSBCS

Anonymous tacit prefix function using Jonah's method.

```
+/1<∪⍧⊢

```

Try it online!

`+/` the total number occurrences
literally the sum of Truths

`1<` where one is less than

the unique elements'

count in

the unmodified argument
> 3 votes

# Answer
# Haskell, 41 bytes

```
f(h:t)=sum[1|filter(==h)t==[h]]+f t
f _=0

```

Try it online!

Count suffixes where the first element `h` appears exactly once in the part `t` that comes after.

---

# Haskell, 40 bytes

```
import Data.List
f l=length$nub$l\\nub l

```

Try it online!

Stealing the method from other answers.
> 3 votes

# Answer
# Haskell, 41 bytes

```
f[]=0
f(a:s)=sum[1|filter(==a)s==[a]]+f s

```

This solution basically counts how many elements of the list have the same element appear exactly once later in the list.
> 3 votes

# Answer
# PHP, 39 bytes

a nice occasion to use variable variables:

```
foreach($argv as$v)$r+=++$$v==2;echo$r;

```

takes input from command line arguments. Run with `-nr` or try it online.

---

`$argv[0]` is `-` and that appears only once in the arguments, so it does not affect the result.
> 3 votes

# Answer
# Haskell, 47 bytes

```
f[]=0
f(a:b)|x<-filter(/=a)b,x/=b=1+f x|1>0=f b

```

Try it online!

This is the naïve approach. There is likely something that could be done to improve this.

```
f[]=0

```

We return `0` for the empty list

```
f(a:b)

```

In the case of a non-empty list starting with `a` and then `b`.

```
|x<-filter(/=a)b,x/=b=1+f x

```

If filtering `a` out of `b` is different from `b` (that is `a` is in `b`) then we return 1 more than `f` applied to `b` with the `a`s filtered out.

```
|1>0=f b

```

If filtering `a`s doesn't change `b` then we just run `f` across the rest.

Here is another similar approach that has the same length:

```
f[]=0
f(a:b)|elem a b=1+f(filter(/=a)b)|1>0=f b

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 40 bytes

```
a=>a.map(o=x=>n+=(o[x]=-~o[x])==2,n=0)|n

```

Try it online!
> 2 votes

# Answer
# Japt, ~~12~~ ~~11~~ ~~9~~ ~~8~~ 6 bytes

```
ü èÈÊÉ

```

With lots of help from @ASCII-Only, and suggestions from @Shaggy and @Luis felipe De jesus Munoz.

Try it online!
> 2 votes

# Answer
# Wolfram Language 34 bytes

```
 Length@DeleteCases[Gather@#,{x_}]&

```

`Gather` groups identical integers into lists. `DeleteCases[...{x_}]` eliminates lists containing a single number. `Length` returns the number of remaining lists (each containing two or more identical integers.
> 2 votes

# Answer
# Pyth, 6 bytes

```
l{.-Q{

```

Try it here

### Explanation

```
l{.-Q{
     {Q   Deduplicate the (implicit) input.
  .-Q     Remove the first instance of each from the input.
l{        Count unique.

```
> 2 votes

# Answer
# Brachylog, 7 bytes

```
ọzt;1xl

```

Try it online!

Explanation:

```
ọ          For every unique element E of the input, [E, how many times E occurs]
 zt        The last elements of the previous value.
   ;1x     With every 1 removed,
      l    how many there are.

```
> 2 votes

# Answer
# Gaia, 6 bytes

```
e:uDul

```

Try it online!

```
e	| eval as a list
 :	| duplicate
  u	| uniquify
   D	| multiset difference; keep only repeated elements
    u	| uniquify
     l	| find length
```
> 2 votes

# Answer
# Arturo, ~~49~~ 31 bytes

```
$=>[tally&|enumerate[k,v]->v>1]

```

Try it

-18 bytes due to Arturo 0.9.83 providing `tally` and `enumerate`.

```
$ => [               ; a function
    tally &          ; create a dictionary of elements and their occurrences from the input
    |                ; then...
    enumerate[k,v]-> ; count the number of key-value pairs where...
    v>1              ; the value (occurrences) is greater than one
]                    ; end function

```
> 2 votes

# Answer
# Pyt, 7 bytes

```
ĐỤ⇹ɔ⁻žŁ

```

Try it online!

```
Đ             implicit input; Đuplicate on the stack
 Ụ            get Ụnique elements
  ⇹ɔ          ɔount occurrences of each in original list
    ⁻žŁ       decrement; remove žeros; get Łength; implicit print

```
> 2 votes

# Answer
# Thunno 2 `L`, 5 bytes

```
Uæc1Q

```

Try it online!

#### Explanation

```
Uæc1Q  # Implicit input
U      # Uniquify the input
 æ     # Filter it by:
  c    #  Count in the input
   1Q  #  Is not equal to 1
       # Push the length
       # Implicit output

```
> 2 votes

# Answer
# Element, 40 bytes

```
_(#'{"2:0+4:'~1+";~2=[''1+""]$2+'[(#]'}`

```

Try it online!

This requires input to be in a precise format like `[234, 2, 1000, 2, 99, 234]` (enclosed with `[]` with a comma and space between integers).

**Explanation:**

```
_                                        input
 (#                                      delete the [ at start of input
   '{"                               '}  WHILE the string is non-empty
   '{"2:                             '}    duplicate it
   '{"  0+                           '}    add 0 to coerce to integer (gets next number in array)
   '{"    4:                         '}    make 3 additional copies
   '{"      '                        '}    temporarily move 1 copy to control stack
   '{"       ~                       '}    fetch the current map value for given integer
   '{"        1+                     '}    increment map value
   '{"          "                    '}    retrieve temporary copy of integer (the key for the map)
   '{"           ;                   '}    store updated map value
   '{"            ~                  '}    fetch map value again (1 if 1st instance, 2 if 2nd, etc.)
   '{"             2=                '}    test for map value = 2, this is the first duplication
   '{"               [      ]        '}    IF
   '{"               [''    ]        '}      move stuff from main stack to control stack
   '{"               [  1+  ]        '}      increment the counter of duplicate (bottom of stack)
   '{"               [    ""]        '}      move stuff back to main stack
   '{"                       $       '}    take length of current integer
   '{"                        2+     '}    add 2 (for the comma and space)
   '{"                          '[  ]'}    FOR loop with that number
   '{"                          '[(#]'}      trim those many characters from front of input string
                                       ` output result

```
> 1 votes

# Answer
# Clean, ~~59~~ 54 bytes

```
import StdEnv,StdLib
$l=sum[1\\[_,_:_]<-group(sort l)]

```

Try it online!

Sorts the list, groups adjacent equal elements, and counts the number with more than 1 item.
> 1 votes

# Answer
# Retina 0.8.2, 19 bytes

```
O`.+
m`^(.+)(¶\1)+$

```

Try it online! Link includes test suite which splits each line on commas. Explanation:

```
O`.+

```

Sort equal values together.

```
m`^(.+)(¶\1)+$

```

Count the number of runs of at least two values.
> 1 votes

# Answer
# Pyth, 10 bytes

```
lf<1/QT.{Q

```

Probably a way to golf it, I'm quite rusty with pyth...

Alternate 10 byte version...

```
lf>lT1.gSk

```

Try it online!
> 1 votes

# Answer
# Rust, 126 bytes

```
let f=|v:Vec<i32>|{let mut u=v.clone();u.sort();u.dedup();u.iter().filter(|i|v.iter().filter(|n|**n==**i).count()>1).count()};

```

I give up. This is basically the same as Ruby. There is "another way" creating an array and indexing into it using the values in the input vector, +100000, however the type conversions (as usize / as i32) take up too much space.
> 1 votes

# Answer
# PowerShell, 33 bytes

```
($args|group|?{$_.Count-1}).Count

```

Try it online!
> 1 votes

# Answer
# MATL, 5 bytes

```
8#uqz

```

Try it online! Or verify all test cases.

### Explanation

```
8#u   % Number of ocurrences of each unique value
q     % Subtract 1
z     % Number of nonzeros

```
> 1 votes

# Answer
## PHP (112 Bytes)

```
<?php $c=0;foreach(array_count_values(json_decode(file_get_contents('php://stdin'))) as $b)if($b>1)$c++;echo $c;

```

The assignment does not make it clear if the input is received via Stdin in exactly given format or as separate parameters in Argv, so here is a variant for argv, 91 Bytes:

```
<?php array_shift($argv);$c=0;foreach(array_count_values($argv) as $b)if($b>1)$c++;echo $c;

```
> 1 votes

# Answer
# Pyth, 8 bytes

```
lfthTr8S

```

Try it online here, or verify all the test cases at once here.
> 1 votes

# Answer
# Factor, 42 bytes

```
: d ( x -- ) duplicates members length . ;

```

Try it online!
> 1 votes

# Answer
## k, 8 bytes

`+/1<#:'=`

reads as: sum (length each group) \> 1

```
+/ is sum (plus over)

#:' is length each

= is group (ex. =1 2 1 6 7 2 generates 1 2 6 7!(0 2;1 5;,3;,4) (dictionary of unique value and its positions)

```

Use example (first test case)

```
+/1<#:'=1 10 16 4 8 10 9 19 2 15 18 19 10 9 17 15 19 5 13 20

```

writes 4
> 1 votes

# Answer
# Perl 5 `-ap`, 35 bytes

```
map$k{$_}++,@F;$_=grep$_>1,values%k

```

Try it online!
> 1 votes

# Answer
# Stax, 5 bytes

```
ëB♀╡╙

```

Run and debug it
> 1 votes

# Answer
# Japt `-x`, 5 bytes

```
ü ®¦q

```

Run it online
> 1 votes

# Answer
# Husk, 5 bytes

```
LuṠ-u

```

Try it online!

```
L        The number of
 u       unique elements of
  Ṡ-u    the input with every unique element removed once.

```
> 1 votes

# Answer
# C (gcc), 71 bytes

```
f(r,l,t)int*r;{int n[7<<15]={};for(t=0;l;t+=!~n[r[--l]+100000]--);r=t;}

```

Try it online!

Naive approach. `7<<15`=229376.
> 1 votes

# Answer
# Vyxal, 5 bytes

```
UÞ⊍UL

```

Try it Online!

Typical symmetric difference with the unique values in the list, take the length of the unique values in that list.
> 1 votes

# Answer
# Vyxal, 4 bytes

```
Ċċ∑t

```

Try it Online!

Just another 4 byter

## Explained

```
Ċċ∑t
Ċ     # [[item, count(item)] for item in input]
 ċ    # Each item != 1?
  ∑   # Summate. Because this is implemented as reduce by addition, it vectorises element-wise when folding.
   t  # Get the last item of that (the number of counts that != 1)

```

Created with the help of Luminespire.
> 1 votes

# Answer
# JavaScript (Node.js), 93 bytes

```
a=>Object.values(a.reduce((a,c)=>Object.assign(a,{[c]:(a[c]|0)+1}),{})).filter(i=>i>1).length

```

Try it online!
> 0 votes

# Answer
# JavaScript (Node.js), 67 bytes

```
a=>[...new Set(a.filter(e=>a.indexOf(e)!=a.lastIndexOf(e)))].length

```

Try it online!
> 0 votes

# Answer
# APL(NARS), 9 chars, 18 bytes

```
{≢∪⍵∼⍦∪⍵}

```

test:

```
  f←{≢∪⍵∼⍦∪⍵}
  f 1 2 2 3 1 1 1 1 1 1
2
  f 234, 2, 12, 234, 5, 10, 1000, 2, 99, 234
2
  f 1, 10, 16, 4, 8, 10, 9, 19, 2, 15, 18, 19, 10, 9, 17, 15, 19, 5, 13, 20
4
  f 11, 8, 6, 15, 9, 19, 2, 2, 4, 19, 14, 19, 13, 12, 16, 13, 0, 5, 0, 8
5

```
> 0 votes

---
Tags: code-golf, array
---


title: Visualize the Euclidean algorithm again

text:
# Question
Title: Visualize the Euclidean algorithm again
# Task

Given two positive integers:

1. Draw the rectangle with dimensions specified by the two integers.
2. Repeat Step 3 until there is no more space.
3. Draw and fill the largest square touching three sides of the (remaining) rectangle.
4. Output the resulting rectangle.

# Example

For example, our input is `6` and `10`.

We draw the hollow rectangle of size 6 x 10:

```
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx

```

After repeatedly filling squares, this is what we would obtain:

```
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaaccdd
aaaaaaccdd

```

There are 4 squares here (`a`, `b`, `c`, `d`), each with side length `6`, `4`, `2`, `2` respectively.

# Rules and freedom

1. You must use a different letter for each square.
2. You can choose which letters to support, as long as the letters supported are all printable characters and there are at least `10` characters supported.
3. In each iteration of Step 3 above, you have two choices (except in the last iteration, where you only have one choice). Both choices are valid.
4. The number of squares required will not exceed the number of letters you support.
5. You can fill in the squares with the letters you support in **any order**.

# Testcases

Input: `6, 10`

Output:

```
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaaccdd
aaaaaaccdd

```

or

```
aaaaaaccdd
aaaaaaccdd
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb
aaaaaabbbb

```

or

```
bbbbaaaaaa
bbbbaaaaaa
bbbbaaaaaa
bbbbaaaaaa
ccddaaaaaa
ccddaaaaaa

```

or

```
ccddaaaaaa
ccddaaaaaa
bbbbaaaaaa
bbbbaaaaaa
bbbbaaaaaa
bbbbaaaaaa

```

or

```
ddddddaaaa
ddddddaaaa
ddddddaaaa
ddddddaaaa
ddddddbbcc
ddddddbbcc

```

Input: `1,1`

Output:

```
a

```

Input: `1,10`

Output:

```
abcdefghij

```

Input: `10,1`

Output:

```
a
b
c
d
e
f
g
h
i
j

```

Note that there are more possibilities than I can include for the testcases above.

# Scoring

This is . Shortest answer in bytes wins.

Standard loopholes apply.

# Answer
# Haskell, 90 bytes

```
(['a'..]!)
a?x=a<$[1..x]
((a:b)!y)x|x*y<1=""?y|x>y=map(a?y++)$b!y$x-y|z<-y-x=a?x?x++(b!z)x

```

Try it online!
> 5 votes

# Answer
# Charcoal, 30 bytes

```
ＮδＮγＦβ¿×γδ«ＵＯγδι¿‹γδＡ⁻δγδＡ⁻γδγ

```

Try it online! Explanation:

```
Ｎδ      Input d
Ｎγ      Input g
Ｆβ      For i In ['a' ... 'z']
 ¿×γδ«   If g * d
  ＵＯγδι   Oblong g, d, i
  ¿‹γδ    If g < d
   Ａ⁻δγδ   d = d - g
   Ａ⁻γδγ   Else g = g - d

```

Annoyingly Charcoal's Oblong command won't take `0` for a dimension, which costs me 4 bytes. The other approach would be to loop while `g * d`, but then I couldn't work out how to iterate over `b` (which is predefined to the lowercase letters).
> 3 votes

# Answer
# Uiua, ~~31 bytes~~ 32 bytes

Edit: The `recur ↬` glyph has been removed from the language

```
|2+@`;⍥(⎋=0⧻.⊙⬚0+.↘⇌×⍖.△.)∞.↯∶1⊂

```

Try it online!

**Explanation:**

```
                                  ⊂   # Put the dimensions into an array
                               ↯∶1    # Make a matrix of 1s with the dimensions
                              .       # Copy the result
      ⍥(                   )∞        # Repeat forever
                          △.          # Get the shape of the latest matrix
                       ⍖.            # Get the descending indices
                      ×              # Multiply these with the shape
                                     # (zeros out the larger dimension)
                     ⇌               # Reverse the array
                    ↘                # Remove the largest square from the latest matrix
              ⊙⬚0+.                 # Add the new matrix to the original
                                     # (using 0s where the shape doesn't match)
         ⎋=0⧻.                       # Break if the length of the new matrix is 0
  +@`;                               # Add char ` to the result to get 1=a, b=2, etc.
|2                                   # Signature of function

```

**Example:**

```
Input: 4 2   Stack (top on left):
             # 4 2
⊂            # [4 2]
↯∶1          # ╭─
             # ╷ 1 1
             #   1 1
             #   1 1
             #   1 1
             #       ╯
.            # ╭─      ╭─
             # ╷ 1 1   ╷ 1 1
             #   1 1     1 1
             #   1 1     1 1
             #   1 1     1 1
             #       ╯       ╯
⍥( )∞
△.           # [4 2] ╭─      ╭─
             #       ╷ 1 1   ╷ 1 1
             #         1 1     1 1
             #         1 1     1 1
             #         1 1     1 1
             #             ╯       ╯
⍖.          # [0 1] [4 2] ╭─      ╭─
             #             ╷ 1 1   ╷ 1 1
             #               1 1     1 1
             #               1 1     1 1
             #               1 1     1 1
             #                   ╯       ╯
×            # [0 2] ╭─      ╭─
             #       ╷ 1 1   ╷ 1 1
             #         1 1     1 1
             #         1 1     1 1
             #         1 1     1 1
             #             ╯       ╯
⇌            # [2 0] ╭─      ╭─
             #       ╷ 1 1   ╷ 1 1
             #         1 1     1 1
             #         1 1     1 1
             #         1 1     1 1
             #             ╯       ╯
↘            # ╭─      ╭─
             # ╷ 1 1   ╷ 1 1
             #   1 1     1 1
             #       ╯   1 1
             #           1 1
             #               ╯
⊙⬚0+.       # ╭─      ╭─
             # ╷ 1 1   ╷ 2 2
             #   1 1     2 2
             #       ╯   1 1
             #           1 1
             #               ╯
⧻.           # 2 ╭─      ╭─
             #   ╷ 1 1   ╷ 2 2
             #     1 1     2 2
             #         ╯   1 1
             #             1 1
             #                 ╯
⎋=0          # No break
△.           # [2 2] ╭─      ╭─
             #       ╷ 1 1   ╷ 2 2
             #         1 1     2 2
             #             ╯   1 1
             #                 1 1
             #                     ╯
⍖.          # [0 1] [2 2] ╭─      ╭─
             #             ╷ 1 1   ╷ 2 2
             #               1 1     2 2
             #                   ╯   1 1
             #                       1 1
             #                           ╯
×            # [0 2] ╭─      ╭─
             #       ╷ 1 1   ╷ 2 2
             #         1 1     2 2
             #             ╯   1 1
             #                 1 1
             #                     ╯
⇌           # [2 0] ╭─      ╭─
             #       ╷ 1 1   ╷ 2 2
             #         1 1     2 2
             #             ╯   1 1
             #                 1 1
             #                     ╯
↘            # [] ╭─
             #    ╷ 2 2
             #      2 2
             #      1 1
             #      1 1
             #          ╯
⊙⬚0+.       # [] ╭─
             #    ╷ 2 2
             #      2 2
             #      1 1
             #      1 1
             #          ╯
⧻.           # 0 [] ╭─
             #      ╷ 2 2
             #        2 2
             #        1 1
             #        1 1
             #            ╯
⎋=0          # Break
+@`;         # ╭─
             # ╷ "bb"
             #   "bb"
             #   "aa"
             #   "aa"
             #        ╯

```

~~Previous solution:~~

```
+@`!(|1 ⬚0+↬>0/+△.↘⇌×⍖.△..)↯∶1⊂

```
> 3 votes

# Answer
# Pyth, 34 bytes

```
M?*GH?<HGCgHG+*G]jk*G]~hZgG-HGYjgF

```

Try it online!
> 2 votes

# Answer
# Haskell, 181 bytes

```
import Data.List
(['!'..'~']&)
a#[]=a
a#b=zipWith(++)a$transpose b
(s&a)b|b<1=[]|b>a=transpose$s&b$a|n<-div a b,(t,u)<-splitAt n s=foldl1(#)((<$[1..b]).(<$[1..b])<$>t)#(u&b$mod a b)

```

Try it online!

For `10` bytes more you get a nice spiral instead :)

```
!!!!!!!!!!!!!$$$#####
!!!!!!!!!!!!!$$$#####
!!!!!!!!!!!!!$$$#####
!!!!!!!!!!!!!%%'#####
!!!!!!!!!!!!!%%&#####
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""
!!!!!!!!!!!!!""""""""

```

Try it online!

### Ungolfed

The `(#)` operator puts two matrices next to each other, but transposes the right one, eg:

```
!!!                !!!"
!!! # "#$    ->    !!!#
!!!                !!!$

a # [] = a
a # b  = zipWith (++) a $ transpose b

```

This is basically the recursive version of Euclid's algorithm, but instead of forgetting the divisors&remainders and returning the `gcd`, it builds squares from it and accumulates these with `(#)`. The `s` variable are the remaining characters that we can use:

```
(s & a) b
  | b == 0 = []                     -- Base case
  | b > a = transpose $ (s & b) a   -- In this case we can just flip the arguments and rotate the result by 90 degrees
  | n <- div a b                    -- set n to the number of squares we need
  , (t,u) <- splitAt n s =          -- take n characters, ..
               ((<$[1..b]).(<$[1..b]) <$> t)                     -- .. build squares from them and ..
    foldl1 (#)                                                   -- put them next to each other
                                             (u & b $ mod a b)   -- recursively build the smaller squares with the remaining characters..
                                            #                    -- .. flip them and put them next to the previous one(s)

```

The actual function just calls the function from above with a string of all printable characters:

```
(['!'..'~']&)

```
> 2 votes

# Answer
# Jelly, 32 bytes

```
Ṁ,ạ/y
³,⁴ÇÐĿp/€Fs2
pµ¢ṣLµ€+95ỌsY

```

Try it online!

`Ṁ,ạ/y` you want an explanation? Here it is.

```
Ṁ,ạ/y          - perform one step of the Euclidean Algorithm, input 2-element list
 ,             - pair of the following two:
Ṁ              -  maximum of the the input list
  ạ/           -  absolute difference of the two elements
    y          - use this as a mapping on the input.

³,⁴ÇÐĿp/€Fs2   - apply Euclidean Algorithm
³,⁴            - start with the pair [input 1, input 2]
   Ç           - apply a step of the Euclidean Algorithm
    ÐĿ         - repetitively until the results repeat
      p/€      - take the Cartesian product of each step
         Fs2   - flatten and split into all coordinate pairs of letters

pµ¢ṣLµ€+95ỌsY
p              - Cartesian product of inputs: provides all possible coordinate pairs.
 µ   µ€       - for each coordinate
   ṣL         - find the number of times it is included in
  ¢           - the above list of covered coordinates.
       +95Ọ   - convert number of times to letters
           s  - split into rows
            Y - join by newlines.

```

I can likely golf a little more by using implicit arguments instead of `³,⁴`.
> 1 votes

# Answer
# , 78 bytes

```
>/|:[:u:97+1(0&g@{:]F.:(((g=.$~,~)~1+0{,),(~:#)|:])}:)@}.0}:@{0|:(<.,|@-)/^:a:

```

Attempt This Online!

Surprisingly tough to golf in J. Tried a few approaches, this was the best of them, but still feels like there's room for improvement.

Basic approach:

* Generate successive differences until a repeat, eg: `10 6` gives `6 4 2 2`.
* "Roll it up" starting from the smaller squares (ie, stack a 2x2 on a 2x2, then transpose it and put a 4x4 on that, then transpose that and put a 6x6x on top of it). We do transposes as needed to make the side lengths line up. We always stack our new larger square atop the result up to that point. The whole computation is expressed as a fold.
* The first square starts as a square of zeroes, and as we add each additional square its number increments by one. At the end we have our result but with numbers instead of letters.
* Convert the numbers to ascii letters.
* Finally, transpose the entire result if needed, so that the result dimensions match the order of the arguments.
> 1 votes

# Answer
# , 30 bytes

```
[:u:97+0]F.:({.>:)(-/:*|.)^:a:

```

Attempt This Online!

Saw `... F.: ... ^:a:` in Jonah's answer and thought it might work better, and it actually did. Remove the leading `[:u:97+` to get a numeric matrix.

```
[:u:97+0]F.:({.>:)(-/:*|.)^:a:    input: a vector of dimensions
                  (      )^:a:    repeat until convergence and collect iterations:
                   -/:*|.         subtract smaller from larger
                                  (it stops when one side becomes zero)
                      [10,4] becomes [[10,4],[6,4],[2,4],[2,2],[2,0]]
       0]F.:({.>:)    construct the numeric matrix:
       0]F.:(    )    fold from the right, starting with single 0,
             {.>:     increment the input matrix and pad with zeros
                      to the size of the next larger dimensions
[:u:97+    map 0, 1, ... to a, b, ...

```

---

# , 37 bytes

```
[:u:97+f=:$&0`({.1+[:f]-/:*|.)@.(~:/)

```

Attempt This Online!

Recursive function seems to be the way here. Takes a vector of two positive integers and returns a character matrix. If a numeric matrix is acceptable, 28 bytes: `$&0`({.1+[:$:]-/:*|.)@.(~:/)`.

```
[:u:97+f=:$&0`({.1+[:f]-/:*|.)@.(~:/)
       f=:$&0`({.1+[:f]-/:*|.)@.(~:/)    inner recursive function
             `                @.(~:/)    if two parts are equal,
          $&0                            create a zero matrix of that dimensions
              (              )      otherwise,
                      ]-/:*|.       subtract the smaller part from the larger part
                   [:f              recurse
               {.1+                 add 1 to each element and pad to the requested size
                                    with zeros
[:u:97+    map 0, 1, ... to a, b, ...

```
> 1 votes

# Answer
# JavaScript (V8), 111 bytes

```
x=>h=(y,i=x,j=y)=>j?(g=(x,y,k)=>(x>y?x-=y:y-=x,i)?x<i|y<j?k:g(x,y,k+1):`
`)(x,y,0)+(i?h(y,i-1,j):h(y,x,j-1)):''

```

Try it online!
> 0 votes

---
Tags: code-golf, ascii-art, arithmetic
---


title: Fold a List in Half

text:
# Question
Title: Fold a List in Half
We are going to fold a list of integers. The procedure to do so is as follows, If the list is of even length, make a list of half of its length where the nth item of the new list is the sum of the nth item of the old list and the nth-to-last item of the old list. For example if we had the list

```
[1 2 3 4 5 6 7 8]

```

We would fold it like so

```
 [8 7 6 5]
+[1 2 3 4]
__________
 [9 9 9 9]

```

If the list is of *odd* length, to fold it we first remove the middle item, fold it as if it were even and the append the middle item to the result.

For example if we had the list

```
[1 2 3 4 5 6 7]

```

We would fold it like so

```
 [7 6 5]
+[1 2 3]
__________
 [8 8 8]
++     [4]
__________
 [8 8 8 4]

```

## Task

Write a program or function that takes a list of integers as input and outputs that list folded.

This is a question so answers will be scored in bytes, with fewer bytes being better.

## Sample implementation

Here's an implementation in Haskell that defines a function `f` that performs a fold.

```
f(a:b@(_:_))=a+last b:f(init b)
f x=x

```

Try it online!

# Answer
> 11 votes
# Python, 46 bytes

```
f=lambda l:l[1:]and[l[0]+l[-1]]+f(l[1:-1])or l

```

Try it online!

Same length:

```
f=lambda l:l[1:]and[l.pop(0)+l.pop()]+f(l)or l

```

A much shorter solution works for even-length lists (30 bytes)

```
lambda l:[x+l.pop()for x in l]

```

Try it online!

I'm still trying to find a short way to correct it for odd length.

# Answer
> 10 votes
# Emojicode, 203 bytes

```
i⏩0➗2➕i➖➕1i1012➗210

```

This was the most painful Emojicode answer to code for me. The unnecessary length :/

Try it online!

# Answer
> 8 votes
# 05AB1E, 5 bytes

### Code

```
2ä`R+

```

Uses the **05AB1E** encoding. Try it online!

### Explanation

```
2ä        # Split the list into two pieces
  `       # Flatten the stack
   R      # Reverse the second element from the list
    +     # Vectorized addition

```

# Answer
> 4 votes
# Japt, ~~21~~ ~~18~~ 16 bytes

```

l
íUj°V/2V w)mx

```

Test it online!

~~Completely awful~~ Slightly less awful thanks to @Oliver. BRB after I implement more built-ins and fix some bugs...

# Answer
> 3 votes
# Jelly, 7 bytes

```
œs2U2¦S

```

Try it online!

-2 thanks to ETHproductions...and me realizing before.

# Answer
> 3 votes
# Gaia, 7 bytes

```
e2÷ev+†

```

### Explanation

```
e        Eval the input (push the list).
 2÷      Split it in half. The first half will be longer for an odd length.
   e     Dump the two halves on the stack.
    v    Reverse the second.
     +†  Element-wise addition. If the first half has an extra element, it is simply appended.

```

# Answer
> 3 votes
# C (gcc), ~~55~~ 41 bytes

```
f(_,l)int*_;{for(;l--;*_+++=l?_[l--]:0);}

```

Try it online!

Overwrites the first \\$\left\lfloor\frac{l}{2}\right\rfloor\\$ entries of the input array.

### C (gcc), 46 bytes

```
f(_,l)int*_;{_=l>1?*_+=_[l-1],1+f(_+1,l-2):l;}

```

Try it online!

Additionally returns the length \\$\left\lceil\frac{l}{2}\right\rceil\\$ of the output.

# Answer
> 3 votes
# Vyxal, 4 bytes

```
I÷Ṙ+

```

Try it Online!

```
I    # Halve the list
 ÷   # Push each half
  Ṙ  # Reverse the second half
   + # Add them together (vectorising)

```

# Answer
> 3 votes
# Pip, ~~14~~ 12 bytes

```
YCHa;@y+Ry@1

```

-2 Thanks to DLosc!

How?

```
YCHa;@y+Ry@1  : One arg; list
   a          : First input
 CH           : Chop iterable into 2 pieces of roughly equal length
Y             : Yank value
         y    : The two halves
          @1  : Get item/slice at index 1; The second half
        R     : Reverse
       +      : Add with
      y       : The two halves
     @        : Get item at index 0; The first half

```

Try It Online!

# Answer
> 3 votes
# Fig, \\$23\log\_{256}(96)\approx\\$ 18.932 bytes

```
J+t_HLxxt_HLx$xs_HLxtHL

```

Try it online!

\\$-26\log\_{256}(96)\approx21.401\\$ thanks to Seggan

First time using Fig. Any golfing tips are welcome.

### Explanation (outdated):

```
fw+[yfy$fy$fyx[yfy$fy$fy$x?h%1HLx[]yfy$fy$fyx]yW1
   [yfy$fy$fyx                                    First Mid
  +                                               Add
              [yfy$fy$fy$x                        Second Mid
fw                                                Concat
                          ?                       If
                           h%1HLx                 List length is odd,
                                 []yfy$fy$fyx     Mid
                                             ]yW1 Else Empty list

```

# Answer
> 3 votes
# Thunno 2, ~~7~~ 5 bytes

```
2ẆẸr+

```

Attempt This Online!

```
2ẆẸr+ # implicit input
2Ẇ    # split list in half
  Ẹ   # push both halves to the stack
   r  # reverse top one
    + # vectorized addition
      # implicit output

```

# Answer
> 2 votes
# , ~~81~~ ~~70~~ ~~68~~ 57 bytes

```
function(l)c((l+rev(l))[1:(w=sum(l|1)/2)],l[w+1][!!w%%1])

```

Try it online!

anonymous function; returns the result.

# Answer
> 2 votes
# Mathematica, 88 bytes

```
(d=Array[s[[#]]+s[[-#]]&,x=⌊t=Length[s=#]/2⌋];If[IntegerQ@t,d,d~AppendTo~s[[x+1]]])&

```

# Answer
> 2 votes
## Mathematica 57 Bytes

```
(#+Reverse@#)[[;;d-1]]&@Insert[#,0,d=⌈Length@#/2⌉+1]&

```

Inserts a zero at the midpoint, adds the list to its reverse and takes the appropriate length.

# Answer
> 2 votes
# JavaScript (Node.js), 53 bytes

```
x=>x.splice(0,x.length/2).map(y=>y+x.pop()).concat(x)

```

Try it online!

Another suggestion:

# JavaScript (Node.js), 43 bytes

```
f=x=>x+x?[x.pop()+(0|x.shift()),...f(x)]:[]

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 41 bytes

```
f=a=>1/a[1]?[a.shift()+a.pop(),...f(a)]:a

```

```
f=a=>1/a[1]?[a.shift()+a.pop(),...f(a)]:a

console.log(JSON.stringify(f([1,2,3,4,5,6,7,8])));
console.log(JSON.stringify(f([1,2,3,4,5,6,7])));
```

# Answer
> 2 votes
# Japt, 12 bytes

```
å@o +Y*(Z<Ul

```

Try it online! with the `-Q` flag to view the formatted array.

## Alternate solution, 14 bytes

```
o(½*Ul)c)íU mx

```

Try it online!

# Answer
> 2 votes
# Zsh, 55 bytes

If the answer must be put to stdout, but output whitespace is flexible, **55 bytes**:

```
for ((;++i<=#/2;))<<<$[$@[i]+$@[-i]]
<<<$@[#%2*(1+#/2)]

```

Try it online!

---

If the output must be stored in an array, **53 bytes**: (We can't use this method in place of the above because of `<<<...[--i]...`. The here-string forces a subshell, so the decremented value of `i` never makes it out.)

```
for n ($@[1,#/2])y+=($[$@[--i]+n])
y+=$@[#%2*(1+#/2)]

```

Try it online!

If the answer must be output in one line separated by spaces, then append `<<<$y` for a 6 byte penalty.

---

Zsh arrays are indexed from the start starting at `1`, or from the end starting at `-1`. So what happens if you attempt to index at `0`? Well, nothing! We take advantage of that here to only output the middle number based on a parity check:

```
$@[#%2*(1+#/2)]
   #      #       # parameter count
       (1+#/2)    # index of the middle element when count is odd
   #%2*(1+#/2)    # multiply by 0 if even, or 1 if odd
$@[           ]   # Index the parameter array

```

# Answer
> 2 votes
# Factor, 35 bytes

```
[ halves reverse 0 pad-longest v+ ]

```

Try it online!

## Explanation

It's a quotation (anonymous function) that takes a sequence from the data stack and leaves a sequence on the data stack. Assuming `{ 1 2 3 4 5 6 7 }` is on the data stack when this quotation is called...

| Snippet | Comment | Data stack (top on right) |
| --- | --- | --- |
| `halves` | Split a sequence in half | `{ 1 2 3 } { 4 5 6 7 }` |
| `reverse` | Reverse a sequence | `{ 1 2 3 } { 7 6 5 4 }` |
| `0 pad-longest` | Pad the shorter of two sequences with 0s until it's the same length as the longer sequence | `{ 1 2 3 0 } { 7 6 5 4 }` |
| `v+` | Vector addition; element-wise addition between two sequences | `{ 8 8 8 4 }` |

# Answer
> 2 votes
# Go, 115 bytes

```
func(x[]int)(o[]int){s:=len(x)
for i:=range x[:s/2]{o=append(o,x[i]+x[s-i-1])}
if s%2>0{o=append(o,x[s/2])}
return}

```

Attempt This Online!

### Generic with custom operator, 136 bytes

```
func f[T any](x[]T,O func(T,T)T)(o[]T){s:=len(x)
for i:=range x[:s/2]{o=append(o,O(x[i],x[s-i-1]))}
if s%2>0{o=append(o,x[s/2])}
return}

```

Attempt This Online!

# Answer
> 2 votes
# C (gcc), ~~62 bytes~~ 60 bytes

-2 bytes thanks to @ceilingcat

```
i;f(v,l)int*v;{for(i=0;i<l/2;++i)v[i]+=v[l+~i];return~l/-2;}

```

`f` is a function taking vector (`v`) and length (`l`) as arguments. It modifies the vector and returns the new length.

Try It Online!

How it works:

```
i;
f(v,l) int*v; // v is an integer pointer (or array), l is an integer
{
    for (i = 0; i < l / 2; ++i) // iterate through half the indices using i (if l is odd, the middle element won't be included)
        v[i] += v[l + ~i]; // add the value at the i'th index from the back to the i'th index from the front. ~i == -i - 1, so l + ~i == l + -i -1 = l - i - 1 (l - 1 is the first index from the back, and we subtract i for each index beyond the first)
    return ~l / -2; // return half the length rounded up (~l == -l - 1 => ~l / -2 == (-l - 1) / -2 => (l + 1) / 2
}

```

# Answer
> 2 votes
# Curry (PAKCS), 34 bytes

```
f(a:b++[c])=a+c:f b
f x@([]?[_])=x

```

Attempt This Online!

Based on the sample implementation in Haskell.

# Answer
> 2 votes
# Julia 1.0, ~~69~~ 68 bytes

```
!s=(~=length;~s%2>0&&insert!(s,(1+~s)÷2,0);(s+reverse(s))[1:~s÷2])

```

Try it online!

-1 byte thanks to MarcMush: replace `==1` with `>0`

# Answer
> 2 votes
# BQN, ~~15~~ 12 bytes

```
(⌊≠÷2˙)⊸↑⊢+⌽

```

Try it online!

-3 thanks to Marshall Lochbaum

Sum the list and its reverse, then take the first `⌊≠÷2˙` digits. `⌊≠÷2˙` the floor of the length divide 2. Floor is necessary because there is no integer division in BQN.  is used to bind the output of `⌊≠÷2˙` to the take operator  on the left and also puts the output of `(⊢+⌽)` on the right. Better explanation here.

# Answer
> 2 votes
# Nibbles, 6.5 bytes

```
/`\~_!:\@0@+

```

Attempt This Online!

```
/   Fold
`\~  split into two parts
_     input (row from STDIN as a list of integers)
!    zip
:     join
\      reverse
@       the second part
0      0
@     the first part
+     with addition

```

# Answer
> 2 votes
# Nekomata, 6 bytes

```
;ᶜç↔ᶻ+

```

Attempt This Online!

```
;ᶜç↔ᶻ+
;       Nondeterministically split the input into two parts
 ᶜç     Optionally prepend a zero to the second part
   ↔    Reverse the second part
    ᶻ+  Zip with addition

```

The `+` operator is automatically vectorized, but it does not check if the two operands have the same length. So here I use  (`\zip`) to make sure that the two parts are of equal length.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 35 bytes

```
Set[f[a_,b___,c_],a+c,f@b]
f@a___=a

```

Try it online!

Input `[list...]`. Returns a sequence.

---

## Wolfram Language (Mathematica), 39 bytes

```
f@{a_,b___,c_}:={a+c,##&@@f@{b}}
f@a_=a

```

Try it online!

Input and output a list instead of a sequence.

# Answer
> 2 votes
# Perl 5 `-aE`, 36 bytes

```
map{$F[$_]+=pop@F}0..$#F/2-1;say"@F"

```

Takes advantage of the autosplit flag and iterates through the first half (rounded down) of the resulting list, modifying it in-place.

Slightly ungolfed:

```
for (0 .. ($#F / 2) - 1) {
    $F[$_] += pop(@F);
}
say "@F";

```

Try it online!

# Answer
> 2 votes
# sed `-E`, 60 bytes

```
s/^/</
:a
s/<(!*);(.*;)?(!*);$/\1\3,<\2/
ta
s/[<;]//g
s/,$//

```

Only works with zero and positive numbers. Input is repeated exclamation marks separated by semicolons. Output is repeated exclamation marks separated by commas.

Try it online!

# Answer
> 2 votes
# Uiua, 12 bytes

```
⬚0+⇌⊃↘↙⌊÷2⧻.

```

Try it online!

```
⬚0+⇌⊃↘↙⌊÷2⧻.   input: a numeric vector
           ⌊÷2⧻     half of length, rounded down (let's call it k)
     ⊃↘↙     .   fork(drop, take): first k elements removed, first k elements
   ⇌               reverse the top
⬚0+                elementwise add, filling with zeros when lengths don't match

```

# Answer
> 1 votes
# Python 3, 101 bytes

```
lambda l:[sum(x)for x in zip(l[:len(l)//2],l[int(len(l)/2+.5):][::-1])]+[[],[l[len(l)//2]]][len(l)%2]

```

Try it online!

# Answer
> 1 votes
# Pyth, ~~18~~ ~~17~~ 13 bytes

```
V.Tc2Q aYsN;Y

```

My original approach was

```
WtQ aY+.)Q.(Q0;+Y

```

*-1 byte thanks to Mr. Xcoder*

*-4 bytes thanks to FryAmTheEggman*

# Answer
> 1 votes
# JavaScript, ~~75~~ 71 bytes

```
a=>a.slice(0,n=a.length/2).map(b=>b+a[--z],z=n*2).concat(n%1?a[n|0]:[])

```

Try it online

*Saved 2 bytes thanks to ETHproductions*

# Answer
> 1 votes
# Python 3, 70 bytes

```
lambda l:[l[i]+l[~i]for i in range(len(l)//2)]+len(l)%2*[l[len(l)//2]]

```

Try it online!

# Answer
> 1 votes
# C# (.NET Core), ~~118~~ 111 bytes

```
a=>a.Reverse().Zip(a,(c,d)=>c+d).Take(a.Length/2).Concat(a.Skip(a.Length/2).Take(a.Length%2))

```

Byte count also includes

```
using System.Linq;

```

Try it online!

As input please use numbers separated either with commas (`,`) or space. Explanation:

```
a =>                                  // Take one input parameter (array)
a.Reverse()                           // Reverse it
.Zip(a, (c, d) => c + d)              // Take every corresponding member of reversed
                                      //    and original, and add them together
.Take(a.Length / 2)                   // Get first half of the collection
.Concat(                              // Add another collection
    a.Skip(a.Length / 2)              // Take input and leave out first half of it
    .Take(a.Length % 2)               // If length is odd, take first element (so the middle)
                                      //    otherwise create an empty collection
);

```

# Answer
> 1 votes
## JavaScript (ES6), ~~46~~ 43 bytes

```
f=(a,[b,...c]=a)=>c+c?[b+c.pop(),...f(c)]:a

```

```
f=(a,[b,...c]=a)=>c+c?[b+c.pop(),...f(c)]:a

console.log(f([1,2,3,4,5,6,7,8]).join(', ')) // 9, 9, 9, 9  ✓
console.log(f([1,2,3,4,5,6,7]).join(', '))   // 8, 8, 8, 4  ✓
```

```
.as-console-wrapper{max-height:100%!important}
```

*Saved 3 bytes with inspiration from Asaf.*

# Answer
> 1 votes
# MATL, 9 bytes

```
`6L&)swtn

```

Try it online!

### How it works

Given an array `[a b c ... x y z]`, let `[a z]` be called the "crust" subarray and `[b c ... y z]` the "core" subarray.

The code consists in a loop that removes the crust, computes its sum, and moves the core to the top of the stack, ready for the next iteration. The loop condition is the number of elements in the core subarray

```
`       % Do...while
  6L    %   Push [2 -1+1j]. As an index, this is interpreted as 2:end-1
  &)    %   2-output reference indexing: pushes a subarray with the indexed
        %   elements (core) and another with the ramaining elements (crust)
  s     %   Sum of (crust) subarray
  w     %   Swap. Moves the core subarray to the top
  t     %   Duplicate
  n     %   Number of elements.
        % End (implicit). Procced with next iteration if top of the stack is
        % nonzero; else exit
        % Display stack (implicit)

```

# Answer
> 1 votes
## Perl, 42 38 chars

sub f{@a=map{$*+pop}splice@*,0,@*/2;@a,@*}

```
sub f{(map{$_+pop}splice@_,0,@_/2),@_}

```

Try for example like so:

```
perl -e 'my @input=(1..9); sub f{(map{$_+pop}splice@_,0,@_/2),@_}  print join(",",f(@input));

```

# Answer
> 1 votes
# WendyScript, 72 bytes

```
<<f=>(l){<<r=[]<<b=l.size#i:0->b/2r+=l[i]+l[b-i-1]?b%2!=0r+=l[(b/2)]/>r}

f([1,2,3,4,5,6,7,8]) // => [9,9,9,9]
f([1,2,3,4,5,6,7]) // => [8,8,8,4]

```

Try it online!

# Answer
> 1 votes
# Scala, 91 bytes

```
(s:Seq[Int])=>(s.take(s.size/2),s.reverse).zipped.map(_+_)++s.drop(s.size/2).take(s.size%2)

```

# Answer
> 1 votes
## *Mathematica*, 52

```
(a=#;i=0;(i++;a[[i;;-i]]*=x)&/@a;(Tr@a+O@x^i)[[3]])&

```

# Answer
> 1 votes
# C++17, ~~75~~ ~~73~~ 71 bytes

As unnamed lambda, accepting a container like `vector` or `list`, returns via modifying the input:

```
[](auto&L){for(auto a=L.begin(),b=L.end();a<--b;L.pop_back())*a+++=*b;}

```

Using the well known 'goes-to' operator `<--` and the triple plus `+++`

Ungolfed and example:

```
#include<iostream>
#include<vector>

using namespace std;

auto f=
[](auto&L){
 for(
  auto a=L.begin(),b=L.end();
  a<--b;
  L.pop_back()
 )
 *a+++=*b;
}
;

void test(auto L) {
 for(auto x:L)cout << x << ", ";
 cout << endl;
 f(L);
 for(auto x:L)cout << x << ", ";
 cout << endl << endl;
}

int main() {
 vector<int> A = {1,2,3,4,5,6,7,8}, B = {1,2,3,4,5,6,7};
 test(A);
 test(B);
}

```

# Answer
> 1 votes
# Java 8, 93 bytes

Double digits! This is a lambda that takes an `int[]` and returns an `int[]`.

```
l->{int n=l.length,i=0;for(;i<n/2;)l[i]+=l[n-++i];return java.util.Arrays.copyOf(l,n/2+n%2);}

```

## Ungolfed lambda

```
l -> {
    int n = l.length, i = 0;
    for (; i < n / 2; )
        l[i] += l[n - ++i];
    return java.util.Arrays.copyOf(l, n / 2 + n % 2);
}

```

Quite straightforward. It folds the second half in place onto the first half of the input and returns a copy of just the first half.

Surprisingly, the array copy in the return statement seems to be the cheapest way to handle the final element quirk for odd-length inputs.

# Answer
> 1 votes
# PHP, 67 bytes

```
function($l){while($l)$o[]=array_shift($l)+array_pop($l);return$o;}

```

Try it online!

# Answer
> 1 votes
# Perl 6, 28 bytes

```
{.[^*/2]Z+.[$_-1...$_/2,$_]}

```

Try it online!

### Explanation:

```
{                          }   # Anonymous code block
 .[^*/2]                       # The first half of the list
        Z+                     # Zip added to
          .[$_-1...$_/2        # The other half of the list
                       ,$_]    # And zero for the middle element

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 21 bytesSBCS

-3 bytes thanks to @Adám.

```
(⌊2÷⍨≢)(↑{+⌿↑⍺⍵}∘⌽↓)⊢

```

Try it online!

Explanation:

```
(⌊2÷⍨≢)(↑{+⌿↑⍺⍵}∘⌽↓)⊢  ⍝ Monadic function train
(⌊2÷⍨≢)                  ⍝ Left portion:
     ≢                   ⍝ Take the length of the input...
  2÷⍨                    ⍝ Divide it by two...
 ⌊                       ⍝ And floor it. This gives our midpoint index. Call it "X"
                      ⊢  ⍝ Right portion: return the original input. Call it "Y"
       (↑{+⌿↑⍺⍵}∘⌽↓)   ⍝ Midddle portion: takes X and Y as arguments
        ↑           ↓    ⍝ Take and drop Y by X. Essentially splits Y in half
                         ⍝ Presents the two halves to the next function
                 ∘⌽     ⍝ Reverse the second half
         {+⌿↑⍺⍵}       ⍝ Final function, takes first half and reversed second half
              ⍺⍵        ⍝ Construct a nested list of first and second halves...
             ↑          ⍝ ...and "mix" them into a matrix. Has the nice property that
                        ⍝ it will pad the first half with a zero if needed.
          +⌿           ⍝ Sum the matrix along the columns, return resulting vector

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 71 bytes

```
x=>{int i=0,l=x.Length;for(;i<l/2;)x[i]+=x[l-++i];return x[..(l-l/2)];}

```

Try it online!

-2 bytes thanks to @ceilingcat!

# Answer
> 1 votes
# , 22 bytes

```
({.+/@,:|.@}.)~>.@-:@#

```

Try it online!

# Answer
> 1 votes
# Ruby, 34 bytes

```
f=->l{l[1]?[l.shift+l.pop]+f[l]:l}

```

Try it online!

# Answer
> 1 votes
## Common Lisp, 106 bytes

```
(lambda(l)(setf(values a b)(floor(length l)2))`(,@(#1=subseq(mapcar'+ l(reverse l))0 a),@(#1#l a(+ a b))))

```

Try it online!

# Answer
> 1 votes
# Java (JDK), ~~102~~ 95 bytes

```
i->{int l=i.length,o=l/2+l%2,r[]=new int[o];for(;o-->0;)r[o]=i[o]+(o<l+~o?i[l+~o]:0);return r;}

```

Try it online!

-7 Thanks to Kevin Cruijssen

# Answer
> 1 votes
# jq, 58 bytes

```
[reverse[:length/2],.[:length/2|floor]]|transpose|map(add)

```

Try it online!

# Answer
> 1 votes
# Scala, 65 bytes

```
l=>l take(l.size+1)/2 zipAll(l.reverse take l.size/2,0,0)map(_+_)

```

Try it in Scastie!

# Answer
> 1 votes
# k9, 12 bytes

```
+/++(;|)@'2^

```

Version 2021.09.20.

Cut in two, reverse second list, pad with zeroes, add.

# Answer
> 1 votes
# Thunno, \\$ 10 \log\_{256}(96) \approx \\$ 8.23 bytes

```
2APAur0Tz+

```

Attempt This Online!

Sort-of port of Adnan's 05AB1E answer

**Explanation:**

```
2APAur0Tz+  # Implicit input
2AP         # Split in half
   Au       # Dump onto stack
     r      # Reverse top item
      0T    # Append a 0
        z+  # Zipped addition

```

Thunno's normal addition (`+`) will provide a nested list of each element of the first list plus each element of the second list.

Thunno's zipped addition (`z+`) zips the two lists together, discarding items if they are not of equal length.

So, we must append a 0 to the top list (since it will be the shorter one if the input contained an odd number of items) and then use zipped addition.

# Answer
> 1 votes
# Japt, 10 bytes

There's gotta be a 9 here, somewhere.

```
òUÊ/2 oÔyx

```

Try it

```
òUÊ/2 oÔyx     :Implicit input of array U
ò              :Partitions of length
 UÊ            :  Length of U
   /2          :  Divided by 2
      o        :Modify last element
       Ô       :  Reverse
        y      :Transpose
         x     :Reduce each by addition

```

## Also 10 bytes

```
íUÔoUÊz¹mx

```

Try it

```
íUÔoUÊz¹mx     :Implicit input of array U
í              :Interleave with
 UÔ            :  Reverse U (mutates the original)
   o           :  Pop this many items (also mutates the original)
    UÊ         :    Length of U
      z        :    Floor divided by 2
       ¹       :End interleave
        m      :Map
         x     :  Reduce by addition

```

# Answer
> 1 votes
# JavaScript (Node.js), 41 bytes

```
f=([b,...c])=>1/b?[b+~~c.pop(),...f(c)]:c

```

Try it online!

So many ways to reach 41

# Answer
> 0 votes
# JavaScript (Node.js), 62 bytes

```
a=>a.map((e,i)=>e+a[c=(b=a.length)-i-1]*(c!=i)).slice(0,++b/2)

```

Try it online!

---
Tags: code-golf, array
---


title: Find the largest value of power.

text:
# Question
Title: Find the largest value of power.
Some numbers can be represented as perfect powers of other numbers. A number x can be represented as x = base^power for some integer base and power.

Given an integer x you have to find the largest value of power, such that base is also an integer.

```
Sample Input:
9
Sample Output:
2

```

# Answer
> 3 votes
## Golfscript - 26 chars

```
~:x,{:b;x,{b?x=b*}%+}*$-1>

```

Rough translation to Python

```
x=input()
acc = []
for b in range(x):
    for _ in range(x):
        acc.append((_**b==x)*b) # most of these are zeros
print max(acc)

```

So it loops way more times that necessary, but that often happens with golfed answers

# Answer
> 3 votes
# APL (Dyalog Extended), 13 bytes

```
⌈/⍳×∘(⊢=⌊)⍳√⊢

```

Try it online!

```
⌈/⍳×∘(⊢=⌊)⍳√⊢     Monadic train taking an input n:
         ⍳√⊢     Get the 1st, ..., nth roots of n.
    (⊢=⌊)        Find whether each element equals its floor; i.e. is an integer.
                Returns a list of 0s and 1s.
  ⍳              List of 1, ..., n
   ×            Multiply that with the binary list.
                Now we have a list starting with 1 (since the 1st root of n is n, an integer)
                and larger nonzero values corresponding to the other roots that are integers.
⌈/              Find the maximum.

```

# Answer
> 3 votes
# Uiua, ~~11~~ 10 bytes

*Edit: -1 byte thanks to ovs*

```
⊢⇌⍖◿1ⁿ÷⇡,1

```

Try it!

A different approach to Bubbler's Uiua answer, for the same number of bytes.

```
       ÷⇡,1   # reciprocals of 0..input
      ⁿ       # input to the power of those (so: roots)
    ◿1        # modulo 1 (so whole numbers become zero)
   ⍖          # fall: indices if it was sorted descending
              # (index of largest root that is a whole number is now last)
⊢⇌            # get the last item

```

# Answer
> 2 votes
## Haskell, ~~63~~ 56 characters

Handles ℤ\>0 (56 characters)

```
main=do n<-readLn;print$last[p|p<-[0..n],b<-[0..n],b^p==n]

```

Handles ℤ≥0 (58 characters)

```
main=do n<-readLn;print$last[p|p<-[0..n+1],b<-[0..n],b^p==n]

```

Handles ℤ (70 characters)

```
main=do n<-readLn;print$last[p|p<-[0..abs n+1],b<-[n..0]++[0..n],b^p==n]

```

# Answer
> 2 votes
# Japt `-h`, 9 bytes

```
õ f@qX v1

```

Try it

```
õ f@qX v1     :Implicit input of integer U
õ             :Range [0,U]
  f@          :Filter as X
    qX        :  Xth root of U
       v1     :  Divisible by 1?
              :Implicit output of last element

```

# Answer
> 2 votes
# 05AB1E (legacy), ~~9~~ ~~8~~ 4 bytes

```
Ó0K¿

```

-1 byte thanks to *@Don't be a x‑triple dot*.
Only works in the Python legacy version of 05AB1E, because  should be `DïQ` in the Elxiir rewrite due to a bug; and it's also way slower due to `zm`.
-4 bytes porting *@recursive*'s Stax answer.

Try it online or verify all integers in the range `[2,100]`.

**Previous ~~9~~ 8 bytes solution:**

```
Lʒzm.ï}à

```

Try it online or verify all integers in the range `[2,100]`.

**Explanation:**

```
Ó      # Get the exponents of the (implicit) input's prime factorization
 0K    # Remove all 0s
   ¿   # Pop and push the Greatest Common Divisor (GCD) of this list
       # (which is output implicitly as result)

```

\\$b^{^\frac{1}a}\\$ is another way to write \\$\sqrt\[^a\]{b}\\$

```
L      # Create a list in the range [1, (implicit) input]
 ʒ     # Filter this list of integers by:
  z    #  Pop the value and push 1/value instead
   m   #  Then take it to the power of the (implicit) input
    .ï #  And check if it's an integer without decimal values after the period
 }à    # After the filter: pop the list and push the maximum
       # (which is output implicitly as result)

```

# Answer
> 2 votes
# Stax, 4 bytes

```
|n|g

```

Run and debug it

`|n` gets the prime factor exponents of the input. `|g` calculates the GCD of the result.

# Answer
> 2 votes
# Uiua, 10 bytes

```
⊢⍖=⊞ⁿ.⇡+1.

```

Try it online!

-1 thanks to Dominic van Essen.

```
⊢⍖=⊞ⁿ.⇡+1.   input: positive integer n >= 2
        ⇡+1    range from 0 to n inclusive
    ⊞ⁿ.       cartesian product with itself by power
               (the k-th row contains x^k for x = 0..n)
   =       .   for each element, 1 if it equals n, 0 otherwise
               (higher power gives 1 at an earlier position,
                so the highest power is the lexicographically highest row)
⊢⍖            index of the maximum row lexicographically

```

---

# Uiua, 11 bytes

```
⊢⍏⊗∶⊞ⁿ.⇡+1.

```

Try it online!

```
⊢⍏⊗∶⊞ⁿ.⇡+1.    input: positive integer n >= 2
         ⇡+1    range from 0 to n inclusive
     ⊞ⁿ.       cartesian product with itself by power
                (the k-th row contains x^k for x = 0..n)
   ⊗∶       .   the index of n in each row of the matrix, n+1 if not present
                (higher power gives lower index)
⊢⍏             index of the minimum element

```

# Answer
> 1 votes
**Buggy Golfscript - 59**

```
~0\1{1{1$1$?3$={p;\)\.(.}{}if).3$=!}do;).2$=!}do;;{}{1p}if

```

This is my first attempt with golfscript, so it probably can be improved in length.

Now the buggy part comes from the fact that this runs perfectly on the interpreter written in perl, but in the original ruby version, I'm having a really weird bug. I spent a couple of hours trying to wrap my head around it but I can't figure it out. I decided to post anyway to maybe get some feedback.

# Answer
> 1 votes
## Python, 72 chars

```
x=range(1,input()+1)
print max(p*sum(b**p==len(x)for b in x)for p in x)

```

# Answer
> 1 votes
# Vyxal, 23 bitsv2, 2.875 bytes

```
∆ǐġ

```

Try it Online!

Bitstring:

```
00010101110010111001101

```

Ports Recursive's answer in Stax

# Answer
> 0 votes
## Mathematica : 61 chars

. First try:

```
Max[k/.Table[Solve[Log@#/Log@b==k,k,Integers],{b,2,#}]][[1]]&

```

# Answer
> 0 votes
### CSharp - 130 chars

```
void Main(){var i = Int32.Parse(Console.ReadLine());Console.WriteLine(Enumerable.Range(2,i-2).Last(k => Math.Pow(i,1.0/k)%1==0));}

```

# Answer
> 0 votes
# APL(NARS), 34 chars, 68 bytes

```
{⍵≤1:∞⋄⌈/i/⍨{0=1∣⍵√w}¨i←⍳n←⌊2⍟w←⍵}

```

The idea is that the max possible exponent is n←⌊2⍟argument, so i build one range on that: 1..n and to get the max possible exponent; test:

```
  f←{⍵≤1:∞⋄⌈/i/⍨{0=1∣⍵√w}¨i←⍳n←⌊2⍟w←⍵}
  f 25
2
  f 30
1
  f 8
3
  f  323*(2×3)
6

```

They want max exponent, right?

# Answer
> 0 votes
# Scala, 70 bytes

Golfed version. Try it online!

```
x=>(for{b<-0 to x-1;a<-0 to x-1;if Math.pow(a,b).toInt==x}yield b).max

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    def f(x: Int): Int = {
      val acc = for {
        b <- 0 until x
        a <- 0 until x
        if scala.math.pow(a, b).toInt == x
      } yield b
      acc.max
    }

    println(f(9))
  }
}

```

---
Tags: code-golf, number-theory
---


title: Is it a Valid Crossword Grid?

text:
# Question
Title: Is it a Valid Crossword Grid?
In crossword terminology, the *grid* is the region into which the crossword answers are inserted, consisting of white and black squares. The crossword answers, called *entries*, are inserted into contiguous sequences of white squares in a row or column, separated by black squares.

For straight (American) crosswords, the grids usually follow a specific set of rules:

* They should have 180 degree rotational symmetry (if there is a black square in the \\$x\\$th row and \\$y\\$th column, there should be a black square in the \\$x\\$th-to-last row and \\$y\\$th-to-last column).
* All entries must be at least 3 squares long.
* All white squares must be joined in a single region.
* No row/column can be completely filled with black squares.
* Every white cell/square must be the intersection of both a horizontal and a vertical entry.

Some examples of invalid and valid crossword grids:

**Your challenge:** given a grid consisting of two unique values representing black and white squares, determine if it's a valid crossword grid. Assume that it's a square grid with \\$n\\$ rows and columns (so there are \\$n^2\\$ white/black cells), where \\$n \geq 3\\$. (You can take input in any reasonable format -- e.g. a 2D array.) For example, if \\$n=3\\$ there is only one valid grid (I'm using `.` for white cells and `#` for black cells):

```
...
...
...

```

If \\$n=4\\$, there are 3 valid grids:

```
....  #...  ...#
....  ....  ....
....  ....  ....
....  ...#  #...

```

If \\$n=5\\$, there are 12 valid grids:

```
.....  #....  ##...  #....  ##...  ##...
.....  .....  .....  #....  #....  ##...
.....  .....  .....  .....  .....  .....
.....  .....  .....  ....#  ....#  ...##
.....  ....#  ...##  ....#  ...##  ...##

....#  ...##  ....#  ...##  ...##  #...#
.....  .....  ....#  ....#  ...##  .....
.....  .....  .....  .....  .....  .....
.....  .....  #....  #....  ##...  .....
#....  ##...  #....  ##...  ##...  #...#

```

Examples:

| Input | Output | Explanation |
| --- | --- | --- |
| `.........` | True | Valid grid |
| `#..............#` | True | Valid grid |
| `...#........#...` | True | Valid grid |
| `.........................` | True | Valid grid |
| `##...#.............#...##` | True | Valid grid |
| `.................................................` | True | Valid grid |
| `........................#........................` | True | Valid grid |
| `....###.....##......##.....##......##.....###....` | True | Valid grid |
| `................................................................` | True | Valid grid |
| `##....####....##...........##......##...........##....####....##` | True | Valid grid |
| `...##.......#...........##.....##.....##...........#.......##...` | True | Valid grid |
| `#...............` | False | No 180 degree symmetry |
| `#...#......#...#` | False | 2-letter entries |
| `#..##..##..##..#` | False | 2-letter entries, filled-in columns |
| `#........................` | False | No 180 degree symmetry |
| `.......#...###...#.......` | False | 1-letter and 1-letter entries |
| `######....#....#....#....` | False | No 180 degree symmetry, filled-in column & row |
| `######...##...##...######` | False | Filled-in columns & rows |
| `...#......#......#......#......#......#......#...` | False | White squares not contiguous, filled-in column |
| `.................###....#....###.................` | False | 1-letter entries |
| `...#......#...............##.....................` | False | No 180-degree symmetry |
| `....#.......#.......#........######........#.......#.......#....` | False | White squares not contiguous |
| `..#.........#.......#......##......#.......#.......#.........#..` | False | 1-letter and 2-letter entries |
| `.#......#..............................................#......#.` | False | 1-letter entries, white squares not contiguous |
| `...........................##......#............................` | False | No 180-degree symmetry |
| `####............................................................` | False | No 180-degree symmetry |
| `#......##......##......##......##......##......##......##......#` | False | Filled-in columns |

Standard loopholes are forbidden. Shortest code wins.

# Answer
# Jelly, ~~40 35~~ 33 bytes

-5 thanks to Nick Kennedy!

```
;ZµŒg§’:2;§Ȧ
ŒṪḢạ§ỊẸʋƇ@ƬiƊȧÇȧU⁼ṚƊ

```

A monadic Link that accepts a list of lists of `1`s (white) and `0`s (black) that yields `1` if valid or `0` if not.

**Try it online!** Or see the test-suite.

### How?

```
;ZµŒg§’:2;§Ȧ - Link 1 (check entry lengths & presence): list of lists of 1/0, Grid
;Z           - concatenate the columns
  µ          - start a new monadic chain - f(rows + columns)
   Œg        - group runs of equal elements of each row/column
     §       - sums of each run
      ’      - decrement (i.e... all black: -1, 1:0, 2:1, 3:2, 4:3, 5: 4, ...)
       :2    - integer divide by two        -1    0    0    1,   1,    2, ...
          §  - {rows + columns} sums
         ;   - concatenate
           Ȧ - any and all? -> 0 if either: an entry of length 1 or 2 exists, or
                                            any row or column has no entry
                               else 1

ŒṪḢạ§ỊẸʋƇ@ƬiƊȧÇȧU⁼ṚƊ - Main Link: list of lists of 1/0, Grid
ŒṪ                   - multidimensional truthy indices -> "WhiteCoordinates)
            Ɗ        - last three links as a monad - f(WhiteCoordinates):
  Ḣ                  -   head (first coordinate -> initial "Current")
          Ƭ          -   collect up while distinct, applying:
         @           -     with swapped arguments - i.e. f(WhiteCoordinates, Current):
        Ƈ            -       filter keep those (of WhiteCoordinates) for which:
       ʋ             -         last four links as a dyad - i.e. f(WhiteCoordinates, Current):
   ạ                 -           absolute difference (vectorises)
    §                -           sum each
     Ị               -           insignificant? (effectively "in (0,1)?")
      Ẹ              -           any? - i.e. any are neighbours/same?
           i         -   index of {WhiteCoordinates} in that (or 0)
                        -> 1 if white cells are fully connected else 0
              Ç      - call link 1
             ȧ       - logical AND
                   Ɗ - last three links as a monad - f(Grid):
                U    - {Grid} reverse each
                  Ṛ  - {Grid} reverse
                 ⁼   - equal? -> 1 if 180-degree symmetry else 0
               ȧ     - logical AND

```

---

Also at 33 as a lone Link (although it performs redundant checks):

```
,ZµŒg§’:2;U⁼ṚƊ;ŒṪḢạ§ỊẸʋƇ@ƬiƊ$;§)Ȧ

```
> 5 votes

# Answer
# Python3, 562 bytes:

```
E=enumerate
def g(b,B):
 q=[(x,y)for x,y in B if b[x][y]=='.']
 Q=[q.pop(0)];S=[Q[0]]
 for x,y in Q:
  for X,Y in[(1,0),(-1,0),(0,-1),(0,1)]:
   u=(x+X,y+Y)
   if u in B and u not in S and'.'==b[x+X][y+Y]:Q+=[u];S+=[u]
 return not{*q}-{*S}
F=lambda x,l,c=0,k=0:k if not x else F(x[1:],l,(T:=c+(x[0]==l))*(x[0]==l),max(k,T))
def f(n,b):
 B=[(x,y)for x,r in E(b)for y,_ in E(r)]
 D=[(x,y)for x,y in B if'#'==b[x][y]]
 return all((n-x-1,n-y-1)in D for x,y in D)and g(b,B)and all(F(i,'.')>2and F(i,'#')<n for i in b)and all(F(i,'.')>2and F(i,'#')<n for i in zip(*b))

```

Try it online!
> 3 votes

# Answer
# Retina 0.8.2, ~~186~~ 183 bytes

```
\.
-
s`^(?!(.)+.?(?<-1>\1)+$(?(1)^)).+

ms`.*^#+$.*|.*(?<!-)--?(?!-).*

O$`.
$.%`
ms`.*^#+$.*|.*(?<!-)--?(?!-).*

1`-
@
+m`^((.)*)(@|-)(.*¶(?<-2>.)*(?(2)$))?(?!\3)[@-]
$1@$4@
^[¶#@]+$

```

Try it online! Takes input as a square array and outputs `1` for valid, `0` for invalid. Explanation:

```
\.
-

```

Change `.`s to `-`s are they're easier to match.

```
s`^(?!(.)+.?(?<-1>\1)+$(?(1)^)).+

```

Delete everything if it isn't rotationally symmetric.

```
ms`.*^#+$.*|.*(?<!-)--?(?!-).*

```

Delete everything if there is a row of `#`s or if there are one or two `-`s on their own.

```
O$`.
$.%`

```

Transpose the array.

```
ms`.*^#+$.*|.*(?<!-)--?(?!-).*

```

Check the transpose for a row of `#`s or one or two `-`s on their own.

```
1`-
@

```

Change one `-` to a `@`.

```
+m`^((.)*)(@|-)(.*¶(?<-2>.)*(?(2)$))?(?!\3)[@-]
$1@$4@

```

Flood fill `-`s with `@`s. Note that I use `(?(2)$)` although I used `(?(1)^)` above because this is a multiline match and so the final character could be at the beginning of a line.

```
^[¶#@]+$

```

Check that all of the `-`s were filled.
> 3 votes

# Answer
# JavaScript (ES11), 176 bytes

*Saved 1 byte thanks to @tsh*

Expects a binary matrix, with `1` for white cells and `0` for black cells. Returns a Boolean value.

```
f=(m,i)=>m<(h=z=>m=m.map((r,y)=>r.map((v,x)=>z?/^(0*222+)+0*$/.test(r.join``)?m[x][m.length-1-y]:z:v&[-1,0,1,2].some(d=>m[y+d%2]?.[x+~-d%2]==i)?i=2:v)))()?f(m,i):h``+""==h(h``)

```

Attempt This Online!

### How?

The same helper function `h` is used to process two passes:

1. We flood-fill the matrix, replacing `1`'s with `2`'s. We start at the first empty cell located on a border. If it doesn't exist, the grid is invalid anyway and will be identified as such during the next pass.
2. We rotate the matrix 3 times by 90°. We convert each resulting row to a string and make sure that it matches the following regular expression:

```
/^(0*222+)+0*$/

```

i.e. the entire string is made of groups of three or more `2`'s (with at least one such group) and optional groups of `0`'s.

Finally, we make sure that the 3rd rotation leads to the same matrix as the 1st one to validate the 180° rotational symmetry.

### Commented

```
f = (                        // f is a recursive function taking:
  m,                         //   m[] = input binary matrix
  i                          //   i = flag used during flood-filling,
) =>                         //       initially undefined
m < (                        // compare m[] with its updated version
  h = z =>                   // h is a helper function ...
  m =                        // ... which updates m[]
  m.map((r, y) =>            // for each row r[] at index y in m[]:
    r.map((v, x) =>          //   for each value v at index x in r[]:
      z ?                    //     if z is truthy:
        /^(0*222+)+0*$/      //       if r[], once converted to a string,
        .test(r.join``) ?    //       matches this regular expression:
          m[x]               //         apply a 90° rotation
          [m.length - 1 - y] //
        :                    //       else:
          z                  //         force the final test to fail (*)
      :                      //     else:
        v &                  //       if v = 1
        [-1, 0, 1, 2]        //       and there's some direction d
        .some(d =>           //       such that:
          m[y + d % 2]       //         the neighbor cell
          ?.[x + ~-d % 2]    //         in that direction
          == i               //         is equal to i
        ) ?                  //       then:
          i = 2              //         set i and the cell to 2
        :                    //       else:
          v                  //         leave this cell unchanged
    )                        //   end of inner map()
  )                          // end of outer map()
)() ?                        // if m[] was modified after flood-filling:
  f(m, i)                    //   try to flood-fill some more
:                            // else:
  h`` + "" == h(h``)         //   do the 1st and 3rd rotation match?

```

(\*) For the 1st and 2nd rotations, `z` is set to `['']`, which is coerced to an empty string. For the 3rd rotation, it is set to the result of the 2nd rotation.
> 3 votes

# Answer
# Charcoal, 67 bytes

```
Ｆθ⊞υＳ¿⁼υＥ⮌υ⮌ι¿⬤⁺υＥθ⭆θ§λκ∧№ι.⬤⪪ι#÷⊖Ｌλ²«Ｅυ⭆ι⎇⁼λ.ψλＪ⌕θ.⁰¤.¿‹ＬＫＡＬΣυ⎚«⎚¹

```

Try it online! Link is to verbose version of code. Takes input as a square array of strings and outputs a Charcoal boolean, i.e. `-` for valid, nothing if not. Explanation:

```
Ｆθ⊞υＳ

```

Input the square array.

```
¿⁼υＥ⮌υ⮌ι

```

Check that it's rotationally symmetric.

```
¿⬤⁺υＥθ⭆θ§λκ∧№ι.⬤⪪ι#÷⊖Ｌλ²«

```

Concatenate the array with its transpose and check that each row contains a `.` but when split on `#`s does not contain runs of exactly `1` or `2` `.`s.

```
Ｅυ⭆ι⎇⁼λ.ψλ

```

Write just the `#`s from the array to the canvas.

```
Ｊ⌕θ.⁰

```

Jump to a position where there should be a `.`.

```
¤.

```

Fill the canvas with `.`s starting from here.

```
¿‹ＬＫＡＬΣυ⎚

```

If this didn't fill all of the original `.`s then just clear the canvas.

```
«⎚¹

```

If all of the `.`s were connected then clear the canvas and output `-`.
> 2 votes

# Answer
# JavaScript (Node.js), 245 bytes

```
s=>new Set([...s].map(p=(c,i,a)=>c^1||[n=s.length**.5|0,(m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0].at?b(v[0]):v)(s)[0]=v:s)(m(a[p=~i+~n]=[p],p-~n),p+1),+a.at(~i),a[i+~n]|a[i-~n]&a[i-~n*2],a[i-1]|a[i+1]&a[i+2]]).flat(1/0)).size<4*!s[-p]*/^1/m.test(s)

```

Try it online!

Input a multi line string, 1 for white cells, 0 for black cells, line break (`\n`) separate each rows. Output true or false.

---

# JavaScript, 263 bytes

```
a=>new Set(a.map((r,y)=>[r.map(e=(c,x)=>!c||[(m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0][1]?v:b(v[0]))(s)[0]=v:s)(m(a[p=x+[,y]]=[p],[x-1,y]),[x,y-1]),e=a.at(~y).at(~x),a[y-1]?.[x]||a[y+1]?.[x]&&a[y+2]?.[x],r[x-1]||r[x+1]&&r[x+2]]),e,a.some(r=>r[y])]).flat(1/0)).size<3

```

```
f=

a=>new Set(a.map((r,y)=>[r.map(e=(c,x)=>!c||[(m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0][1]?v:b(v[0]))(s)[0]=v:s)(m(a[p=x+[,y]]=[p],[x-1,y]),[x,y-1]),e=a.at(~y).at(~x),a[y-1]?.[x]||a[y+1]?.[x]&&a[y+2]?.[x],r[x-1]||r[x+1]&&r[x+2]]),e,a.some(r=>r[y])]).flat(1/0)).size<3

const parse = (s, n = s.length ** .5) => [...Array(n)].map((_, i) => [...s.slice(i * n, (i + 1) * n)].map(v => v === '.'));
const testcases = `
......... True
##.....................## True
#..............# True
...#........#... True
...#........#... True
......................... True
##...#.............#...## True
................................................. True
........................#........................ True
....###.....##......##.....##......##.....###.... True
................................................................ True
##....####....##...........##......##...........##....####....## True
...##.......#...........##.....##.....##...........#.......##... True
#............... False
#...#......#...# False
#..##..##..##..# False
#........................ False
.......#...###...#....... False
######....#....#....#.... False
######...##...##...###### False
...#......#......#......#......#......#......#... False
.................###....#....###................. False
...#......#...............##..................... False
....#.......#.......#........######........#.......#.......#.... False
..#.........#.......#......##......#.......#.......#.........#.. False
.#......#..............................................#......#. False
...........................##......#............................ False
####............................................................ False
#......##......##......##......##......##......##......##......# False
`.trim().split('\n').map(r => [parse(r.split(' ')[0]), r.endsWith('True')])

testcases.forEach(([i, e]) => {
  console.log(f(i), e);
});
```

Input boolean matrix, output true or false.

```
a=>new Set(
  a.map((r,y)=>[
    r.map(e=(c,x)=>!c||[ // for each cell, which is either empty or
      // generate an unique symbol for its connected area
      (m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0][1]?v:b(v[0]))(s)[0]=v:s)(m(a[p=x+[,y]]=[p],[x-1,y]),[x,y-1]),
      // its 180 rotated position is non-empty
      e=a.at(~y).at(~x),
      // its ^ cell is non-empty or its v and vv cells are non-empty
      a[y-1]?.[x]||a[y+1]?.[x]&&a[y+2]?.[x],
      // its < cell is non-empty or its > and >> cells are non-empty
      r[x-1]||r[x+1]&&r[x+2]
    ]),
    // at least one non-empty cell this row
    e,
    // at least one non-empty cell this column
    a.some(r=>r[y])
  ]).flat(1/0)
).size<3 // if every non-empty cell connected, they have same symbol (count as 1)
         // if all other condition holds, they will be all true (count as 1)

```

Transpose the matrix also costs 263 bytes, maybe someone can golf one of them a bit

```
m=>new Set([m,m.map((r,y)=>r.map((_,x)=>m[x][y]))].map(a=>a.map((r,y)=>[r.map(e=(c,x)=>!c||[a==m||(m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0][1]?v:b(v[0]))(s)[0]=v:s)(m(a[p=x+[,y]]=[p],[x-1,y]),[x,y-1]),e=a.at(~y).at(~x),r[x-1]||r[x+1]&&r[x+2]]),e])).flat(1/0)).size<3

```
> 2 votes

# Answer
# , ~~196~~ ~~185~~ ~~184~~ ~~177~~ 176 bytes

```
\(x,`~`=t,`+`=sum,a=apply,e=~which(x,T),i=~~e[,1],`?`=any){while(+i<+(i=e[,a(e,2,\(y)?colSums((i-y)^2)<2)]))1
+i-+e?x-rev(x)?a(rbind(x,~x),1,\(y,z=rle(y))?!(z$v*z$l-1)%/%2&+y)}

```

Attempt This Online!

A function taking a square matrix of logical values and returning a single logical value. This was inspired by and works more or less the same as @JonathanAllan’s Jelly answer so be sure to upvote that one too!

Thanks to @pajonk for saving 9 bytes!
> 2 votes

# Answer
# , 95 93 92 bytes

```
(2<*#])@((#;._2"1@,.&0,&,0=1&#.)@,|:)*/@,(-:|."1@|.),&,[:(]+.+./ .*)^:_~1=[:|@-/~$j./@#:I.@,

```

Attempt This Online!

*-2 thanks to Neil's idea of catting transpose with input instead of using over*

Takes input as a 0-1 matrix, where 1 means empty space.
> 1 votes

# Answer
# 05AB1E, 61 bytes

```
˜ƶIgôΔ2Fø0δ.ø}2Fø€ü3}*εεÅsyøÅs«à]˜0KÙgIDø«εÅγsÏ3@DgĀª}˜`IÂíQP

```

Input as as matrix of `1`s for white squares and `0`s for black squares.
Outputs a 05AB1E-truthy/falsey result, so `1` as truthy, and `0` or a positive integer as falsey.

Try it online or verify all test cases.

**Explanation:**

Step 1: Verify rule "*All white squares must be joined in a single region.*":

```
˜             # Flatten the (implicit) input-matrix to a single list
 ƶ            # Multiply each value by its 1-based index (so all 1s become unique)
  Igô         # Convert this list back into a matrix equal of the input-dimensions
Δ             #  Loop until it no longer changes to flood-fill:
 2Fø0δ.ø}     #   Add a border of 0s around the matrix:
 2F     }     #    Loop 2 times:
   ø          #     Zip/transpose; swapping rows/columns
     δ        #     Map over each row:
    0 .ø      #      Add a leading/trailing 0
 2Fø€ü3}      #   Convert it into overlapping 3x3 blocks:
 2F    }      #    Loop 2 times again:
   ø          #     Zip/transpose; swapping rows/columns
    €         #     Map over each inner list:
     ü3       #      Convert it to a list of overlapping triplets
 *            #   Multiply each 3x3 block by the value in the (implicit) input-matrix
              #   (so the 0s remain 0s)
 εεÅsyøÅs«à   #   Get the largest value from the horizontal/vertical cross of each 3x3
              #   block:
 εε           #    Nested map over each 3x3 block:
   Ås         #      Pop and push its middle row
     y        #      Push the 3x3 block again
      ø       #      Zip/transpose; swapping rows/columns
       Ås     #      Pop and push its middle rows as well (the middle column)
         «    #      Merge the middle row and column together to a single list
          à   #      Pop and push its maximum
]             #  Close the nested maps, flood-fill loop, and outer loop
 ˜            # Flatten the resulting flood-filled matrix
  0K          # Remove all 0s (the black squares)
    Ù         # Uniquify the values of each island
     g        # Pop and push its length (which is 1 if it was a single island of 1s)

```

Try just step 1 online for all test cases.

Step 2: Verify rules "*All entries must be at least 3 squares long.*" and "*No row/column can be completely filled with black squares.*":

```
I             # Push the input-matrix again
 D            # Duplicate it
  ø           # Zip/transpose the copy; swapping its rows/columns
   «          # Merge the two matrices together
    ε         # Map over each inner list:
     Åγ       #  Run-length encode it; pushing a list of values and lengths
       s      #  Swap so the values are at the top
        Ï     #  Only keep the lengths for the truthy (==1) values
         3@   #  Check for each whether it's >= 3
         D    #  Duplicate this list
          g   #  Pop and push its length
           Ā  #  Check whether it's truthy (>= 0)
            ª #  Append this check to the list
    }˜        # After the map: Flatten the list of lists
      `       # Pop and dump all values to the stack
...
P             # Take the product of all values on the stack

```

Try just step 2 online for all test cases.

Step 3: Verify rule "*They should have 180 degree rotational symmetry.*":

```
I             # Push the input-matrix yet again
 Â            # Bifurcate it; short for Duplicate & Reverse
  í           # Also reverse each inner row
   Q          # Check if the two matrices are still the same

```

Try just step 3 online for all test cases.

Step 4: Combine all checks and output the result:

```
P             # Pop all values on the stack and push its product
              # (which is output implicitly as result)

```
> 0 votes

---
Tags: code-golf, decision-problem, grid, crossword
---


# Question
Title: Repeating slices of an array incrementally
Let's say I have a non-empty list (array):

```
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

```

I want to incrementally slice the list into incremented amount of elements per chunk.

For this array, my desired output is:

```
[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]

```

What would be the best way to slice the array in multiple chunks.

This is , so shortest code in bytes wins!

Note: For the final chunk, if the number of elements left in `r` is less than what the incremented output requires, the last chunk should just be all that remains in the list.

# Test cases:

```
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
-> [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]

l = [10, 20, 30, 40]
-> [[10], [20, 30], [40]]

l = [100, 200, 300, 400, 500]
-> [[100], [200, 300], [400, 500]]

```

# Answer
> 8 votes
# Python, 40 bytes

```
f=lambda a,n=1:a and[a[:n]]+f(a[n:],n+1)
```

Attempt This Online!

# Answer
> 7 votes
# Vyxal, 2 bytes

```
żẇ

```

Try it Online!

Upgrading got me like

## Explained

```
żẇ
ż   # The range [1, len(input)]
 ẇ  # Wrap the input list into chunks of each number. Stops grouping when there's no more items

```

Created with the help of Luminespire.

# Answer
> 7 votes
# Husk, ~~3~~ 2 bytes

*Edit: -1 byte thanks to Razetime*

```
CN

```

Try it online!

```
C       # Cut off substrings of the following lengths:
 N      # natural numbers

```

# Answer
> 6 votes
# Jelly, 5 bytes

```
JÄ‘œṖ

```

**Try it online!**

### How?

```
JÄ‘œṖ - Link: list, L                  e.g. [5,4,3,2,1,0,1,2]
J     - range of length of L                [1,2,3,4,5,6,7,8]
 Ä    - cumulative sums                     [1,3,6,10,15,21,28,36]
  ‘   - increment                           [2,4,7,11,16,22,29,37]
   œṖ - partition L before those indices    [[5],[4,3],[2,1,0],[1,2]]

```

---

Also 5 bytes TIO:

```
Jx`¹ƙ

```

...(`J`) range of length, (```) use right as both arguments with (`x`) repeat elements then (`ƙ`) apply to groups of identical values (`¹`) a no-op function.
i.e. build a list like `[1,2,2,3,3,3,4,4,4,4,...]` and group the original values like its equal values, `[[1],[2,2],[3,3,3],[4,4,4,4],...]`.

or, equivalently (just reapplying `J` rather than using the quick ```):

```
JxJ¹ƙ

```

# Answer
> 6 votes
# Factor \+ `grouping.extras math.unicode`, ~~58~~ 57 bytes

```
[ dup '[ _ index 1 + 2 * √ .5 + ⌊ ] group-by values ]

```

Try it online!

Group elements by the integer inverse triangular function of their indices. In other words, given a zero-based index \\$i\\$, its element belongs to group

$$\left\lfloor\sqrt{2(i + 1)} + \frac{1}{2}\right\rfloor$$

# Answer
> 5 votes
# Ruby, 38 bytes

```
->l{(1..l.size).map{l.shift(_1)}-[[]]}

```

# Answer
> 4 votes
# Haskell, 40 bytes

```
n![]=[]
n!x=take n x:(n+1)!drop n x
(1!)

```

Try it online!

There seems like there should be a shorter way to do this maybe with scans or folds, but I can't figure it out.

# Answer
> 4 votes
# Charcoal, 21 bytes

```
≔⮌ＡθＷθ⊞υＥ⌊⟦Ｌθ⊕Ｌυ⟧⊟θＩυ

```

Try it online! Link is to verbose version of code. Explanation:

```
≔⮌Ａθ

```

Reverse the input list.

```
Ｗθ

```

Repeat until it is empty...

```
⊞υＥ⌊⟦Ｌθ⊕Ｌυ⟧⊟θ

```

... pop up to the next number of items from the input list into a new group.

```
Ｉυ

```

Output the grouped list.

# Answer
> 4 votes
# , 40 bytes

```
function(x)split(x,rep(s<-seq(!x),s)[s])

```

Try it online!

Inspired by Giuseppe's answer to "Chunk sort a sequence".

# Answer
> 4 votes
# , 12 bytes

```
</.~#{.#\##\

```

Try it online!

Consider `10 20 30 40 50 60`:

* `#\` Gives `1 2 3 4 5 6` (ie, 1...n).
* `#\##\` Uses that list to "copy" itself:

```
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6

```
* `#{.` Take only the first n elements of that:

```
1 2 2 3 3 3

```
* `</.~` Group the original input using that mask:

```
┌──┬─────┬────────┐
│10│20 30│40 50 60│
└──┴─────┴────────┘

```

# Answer
> 3 votes
# APL+WIN, 18 bytes

Prompts for a vector of numbers or a string of characters. Outputs a nested vector.

```
(m↑(⍳m)/⍳m←⍴n)⊂n←⎕

```

Try it online! Thanks to Dyalog Classic

# Answer
> 3 votes
# C (gcc), ~~86~~ \\$\cdots\\$ ~~77~~ 76 bytes

```
r;i;f(a,n)int*a;{for(i=r=1;n--;r+=r*~r/2+i++?0:puts(""))printf("%d ",*a++);}

```

Try it online!

*Saved a byte thanks to ceilingcat!!!*

Inputs a pointer to an array of integers and its length (because pointers in C carry no length info).
Outputs to `stdout` each array slice with the array elements separated by spaces and the slices separated by newlines.

# Answer
> 3 votes
# BQN, ~~24~~ ~~22~~ ~~15~~ ~~14~~ 12 bytes

*Edit: -2 bytes thanks to Razetime, and -2 more bytes (and a BQN lesson) thanks to ovs*

```
 1↓⊢⊔˜≠⥊·/˜⊒˜

```

Try it at BQN online REPL

# Answer
> 3 votes
# Scala, 92 bytes

```
a=>if(a.last.size>a.size)f(a.init++Seq(a.last.take(a.size))++Seq(a.last.drop(a.size)))else a

```

Try it online!

# Answer
> 3 votes
# Perl 5, 45 bytes

```
sub{my@r;push@r,[splice@_,0,1+@r]while@_;\@r}

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 33 bytes

```
GatherBy[#,i=1;Round@√(2i++)&]&

```

Try it online!

# Answer
> 3 votes
# Uiua, 11 bytes

```
⊜□⬚2↙⧻,⊚⇡⧻.

```

Try it!

```
⊜□⬚2↙⧻,⊚⇡⧻.
          .  # duplicate
         ⧻   # length
        ⇡    # range
       ⊚     # where
      ,      # over
     ⧻       # length
  ⬚2↙        # take with fill element of 2
⊜□           # partition with boxing

```

# Answer
> 2 votes
# Python 2, 47 bytes:

```
def f(l,c=1):
 while l:yield l[:c];l=l[c:];c+=1

```

Try it Online!

# Answer
> 2 votes
# Python 3, 71 bytes

```
g=lambda x,s=1:[[c for c,_ in zip(x,range(s))]]+g(x[s:],s+1)if x else[]

```

Try it online!

*-3* Thanks to @U12-Forward

# Answer
> 2 votes
# JavaScript (ES6), 42 bytes

*-2 thanks to @emanresuA because I'm a potato*

```
x=>(f=n=>x+x&&[x.splice(0,++n),...f(n)])``

```

# Answer
> 2 votes
# Pip `-xp`, 12 bytes

```
a^@$+*\,\,#a

```

Attempt This Online!

### Explanation

```
a^@$+*\,\,#a
          #a  Length(argument)
        \,    Inclusive range from 1 to ^
      \,      Inclusive range from 1 to each number in ^
   $+*        Sum each
a^@           Split argument at those indices

```

# Answer
> 2 votes
## Scala, 74 bytes

```
a=>(0 to a.size).map(i=>a.slice(i*(i+1)/2,(i+1)*(i+2)/2)).filter(_.size>0)

```

Try it online!

The obvious way to avoid the filter at the end is to make the range from 0 to the biggest triangle number whose value is less than `a.size`, but the shortest way I could find to express that in Scala 2.13 was longer than the thing it was supposed to replace:

```
BigDecimal(0).until(pow(2*a.size+.25,.5)-.5,1)

```

# Answer
> 1 votes
# Raku, 22 bytes

```
*.rotor(1..*,:partial)

```

Try it online!

The `rotor` method splits an array into chunks of a given size or sizes, eg:

* `rotor(5)` splits an array into 5-element chunks.
* `rotor(2, 3)` splits an array into chunks of alternating sizes 2 and 3.

Here, I pass the infinite range `1 .. *` as the argument, so `rotor` will emit chunks of sizes 1, 2, 3, .... The `:partial` keyword argument causes all remaining elements to be grouped into the final chunk, even if there aren't enough of them.

# Answer
> 0 votes
# APL (Dyalog Unicode), 17 bytes

This is a dfn that takes a vector as a right argument. It groups segments per specification into a nested array of vectors.

```

{⍵⊆⍨1+q⍸⍨+\q←⍳⍴⍵}

```

The index origin is set to 0 (⎕IO←0).

Try it on TryAPL.org!

This was an interesting challenge and demonstrates that there are many ways to get to a solution in the APL language. None I found had a lesser byte count, but the approaches may be of interest:

by recursion: {⍺←1 ⋄ ⍺≥⍴⍵:⊂⍵ ⋄ (⊂⍺↑⍵),(⍺+1)∇ ⍺↓⍵}

by formula: {⍵⊆⍨⌊0.5+0.5\*⍨2×⍳⍴⍵}

by iteration: {p⊆⍨q↑∊{⍵⍴⍵}¨⍳q←⍴⍵}

---
Tags: code-golf, array
---