title: Swap Two Values in a List

text:
# Question
Title: Swap Two Values in a List
## Introduction:

Although we have a lot of challenges where swapping two items in a list is a subtask, like Single swaps of an array; Swap to Sort an Array; \\$n\\$ swaps into a nop; etc., we don't have the simple challenge of just swapping two items given a list and two indices.

**Input:**
A list with some positive integers \\$L\\$, and two indices \\$a\\$ and \\$b\\$.

**Output:**
The same list, with the two items at the given indices swapped.

## Challenge rules:

* The input-list is guaranteed to contain at least two items.
* The input-list is guaranteed to only contain positive integers.
* The input-indices can be either 0-based or 1-based (please specify in your answer which of the two you've used).
* The input-indices are guaranteed to be valid indices based on the length of the input-list.
* The input-indices are distinct, so will never be the same index. (The values in the input-list won't necessarily be distinct.)
* You can assume \\$a\<b\\$ (and you're allowed to take the inputs in reversed order if it helps).
* I/O is flexible. You're allowed to take the input as a list/array/stream, from STDIN, as a delimited string, etc. You're allowed to modify the input-list directly, or return a new one with the two items swapped.

## General rules:

* This is , so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (e.g. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases

All test cases use 0-based indices.

```
Inputs: L=[1,2,3,4,5,6,7,8,9,10], a=3, b=7
Output:   [1,2,3,8,5,6,7,4,9,10]

Inputs: L=[ 3, 8, 1, 4,10,10,10,10], a=0, b=5
Output:   [10, 8, 1, 4,10, 3,10,10]

Inputs: L=[5,1,4,2,3], a=0, b=4
Output:   [3,1,4,2,5]

Inputs: L=[5,6], a=0, b=1
Output:   [6,5]

Inputs: L=[2,2,2], a=0, b=1
Output:   [2,2,2]

```

# Answer
# MathGolf, 1 byte

```
µ

```

Apparently MathGolf has a builtin for this. Came across it in the docs when I was working on another challenge today. ¯\\\_(ツ)\_/¯.

Takes the loose index-inputs before the list.

Try it online.
> 1 votes

# Answer
# Java, 27 bytes

```
java.util.Collections::swap

```

Try it online!
> 15 votes

# Answer
# Python 2, 32 bytes

```
def f(a,b,l):l[a],l[b]=l[b],l[a]
```

Attempt This Online!

Mutates the input in-place.

---

26 bytes with a NumPy array:

```
def f(l,a):l[a[::-1]]=l[a]

```

Try it online!
> 9 votes

# Answer
# Brain-Flak, 122 bytes

```
(([{}]{()<({}[()]<({}<>)<>>)>}{})<(({}({}))([{}]{})<{({}()<<>({}<>)>)}{}>)>())<>({}<<>{({}[()]<({}<>)<>>)}{}>){<>({}<>)}{}

```

Try it online!

# Works with all integers, 138 bytes

```
(([{}]{()<({}[()]<({}<>)<>>)>}{})<(({}({}))([{}]{})<{({}()<<>({}<>)>)}{}>)>())<>({}<<>{({}[()]<({}<>)<>>)}{}>)<>([]){({}[()]<({}<>)<>>)}<>

```

Try it online!

The difference here is that while the first uses

```
{<>({}<>)}{}

```

To pull all the items from the off stack onto the on stack this one has to use

```
<>({}){({}[()]<({}<>)<>>)}<>

```

The first one pulls until it hits a zero and then stops, so this will fail to produce the correct result when there is a zero before the first swapped value. The second checks the height and pulls that many times, thus it will work for any list.
> 9 votes

# Answer
# , 31 bytes

Or **\>=4.1, 24 bytes** by replacing the word `function` with `\`.

```
function(L,A){L[A]=L[rev(A)];L}

```

Try it online!

Takes input as a vector and a vector of two `1`-based indices.
> 7 votes

# Answer
# Factor, 21 bytes

```
[ [ exchange ] keep ]

```

Try it online!

It's almost a built-in, but `exchange` has stack effect `( m n seq -- )` so we need `keep` to actually keep the sequence around on the data stack. 0-indexed.
> 7 votes

# Answer
# Rust, 11 bytes

```
<[_]>::swap

```

Modify the input in-place.

Try it online!
> 7 votes

# Answer
# Jelly, ~~7~~ 5 bytes

```
œPżịF

```

Try it online!

Takes indexes as 1 indexed and reversed (so `[b, a]`), the Footer on TIO does this for you.

## How it works

```
œPżịF - Main link. Takes indices I on the left, array A on the right
œP    - Partition A at the indices in I, not keeping the borders
   ị  - Retrieve the elements of A at the indices in I; [A[b], A[a]]
  ż   - Zip together
    F - Flatten

```
> 6 votes

# Answer
# APL (Dyalog Unicode), 5 bytes

1-indexed. Reverse the sublist at the indices given by the second input of the first input.

```
⌽@⎕⊢⎕

```

Try it online!
> 6 votes

# Answer
# Lean, ~~211~~ 205 bytes

Helper:

```
notation `L`:=list ℕ
structure R:=m::(A:L)(B:ℕ)(C:L)
def r:L->L->ℕ->R
|p(h::t)0:=R.m p h t
|p(h::t)(n+1):=r(p++[h])t n
|_[]_:=R.m[]0[]

```

Actual function:

```
λl a b,let f:=r[]l a,z:=r[]f.C(b-a-1)in f.A++z.B::z.A++f.B::z.C

```

Try it online!

There's got to be a way to make product types and define type aliases easily, but I couldn't find it.
> 6 votes

# Answer
# Jelly, 7 bytes

```
,U$yJ}ị

```

Try It Online!

A totally different Jelly 7-byter, so I figured I'd post this too. This is 1-indexed.

```
,U$yJ}ị    Main link; take indices on the left
,U$        Pair the indices with the reverse of itself ([[a, b], [b, a]])
   y       Apply this as a translation to
    J}     The indices of the right list (J takes a list of length L and returns [1, 2, ..., L])
      ị    Index back into the original list

```
> 5 votes

# Answer
# Haskell, 56 bytes

```
(?)=splitAt
(x!y)z|(q,d:e)<-y?z,(a,b:c)<-x?q=a++d:c++b:e

```

Try it online!

`splitAt` breaks the list into two parts at the particular index. This is useful because unlike `(!!)` we can get all the parts first.

To start we split at the second element, then the first. Splitting at the second first means we don't have to do extra arithmetic do calculate the offset which is required if we split at the first.

We use a pattern match to then get the first element of various pieces.
> 4 votes

# Answer
# JavaScript, 31 bytes

```
l=>a=>b=>l[a]^=l[b]^(l[b]=l[a])

```

Only works for integers.

Try it online!

*Thanks to Arnauld.*

# JavaScript, 32 bytes

```
l=>a=>b=>[l[a],l[b]]=[l[b],l[a]]

```

Try it online!
> 4 votes

# Answer
# Julia 1.0, 20 bytes

```
L*i=L[i]=L[i[[2,1]]]

```

Try it online!

1-indexed

expects `L*[a,b]` and mutates `L`
> 4 votes

# Answer
# CJam, 4 bytes

```
{e\}

```

Code block (analogous to a function) that pops three elements from the stack: `L`, `a`, `b`, and pushes the swapped version of `L`. Indices `a`, `b` are 0-based.

**Try it online!**

### Explanation

```
{  }  e# Define code block
 e\   e# Swap elements in array

```
<sub>

*Header:*

```
q     e# Read all input as an unevaluated string, and push it to the stack
 ~    e# Evaluate string. Gives an array and two numbers, that are pushed

```

*Footer:*

```
~     e# Execute block
 p    e# Print string representation of the top of the stack

```
</sub>
> 4 votes

# Answer
# stacked, 5 bytes

```
$exch

```

Try it online!

You can remove the `$` if input is allowed to be taken from the stack for 4 bytes. Convenient builtin to be sure.

## 22 bytes

```
[@j@i[i j nswap]apply]

```

Function. `nswap` performs a stack operation of swapping the `i`th and `j`th members, so we simply pop `i` and `j` and treat the stack at the top of the stack *as* the stack for `nswap`.
> 4 votes

# Answer
# Kotlin, 34 bytes

```
{l,x,y->l[x]=l[y].also{l[y]=l[x]}}

```

Ungolfed:

```
{ l, x, y ->
    l[x] = l[y].also { l[y] = l[x] }
}

```

This answer is a bit of an idiom in Kotlin.

`Any#also()` basically executes the given function, but then returns the receiver. In this case, the outer `l[y]` is evaluated, then `.also()` runs the lambda `{ l[y] = l[x] }`, and returns the old value of `l[y]`.

Try it online!
> 4 votes

# Answer
# Zsh, 39 bytes

```
eval "t=$`<i`;`<i`=$`<j`;`<j`=$"t
<<<$@
```

Attempt This Online!

Takes the array on the command line, with the two indices in files called `i` and `j`.

A bit of quote trickery to avoid escapes.
> 3 votes

# Answer
# Pip `-xp`, 8 bytes

```
aRAba@Rb

```

Takes input as two command-line arguments: the list, and a list containing the two indices (0-based). Attempt This Online!

### Explanation

The `-x` flag is for taking the arguments as lists rather than strings; the `-p` flag is for displaying the result as a list rather than concatenated together.

```
a         ; In the first argument
 RA       ; replace the items at indices given by
   b      ; the second argument
    a     ; with the values in the first argument
     @    ; at indices
      Rb  ; reverse(second argument)

```

---

The straightforward version, which takes the indices as separate arguments, comes in at 9 bytes:

```
a@b::a@ca
   ::      ; Swap
a@b        ; the item in a at index b
     a@c   ; with the item in a at index c
        a  ; Output the new value of a

```
> 3 votes

# Answer
# C (clang), 34 bytes

```
f(*a,i,j){a[i]^=a[j]^(a[j]=a[i]);}

```

Try it online!

*Port of Unmitigated's C++ answer*
> 3 votes

# Answer
# TI-Basic, ~~39~~ 33 bytes

```
Prompt L,A,B
ʟL(A→X
ʟL(B→ʟL(A
X→ʟL(B
ʟL

```

-6 bytes thanks to MarcMush.

Input indices are 1-based. Output is stored in `Ans` and is displayed.
> 3 votes

# Answer
# ErrLess, 6 bytes

```
0m:r.M

```

A macro.

## Explanation

```
0 { Push a 0 to the stack to identify the macro }
m { Start macro definition }
: { (L a b) -> (L (a b)) }
r { Rotate }
. { Halt (Return) }
M { End macro definition }

```

You can test it with the following program:

```
0m
 :r.
M

{ Test cases: }

1,2x3x4x5x6x7x8x9xax 3 7
0" # a? { Outputs "(1 2 3 8 5 6 7 4 9 10)" and a newline }

3,8x1x4xaxaxaxax 0 5
0" # a? { Outputs "(10 8 1 4 10 3 10 10)" and a newline }

5,1x4x2x3x 0 4
0" # a? { Outputs "(3 1 4 2 5)" and a newline }

5,6x 0 1
0" # a? { Outputs "(6 5)" and a newline }

2,2x2x 0 1
0" # a? { Outputs "(2 2 2)" and a newline }
.

```

Try it online!
> 3 votes

# Answer
# Python 2, 49 bytes

```
lambda a,b,c:a[:b]+[a[c]]+a[b+1:c]+[a[b]]+a[c+1:]

```

Try it online!
> 2 votes

# Answer
# PHP, 46 bytes

```
fn(&$a,$i,$j)=>[$a[$i],$a[$j]]=[$a[$j],$a[$i]]

```

Try it online!

changes the array in place, 0 indexing

My first shot was with `list`, but PHP has array destructuring since 7.1, so it ends up like the JS answer with lots of dollars (money money money!)
> 2 votes

# Answer
# Vyxal, 7 bytes

```
İṘZ(n÷Ȧ

```

Try it Online!

This could almost certainly be a bit smaller, but I got smol brain and can't think of a good way to swap values.

Explanation:

```
İ        # Get the values at the indexes
 Ṙ       # Reverse the values
  Z      # Zip the values with the new indexes
   (n    # For each value/index pair:
     ÷   #  Split the value/index
      Ȧ  #  Put the value at that index

```
> 2 votes

# Answer
# Retina 0.8.2, 99 bytes

```
2`\d+
$*
1*(,1*);
$1,$&
(?<=(?=.*;(?<-2>\d+,)*(\d+))(1)*,(?(4)$)(?<-4>1)*(,1*)?;(\d+,)*)\d+
$1
.*;

```

Try it online! Link includes test cases. Takes input in the form `a,b;L`. Explanation:

```
2`\d+
$*

```

Convert the indices to unary.

```
1*(,1*);
$1,$&

```

Make a second copy of `b` so that we now have `b,a,b;L`.

```
(?<=(?=.*;(?<-2>\d+,)*(\d+))(1)*,(?(4)$)(?<-4>1)*(,1*)?;(\d+,)*)\d+
$1

```

Match an integer in `L`, with index `$#4` equalling either `a` or `b` (using a .NET balancing group), then match the other index in `$#2`, and match the integer at that index as the replacement for this integer (also using a .NET balancing group).

```
.*;

```

Delete `a` and `b`.
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~24~~ 21 bytes

1-based indices, input is a list and a tuple of indices to reverse

```
Reverse~SubsetMap~##&

```

Try it online!

-3 bytes thanks to att.
> 2 votes

# Answer
# Perl 5, 42 bytes

*Updated TIO link to show positive indices only per challenge instructions (thanks, Kevin!)*

```
sub a{($a,$b,$l)=@_;@$l[$a,$b]=@$l[$b,$a]}

```

Try it online!

Takes arguments as (first index, second index, 0-bound array). Mutates array in-place. Works with arrays containing any valid values, not just positive integers!
> 2 votes

# Answer
# Red, 33 bytes

```
func[l a b][swap at l a at l b l]

```

Try it online!

1-indexed
> 2 votes

# Answer
# Core Maude, 158 bytes

```
mod S is pr ARRAY{Nat,Nat0}*(sort Array{Nat,Nat0}to A). var I J X Y : Nat . op
s : A Nat Nat -> A . eq s(A:A,I,J)= insert(I,A:A[J],insert(J,A:A[I],A:A)). endm

```

### Example Session

```
             \||||||||||||||||||/
           --- Welcome to Maude ---
             /||||||||||||||||||\
         Maude 3.1 built: Oct 12 2020 20:12:31
         Copyright 1997-2020 SRI International
               Sat Oct 16 22:01:13 2021
Maude> mod S is pr ARRAY{Nat,Nat0}*(sort Array{Nat,Nat0}to A). var I J X Y : Nat . op
> s : A Nat Nat -> A . eq s(A:A,I,J)= insert(I,A:A[J],insert(J,A:A[I],A:A)). endm
Maude> red s(0 |-> 1 ; 1 |-> 2 ; 2 |-> 3 ; 3 |-> 4 ; 4 |-> 5 ; 5 |-> 6 ; 6 |-> 7 ;
>       7 |-> 8 ; 8 |-> 9 ; 9 |-> 10, 3, 7) .
result A: 0 |-> 1 ; 1 |-> 2 ; 2 |-> 3 ; 3 |-> 8 ; 4 |-> 5 ; 5 |-> 6 ; 6 |-> 7 ;
    7 |-> 4 ; 8 |-> 9 ; 9 |-> 10
Maude> red s(0 |-> 3 ; 1 |-> 8 ; 2 |-> 1 ; 3 |-> 4 ; 4 |-> 10 ; 5 |-> 10 ; 6 |-> 10 ;
>       7 |-> 10, 0, 5) .
result A: 0 |-> 10 ; 1 |-> 8 ; 2 |-> 1 ; 3 |-> 4 ; 4 |-> 10 ; 5 |-> 3 ; 6 |->
    10 ; 7 |-> 10
Maude> red s(0 |-> 5 ; 1 |-> 1 ; 2 |-> 4 ; 3 |-> 2 ; 4 |-> 3, 0, 4) .
result A: 0 |-> 3 ; 1 |-> 1 ; 2 |-> 4 ; 3 |-> 2 ; 4 |-> 5
Maude> red s(0 |-> 5 ; 1 |-> 6, 0, 1) .
result A: 0 |-> 6 ; 1 |-> 5
Maude> red s(0 |-> 2 ; 1 |-> 2 ; 2 |-> 2, 0, 1) .
result A: 0 |-> 2 ; 1 |-> 2 ; 2 |-> 2

```

### Ungolfed

```
mod S is
    pr ARRAY{Nat,Nat0} * (sort Array{Nat,Nat0} to A).
    var I J X Y : Nat .
    op s : A Nat Nat -> A .
    eq s(A:A, I, J) = insert(I, A:A[J], insert(J, A:A[I], A:A)) .
endm

```

The answer is obtained by reducing the function `s` with the list, given as a Maude array (e.g., `0 |-> 1 ; 1 |-> 2` for `[1, 2]`), and the two indices, zero-indexed.

Maude does have lists (e.g., `0 1` for the same list `[1, 2]`), but this is one case where it's actually shorter to use arrays (which are generally very verbose) because we don't need to use an array literal syntax in the code, and because we need indexing. The FAQ says it's allowed to accept input as either an array or a list.
> 2 votes

# Answer
# Javascript 38 bytes

```
(l,a,b)=>(l[a]=[l[b],l[b]=l[a]][0])&&l

```
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
è¹Rǝ

```

Since no one posted an 05AB1E answer yet and it's been a couple of days, I'm gonna post my prepared 4-byter.

First input is a pair of indices \\$\[a,b\]\\$, second input is the list \\$L\\$.

Try it online or verify all test cases.

**Explanation:**

```
è    # Index the first (implicit) input into the second (implicit) input-list
 ¹   # Push the first input-indices again
  R  # Reverse them
   ǝ # Insert the values at those reversed indices into the (implicit) second input-list
     # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Raku, ~~19~~ 18 bytes

```
{@^a[@^i].=rotate}

```

Try it online!

0-based indexing. Modifies the list in-place. Takes the indices as a two-element list.

*Edit*: `rotate` has the same effect as `reverse` and is one character shorter. D'oh!
> 2 votes

# Answer
## Clojure, 27 bytes

```
#(assoc % %2(% %3)%3(% %2))

```

The first argument `%` is a vector of numbers (not a list!) so that we don't need to use the function `nth`.

Edit: TIO

Edit 2: And actually you cannot `assoc` a list anyway.
> 2 votes

# Answer
# Charcoal, 14 bytes

```
ＩＥθ⎇№ηκ§θ⁻Σηκι

```

Try it online! Link is to verbose version of code. Takes the 0-indexed indices as a 2-element array. Explanation:

```
  θ             Input array
 Ｅ              Map over elements
    №           Count of
      κ         Current index in
     η          Input indices
   ⎇            If found then
        θ       Input array
       §        Indexed by
           η    Input indices
          Σ     Take the sum
         ⁻      Minus
            κ   Current index
             ι  Else current element
Ｉ               Cast to string
                Implicitly print

```
> 1 votes

# Answer
# C++, ~~51~~ ~~46~~ 38 bytes

```
#define f(a,i,j)a[i]^=a[j]^(a[j]=a[i])

```

*Saved 5 bytes thanks to Kevin Cruijssen.*

*Saved 8 bytes thanks to AZTECCO.*

Try it online!
> 1 votes

# Answer
# Python 2, 52 49 bytes

(longer than the approach by @pxeger, but **doesn't** mutate in-place

```
lambda a,b,l:l[:a]+[l[b]]+l[a+1:b]+[l[a]]+l[b+1:]
```

Try it Online!

**EDIT:** Thanks @Stephen Universe for saving me few bytes!

---

56 bytes by using `list.pop` and `list.insert`:

```
def f(a,b,l):l.insert(b,l.pop(a)),l.insert(a,l.pop(b-1))

```

Try it online!
> 1 votes

# Answer
# Icon, ~~43~~ 34 bytes

-9 bytes thanks to Kevin Cruijssen

```
procedure s(l,a,b)
l[a]:=:l[b]
end

```

Try it online!

1-indexed
> 1 votes

# Answer
# Python 3, 49 bytes

```
lambda l,a,b:l[:a]+[l[b]]+l[a+1:b]+[l[a]]+l[b+1:]

```

Try it online!

The very simple way.
> 1 votes

# Answer
# x86-16 machine code, 7 bytes

```
00000000: 8a01 8600 8801 c3                        .......

```

Listing

```
8A 01   MOV  AL, BYTE PTR[BX][DI]       ; put 'b' value into AL
86 00   XCHG AL, BYTE PTR[BX][SI]       ; swap 'b' value with 'a' position
88 01   MOV  BYTE PTR[BX][DI], AL       ; put 'a' value into 'b' position
C3      RET                             ; return to caller

```

Input \\$L\\$ at `[BX]`, indices \\$a\\$ in `SI`, \\$b\\$ in `DI`, `0`-based.

A test with our old friend DOS DEBUG:
> 1 votes

# Answer
# Pari/GP, 34 bytes

```
f(l,a,b)=[l[a],l[b]]=[l[b],l[a]];l

```

Try it online!

1-indexed
> 1 votes

# Answer
# Ruby, 30 bytes

`->(l,a,b){l[a],l[b]=l[b],l[a]}`

Mutates the input in-place. Direct port of @pxeger's approach including the link below:

Attempt This Online!
> 1 votes

# Answer
# Desmos, 49 bytes

```
l=[1...L.length]
f(L,a,b)=\{l=a:L[b],l=b:L[a],L\}

```

Try It On Desmos!

Try It On Desmos! - Prettified

Surprisingly readable (if you know a bit of Desmos) even after I code golfed it.

### Python Equivalent (switching to 0-based)

```
def f(L,a,b):
    returnList = []
    for l in range(len(L)):
        if l == a:
            returnList.append(L[b])
        elif l == b:
            returnList.append(L[a])
        else:
            returnList.append(L[l])
    return returnList

```
> 1 votes

# Answer
# Tcl, 75 bytes

```
proc S {L a b} {set x [lindex $L $a]
lset L $a [lindex $L $b]
lset L $b $x}

```

Try it online!
> 1 votes

# Answer
# C++ (gcc), 36 bytes

```
#define f(a,i,j)std::swap(a[i],a[j])

```

Try it online!
> 1 votes

# Answer
# AWK, 36 bytes

```
$$(NF-1)+=$$NF-($$NF=$$(NF-1)),NF-=2

```

Try it online!

## Expected input

The input is a list of integers separated by spaces; the last two integers are the indexes of the values that must be swapped:

```
Input:
3 8 1 4 10 10 10 10 1 6
\_________________/ | |
 List of integers,  | L> Second index
starting index at 1 |
                    L> First index

Output:
10 8 1 4 10 3 10 10
|           |
\___________/
   Swapped

```

## How it works

```
$$(NF-1)                        We take the integer which index is the value of the second-to-last integer,
        +=                      and add:
          $$NF                  the integer which index is the last integer
              -($$NF            minus itself,
                    =$$(NF-1))  except that it is now the integer which index is the second-to-last integer.
,NF-=2                          And let's remove the last two integers.
                                Phew! It should print the modified input, at last.

```

It uses this swapping oneliner: `a+=b-(b=a)`.

For better understanding: `NF` is the variable for the number of fields, i.e, the number of integers in the input. `$n` is the `n`th integer in the input, so `$NF` is the last integer, and `$(NF-1)` the second-to-last integer. `$$NF` equals `$($NF)`, that is the integer which index is the last integer.

`NF-=2` reduces the number of fields by two, ignoring the two indexes.
> 1 votes

# Answer
# BQN, ~~18~~ 10 bytes

*Edit: -8 bytes thanks to Razetime*

```
{⌽⌾(⊸⊏)}

```

Try it at BQN online REPL

~~Probably not the tersest code, but it works, which was no trivial accomplishment for my very limited BQN ability~~. Now quite short...
~~Will try to golf-down better as my abilities (gradually) improve~~. ...thanks to Razetime.

```
Swap ← {⌽⌾(⊸⊏)}          # define Swap function:
                            # list of 2 indices to swap on left =
                            # array on right = .

         ⌾                  # 'under' = apply function on LHS
                            # to elements specified by RHS
          (⊸⊏)            #   RHS: elements of  at indices
        ⌽                   #   LHS: reverse

```
> 1 votes

# Answer
# Uiua, 3 bytes

```
⍜⊏⇌

```

Try it!

0-indexed.
> 1 votes

# Answer
# C# (Visual C# Compiler), 75 bytes

```
List<int> f(List<int> L,int a,int b){var x=L[a];L[a]=L[b];L[b]=x;return L;}

```

Try it online!

Working only for int's. Thinking about evolving it to generics after.
> 0 votes

---
Tags: code-golf, number, array, integer
---


# Question
Title: Compute the minimum \$a(n)>a(n-1)\$ such that \$a(1)+a(2)+\dots+a(n)\$ is prime (OEIS A051935)
## Background

Consider the following sequence (A051935 in OEIS):

* Start with the term \\$2\\$.
* Find the lowest integer \\$n\\$ greater than \\$2\\$ such that \\$2+n\\$ is prime.
* Find the lowest integer \\$n'\\$ greater than \\$n\\$ such that \\$2 + n + n'\\$ is prime etc.

A more formal definition:

$$a\_n=\begin{cases}2 & \text{if }n=0 \\ \min\\{x\in\Bbb{N}\mid x\>a\_{n-1} \text{ and }\left(x+\sum\_{i=0}^{n-1}a\_i\right) \text{ is prime}\\} & \text{otherwise}\end{cases}$$

The first few terms of the sequence are (please refer to these as test cases):

```
2, 3, 6, 8, 10, 12, 18, 20, 22, 26, 30, 34, 36, 42, 44, 46, 50, 52, 60, 66, 72, 74, ...

```

## Task

Your task is to generate this sequence in any of the following ways:

* Output its terms indefinitely.
* Given \\$n\\$, output \\$a\_{n}\\$ (\\$n^{\text{th}}\\$ term, \\$0\\$ or \\$1\\$ indexed).
* Given \\$n\\$, output \\$\\{a\_1, a\_2, \dots, a\_n\\}\\$ (first \\$n\\$ terms).

You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is , so the shortest submission (in bytes) for *every language* wins.

# Answer
> 5 votes
# Brachylog, 13 bytes

```
~l.<₁a₀ᵇ+ᵐṗᵐ∧

```

Try it online!

Output is the list of first **n** terms of the sequence.

```
?~l.<₁a₀ᵇ+ᵐṗᵐ∧    Full code (? at beginning is implicit)

?~l.              Output is a list whose length is the input
    <₁            Output is an increasing list
      a₀ᵇ+ᵐ       And the cumulative sum of the output
           ṗᵐ     Consists only of prime numbers
             ∧    No further constraints on output

Explanation for a₀ᵇ+ᵐ:
a₀ᵇ               Get the list of all prefixes of the list
                  Is returned in increasing order of length
                  For eg. [2, 3, 6, 8] -> [[2], [2, 3], [2, 3, 6], [2, 3, 6, 8]]
   +ᵐ             Sum each inner list  -> [2, 5, 11, 19]

```

# Answer
> 4 votes
# Jelly, ~~11~~ 9 bytes

```
0Ḥ_ÆnɗÐ¡I

```

This is a full program that takes **n** as an argument and prints the first **n** terms of the sequence.

Try it online!

### How it works

```
0Ḥ_ÆnɗÐ¡I  Main link. Argument: n

0          Set the return value to 0.
      Ð¡   Accumulating iterate. When acting on a dyadic link d and called with
           arguments x and y, the resulting quicklink executes
           "x, y = d(x, y), x" n times, returning all intermediate values of x.
           Initially, x = 0 and  y = n.
     ɗ       Drei; combine the three links to the left into a dyadic chain.
 Ḥ             Unhalve; double the left argument.
  _            Subtract the right argument.
   Æn          Compute the next prime.
           This computes the partial sums of the sequence a, starting with 0.
        I  Increments; compute the forward differences.

```

# Answer
> 4 votes
# Python 2, ~~63~~ 62 bytes

```
n=f=a=b=1
while 1:
 f*=n;n+=1;a+=1
 if~f%n<a-b:print a;b=a;a=0

```

Try it online!

# Answer
> 4 votes
# 05AB1E v2, 10 bytes

```
2λλOD₁+ÅNα

```

Try it online!

This only works in the non-legacy version, the Elixir rewrite. Outputs an infinite stream of integers. There are some bugs with the prime test that have been fixed in the latest commits, but are not yet live on TIO. It does work locally, though. Here is a GIF of its execution on my machine, modified to output the first few terms rather than the whole stream.

### How it works

Defines a recursive infinite sequence with base case \\$2\\$. The `λ` structure is among 05AB1E's very cool new features. Briefly speaking, it takes a function \\$a(n)\\$, setting \\$a(0)\\$ to the integer argument given, in this case \\$2\\$.

```
λO

```

In this portion of code, `λ`'s role is different. Already being inside a recursive environment, it instead generates \\$\[a(0),a(1),\dots,a(n-1)\]\\$, the list of all previous results. Then, `O` sums them up.

```
D₁+

```

Duplicate the sum for later use and add \\$a(n-1)\\$ to the second copy.

```
ÅN

```

Generates the lowest prime stricly greater than the above sum.

```
α

```

Finally, retrieve the absolute difference between the prime computed above and the first copy of the sum computed earlier (the sum of all previous iterations).

The stream is then implicitly printed to STDOUT indefinitely.

# Answer
> 3 votes
# Ruby `-rprime`, 34 bytes

```
2.step{|i|$.+=p(i)if($.+i).prime?}

```

Try it online!

Outputs indefinitely.

# Answer
> 3 votes
# Pyth, ~~12~~ 11 bytes

```
.f&P-;Z=-;Z

```

Try it online!

Saved 1 byte thanks to isaacg.

Generates the first `n` such numbers, using a 1 based index.

`.f` finds the first `k` integers that satisfy a particular criterion starting from zero. Here, the criterion is that the previous prime we calculated, `;`, plus the current number, `Z`, is prime (`P`). If it is, we also update the last calculated prime using the short-circuiting behaviour of the logical and function (`&`). Unfortunately `.f`'s default variable is `Z` which costs a byte in the update.

The trick that isaacg figured out was to store the negation of the last prime and test on that minus the current value. This is shorter in Pyth since the primality check is overloaded: on positive numbers it finds the prime factorisation while on negative numbers it determines if the positive value of the number is prime.

This more or less translates into:

```
to_find = input()
last_prime = 0
current = 0
results = []
while to_find > 0:
    if is_prime( current + last_prime ):
        results.append( current )
        to_find -= 1
        last_prime += current
    current += 1
print results

```

# Answer
> 2 votes
# Perl 6, 45 bytes

```
2,{first (*+@_.sum).is-prime,@_[*-1]^..*}...*

```

Try it online!

Returns a lazy list that generates the sequence with no end.

### Explanation:

This uses the Sequence operator `...` which defines the sequence as:

```
2,  # The first element is 2
  {  # The next element is:
    first  # The first value that:
          (*+@_.sum).is-prime,  # When added to the sum is a prime
          @_[*-1]^..*  # And is larger than the previous element
  }
...*  # And continue the sequence indefinitely

```

# Answer
> 2 votes
# Haskell, 67 bytes

```
(1#1)2 2
(p#n)s k|p`mod`n>0,n-s>k=k:(p#n)n(n-s)|w<-p*n=(w#(n+1))s k

```

Try it online!

`(1#1)2 2` is a functions that takes no input and outputs an infinite list.

---

old answer:

# Haskell, ~~88~~ ~~83~~ ~~78~~ 76 bytes

The primality test is from this answer and improved by Christian Sievers (-2 bytes).

-5 bytes thanks to W W.

```
2#2
(p#s)n|n<1=p|w<-until(\m->mod(product[1..m-1])m>0)(+1)$s+p+1=(w-s)#w$n-1

```

Try it online!

# Answer
> 2 votes
# MATL, 21 bytes

```
O2hGq:"t0)yd0)+_Yqh]d

```

Try it online!

Output is the first **n** terms of the sequence.

### Explanation:

Constructs a list of primes (with an initial 0), and at the end finds the returns the differences between successive primes in the list.

```
              % Implicit input, say n
O2h           % Push P = [0, 2] on the stack
Gq:"          % for loop: 1 to n-1
  t0)           % Take the last element of P
                %  Stack: [[0, 2], [2]] (in first iteration)
  yd0)          % Take the difference between the last
                %   two elements of P
                %  Stack: [[0, 2], [2], [2]]
  +             % Add those up
                %  Stack: [[0, 2], [4]]
  _Yq           % Get the next prime higher than that sum
                %  Stack: [[0, 2], [5]]
  h             % Concatenate that to the list P
                %  Stack: [[0, 2, 5]]
]             % End for loop
d             % Get the differences between successive elements of
              %   the final list P

```

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

Returns the \\$n^{th}\\$ term, 1-indexed.

```
n=>(k=0,s=1,g=d=>s%d?g(d-1):d<2?--n?g(s-=k-(k=s)):s-k:g(s++))()

```

Try it online!

# Answer
> 2 votes
# 05AB1E (legacy), 12 bytes

```
0U[XN+DpiN,U

```

Try it online!

**Explanation**

```
0U              # initialize X as 0
  [             # start an infinite loop
   XN+          # add X to N (the current iteration number)
      Dpi       # if the sum is prime:
         N,     #   print N
           U    #   and store the sum in X

```

There are a couple of different 12-byte solutions possible.
This particular one could have been 10 bytes if we had a usable variable initialized as 0 (instead of 1 and 2).

# Answer
> 1 votes
# Python 2, 119 bytes

```
f=lambda n,k=1,m=1:m%k*k>n or-~f(n,k+1,m*k*k)
def g(i):
 r=[2]
 for j in range(i):r+=[f(sum(r)+r[-1])-sum(r)]
 return r

```

Try it online!

Next Prime function f() taken from this answer.

Function g() takes a non-negative integer i and returns a list of all items in the sequence up to that index.

# Answer
> 1 votes
# C (gcc), ~~100~~ 99 bytes

```
p(r,i,m,a,l){for(l=m=a=0;a-r;)m+=i=p(a++);while(r*!l)for(++i,l=a=2;a-m-i;)l=(m+i)%a++?l:0;r=r?i:2;}

```

Try it online!

# Answer
> 1 votes
# Haskell, ~~101 99~~ 97 bytes

The function `l` takes no arguments and returns an infinite list. Not as short as the more direct approach by @ovs (and I obviously stole some parts form their answer), but maybe still golfable?

Thanks @H.PWiz for -2 bytes!

```
import Data.List
p m=mod(product[1..m-1])m>0
l=2:[until(p.(+sum a))(+1)$last a+1|a<-tail$inits l]

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~99~~ 98 bytes

```
def f(n,s=2,v=2):
 k=s-~v
 while any(k%i<1for i in range(2,k)):k+=1
 return n and f(n-1,k,k-s)or v

```

Try it online!

1 byte thx to Mr. Xcoder.

# Answer
> 1 votes
# Python 2, ~~82~~ 80 bytes

```
s=p=2
i=input()
P=n=1
while i:
 P*=n;n+=1
 if P%n>0<n-s-p:p=n-s;s=n;i-=1
print p

```

Try it online!

This outputs the nth number of the sequence (0-based). By moving the `print` in the loop, this can be modified to output the first `n` items at the same bytecount: Try it online!

# Answer
> 1 votes
# PARI/GP 73 bytes

```
a(n)=v=[2];s=vecsum;while(n--,v=concat(v,nextprime(s(v)+v[#v]+1)-s(v)));v

```

1-indexed, output: first n terms

# Answer
> 1 votes
# Pyth, 13 bytes

```
I%sjs.BQ2 2\1.?0

```

Simply converts a given input to binary and prints the respective output whether the sum of 1's in the output list is even or not. Made in about 5 seconds, and can probably be done in way fewer characters than I have, but hey, I tried.

# Answer
> 0 votes
# Japt, 17 bytes

Outputs the `n`th term, 0-indexed.

```
@_+T j}aXÄT±X}g2ì

```

Try it

---
Tags: code-golf, math, sequence, number-theory, primes
---


title: Make every other vowel uppercase

text:
# Question
Title: Make every other vowel uppercase
Given a lower case string. Ex:

```
s = 'abcdefghijklmnopqrstuvwxyz'

```

The goal is to make every other vowel uppercase.

Desired output here:

```
abcdEfghijklmnOpqrstuvwxyz

```

As you can see, from `aeiou`, \\$\`e\`\\$ and \\$\`o\`\\$ get uppercased.

For `aeiou`, the desired output is:

```
aEiOu

```

There are only lowercase characters in the strings in all cases.

This is , so shortest code in bytes wins.

*P.S. The vowels are `aeiou`*

# Answer
# Perl 5, 23 bytes

```
s/[aeiou]/$&^$"x$|--/ge

```

Try it online!

## Explanation

`s///`ubstitutes each of the lowercase vowels with itself XORed with either 1 or 0 spaces (`$"` defaults to space) based on `$|--` which will alternate each time it's decremented.
> 13 votes

# Answer
# C (gcc), 61 bytes

A full program, where input is taken from STDIN.

```
x;main(c){for(;read(0,&c,1);)putchar('Xz'%c?c:c^x++%2*32);}

```

Try it online!

### Checking for vowels

Vowels are `aeiou`, which have the corresponding ASCII codes `97,101,105,111,117`. The LCM of these numbers is `1484392455`, which has the property of being evenly divisible by only the letters `aeiou`. Therefore, we can say that `c` is a vowel if `1484392455%c` equals `0`. We can compress this number by the use of multi-character constants, giving `'Xz\x08\x07'`.

# C (clang), 48 bytes

As offered by @AZTECCO, a function which takes a wide string as input, and modifies the string in-place.

```
x;f(*s){for(x=0;*s;)*s++^='Xz'%*s?0:x++%2*32;}

```

Try it online!
> 12 votes

# Answer
# Python, ~~73~~ ~~71~~ ··· 58 bytes

```
lambda s,c=0:bytes(a^c|(c:=c^34087456>>a-97&32)for a in s)
```

Attempt This Online!

Inputs and outputs as a byte string.

Explanation (I use a `$` sigil on variables to distinguish them from letters):

* Consider the lookup table for "letter `$a` is a vowel": this is the binary array `10001000100000100000100000` (the `1`s are at the alphabet positions of `aeiou`)
* If we store this as an integer (converting the binary array into a decimal number `35784736`), we can lookup into it using `35784736 >> 97 - alphabet_index($a) & 1`
* If `$a` is actually the ASCII code of the character, we can get its alphabet index using `$a - 97` (since `'a' == 97`)
* By taking input and output as `bytes` in Python, we can get this ASCII code basically for free
* We can reverse the lookup table to make it shorter by changing `$a - 97` to `97 - $a`, because by reversing it the trailing zeroes (for `vwxyz`) become leading zeroes and make the number smaller
* The reverse lookup table is `00000100000100000100010001 = 100000100000100010001`, or `1065233` in decimal, giving us `1065233 >> $a - 97 & 1`
* We can toggle the flag variable `$c` if `$a` is a vowel, using `$c := $c ^ (1065233 >> $a - 97 & 1)`
* We also want to uppercase `$a` sometimes. Observe that the uppercase ASCII letters differ from the lowercase letters by exactly `32`, so we can toggle the case of `$a` using `$a ^ 32`
* The case toggling should happen if both:
    + `$c` is *on* (since we initialise it to `0`, and every vowel starting with the *second* should be capitalised)
    + `$a` is a vowel
* This is equivalent to `$a ^ 32 * ($c & (1065233 >> $a - 97 & 1))`
* If we store "on" as `32` rather than just `1`, and we adjust the lookup table to return `32`/`0` rather than `1`/`0`, we'll save bytes.
* We can do this by using `1065233 * 32 = 34087456` as the magic number and `&`-ing with `32` instead of `1`. The resulting expression is `34087456 >> ($a - 97) & 32`
* We want to avoid using `34087456 >> ($a - 97) & 32` in more than one place, because it's a long expression
* Since we're modifying `$c` with a `:=` expression, we can do a computation on its value before and after modification to extract the correct value. Let `$c` be the value before modification and `$c'` be the new value
* `$c'` is different to `$c` if and only if `$a` is a vowel, so we want to capitalise if `$c` is *on* and `$c' != $c`, i.e. **`$c` is on and `$c'` is off**
* Recall that lowercase letters have the `32`s bit set, and to uppercase a letter we need to unset it. This means `$a` has the `32`s bit set initially
* By `xor`ing `$a` and `$c`, when `$c` is on, we remove the `32`s bit, uppercasing the letter
* But we only want to do this when `$a` is a vowel, so we can re-set the `32`s bit when it isn't. Thus by adding `| $c'`, the `32`s bit is added again when `$c'` is `32`. This is the case if `$c` was `32` and `$a'` was not a vowel, so the bit is only removed when `$a` is a vowel *and* `$c` is `32`
> 7 votes

# Answer
# Retina, 17 bytes

```
1,2,T`l`L`[aeiou]

```

Try it online! Link includes test cases. Explanation:

```
[aeiou]

```

Match lower case vowels.

```
1,2,

```

Only process every other vowel.

```
T`l`L`

```

Upper case them.

Although the transliterate command has a shortcut code for vowels, they aren't of any help here so I haven't used them.
> 7 votes

# Answer
# , 57 bytes

```
function(s,t=s%in%utf8ToInt("aeiou"))s-t*32*!cumsum(t)%%2

```

Try it online!

Input is vector of character codes (for comparison to pajonk's answer). Would be 77 bytes with input as string (for comparison to Maël's answer).

---

*Edit*: this approach would be only 48 bytes by porting dingledooper's great modulo trick...
> 7 votes

# Answer
# Jelly, 13 bytes

```
e€ØẹTḊm2
Œuç¦

```

Try It Online!

```
e€ØẹTḊm2  Helper Link; get every other vowel
e€        For each element, is it in
  Øẹ      the list of vowels ("aeiou")?
    T     Get said indices
     Ḋm2  Pop off the first one and take every other one
Œuç¦      Main Link
   ¦      Apply
Œu        to-uppercase
  ç       to every other vowel

```
> 6 votes

# Answer
# Vyxal, 9 bytes

```
ATy$_⁽⇧¨M

```

Try it Online!

The power of triads!

## Explained

```
ATy$_⁽⇧¨M
AT       # indices of vowels
  y      # uninterleave into two lists - this pushes a list of every second vowel and every first vowel
   $_    # remove the list of every first vowel
     ⁽⇧¨M # and apply upper-case (a function pushed by ⁽⇧) to those indices (¨M)

```
> 6 votes

# Answer
# , 94 bytes

*-26 bytes thanks to Giuseppe. -2 bytes thanks to Robin Ryder*

```
function(s){s=el(strsplit(s,""))
s[i]=toupper(s[i<-grep("[aeiou]",s)[!1:0]])
Reduce(paste0,s)}

```

See pajonk's and Dominic van Essen's answers for a clever use of `intToUtf8` and `utf8ToInt`.

Try it online!
> 6 votes

# Answer
# x86 / x86-64 machine code, 22 bytes

Takes pointer (RSI), length (RCX) in registers, modifies the string in-place. Callable from C with the x86-64 SysV calling convention as `void vowel_alt_caseflip(int dummy, char *RSI, int dummy, size_t RCX)`. Same machine code works in 32-bit mode, although none of the standard 32-bit C calling conventions match.

NASM listing, with address, machine-code bytes, and source the machine-code answer was generated from.

```
     1                         ;;; char *str /* RSI */,  size_t len /* RCX */
     2                         vowel_alt_caseflip:
     3 00000000 BF22822000         mov edi, 0x0208222      ; ASCII vowel bitmap, 1-indexed like ASCII codes are with 'a' = 0x61 not 0x60
     4 00000005 31D2               xor edx, edx            ; first vowel is not flipped
     5                         .loop:
     6 00000007 AC                 lodsb                   ; al = *str++
     7 00000008 0FA3C7             bt  edi, eax            ; if (bitmap & (1<<(al&31)))
     8 0000000B 7306               jnc .non_vowel
     9 0000000D 3056FF             xor [rsi-1], dl         ; caseflip or not the current character
    10 00000010 80F220             xor dl, 0x20            ; toggle state for the next
    11                         .non_vowel:
    12 00000013 E2F2               loop  .loop
    13 00000015 C3                 ret

; next address is 0x16, size is 0x16 = 22 bytes

```

Since the input string is guaranteed to be all lowercase alphabetic, I just used XOR instead of AND with `~0` / `~0x20` to flip instead of clear the ASCII lower-case bit. It would work out to the same size with `mov dl, 0xFF` / `and [rsi-1], dl`.

Try it online! with a Linux `_start` caller that passes it the alphabet twice and makes write system calls before/after, so we can see that it correctly treats `u` as a vowel.

For more about the immediate bitmap strategy, and variations like using it branchlessly, see SO and two of my previous x86 answers:

---

#### Alternate version, same size

I had hoped to be able to use `xor al, 0x20` to save a byte vs. DL, but we need AL for efficient string-reading via `lodsb`. (We need a char from the string in a register to use as a source for `bt`.) We could start with `mov` there and use `stosb` to store, but that would have to be separate from a reg-reg XOR or AND, and still doesn't free up AL.

We could use `scasb` as a 1-byte `inc rdi`. Using `mov dl, [rdi]` to start, and saving the `-1` in the memory-dest addressing mode, and another byte from `xor al, 0x20` short-form, that's break-even for size and worse for efficiency (useless `scasb` reload). Or similar efficiency in 32-bit mode since we could use `inc edi` there.

```
;;; char *str /* RDI */,  size_t len /* RCX */
vowel_alt_caseflip_scasb:
    mov esi, 0x0208222      ; ASCII vowel bitmap, 1-indexed like ASCII codes are with 'a' = 0x61 not 0x60
    xor eax, eax            ; first vowel is not flipped
.loop:
    mov dl, [rdi]
    bt  esi, edx            ; if (bitmap & (1<<(c&31)))
    jnc .non_vowel
    xor [rdi], al           ; caseflip or not the current character
    xor al, 0x20            ; toggle state for the next
.non_vowel:
    scasb                   ; inc rdi   in one byte even on x86-64
    loop  .loop
    ret

```
> 6 votes

# Answer
# Dyalog APL, 23 bytes

```
1∘⎕C@(=\≠⍨)@(∊∘'aeiou')

```

`1∘⎕C` uppercase…

`@(``)` at…

`=\` XNOR scan (i.e. every other) of the
`≠⍨` XOR selfie (i.e. all 0s)

`@(``)` at…

member
of
`'aeiou'` vowels

Try APL online!
> 5 votes

# Answer
# Javascript, 57 5654 bytes

```
s=>s.replace(/[aeiou]/g,c=>(s=!s)?c.toUpperCase():c)

```

-1 Thanks to Patrick Stephansen.
-2 Thanks to tsh. -2 Thanks to l4m2.

Usage:

```
console.log((s=>s.replace(/[aeiou]/g,c=>(s=!s)?c.toUpperCase():c)))("string goes here"))

```

Try it online
> 5 votes

# Answer
# BQN, 19 bytesSBCS

```
⊢-32×·≠`⊸<∊⟜"aeiou"

```

Run online!

Textbook use for under, but character arithmetic is much, much shorter. -10 from Marshall, then -3 from Marshall.

# Explanation

```
⊢-32×·≠`⊸<∊⟜"aeiou"
          ∊⟜"aeiou" bitmask of vowels
      ≠`            inequality scan(XOR scan)
        ⊸<          lesser than original bitmask?
  32×·              32 × that
⊢-                  subtract from the input

```
> 5 votes

# Answer
# Jelly, 14 bytes

```
e€Øcn\<$a32^OỌ

```

Try it online!

```
e€Øc            For each input character: is it in Øc (vowels)?
                This gets a mask with 1s where vowels are, e.g.
                  “b x d e f h i z k o m u p”
                   0 0 0 1 0 0 1 0 0 1 0 1 0

    n\<$        scanl(≠, mask) < mask: This selects every other 1.
                  scanl(≠):  0 0 0 1 1 1 0 0 0 1 1 0 0
                  original:  0 0 0 1 0 0 1 0 0 1 0 1 0
                         <:  0 0 0 0 0 0 1 0 0 0 0 1 0

        a32     Replace all 1s by 32.
           ^O   XOR by ord(input string).
             Ọ  chr()

```
> 4 votes

# Answer
# , 65 bytes

```
function(s){s[i]=s[i<-which(s%in%utf8ToInt("aeiou"))[!1:0]]-32;s}

```

Try it online!

Takes input and outputs as vectors of char codes.

Some parts borrowed from @Maël's R answer.
> 4 votes

# Answer
# Ruby, 41 bytes

Uses the `-p` flag.

```
i=1
gsub(/[aeiou]/){[$&,$&.upcase][i^=1]}

```

Try it online!
> 4 votes

# Answer
# APOL, 35 bytes

`j(ƒ(i ¿(&(c(Ⓔ ↓(∋)) ≐(∈)) ∋ ↑(∋))))`

## Explanation

```
j(  Join a list to a string
  ƒ(  Listbuilder for
    i  Input
    ¿(  Returning if (called for each item in the input)
      &(  And (condition)
        c(  String contains
          Ⓔ  The constant string "aeiou"
          ↓(  To lowercase
            ∋  Current character
          )
        )
        ≐(  Is even
          ∈  For loop counter
        )
      )
      ∋  For loop item (executed if true)
      ↑(  To uppercase
        ∋  For loop item
      )
    )
  )
)

```
> 4 votes

# Answer
# Python 2, 86 bytes

-26 thanks to ElPedro.

-2 thanks to Daniel.

```
c,S=0,''
for i in input():
 if i in'aeiou':S+=(i,i.upper())[c];c^=1
 else:S+=i
print S

```

**Try it online**
> 3 votes

# Answer
# C (tcc), ~~174~~ 111 bytes

*Saved 63 bytes thanks to manatwork*

```
i,b;f(char*a,int l){for(i=0;i<l;i++)if(a[i]==97||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u')if(b++%2)a[i]-=32;}

```

Try it online!

### Unminified

```
i, b;
f(char* a, int l) {
    for (i = 0; i < l; i++)
        if (a[i] == 97 || a[i] == 'e' || a[i] == 'i' || a[i] == 'o' || a[i] == 'u')
            if (b++ % 2)
                a[i] -= 32;
}

```
> 3 votes

# Answer
# Japt v2.0a0, 10 bytes

```
r\vÈpu gT°

```

Try it
> 3 votes

# Answer
# , 33 31 bytes

```
(>~:/\)@e.&'aeiou'`(,:toupper)}

```

Try it online!

-2 thanks to Lynn

Kind of shockingly long, but best I could find so far...
> 3 votes

# Answer
# Charcoal, 21 bytes

```
⭆Ｓ⎇№aeiouι§⁺↥ιιＬ⊞Ｏυιι

```

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

```
 Ｓ                      Input string
⭆                       Map over characters and join
   №                    Count of
         ι              Current character
    aeiou               In literal string `aeiou`
  ⎇                     If exists then
             ι          Current character
            ↥           Uppercase
           ⁺            Plus
              ι         Current character
          §             Indexed by
                   ι    Current character
                ⊞Ｏ      Pushed to
                  υ     Predefined empty list
               Ｌ        Length after push
                    ι   Otherwise current character
                        Implicitly print

```
> 2 votes

# Answer
# APL+WIN, 39 bytes

Prompts for string

```
⎕av[(⎕av⍳s)-32×1=i+i×≠\i←(s←⎕)∊'aeiou']

```

Index offset from lower to upper case changed in TIO from -32 to +48 to account for differences between APL+WIN and Dyalog atomic vectors.

Try it online!Thanks to Dyalog Classic
> 2 votes

# Answer
# Retina 0.8.2, 25 bytes

```
0T-1=`l`L`(.*?[aeiou]){2}

```

Try it online! Link includes test cases. Explanation:

```
(.*?[aeiou]){2}

```

Match the shortest possible substrings containing two vowels.

```
-1=

```

Only transliterate the last character of each match. (The `0` indicates that this modifier applies to the characters of the match rather than the matches themselves.)

```
T`l`L`

```

Upper case them.
> 2 votes

# Answer
# Lua, 81 bytes

```
print(((...):gsub("[aeiou]",function(x)u=not u;return u and x or(x):upper()end)))

```

Try it online!

Expects the input as first argument, prints output. Is one character shorter if `return` instead of `print` is used.
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~148~~ 123 bytes

```
	S =INPUT
N	S ARB . L ANY('aeiou') . C REM . S	:F(O)
	X =1 - X
	C =CHAR(ORD(C) - 32) EQ(X)
	O =O L C	:(N)
O	OUTPUT =O S
END

```

Try it online!

## Explanation:

```
	S =INPUT			;* Read input
N	S ARB . L ANY('aeiou') . C REM . S	:F(O)
					;* Match in S:
					;* ARBitrary string (store as L), ANY single vowel (store as C)
					;* and the REMainder of the string (store as S).
					;* If there is no match, goto O.
	X =1 - X			;* Set X (initially treated as 0) to 1-X.
	C =CHAR(ORD(C) - 32) EQ(X)	;* if X == 0, set C to uppercase, otherwise do nothing.
	O =O L C	:(N)		;* append to O L and C, then goto N.
O	OUTPUT =O S			;* Output updated string
END

```
> 2 votes

# Answer
# 05AB1E, 11 bytes

```
žMÃDεNÉiu]‡

```

Try it online.

Or alternatively the `εNÉiu]` could be `2ι`u.ι`.

Try it online.

**Explanation:**

```
žM         # Push the constant "aeiou"
  Ã        # Only keep those letters from the (implicit) input
   D       # Duplicate it
    ε      # Map the vowels in the copy to:
     NÉi   #  If the 0-based index is odd:
        u  #   Uppercase the vowel
    ]      # Close the if-statement and map
     ‡     # Transliterate the lowercase vowels to the alternating cased vowels
           # in the (implicit) input
           # (after which the result is output implicitly)

    2ι     # Uninterleave into two parts
      `    # Pop and push both parts separated to the stack
       u   # Uppercase the second part
        .ι # And interleave the two parts back again (to a list of characters)

```
> 2 votes

# Answer
# Headascii, 142 bytes

```
----[]]]][]][++++^^^^D^^^^^+^{{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P};RP{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P};R]P}.!

```

Try it here! Code will have to be copied, and executed like this:

```
erun("----[]]]][]][++++^^^^D^^^^^+^{{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P};RP{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P};R]P}.!","your input")

```

This one was fun, not sure if there's any room for serious golfing without a different approach. Maybe something with an oscillator to decide whether to uppercase a given vowel? But the 3 main storage registers are used up for comparison, storing -32 (uppercase constant), and storing 97 (ascii a, first vowel). So I'm not sure where the constant would be held. I'll take another whack at it sometime though.

```
----[]]]][]][++++^^^^D^^^^^+^ Constants -32 and 97
----                          -4
    []]]]                     *4
         []][                 *2, and store
             ++++             4
                 ^^^^         *4
                     D^^^^^+^ *6+1, already stored

{{...};RP{...};R]P}. The rest of block 0
{                 }  Loop
 {   }               Loop until a vowel is found
      ;RP            Concatenate it to the string register
         {   }       Loop until a vowel is found
              ;R]P   Subtract 32 (uppercase) and concatenate to string register
                   . Block separator

{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P} First loop
{                                                 } Loop
 D^(U)                                              If byte is "a",
       ++++(R)                                      "e"
               ++++(R)                              "i"
                       ++++++(R)                    "o"
                                 ++++++(R)          or "u",
      :       :       :         :         :           Exit loop.
                                                    Else,
                                           R()        If byte is null (i.e. string ended)
                                              +E        Go to block 1
                                                :     Else,
                                                 P      Concatenate byte to string register

{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P} Second Loop is identical to the first
                                                    Avoiding two identical loops would be
                                                    a major golfing opportunity

!  Block 1
!  Print string register, end of execution

```
> 2 votes

# Answer
# Factor, 65 bytes

```
[ dup [ "aeiou"in? ] arg-where <odds> over [ 32 - ] change-nths ]

```

Try it online!

## Explanation

Get the indices of the vowels from the input, take the odd-indexed elements of those, then subtract 32 from the input at those indices. `change-nths` is a mutating word which has the usual `( indices seq -- )` stack effect which is why we need an extra copy on the stack before we call it.

```
                          ! "abcdefghijklmnopqrstuvwxyz"
dup                       ! "abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz"
[ "aeiou"in? ] arg-where  ! "abcdefghijklmnopqrstuvwxyz" V{ 0 4 8 14 20 }
<odds>                    ! "abcdefghijklmnopqrstuvwxyz" { 4 14 }
over                      ! "abcdefghijklmnopqrstuvwxyz" { 4 14 } "abcdefghijklmnopqrstuvwxyz"
[ 32 - ] change-nths      ! "abcdEfghijklmnOpqrstuvwxyz"

```
> 2 votes

# Answer
# Uiua, 17 bytes

```
-×32×\≠.∊,"aeiou"

```

Try it!

Port of Razetime's BQN answer.

```
-×32×\≠.∊,"aeiou"
        ∊,"aeiou"  # mask of where vowels are in input
       .           # duplicate
     \≠            # inequality scan
    ×              # multiply
 ×32               # multiply by 32
-                  # subtract (capitalize)

```
> 2 votes

---
Tags: code-golf, string
---


title: Positions on the Pickleball Court

text:
# Question
Title: Positions on the Pickleball Court
My doubles pickleball group often has five people. Four are playing and one is awaiting the next game. We can represent the state of the game with a string of five characters like abCde. This indicates that a and b are playing against c and d with c serving. We want to write a routine that gives the possible positions after the next rally is complete. The examples below will assume we start with this configuration.

For those unfamiliar with the game, two players are paired to play against the other two. One of the players serves to put the ball in play. A rally consists of play until one side fails to hit the ball back legally, at which point it is won by the side that did not fail. Only the serving side scores points for winning a rally. The receiving side only moves the serve along by winning a rally.

There are four possible outcomes of a rally.

1. The serving side wins the rally but does not win the game. The players on the serving side change places and the same player serves, so we go to abdCe.
2. The serving side wins the rally and thereby wins the game. The players rotate one position right and the serve goes to the first position, so we go to Eabcd
3. The receiving side wins the rally, but the partner of the server has not served yet. The players stay in position and the serve goes to the partner, so we go to abcDe
4. The receiving side wins the rally and the partner of the server has served. The players stay in position and the serve goes to the first player of the other side, the one in first or third position. Here we go to Abcde

Your task is to write a routine that takes a configuration at the start of a rally and returns or prints the four possible configurations at the end of the rally in the order of the possibilities above. A configuration has the five characters in any order with the server any of the first four. This is code golf, so the shortest solution wins. You can use other characters and other ways of indicating the server if you wish, like digits and making the server negative or adding $5$ to the server or putting an asterisk after the server. There needs to be a clear break between the four possibilities, like a space, a newline, or separate elements of a list. You can take your input in any convenient way, as a string or array for example. The characters used should be the same on input and output.

Test cases-input first column, output the remaining four

```
Abcde bAcde Eabcd aBcde abCde

caBed caeBd Dcabe cabEd Cabed

dBace Bdace Edbac Dbace dbAce

bcdAe bcAde Ebcda bcDae Bcdae

```

# Answer
# Jelly, 40 bytes

```
AN⁸NM’ỊḤ‘¤¦,@ṙ-AN1¦Ɗż@s2WU,NƊṠE$?€ŒpF€ƲẎ

```

Try it online!

A monadic link taking a list of integers and returning a list of lists of integers in the order specified. Servers are indicated by negative numbers. If the order of results could be more flexible, I can save three bytes.

## Explanation

```
AN⁸NM’ỊḤ‘¤¦,@ṙ-AN1¦Ɗż@s2WU,NƊṠE$?€ŒpF€ƲẎ
A                                         # Absolute
 N⁸      ¤¦                               # Negate at the index given by running the following on the original argument:
   N                                      # - Negate
    M                                     # - Indices (here single index) of max (will be the index of the server)
     ’                                    # - Decrement by 1
      Ị                                   # - <= 1
       Ḥ                                  # - Double
        ‘                                 # - Increment by 1
           ,@      Ɗ                      # Pair in reverse order with the result of running the following on the original argument:
             ṙ-                           # - Rotate once to the right
               A                          # - Absolute
                N1¦                       # - Negate first index
                    ż@                Ʋ   # Zip in reverse order with the result of applying the following to the original argument:
                      s2                  # - Split into lists of length 2
                             ṠE$?€        # - For each of these sublists, if the signs are equal:
                        W                 #   - Then wrap in a further list
                         U,NƊ             #   - Else pair the reversed sublist with the negated sublist
                                  Œp      # - Cartesian product
                                    F€    # - Flatten each
                                       Ẏ  # Join outermost lists

```

Created with the help of Luminespire.
> 3 votes

# Answer
# APL+WIN, ~~93~~ 85 bytes

Prompts for players as integers 1 to 5 with the server shown as negative:

```
m←⎕⋄m⋄t←⊂[2]2 2⍴m⋄m←4↓m⋄(∊(+/¨0>¨t)⌽¨t),m⋄(-m),∊s←|t⋄(∊t×2/¨u←×/¨×t),m⋄(∊s×(⌽u),¨1),m

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# Charcoal, 57 bytes

```
⟦⭆⪪θ²⎇⊙ι№αλ⮌ιι⁺↥§θ⁴↧…θ⁴⭆⪪θ²⭆ι⎇№α§ι¬μ↥λ↧λ⭆θ⎇⁼κ⊗⊙…θ²№αλ↥ι↧ι

```

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

Print each of the following expressions on their own line.

```
⭆⪪θ²⎇⊙ι№αλ⮌ιι

```

Split the input into pairs of letters and reverse the pair which contains an uppercase letter. (The last letter is always unaffected; even if it was in upper case, reversing it would have no effect.)

```
⁺↥§θ⁴↧…θ⁴

```

Uppercase the last letter of the input and concatenate that with the lowercased first four letters.

```
⭆⪪θ²⭆ι⎇№α§ι¬μ↥λ↧λ

```

Split the input into pairs of letters and set each letter's case to that of the other letter in the pair. (The last letter becomes set to its case, which has no effect.)

```
⭆θ⎇⁼κ⊗⊙…θ²№αλ↥ι↧ι

```

If one of the first two letters is in uppercase then uppercase only the third letter otherwise uppercase only the first letter.
> 1 votes

# Answer
# C (GCC), ~~238~~ 226 bytes

```
#define Q),q(
q(x){putchar(x+48);}f(a,b,c,d,e,z){z=(a|b)&1;z?q(b Q a Q c Q d):(q(a Q b Q d Q c)Q e Q'/'Q e|1 Q~1&a Q~1&b Q~1&c Q~1&d Q'/'Q a^z Q b^z Q!z^c Q!z^d Q e Q 47);z?q(a&~1 Q~1&b Q c|1 Q d):(q(a|1 Q b Q~1&c Q~1&d)Q e);}

```

Attempt This Online!

While it looks daunting, the way this works is actually simple. `f` takes 5 players as parameters, where odd numbers denote the server (aka least-significant bit). That is, numbers 0 and 1 are the same player, 2 and 3, etc.

The function `q` outputs a digit. `z` tests whether one of the first players is the server and is used later for some conditions. The random-looking 47 is the separator between the outcomes, as 47+48=95, so an underscore. Any number from 10 to 99 or even -1 to -9 would work. Sadly, one digit is not possible, as all numbers from 0 through 9 are possible players.

The outputs are constructed using bit manipulation to set, remove or flip the LSB.

-12 bytes thanks to ceilingcat
> 1 votes

---
Tags: code-golf
---


title: Turn this array into a matrix

text:
# Question
Title: Turn this array into a matrix
Take a non-nested array as input. Turn it into a matrix by using the following method:

Let's say my array is `[1, 2, 3, 4, 5]`

First, I repeat that array 5 times: (the length)

```
[[1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5]]

```

Then, I read it along the diagonals:

```
[[1],
 [2, 1],
 [3, 2, 1],
 [4, 3, 2, 1],
 [5, 4, 3, 2, 1],
 [5, 4, 3, 2],
 [5, 4, 3],
 [5, 4],
 [5]]

```

I flatten this array and split it into pieces of five (the length):

```
[[1, 2, 1, 3, 2],
 [1, 4, 3, 2, 1],
 [5, 4, 3, 2, 1],
 [5, 4, 3, 2, 5],
 [4, 3, 5, 4, 5]]

```

This is code golf. Fewest bytes wins.

# Answer
# 05AB1E, 13 bytes

```
.p¹.sR¦«í˜¹gä

```

Try it online!

Explanation:

```
                # Implicit input
 .p             # Get prefixes
   ¹            # Get first input
    .s          # Get suffixes
      R         # Reverse
       ¦        # Remove first element
        «       # Concatenate
         í      # Reverse every one
          ˜     # Flatten
           ¹gä  # Split into pieces of the length
                # Implicit print

```
> 2 votes

# Answer
# Jelly, 11 bytes

```
WẋLŒDUṙLFsL

```

Try it online!

## Explanation

```
               Input: array z
WẋL            length(z) copies of z
   ŒD          Diagonals (starting with main diagonal)
     U         Reverse each
      ṙL       Rotate left length(z) places
               (now the top-left diagonal is in front)
        F      Flatten
         sL    Split into chunks of size length(z)

```
> 6 votes

# Answer
# Python 2, ~~105~~ 96 bytes

-1 and -4 and -4 bytes thanks to Flp.Tkc

```
a=input()
n=len(a)
L,M=[],[]
for i in range(n):L+=a[i::-1];M+=a[:i:-1]
print zip(*[iter(L+M)]*n)

```

The for loop adds the items like in the description, the real magic happens in the zip which is from here
> 3 votes

# Answer
# JavaScript (ES6) 100 ~~101 105~~

```
a=>eval("for(u=r=[],i=l=a.length;i+l;i--)for(j=l;j--;v&&((u%=l)||r.push(s=[]),s[u++]=v))v=a[j-i];r")

```

*Less golfed*

```
a => {
  u = 0
  for(r=[], i=l=a.length; i+l>0; i--)
    for(j=l; j--; )
    {
      v = a[j-i]
      if (v)
      {
        u %= l
        if (u==0) r.push(s=[])
        s[u++] = v
      }
    }
  return r
}

```

**Test**

```
F=
a=>eval("for(u=r=[],i=l=a.length;i+l;i--)for(j=l;j--;v&&((u%=l)||r.push(s=[]),s[u++]=v))v=a[j-i];r")

function update() {
  var a=I.value.match(/\d+/g)
  if (a) {
    var r=F(a)
    O.textContent = r.join`\n`
  }
}

update()
```

```
<input id=I value='1 2 3 4 5' oninput='update()'>
<pre id=O></pre>
```
> 3 votes

# Answer
# MATL, 17 bytes

```
!Gg*tRwZRhPXzGne!

```

Try it online!

### How it works

The following explanation uses input `[1 2 3 4 5]` as an example. To visualize the intermediate results, insert `%` (comment symbol) after any statement in the code.

Note that `;` is the row separator for matrices. So `[1 2]` is a row vector, `[1; 2]` is a column vector, and `[1 0; 0 1]` is the 2×2 identity matrix.

```
!     % Implicitly input a row vector. Transpose. Gives a column vector
      % STACK: [1; 2; 3; 4; 5]
Gg    % Push input with all (nonzero) values replaced by ones
      % STACK: [1; 2; 3; 4; 5], [1 1 1 1 1]
*     % Multiply, with broadcast. Gives a square matrix
      % STACK: [1 1 1 1 1;
                2 2 2 2 2;
                3 3 3 3 3;
                4 4 4 4 4;
                5 5 5 5 5]
tR    % Duplicate. Upper triangular part
      % STACK: [1 1 1 1 1;
                2 2 2 2 2;
                3 3 3 3 3;
                4 4 4 4 4;
                5 5 5 5 5],
               [1 1 1 1 1
                0 2 2 2 2;
                0 0 3 3 3;
                0 0 0 4 4;
                0 0 0 0 5]
wZR   % Swap. Lower triangular part, below main diagonal
      % STACK: [1 1 1 1 1;
                0 2 2 2 2;
                0 0 3 3 3;
                0 0 0 4 4;
                0 0 0 0 5],
               [0 0 0 0 0;
                2 0 0 0 0;
                3 3 0 0 0;
                4 4 4 0 0;
                5 5 5 5 0]
h     % Concatenate horizontally
      % STACK: [1 1 1 1 1 0 0 0 0 0;
                0 2 2 2 2 2 0 0 0 0;
                0 0 3 3 3 3 3 0 0 0;
                0 0 0 4 4 4 4 4 0 0;
                0 0 0 0 5 5 5 5 5 0]
P     % Flip vertically
      % STACK: [0 0 0 0 5 5 5 5 5 0;
                0 0 0 4 4 4 4 4 0 0;
                0 0 3 3 3 3 3 0 0 0;
                0 2 2 2 2 2 0 0 0 0;
                1 1 1 1 1 0 0 0 0 0]
Xz    % Column vector of nonzeros, taken in column-major order
      % STACK: [1;2;1;3;2;1;4;3;2;1;5;4;3;2;1;5;4;3;2;5;4;3;5;4;5]
Gne   % Reshape into a matrix with as many rows as input size
      % STACK: [1 1 5 5 4;
                2 4 4 4 3;
                1 3 3 3 5;
                3 2 2 2 4;
                2 1 1 5 5]
 !    % Transpose. Implicitly display
      % STACK: [1 2 1 3 2;
                1 4 3 2 1;
                5 4 3 2 1;
                5 4 3 2 5;
                4 3 5 4 5]

```
> 2 votes

# Answer
# , 14 bytes

```
#($$&;</.)@#,:

```

Attempt This Online!

* `#...#,:` Duplicate the input n times, where n is the input length. We require `,:` to make the duplication work at the "row level" rather than the element level.
* `</.` Box every diagonal of the resulting n by n matrix. J's `/.` does the heavy lifting here.
* `$$&;` Unbox that result `;` into a single list and reshape it `$` to the shape of duplicated input `$`.
> 2 votes

# Answer
# Uiua, 12 bytes

```
⊏⍜♭⍏⊞+.⊃⇡▽⧻.

```

Try it online!

```
⊏⍜♭⍏⊞+.⊃⇡▽⧻.   input: vector V of length N
               ⧻.    keep V and push N
           ⊃⇡▽     consume both and push [0..N-1], V cycled N times
       ⊞+.          self outer product of range by addition
 ⍜♭⍏              flatten, replace the array with its sorting order, and
                     put it back into the same sized matrix
⊏                   for each number in the matrix, select the item at that index
                    in "V cycled N times"

```

The above is a slightly golfuscated version of the code below:

# Uiua, 14 bytes

```
⍜∩♭'⊏⍏⊞+.⍏.↯⧻.

```

Try it online!

```
⍜∩♭'⊏⍏⊞+.⍏.↯⧻.    input: a vector of integers of length N
               ↯⧻.     make the input a matrix by copying the input N times -> X
             ⍏         rise; sorting order of the rows (same as range N)
         ⊞+.           self outer product by addition -> Y
⍜∩♭          .        operate on X and Y flattened and assemble back..
    '⊏⍏                reorder elements of X by sorted order of elements of Y

```
> 2 votes

# Answer
## JavaScript (ES6), 116 bytes

```
a=>a.map(_=>b.splice(0,a.length),b=[].concat(...a.map((_,i)=>a.slice(~i)),...a.map((_,i)=>a.slice(0,~i))).reverse())

```

Well, it's a start...
> 1 votes

# Answer
## R, 84 bytes

```
t(matrix(unlist(split(m<-t(matrix(rev(x<-scan()),l<-sum(1|x),l)),row(m)-col(m))),l))

```

Reads input from stdin and outputs/returns an R-matrix.

```
reversed_x <- rev(x<-scan())                # Read input from stdin and reverse
m <- t(matrix(reversed_x,l<-sum(1|x),l))    # Repeat and fit into matrix
diag_list <- split(m,row(m)-col(m))         # Split into ragged list of diagonals
t(matrix(unlist(diag_list),l))              # Flatten and transform back to matrix

```

**Explained**

The most interesting aspect about this answer is how the diagonals are retrieved. In general an object can be split up using the `split` function if supplied an object containing factors upon which the object is split into. To create these factors we can use `col` and `row` which return a matrix containing the column and row indices respectively. By taking the differences: `row(m)-col(m)` we get a matrix like:

```
     [,1] [,2] [,3] [,4] [,5]
[1,]    0   -1   -2   -3   -4
[2,]    1    0   -1   -2   -3
[3,]    2    1    0   -1   -2
[4,]    3    2    1    0   -1
[5,]    4    3    2    1    0

```

in which each diagonal is uniquely identified. We can now split based on this matrix and turn it into a ragged list by applying `split`:

```
$`-4`
[1] 1
$`-3`
[1] 2 1
$`-2`
[1] 3 2 1
$`-1`
[1] 4 3 2 1
$`0`
[1] 5 4 3 2 1
$`1`
[1] 5 4 3 2
$`2`
[1] 5 4 3
$`3`
[1] 5 4
$`4`
[1] 5

```

(Note how the name of each vector correspond to the diagonal values in the matrix above).

The last step is just to flatten and turn it into a matrix of the form:

```
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    1    3    2
[2,]    1    4    3    2    1
[3,]    5    4    3    2    1
[4,]    5    4    3    2    5
[5,]    4    3    5    4    5

```
> 1 votes

# Answer
# Ruby, 110 bytes

```
n=a.size
b=[*(0...n)]
b.product(b).group_by{|i,j|i+j}.flat_map{|_,f|f.sort.map{|i,j|a[i][j]}}.each_slice(n).to_a

```

```
      #=> [[1, 2, 1, 3, 2],
      #    [1, 4, 3, 2, 1],
      #    [5, 4, 3, 2, 1],
      #    [5, 4, 3, 2, 5],
      #    [4, 3, 5, 4, 5]]

```

The `sort` operation may not be required, but the doc for Enumerable#group\_by does not guarantee the ordering of values in the hash values (which are arrays), but current versions of Ruby provide the ordering one would expect and the ordering I would need if `sort` were removed from my code.

The steps are as follows.

```
n=a.size
  #=> 5
b=[*(0...n)]
  #=> [0, 1, 2, 3, 4]
c = b.product(b)
  #=> [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3],
  #    [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2],
  #    [3, 3], [3, 4], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
d=c.group_by{|i,j|i+j}
  #=> {0=>[[0, 0]],
  #    1=>[[0, 1], [1, 0]],
  #    2=>[[0, 2], [1, 1], [2, 0]],
  #    3=>[[0, 3], [1, 2], [2, 1], [3, 0]],
  #    4=>[[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]],
  #    5=>[[1, 4], [2, 3], [3, 2], [4, 1]],
  #    6=>[[2, 4], [3, 3], [4, 2]],
  #    7=>[[3, 4], [4, 3]],
  #    8=>[[4, 4]]}
e=d.flat_map{|_,f|f.sort.map{|i,j|a[i][j]}}
  #=> [1, 2, 1, 3, 2, 1, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 5, 4, 3, 5, 4, 5]
f=e.each_slice(n)
  #=> #<Enumerator: [1, 2, 1, 3, 2, 1, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2,
  #                  5, 4, 3, 5, 4, 5]:each_slice(5)>

```

Lastly, `f.to_a` returns the array shown earlier.
> 1 votes

# Answer
# Vyxal, 55 bitsv2, 6.875 bytes

```
LẋÞ`f?Lẇ

```

Try it Online!

Bitstring:

```
0110000101111000101000101100100011000011001101100100000

```

```
LẋÞ`f?Lẇ
# implicit input
Lẋ        # repeated [length] times
  Þ`      # antidiagonals
    f?Lẇ  # flatten and wrap in chunks the size of the length

```

Created with the help of Luminespire.
> 1 votes

# Answer
# K (ngn/k), 22 bytes

```
{x@l!s#,/=+/!s:2#l:#x}

```

Try it online!
> 1 votes

# Answer
# Ruby, 72 bytes

```
->a,*r{t=[]
a.map{r+=t=[_1]+t}
r+=t while t.pop
[*r.each_slice(a.size)]}

```

Attempt This Online!
> 1 votes

# Answer
# Scala, 154 bytes

Golfed version. Try it online!

```
a=>{val n=a.size;var L,M=List[Int]();for(i<-0 to n-1){L=L:::a.slice(0,i+1).reverse.toList;M=M:::a.slice(i+1,n).reverse.toList};(L::: M).grouped(n).toList}

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val a = Array(1, 2, 3, 4, 5)
    val n = a.length
    var L, M = List.empty[Int]

    for (i <- 0 until n) {
      L = L ::: a.slice(0, i+1).reverse.toList
      M = M ::: a.slice(i+1, n).reverse.toList
    }

    val zipped = (L ::: M).grouped(n).toList

    println(zipped)
  }
}

```
> 1 votes

# Answer
# Uiua (0.1.0), 20 bytes

```
↯~√⧻./⊐⊂≐(□↘)-⇡×2.⧻.

```

Try it online

## Explanation

```
                  ⧻. # (nondestructively) get array length
             -⇡×2.   # construct a range from len down to -len + 1
        ≐(□↘)        # for each element of the range, drop that many from the array
     /⊐⊂             # join all resulting arrays together
  √⧻.                # get square root of length, suppose we call it N...
↯~                   # ...then this reshapes the array to MxN, where M is inferred

```
> 1 votes

# Answer
## Mathematica 93 Bytes

```
Partition[Flatten[Table[If[i>n,#[[n;;(i-n+1);;-1]],#[[i;;1;;-1]]],{i,1,2(n=Length@#)-1}]],n]&

```

Here's how I'd ordinarily write this code (109 Bytes):

```
Partition[Reverse@Flatten[Table[Reverse@Diagonal[ConstantArray[Reverse@#,n],k],{k,-(n=Length@#)+1,n-1}]],n]&

```

This matrix plot gives a good idea from the structure due to a sequentially increasing input vector.

Here's the matrix plot with a random input vector. Obviously some structure still exists.
> 0 votes

# Answer
# Mathematica, 92 bytes

```
n=NestList[#2,(r=Reverse)@#,(l=Length@#)-1]&;{Most@r[#~n~Rest],#~n~Most}~ArrayReshape~{l,l}&

```

Unnamed function taking a list as its argument. There might be other structures to such a function, but hopefully I golfed this structure pretty good....

The first part `n=NestList[#2,(r=Reverse)@#,(l=Length@#)-1]&` defines a function `n` of two arguments: the first is a list of length `l`, and the second is a function to apply to lists. `n` applies that function `l-1` times to the reversed argument list, saving all the results in its output list. (Defining `r` and `l` along the way is just golfing.)

`n` is called twice on the original list, once with the function being `Rest` (drop the first element of the list) and once with the function being `Most` (drop the last element). This produces all the desired sublists, but the whole list is there twice (hence the extra `Most`) and the first half is there in backwards order (hence the `r[...]`). Finally, `~ArrayReshape~{l,l}` forgets the current list structure and forces it to be an `l`x`l` array.
> 0 votes

# Answer
**Mathematica, 85 bytes**

Literally performing the steps suggested:

```
(l=Length@#;Partition[Flatten@Table[Reverse@Diagonal[Table[#,l],i],{i,-l+1,l-1}],l])&

```

My gut says that there should be a clever way to use `Part` to do this shorter, but every attempt I've made has been longer than 85 bytes.
> 0 votes

# Answer
# Husk, ~~9~~ 8 bytes

```
CL¹Σ∂RL¹

```

Try it online!

-1 byte from Zgarb.

## Explanation

```
CL¹Σ∂*L¹;
       ¹  input(appends a ¹ to the end)
        ; enclosed
     *L   repeated length times
    ∂     antidiagonals
   Σ      flattened into a single list
C         cut into pieces of size
 L¹       of the length of the input

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 60 bytes

```
Partition[Join@@Reverse[#~Drop~i]~Sum~{i,l=-Tr[1^#],-l},-l]&

```

Try it online!
> 0 votes

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


title: Add an array with itself

text:
# Question
Title: Add an array with itself
Your challenge today is to take an array, split it into chunks, and add those chunks.

Here's how this works: Your program or function will be given an array of integers `a` and a chunk size `L`. The array should be split into arrays of size `L`, if the array length is not divisible by `L` then the array should have 0's appended to it so that it is evenly divisible. Once the array is chunked, all chunks are to be added together element-wise. The resulting array is then output.

You can assume `L` is greater than 0, and that `a` is nonempty. You cannot make the assumption that `a`'s contents are positive.

Here's an example:

```
[1,2,3,4,5,6,7,8], 3 => [1,2,3]+[4,5,6]+[7,8,0] =>  [1+4+7,2+5+8,3+6+0] => [12,15,9]

```

Test cases:

```
Array                           Length   Output
[1]                             1        [1]
[1]                             3        [1,0,0]
[0]                             3        [0,0,0]
[1,2]                           3        [1,2,0]
[1,2]                           1        [3]
[-1,1]                          2        [-1,1]
[-7,4,-12,1,5,-3,12,0,14,-2]    4        [12,-1,0,1]
[1,2,3,4,5,6,7,8,9]             3        [12,15,18]

```

This is , fewest bytes wins!

# Answer
# MATL, 4 bytes

```
e!Xs

```

Try it online!

First bit of MATL code I've written! Takes two inputs, `a` as a row vector (comma-separated) and `l` as a number. Works out to be

```
e          # reshape `a` into `l` rows (auto pads with 0)
 !         # transpose
  Xs       # sum down the columns

```
> 11 votes

# Answer
# Python 3, 67 65 42 bytes

Uses the fact that the sum of an empty array is 0

```
lambda x,y:[sum(x[i::y])for i in range(y)]

```

Try it online!
> 13 votes

# Answer
# Jelly, ~~7~~ 6 bytes

1 byte thanks to Dennis.

```
;0$¡sS

```

Try it online!
> 7 votes

# Answer
# Mathematica, 27 bytes

~~*Mathematica almost had a builtin for this*~~

```
Total@Partition[##,#2,1,0]&

```

Try it on Wolfram Sandbox

### Usage

```
Total@Partition[##,#2,1,0]&[{-7, 4, -12, 1, 5, -3, 12, 0, 14, -2}, 4]

```

> `{12, -1, 0, 1}`

### Explanation

```
Total@Partition[##,#2,1,0]&

      Partition[##,#2,1,0]   (* Partition the first input into sublists of length
                                second input, using offset second input, and
                                right-pad zeroes for incomplete partitions *)
Total@                       (* Add all *)

```
> 6 votes

# Answer
# Python 2, 49 bytes

```
lambda x,n:map(sum,zip(*zip(*[iter(x+n*[0])]*n)))

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), 51 bytes

```
a=>n=>a.map((v,i)=>o[i%n]+=v,o=Array(n).fill(0))&&o

```

Takes input in currying syntax: `f([1,2])(3)`.

## Test Cases

```
let f=
a=>n=>a.map((v,i)=>o[i%n]+=v,o=Array(n).fill(0))&&o

;[[[1], 1], [[1], 3], [[0], 3], [[1,2], 3], [[1,2], 1], [[-1,1], 2], [[-7,4,-12,1,5,-3,12,0,14,-2], 4], [[1,2,3,4,5,6,7,8,9], 3]]
.forEach(([A,N])=>console.log(`${JSON.stringify(A)}, ${N} -> ${f(A)(N)}`))
```

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

# Answer
# Mathematica, 58 bytes

```
Total@Partition[PadRight[#,(s=Length@#)+Mod[-s,#2]],{#2}]&

```

**Input**

> \[{1},3\]

**Output**

> {1,0,0}
> 4 votes

# Answer
## Java 7, 86 bytes

No fancy folds or matrices, just a good ol' fashioned `for` loop :)

```
int[]o(int[]a,int l){int i=0,o[]=new int[l];for(;i<a.length;)o[i%l]+=a[i++];return o;}

```

Try it on Ideone

Lined:

```
int[]o(int[]a,int l){
    int i=0,
        o[]=new int[l];
    for(;i<a.length;)
        o[i%l]+=a[i++];
    return o;
}

```
> 4 votes

# Answer
# Husk, 9 bytes

```
S↑ȯ¡¬Fż+C

```

Try it online!

### Explanation

```
        C    Cut into lists of length n
     Fż+     Sum them element-wise
  ȯ¡¬        Append infinitely many 0s
S↑           Take the first n elements

```
> 4 votes

# Answer
# Perl 6, 36 bytes

```
{[Z+] flat(@^a,0 xx$^b*2).rotor($b)}

```

Test it

## Expanded:

```
{  # bare block lambda with 2 placeholder parameters ｢@a｣, ｢$b｣
  [Z+]
    flat(
      @^a,         # declare and use the first parameter
      0 xx $^b * 2 # 0 list repeated 2 * the second parameter
    )
    .rotor($b)     # split into chunks that are the size of the second param
}

```

```
[1,2], 3

( [1,2], (0,0,0,0,0,0) ) # @^a,0 xx$^b*2
(1,2,0,0,0,0,0,0)        # flat(…)
( (1,2,0), (0,0,0) )     # .rotor($b) # (drops partial lists)
(1,2,0)                  # [Z+]

```
> 4 votes

# Answer
# BQN, 8 bytesSBCS

```
+˝↑˙⊸⋈⊸⥊

```

Run online!

`{+˝↑‿⥊}` is 1 longer. BQN's reshape is very good.
> 4 votes

# Answer
# , ~~62~~ 57 bytes

*-5 bytes thanks to user2390246*

```
function(a,l)rowSums(matrix(c(a,rep(0,l-sum(a|1)%%l)),l))

```

Try it online!

Updated since it no longer has to handle the empty case.

pads `a` with zeros, constructs a matrix of `l` rows, and computes and returns the row sums.
> 3 votes

# Answer
# Pyth, 8 bytes

```
m+F%Q>vz

```

**Try it here!**

# Pyth, 10 bytes

```
sMCc.[EZQQ

```

**Try it here!**

# Explanation

### Explanation #1

```
m+F%Q>vz   Full program. Q means input.

m          Map over the implicit range [0, input_1), with a variable d.
     >vz  All the elements of input_2 after d; input_2[d:] in Python.
   %Q     Every Qth element of ^.
 +F       Sum. Implicitly output the result.

```

### Explanation #2

```
sMCc.[EZQQ   Full program.

    .[E      Pad the second input to the right, with repeated copies of...
       Z     ... Zero (0), up to the nearest multiple of...
        Q    ... The first input.
   c     Q   Chop into chunks of length equal to the first input.
  C          Matrix transpose. Get all the columns of the nested list.
sM           Sum each.
             Output (implicitly).

```
> 3 votes

# Answer
# Haskell, ~~59~~ 49 bytes

```
a%l=[sum$map((0:a)!!)[i,l+i..length a]|i<-[1..l]]

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog), 22 bytes

Takes `l` as left argument and `a` a right argument.

```
{+⌿s⍴⍵↑⍨×/s←⍺,⍨⌈⍺÷⍨≢⍵}

```

Try it online!

`{``}` anonymous function where  is the left argument (`l`) and  the right argument (`a`).

`≢⍵` tally (length) of `a`

`⍺÷⍨` divide by `l`

ceiling (round up)

`⍺,⍨` append `l`

`s←` store in `s` (for **s**hape)

`×/` product of that (i.e. how many integers are needed)

`⍵↑⍨` take that many integers from `a` (padding with zeros)

`s⍴`**r**eshape to shape `s` (rows, columns)

`+⌿` columnar sums
> 3 votes

# Answer
# Perl 6, 40 bytes

```
{[Z+] (|@^a,|(0 xx*)).rotor($^l)[0..@a]}

```

Try it online!

If you like the number 42, you can swap the `*` for an . That will make it 42 bytes :—).

**Explanation**:

```
{[Z+] (|@^a,|(0 xx*)).rotor($^l)[0..@a]} The whole function
{                                      } Anonymous block
      (    ,        )                    List with 2 elements
        @^a                              The first argument (it is a list)
             (0 xx*)                     Infinite list of zeroes
       |    |                            Flatten both of the lists into the larger list.
                    .rotor($^l)          Split the list into a list of lists, each (the second argument) long.
                               [0..@a]   Only the first (1 + length of the first argument) of them.
 [Z+]                                    Add the corresponding elements up.

```

The magic behind the last "add up" is that the operator is a "reduce with zip with +". By the way, this would break down if we used it only on a list with 1 list inside, but that never happens if the original list was non-empty (due to the second-to-last row). Also note that we end up taking not only `@a`, but `@a * $l` items. Fortunately we added only zeroes which won't affect the final result.
> 3 votes

# Answer
# , ~~15~~ 12 bytes

```
]{.+/@(]\~-)

```

Try it online!

## Explanation

```
]{.+/@(]\~-)  Input: array A (LHS), chunk size L (RHS)
          -   Negate L
       ]\~    Take each non-overlapping sublist of size L in A
   +/@        Reduce the columns by addition
]             Get L
 {.           Take that many, filling with 0's

```
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
ô0ζO²Å0+

```

Try it online!

```
ô0ζO²Å0+   Full program
ô          Push <1st input> split into a list of <2nd input> pieces
 0ζ        Zip sublists with 0 as a filler
   O       Sum each sublist
           --- from here, the program handles outputs shorter
               than the required length
    ²Å0    Push a list of zeros of length <2nd input>
       +   Sum the result with that list

```
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
Å0+¹ô0ζO

```

Try it online!

```
Å0       # Push an arrary of all 0s with length l
  +      # Add that to the array
   ¹ô    # Split into chunks of length l
     0ζ  # Zip, padding with 0s
       O # Sum each chunk

```
> 3 votes

# Answer
# Vyxal, 7 bytes

```
ẇR∆ZR∩Ṡ

```

Try it Online!
> 3 votes

# Answer
# SOGL V0.12, 14 bytes

```
l⁵%⁵κ{0+}nI⌡∑¹

```

Try it Here! or Try all the test-cases. this is written as an unnamed function and expects `chunk length; array` on the stack.

Explanation:

```
padding zeroes
l          get the array's length
 ⁵%        modulo the chunk length
   ⁵κ      chunk length - result of above
     {  }  that many times
      0+     append a 0 to the array

adding the array together
n      split into the chunks
 I     rotate clockwise
  ⌡    for each
   ∑     sum
    ¹  wrap the results in an array

```
> 2 votes

# Answer
# 05AB1E, 12 bytes

```
gs÷*+Å0¹+ôøO

```

Try it online!

### Explanation

```
gs÷*+Å0¹+ôøO
g            # Get the length of the first input (the array)
 s           # Push the second input on top of the result
  ÷          # integer divide the two values
   *         # Multiply with the second input (the length)...
    +        # and add the second input to the result
     Å0      # Create a list of zeros with that length
       ¹+    # Add it to the first input
         ô   # And finally split it into chunks of the input length...
          ø  # ...transpose it...
           O # and sum each resulting subarray
             # Implicit print

```
> 2 votes

# Answer
## Mathematica, 43 bytes

```
Plus@@#~ArrayReshape~{⌈Tr[1^#]/#2⌉,#2}&

```
> 2 votes

# Answer
# Husk, 10 bytes

```
Fż+So:`R0C

```

Try it online!

### Ungolfed/Explanation

```
             -- implicit inputs n & xs                   | 3  [1,2,3,4]
   S      C  -- cut xs into sublists of length n & ...   | [[1,2,3], [4]]
    (:`R0)   -- ... prepend [0,...,0] (length n)         | [[0,0,0], [1,2,3], [4]]
F            -- accumulate the sublists with             |
 ż+          -- element-wise addition                    | [0+1+4, 0+2, 0+3]

```
> 2 votes

# Answer
# Clojure, 42 bytes

```
#(apply map +(partition %2 %2(repeat 0)%))

```

Try it online!
> 2 votes

# Answer
# Jq 1.5, 31 bytes

```
[_nwise($n)]|transpose|map(add)

```

Sample Run

```
$ jq -Mc --argjson n 3 '[_nwise($n)]|transpose|map(add)' <<< "[1,2,3,4,5,6,7,8]"
[12,15,9]

```

Takes advantage of builtins: \_nwise, transpose, add and map
> 2 votes

# Answer
# Japt, 7 bytes

Man, I fought with the wrong Japt method for far too long trying to get it to work for the `[1], 3` test case in a reasonable amount of bytes!

```
VÆëVX x

```

Try it

---

## Explanation

Implicit input of array `U` and integer `V`.

Generate an array of integers from `0` to `V-1` and pass each through a function with `X` being the current element.

```
ëVX

```

Grab every `V`th element of `U`, beginning at index `X`.

```
x

```

Reduce that array by addition.
> 2 votes

# Answer
# Stacked, 24 bytes

```
[:@z#<[0 z rpad]map sum]

```

Try it online!

## Explanation

```
[:@z#<[0 z rpad]map sum]
[                      ]   anonymous function
 :@z                       stores TOS as `z` (the length)
    #<                     cut STOS in TOS slices
      [        ]map        for each slice
       0 z rpad               pad the slice with `z` zeroes
                    sum]   summate all inner slices

```
> 2 votes

# Answer
# Java (OpenJDK 8), 64 bytes

```
n->a->{int k=0,r[]=new int[n];for(int i:a)r[k++%n]+=i;return r;}

```

Try it online!
> 2 votes

# Answer
# C, (GCC) 101 86 Bytes

Try it online!

```
f(int*a,int l,int s,int*m){if(s){int i=l;while(i&&s){m[l-i--]+=*a++;s--;}f(a,l,s,m);}}

```

## Usage

```
int main() {
   int l = 3;
   int a[8] = {1,2,3,4,5,6,7,8};
   int *m = (int *)malloc(sizeof(int) * l);
   f(a, l, 8, m);
   for (int i=0; i<3; i++) {
    printf("%d, ",m[i]);
   }
}

```

Note that you have to pass in the length of the array (s) and a new dynamic array on the heap (m).
> 2 votes

# Answer
# Ruby, 43 bytes

```
->a,n{b=[w=0]*n;a.map{|r|b[w%n]+=r;w+=1};b}

```

I wanted to outgolf at least python, but I couldn't, so here is the best I could do.

### How it works:

* create an array of size n filled with zeroes
* iterate on the input array, and calculate sums, repeat wrapping around the output array

Try it online!
> 2 votes

# Answer
# Julia 0.6, 49 bytes

```
V\n=sum(reshape([V;zeros(n-endof(V)%n,1)],n,:),2)

```

Try it online!
> 2 votes

# Answer
# PowerShell, 62 bytes

```
param($a,$l)1..$l|%{$y=--$_;($o=0)..$l|%{$o+=$a[$y+$_*$l]};$o}

```

Try it online!

We take input `$a`rray and `$l`ength. Then loop from `1` to `$l`. Each iteration we set helper `$y` to be one less than the current number (this is because PowerShell 0-indexes but the `$l`ength is in 1-indexing). Then we set our `$o`utput to `0` and loop again up to `$l`. Each inner iteration we're simply accumulating into `$o` the appropriately-indexed `$a`rray element. This leverages the fact that indexing past the end of the array returns `$null` and `0 + $null = 0`.

Once the inner loop is done, we output `$o` and move on to the next chunk. The various outputs are left on the pipeline and output via implicit `Write-Output` happens on program completion.
> 1 votes

# Answer
# Perl 5, 44 + 1 (-a) = 45 bytes

```
@r=(0)x($l=<>);map$r[$i++%$l]+=$_,@F;say"@r"

```

Try it online!

*Edit: fixed the case where the length requested was smaller than the input array*
> 1 votes

# Answer
# **Scala 2.12.2**, 80 bytes

```
(a:Array[Int],b:Int)=>(0 to b-1).map(i=>a.indices.filter(_%b==i).collect(a).sum)

```

It is slightly shorter than the Java solution.
> 1 votes

# Answer
# Javascript, ~~59~~ ~~57~~ 56 bytes

```
f=(a,l)=>(r=Array(l).fill(0),a.forEach((c,i)=>r[i%l]+=c),r)

```

## usage

```
f([1,2,3,4,5,6,7,8], 3);
// returns [12, 15, 9]

```

## edit 1

According to @Shaggy in the comments, the `f=` part is not needed if the function is not recursive. So:

```
(a,l)=>(r=Array(l).fill(0),a.forEach((c,i)=>r[i%l]+=c),r)

```

with usage off course of:

```
((a,l)=>(r=Array(l).fill(0),a.forEach((c,i)=>r[i%l]+=c),r))([1,2,3,4,5,6,7,8], 3)
// returns [12, 15, 9]

```

## edit 2

Golfing down 1 more character, as the extra parenthesis are no longer needed then.

```
(a,l,r=Array(l).fill(0))=>a.forEach((c,i)=>r[i%l]+=c)||r

```

with usage off course of:

```
((a,l,r=Array(l).fill(0))=>a.forEach((c,i)=>r[i%l]+=c)||r)([1,2,3,4,5,6,7,8], 3)
// returns [12, 15, 9]

```
> 1 votes

# Answer
# Pari/GP, 33 bytes

```
a->l->Vecrev(Polrev(a)%(x^l-1),l)

```

Converts `a` to a polynomial, mod `x^l-1`, and then converts it back to a list.

Try it online!
> 1 votes

# Answer
# Common Lisp, 90 bytes

```
(lambda(a l)(dotimes(i(-(length a)l)(subseq a 0 l))(incf(elt a(mod i l))(elt a (+ l i)))))

```

Try it online!
> 1 votes

# Answer
# POSIX shell, 45 bytes

This requires the utilities `jot` and `rs` to be installed, as well as the more common `sed` and `bc`. The chunk size is passed as the first argument, and the array as space-separated values on standard input

```
(jot -b0 $1;cat)|rs -tjg1 -C+ $1|sed s/.//|bc

```

The `jot` command generates a row full of zeros (in case the chunk size is smaller than the input); `cat` appends the input, then `rs` transforms that into the specified number of rows. Each line now begins with `+`, and `bc` won't accept that, so remove it with `sed` before performing the summation of each line.
> 1 votes

# Answer
# Scala, 75 bytes

```
a=>n=>(a++Seq.fill(n-a.size/n)(0)).grouped(n).toSeq.transpose.map(_.sum)

```

To use this, you have to add a type:

```
val f:(Seq[Int]=>Int=>Seq[Int])=
    a=>n=>(a++Seq.fill(n-a.size/n)(0)).grouped(n).toSeq.transpose.map(_.sum)

f(Seq(1,2,3,4,5,6,7,8))(3)

```
> 1 votes

# Answer
# Add++, 25 bytes

```
D,f,@@*,d0b]*$@$+TbUpBcBs

```

Try it online!

## How it works

First, we define our function \\$f(a, x)\\$. It takes two arguments (`@@`) and returns the entire stack (`*`), rather than the top element. Here, \\$a\\$ denotes the array of elements, such as \\$a := \[0, 1, 2, 3, 4, 5, 6, 7, 8, 9\]\\$, and \\$x\\$ represents slice length, \\$x := 4\\$ for example. The stack is \\$\[a, x\]\\$ at the start of execution. We then duplicate \\$x\\$, and repeat \\$\[0\]\\$ \\$x\\$ times. We call this array \\$z\\$, rearrange the stack so it looks like \\$\[x, a, z\]\\$ and concatenate \\$a\\$ with \\$z\\$. This appends \\$x\\$ zeroes to the end of \\$a\\$.

Next, we take slices of length \\$x\\$ from \\$a ^ \frown z\\$. For the example inputs above, this would yield \\$\[\[0, 1, 2, 3\], \[4, 5, 6, 7\], \[8, 9, 0, 0\], \[0, 0\]\]\\$. For every possible inputs, this yields an array where the final element always contains only superfluous zeroes, so we splat the elements of the array to the stack and remove the last element. Finally, we zip the arrays together and take the sum of each.
> 1 votes

# Answer
# Factor \+ `grouping.extras math.unicode`, 47 bytes

```
[ [ 0 pad-groups ] keep group flip [ Σ ] map ]

```
> 1 votes

# Answer
# , 54 bytes

```
function(a,l,m=matrix(a,l))rowSums(m*(seq(m)<=seq(a)))

```

Try it online!

Somewhat based on Giuseppe's answer, but uses a different trick to counteract 's recycling the first elements of `a` to fill the last chunk.
> 1 votes

# Answer
# Burlesque, 21 bytes

```
J0bcj.+2MVj_+jcotp)++

```

Try it online!

```
J    # Dup L
0bc  # Infinite list of zeros
j.+  # Select L 0s
2MV  # Put list at top of stack
j_+  # Append zeros
jco  # Split into chunks of length L
tp   # Transpose
)++  # Map sum

```
> 1 votes

# Answer
# C(GCC), 44 bytes

```
m(a,L,l,o)int*a,*o;{for(;l--;)o[l%L]+=a[l];}

```

Try it online It doesn't get more stupid than this :) In the tio version, i added a few macros, but they only help me do the tests in main more easily, and aren't used in the actual function. It modifies a given array instead of directly outputting one, because that's a real pain to do in c. It expects a zeroed array in o.
> 1 votes

# Answer
# Desmos, ~~106~~ 71 bytes

```
l=[1...s]
f(a,s)=[∑_{q=1}^{ceil(a.length/s)}join(a,l0)[qs-s+t]fort=l]

```

*-35 bytes thanks to Aiden Chow*

Try it on Desmos!
> 1 votes

# Answer
# Thunno 2, 4 bytes

```
ẇ0Ƭʂ

```

Try it online!

#### Explanation

```
ẇ0Ƭʂ  # Implicit input - A (array), N (integer)
ẇ     # Split (A) into chunks of length (N)
 0Ƭ   # Transpose the list with filler 0
   ʂ  # Sum each inner list
      # Implicit output

```
> 1 votes

# Answer
# Uiua, 6 bytes

```
/+⬚0↯~

```

Try it!

```
/+⬚0↯~
    ↯~  # reshape into matrix with number of columns indicated by input
  ⬚0    # filling excess elements with zeros
/+      # sum columns

```
> 0 votes

# Answer
# Julia 0.6, 28 bytes

```
V\n=1:n.|>i->sum(V[i:n:end])

```

Try it online!

also works in Julia 1.0+
> 0 votes

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