title: Output a Latin Square

text:
# Question
Title: Output a Latin Square
An \\$n\times n\\$ Latin Square is a grid containing exactly \\$n\\$ distinct values where the values in each row and column are distinct. For example,

$$\begin{matrix} A & B & C \\ C & A & B \\ B & C & A \\ \end{matrix}$$

is a Latin square as no row or column contains a repeated value.

You are to take a positive integer \\$n\\$ as input and output an \\$n\times n\\$ Latin Square. The values can be any \\$n\\$ distinct values, and do not have to be consistent for different \\$n\\$. Your program should be consistent and deterministic, so running it with the same input should always produce the same output.

You may output in any reasonable manner, including a flat array consisting of \\$n^2\\$ values, or as a list of \\$n\\$ lists, each containing \\$n\\$ values. You may input and output in any convenient method

This is , so the shortest code in bytes wins.

## Test cases

These are just some possible outputs, your program may differ so long as the output is correct

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

```

# Answer
> 18 votes
# Python 2, 37 bytes

Outputs a flattened \\$ n \times n \\$ latin square.

```
lambda n:((range(n)*-~n)[1:]*n)[::~n]

```

Try it online!

# Answer
> 12 votes
# Jelly, 3 bytes

```
RṙⱮ

```

Try it online!

## Explanation

```
RṙⱮ  Monadic link, takes an argument z
R    [1, 2, ..., z-1, z]
  Ɱ  For each on right argument (z, defaults to loop over range)
 ṙ   Rotate the left list by the right amount

```

Alternative solution: `+þ%`. Generates the \\$n\times n\\$ addition table and then applies modulo to bring the elements into range.

# Answer
> 11 votes
# , 30 bytes

```
n=scan();outer(1:n,1:n,`+`)%%n

```

Try it online!

# Answer
> 10 votes
# APL (dzaima/APL), 4 bytes

```
⌽ᐵ⍨⍳

```

```
⌽ rotate
ᐵ each left, apply each left element to the entire right argument
⍨ apply to both arguments
⍳ range

```

Try it online!

# Answer
> 10 votes
# APL (Dyalog Unicode), 6 bytes

```
⍳⌽,⍨⍴⍳

```

Try it online!

There's already a nice 4-byter in dzaima/APL by rak1507, but I wanted to share a non-trivial short one in vanilla Dyalog. It is shorter than a modulo addition table `⊢|⍳∘.+⍳` and ties with the trivial port of rak's `⍳⌽¨∘⊂⍳`.

Takes n and creates a flat matrix of numbers.

```
⍳⌽,⍨⍴⍳   ⍝ Input: n
  ,⍨     ⍝ [n, n]
    ⍴⍳   ⍝ Reshape [1..n] into an n×n matrix
         ⍝ For n = 4, this looks like this:
         ⍝ 1 2 3 4
         ⍝ 1 2 3 4
         ⍝ 1 2 3 4
         ⍝ 1 2 3 4
⍳⌽       ⍝ Rotate first row once, second row twice, ..., n-th row n times
         ⍝ 2 3 4 1
         ⍝ 3 4 1 2
         ⍝ 4 1 2 3
         ⍝ 1 2 3 4

```

# Answer
> 7 votes
# Haskell, 32 bytes

```
f n=[[x..n]++[1..x-1]|x<-[1..n]]

```

Try it online!

A kind-of boring approach, just concatenates the ranges.

**34 bytes**

```
f n=[mod(k+div(-k)n)n|k<-[1..n*n]]

```

Try it online!

Outputs a flat list, zero-indexed, using the method from my Python answer. A slight adaptation is needing to make it work for `[1..n*n]` instead of `[0..n*n-1]`.

# Answer
> 6 votes
# , 7 bytes

```
|i.+/i.

```

Try it online!

Creates an "addition table" of the range 0..n with itself `i.+/i.` and then takes the mod of each element by n `|`.

# Answer
> 6 votes
# Julia 1.0, 19 bytes

```
!n=((N=1:n).+N').%n

```

Try it online!

# Answer
> 5 votes
# Wolfram Language (Mathematica), 23 bytes

```
+##&~Array~{#,#}~Mod~#&

```

or (as @Roman suggested)

```
Plus~Array~{#,#}~Mod~#&

```

Try it online!

-2 bytes thanks to @att

# Answer
> 5 votes
# Haskell, ~~37~~ 35 bytes

Saved 2 bytes thanks to @Delfad0r Would have saved 5 bytes thanks to @AZTECCO (see xnor's answer)

```
f n=[mod(x+o)n|x<-[1..n],o<-[1..n]]

```

Try it online!

# Answer
> 5 votes
# Python 2, 40 bytes

```
lambda n:[(k+k/n)%n for k in range(n*n)]

```

Try it online!

Since the challenge allows a flat list of `n*n` outputs, we make do mapping `k=0, 1, ... n*n-1` to the corresponding entry with `(k+k/n)%n`. We can get this by adding the row index `k/n` and column `k%n` and reducing modulo `n`, and removing the redundant inner `%n`. We could also do `k*-~n/n%n`.

# Answer
> 5 votes
# Retina, 22 bytes

```
.+
*
Y`\_`w
L$`.
$<'$`

```

Try it online! Explanation:

```
.+
*

```

Convert the input to unary.

```
Y`\_`w

```

Take the first `n` word characters (or use `p` for printable ASCII etc.)

```
L$`.
$<'$`

```

Create cycled rows. (`$<'` is the same as `$&$'`.)

# Answer
> 5 votes
# Octave, 21 bytes

```
@(n,x=1:n)mod(x+x',n)

```

Try it online!

The same thing as many other answers...

-2 bytes by Giuseppe

# Answer
> 5 votes
# Arturo, 33 bytes

```
$[n][map 0..(n*n)-1'x[(x+x/n)%n]]

```

Try it on the Arturo Playground! **Note: it seems that editing the code edits it for everyone, so don't do that.**

# Answer
> 5 votes
# Perl 5 `-a`, 34 bytes

```
$,=$";say$_.."@F",1..$_-1for 1..$_

```

Try it online!

# Answer
> 5 votes
# yuno (abandoned), 4 bytes

```
ップア＠％

```

## Explanation

```
ップ　　　　outer product table; for each (first) and for each (second)
　　ア　　　add
　　　＠　　swap top two
　　　　％　modulo

```

Can be written as `ppua@%`. Code is grouped as `[ップ][ア][＠][％]`. To prove this is actually 4 bytes, the bytecode is `'~\x00ðó'` (use the `b` flag to interpret code from bytecode).

# Answer
> 5 votes
# jq, 20 bytes

```
range(.*.)*(1+1/.)%.

```

Try it online!

output is flattened

(my first jq answer)

# Answer
> 4 votes
# JavaScript (ES6), 46 bytes

```
n=>[...Array(n)].map((_,i,a)=>a.map(_=>i++%n))

```

Try it online!

---

# JavaScript (ES6), 42 bytes

As pointed out by @tsh, returning a flatten array is shorter.

```
n=>[...Array(n*n)].map((_,i)=>(i/n+i)%n|0)

```

Try it online!

# Answer
> 4 votes
# Python 2, 43 bytes

```
lambda x,r=range:[r(i,x)+r(i)for i in r(x)]

```

Try it online!

# Answer
> 4 votes
# C (clang), ~~73~~ \\$\cdots\\$ ~~49~~ 46 bytes

Saved 3 bytes thanks to dingledooper!!!

```
a;f(n){for(a=n*n;a;)printf("%d ",--a*~n/n%n);}

```

Try it online!

Inputs \\$n\\$ and prints the Latin Square as a flat array consisting of \\$n^2\\$ values.

# Answer
> 4 votes
# Japt `-m`, 3 bytes

Output as a 2D array.

```
WéU

```

Try it

Or without the `-m` flag:

## Japt, 4 bytes

```
ÆZéX

```

Try it

# Answer
> 4 votes
# MATL, 3 bytes

```
5YL

```

Try it online!

```
          %implicit input n
5YL       % create circular matrix of size n

```

Equivalent to the following Octave/MATLAB code

# Octave, 23 bytes

```
@(n)gallery('circul',n)

```

Try it online!

Alternately, this is equivalent to tsh's Octave answer.

# MATL, 5 bytes

```
:&+G\

```

Try it online!

```
	% implicit input n
:	% range 1:n
&+	% add to itself transposed, with broadcast
G\	% push n and modulo n
	% implicit output

```

# Answer
> 3 votes
# Scala, 44 bytes

```
n=>1 to n flatMap(_=>1 to n)sliding n take n

```

Try it in Scastie!

This is so simple it hardly needs an explanation, but here's one anyway:

```
n =>                     //The input
1 to n                   //Make a range of n numbers
  flatMap(_ => 1 to n)   //Map each to the range [1, n] and flatten
                         //This creates a list of n*n numbers
  sliding n              //Take n-sized chunks and move ahead by one each time
  take n                 //Keep the first n chunks

```

# Answer
> 3 votes
# 05AB1E, 4 bytes

```
LD._

```

Try it online!

```
LD._  # full program
  ._  # push...
L     # [1, 2, 3, ...,
      # ..., implicit input...
L     # ]...
  ._  # rotated to the left...
      # (implicit) each element in...
LD    # [1, 2, 3, ...,
      # ..., implicit input...
LD    # ]
      # implicit output

```

# Answer
> 3 votes
# Japt, 7 bytes

```
o £o éX

```

Try it

```
o   - [0..U)
£   - map by:
o éX    > rotate X times [0..U)

```

# Answer
> 3 votes
# PowerShell, 61 bytes

```
param($n)(0..($n*$n-1)|%{[math]::floor($_+$_/$n)%$n})-join" "

```

Try it online!

# Answer
> 3 votes
# V (vim), ~~38~~ 30 bytes

```
"aD@aO0<ESC>V{g<C-A>V}JqqYpdw$pq@a@qdk

```

Try it online!

Input as a single number.

Range creating script taken from Leo's Range, Reverse, Sum answer.

-8 bytes from Leo using `J`.

Fixed the problem with multidigit numbers.

## Explanation

```
"aD@aO0<ESC>V{g<C-A>V}J
"aD                          delete first line and store in register a
   @aO0<ESC>                 print 0 on a newline a times
            V{g<C-A>         convert the zeroes to a range
                    V}J      select all, join with spaces

$xqqYp2x$pq@a@qdk
$x                           remove the last space
  qq                         start macro q:
    Yp                        duplicate current line
      dw                      remove first word (number + space)
        $p                    paste at the end
          q                  end macro
           @a@q              replay macro a times
               dk            delete last two extra iterations

```

# Answer
> 3 votes
# Ruby, 33 bytes

```
->n{(0..n*n-1).map{|x|(x+x/n)%n}}

```

Try it online!

A lambda proc returning a flat array of n\*n elements.

# Answer
> 3 votes
# Java (JDK), 56 bytes

```
n->{for(int i=n*n;i-->0;)System.out.println((i/n+i)%n);}

```

Try it online!

# Answer
> 3 votes
# Python 2, 79 bytes

```
n=input()
f=lambda b:f(b+b[-1:]+b[-n:-1])if len(b)<n*n else b
print f(range(n))

```

Try it online!

# Answer
> 3 votes
# Vyxal `r`, 4 bytes

```
ƛ⁰ɾǔ

```

Try it Online!

```
ƛ      for each in [1, ..., N]
 ⁰     push N
  ɾ    pop N, push [1, ..., N]
   ǔ   rotate

```

-1 byte thanks to Aaron Miller

# Answer
> 3 votes
# yuno (abandoned), 2 bytes

```
メリョ

```

(Disclaimer - rotate was implemented after this challenge, and I'm not sure about map. However, neither of these nor the way empty-stack is treated were designed with this challenge in mind, it just turns out that the way I want my functions to work supports this challenge more nicely than Jelly)

(`リョ` is one byte)

By abusing the way I manage my stack, we can get this down to two bytes, which is pretty much the minimum possible unless you either have a latin square built-in for some reason, or a "rotate by each in range" built-in.

```
メ　　  For each element in the second-from-top-of-stack
　リョ  Rotate Left

```

If the stack's size is insufficient, popping will give the first command line argument instead. If that doesn't exist, it will input each time. Thus, you can make this rectangular by using STDIN. Otherwise, supply the number as a command line argument, and it'll use that value for the TOS and second-TOS.

Thus, for each `x` in `1, ..., N`, it rotates `N` to the left by `x`, and rotating a number casts it to a range by default.

# Answer
> 2 votes
# Python 3 - ~~127~~ 118 bytes

```
n=int(input())
m,o=[],[]
for i in range(n):
  m.append(i)
for i in range(n):
  o.append(m)
  m=m[-1:]+m[:-1]
print(o)

```

Try it online!

Simple answer - takes a contiguous subset of numbers, cycles it every row, and prints (aka, the usual formula).

# Answer
> 2 votes
# Bash, 45 44 bytes

```
for((i=0;i<$1*$1;)){
echo $[(i/$1+i++)%$1]
}

```

Try it online!

-1 thanks to dingledooper

Prints flattened square, one element per line.

# Answer
> 2 votes
# Excel, 36 bytes

```
=MOD(SEQUENCE(A1)+SEQUENCE(1,A1),A1)

```

This seems to be similar to some of the solutions in other languages.

# Answer
> 2 votes
# Charcoal, 12 bytes

```
ＮθＩＥθ⁺…ιθ…⁰ι

```

Try it online! Link is to verbose version of code. Note that Charcoal's default output doesn't look much like an array. Other 12-byte variants are possible, e.g. modular arithmetic between range and row number or modular sum of row and column. Explanation: Simply concatenates the ranges from `i` to `n` and from `0` to `i` for every row.

# Answer
> 2 votes
# Pyth, 5 bytes

```
.>LUQ

```

Test suite

Explanation:

```
.>LUQ  | Full program
.>LUQQ | with implicit variables
-------+----------------------------------
.>LUQ  | rotate range(input) right d times
  L  Q | for each d in range(input)

```

Python 3 translation:

```
Q = eval(input())

print(list(map(lambda d: list(range(Q)[-d:])+list(range(Q)[:-d]), range(Q))))

```

# Answer
> 2 votes
# TI-Basic, 28 bytes

```
Prompt N
For(I,1,N
Disp remainder(I+seq(J,J,1,N),N
End

```

Outputs each row as a list on a separate line. Note that `remainder(` only works for TI-84+/SE with the 2.53 MP OS. The below version uses 2 more bytes but is compatible with earlier OS's.

### 30 bytes

```
Prompt N
For(I,1,N
Disp NfPart((I+seq(J,J,1,N))/N
End

```

# Answer
> 1 votes
# Python 3, ~~43~~ 41 bytes

Saved 2 byte thanks to caird coinheringaahing!!!

```
lambda n:[(a+a//n)%n for a in range(n*n)]

```

Try it online!

Port of my C answer (turns out to be the same as xnor's Python 2 answer).

# Answer
> 1 votes
# Zsh, 35 bytes

```
n=$1
repeat n\*n echo $[a++*~n/n%n]

```

Try it online!

Port of @dingledooper's golf to @Noodle9's C answer, but in reverse.

The `\` is a work-around for a bug in `zsh`, and could be removed in a later version for -1.

# Answer
> 1 votes
# Befunge-98 (PyFunge), 64 bytes

```
&::01-v_@
99+*77<^\-*86g99`+1\*:\-*86g99:::.%\+-*86g99/\-*86g99p

```

Try it online!

This is my first Befunge answer, so I'm sure it can golfed a lot more. I'm particularly frustrated about the repetition of `99g68*-`, which is the best way I could store an extra counter, since I couldn't find an equivalent of Factor/Forth's `2dup` or `rot` for Befunge, nor can I define a function.

# Answer
> 1 votes
# Ruby, 30 bytes

```
->n{w=*1..n;w.map{w=w.rotate}}

```

Try it online!

A little late, sorry.

# Answer
> 1 votes
# MMIX, 56 bytes (14 instrs)

Stores a flattened \\$n\times n\\$ Latin square into second argument. The pattern is:

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

```

Declaration:

```
void __mmixware latinsq(wyde n, wyde *storage);

```

(jxd -T)

```
00000000: c1020000 c1030000 c1040000 a7020100  Ḋ£¡¡Ḋ¤¡¡Ḋ¥¡¡ʂ£¢¡
00000010: e7010002 27030301 73ff0301 220202ff  ḃ¢¡£'¤¤¢s”¤¢"££”
00000020: 260404ff 27020201 62030300 62020200  &¥¥”'££¢b¤¤¡b££¡
00000030: 5b04fff7 f8000000                    [¥”ẋẏ¡¡¡

```

```
latinsq SET  $2,$0          // i = n
        SET  $3,$0          // j = n
        SET  $4,$0          // k = n
0H      STWU $2,$1,0
        INCL $1,2           // loop: *storage++ = i
        SUBU $3,$3,1
        ZSZ  $255,$3,1      // t = !--j
        ADDU $2,$2,$255     // i += t
        SUBU $4,$4,$255     // k -= t
        SUBU $2,$2,1        // i--
        CSZ  $3,$3,$0       // if(!j) j = n
        CSZ  $2,$2,$0       // if(!i) i = n
        PBNZ $4,0B          // iflikely(k) goto loop
        POP  0,0            // return

```

# Answer
> 1 votes
# Risky, 21 bytes

```
00?+0*_?-1/_?-1+_0+02-0?+0+_]+]+_]+]+_]+]

```

Try it online!

# Answer
> 0 votes
# Go, 67 bytes

```
import."fmt"
func f(n int){
for k:=0;k<n*n;k++{Println((k+k/n)%n)}}

```

Attempt This Online!

Outputs each element of the flattened square on a newline.

# Answer
> 0 votes
# Octave/MATLAB, 21 bytes

with the help of the built-in function `magic`

> M = magic(n) returns an n-by-n matrix constructed from the integers 1 through n^2 with equal row and column sums. The order n must be a scalar greater than or equal to 3 in order to create a valid magic square.

---

Try it online!

```
@(n)mod(magic(n),n)+1

```

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


title: Interlaced array

text:
# Question
Title: Interlaced array
You are given an array `A` of length `N` and an array `B` of length `N-1`.

You need to output array where items alternates:

```
A[0], B[0], A[1], B[1], ..., B[N-2], A[N-1]

```

**Restrictions:**

```
N>0

```

Type of items is not specified, but code should work at least for unsigned integers.

**Sample input:**

```
A = [1,2,3,4]
B = [7,8,9]

```

**Sample output:**

```
[1,7,2,8,3,9,4]

```

**Edge case input:**

```
A = ['Hello, world']
B = []

```

**Edge case output:**

```
['Hello, world']

```

---

This question is a simplified version of Zip uneven lists.

# Answer
# Python 3, <sup>~~36~~</sup> 34 bytes

*-2 bytes thanks to @Jonathan Allan*

```
lambda a,b:sum(zip(a,b+a),())[:-1]

```

Try it online!
> 2 votes

# Answer
# Vyxal, 1 byte

```
Y

```

Try it Online!

It's a built in. Takes B then A
> 1 votes

# Answer
# JavaScript (ES6), 35 bytes

Expects `(A,B)` and returns a new array.

-2 bytes if the integers are guaranteed to be positive, in which case this is identical to my answer to this closely related challenge.

```
f=([v,...a],b)=>1/v?[v,...f(b,a)]:a

```

Try it online!

---

# JavaScript (ES6), 38 bytes

Expects `(A)(B)`. Outputs by modifying `A`.

```
a=>b=>b.map((v,i)=>a.splice(i-~i,0,v))

```

Try it online!
> 1 votes

# Answer
# Perl 5, 40 bytes

```
sub{grep/./,map{$_,$_[1][$i++]}@{$_[0]}}

```

Try it online!
> 1 votes

# Answer
# Jelly, 2 bytes

```
żẎ

```

Try It Online!

I don't think there's a built-in directly for this...? Interleaving returns a 2D list and then we flatten it by one level (so even if either list is more than depth 1, this should be correct).
> 1 votes

# Answer
# Haskell, 19 bytes

```
(a:x)!b=a:b!x
a!_=a

```

Try it online!

-4 bytes thanks to Wheat Wizard

Defines an infix function `!` (thanks to Wheat Wizard for this optimization) that returns `[a[0], ...]` (swapping arguments, so next we get `[b[0], ...]` which is followed by `[a[1], ...]`, etc.) or if `b` is empty, just `a`.

---

### Standard ML (MLton), 28 bytes

```
fun f[]a=a|f(a::x)b=a::f b x

```

Try it online!

---

### Proton, 31 bytes

```
f=(a,b)=>b?a[to1]+f(b,a[1to]):a

```

Try it online!
> 0 votes

# Answer
# Retina 0.8.2, 28 bytes

```
O#$`\d+(?<=((,)|.)+)
$#2
¶
,

```

Try it online! Takes two comma separated lists of unsigned integers as input. Explanation:

```
O#$`\d+(?<=((,)|.)+)
$#2

```

Sort each value by the number of preceding commas in its line.

```
¶
,

```

Join the two lists together.

# Charcoal, 13 bytes

```
ＵＭθ⮌ιＷ§θⅉ⟦Ｉ⊟ι

```

Try it online! Takes input as a pair of lists. Explanation: Same as my answer to the duplicate challenge.

```
ＵＭθ⮌ι

```

Reverse each of the two lists.

```
Ｗ§θⅉ

```

Cyclically index the lists according to the number of values already output and repeat until that list is empty.

```
⟦Ｉ⊟ι

```

Output the "next" value from that list on its own line.
> 0 votes

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


title: Randomly select from an array

text:
# Question
Title: Randomly select from an array
This challenge is rather simple:
You are given an array of positive (not including 0) integers, and have to select a random element from this array.

But here's the twist:
The probability of selecting an element is dependent on the value of the integer, meaning as the integer grows larger, the probability of it to get selected does too!

# Example

You are given the array `[4, 1, 5]`.

The probability of selecting 4 is equal to *4 divided by the sum of all elements in the array*, in this case `4 / ( 4 + 1 + 5 ) = 4 / 10 =` **`40%`**.
The probability of selecting 1 is `1 / 10` or **`10%`**.

# Input

An array of positive integers.

# Output

Return the selected integer if using a method, or directly print it to `stdout`.

# Rules

* This is so shortest code in bytes in any language wins.
* Standard loopholes are forbidden.

# Answer
# Jelly, 3 bytes

```
x`X

```

Try it online!

Look 'ma, no Unicode!

Explanation:

```
x`X
 `  Make monad from dyad and use same left and right arguments
x   Repeat each element of the left argument (implicit) list its respective number of times in the right argument list
  X Random element

```
> 21 votes

# Answer
# , 25 bytes

```
function(s)sample(s,1,,s)

```

Try it online!

Explanation:

```
function(s){
 sample(x = s, size = 1, replace = FALSE, prob = s)
}

```

Takes a sample from `s` of size `1` without replacement, with weights `s`; these are rescaled to be probabilities.

To verify the distribution, use this link.
> 16 votes

# Answer
# Pyth, 4 bytes

```
OsmR

```

**Try it here.**

Saved one byte, thanks to @Jakube, with a rather unusual approach.

# Pyth, 5 bytes

```
Osm*]

```

**Try it here!**

# How?

### #1

```
OsmR   - Full program.

   R   - Right Map...
  m    - ... Using Map. This essentially creates the list [[4,4,4,4], [1], [5,5,5,5,5]].
       - ... Credit goes to Jakube for this!
 s     - Flatten.
O      - Random element of ^. Display implicitly.

```

### #2

```
Osm*]   - Full program.

  m     - Map over the input.
    ]   - The current element, d, wrapped; [d].
   *    - Repeated d times.
 s      - Flatten.
O       - Random Element. Implicitly print the result.

```
> 13 votes

# Answer
## CJam (9 bytes)

```
q~_]ze~mR

```

Online demo. This is a full program which takes input in CJam array format on stdin and prints the selected element to stdout.

### Dissection

```
q~   e# Read and parse input
_]z  e# Copy and transpose
e~   e# Run-length decode
mR   e# Select random element uniformly

```
> 8 votes

# Answer
# Perl 6, 20 bytes

*Saved 1 byte thanks to @Brad Gilbert b2gills.*

```
{bag(@_ Zxx@_).pick}

```

Try it online!

This takes 1 list argument. We zip 2 copies of this list using the `xx` operator. So with `@_ Zxx@_`, we get a list in which element `x` is presented `x` times. It is then coerced to `Bag`, which is a collection that stores objects along with how many times they appear in the collection. Finally, we pick a random element from this collection with `pick`, which takes the counts into the account and does The Right Thing™.
> 7 votes

# Answer
# Python 3.6, 44 bytes

```
lambda A:choices(A,A)[0]
from random import*

```

Yay for built-ins. The other `A` in `choices(A, A)` is an optional `weights` argument.

Try it online!
> 7 votes

# Answer
# Ruby, 32 bytes

```
->a{a.flat_map{|x|[x]*x}.sample}

```

Try it online!
> 6 votes

# Answer
# MATL, ~~8~~ 6 bytes

```
tY"1Zr

```

Try it at **MATL Online!**

### Explanation

```
t    % Implicit input. Duplicate
Y"   % Run-length decoding
1Zr  % Randomly take one value with uniform distribution. Implicitly display

```
> 5 votes

# Answer
# Mathematica, 19 bytes

```
RandomChoice[#->#]&

```
> 5 votes

# Answer
# Python 3, 62 bytes

```
lambda k:choice(sum([x*[x]for x in k],[]))
from random import*

```

Try it online!
> 4 votes

# Answer
# Java (OpenJDK 8), ~~88~~  ~~87~~ ~~86~~ 83 bytes

```
a->{int r=0,x=-1;for(int i:a)r-=i;for(r*=Math.random();r<1;)r+=a[++x];return a[x];}

```

Try it online!
> 4 votes

# Answer
# J, ~~8~~ ~~7~~ 8 bytes

The 7 byter is invalid; I'll revert this to a previous edit when I get back to my computer in a day or two.

Try it online!

```
?@+/{#~

```

:( selecting random elements from an array is costly.

**8 bytes**

```
#~{~1?+/

```

**9 bytes**

```
(1?+/){#~

```

# Explanation

```
?@+/{#~
?        Choose random number in range
  +/     Sum of the array
    {    Select that element from
     #~  The elements duplicated as many times as their value

```
> 3 votes

# Answer
# JavaScript (ES6), 50 bytes

```
a=>a.sort((a,b)=>b-a)[Math.random()**2*a.length|0]

```

Hopefully it's apparent how this works, but I'll explain it here anyway. It sorts the integers in descending order, then chooses one at random with a beta distrubution (1/2,1).
> 3 votes

# Answer
# 05AB1E, 9 bytes

```
εD¸.×}˜.R

```

Try it online!
> 2 votes

# Answer
# PowerShell, 27 bytes

```
($args[0]|%{,$_*$_})|Random

```

Try it online!

Takes input `$args[0]` as a literal array. Loops through each element `|%{...}` and each iteration constructs a new array `,$_` of `$_` elements -- e.g., for `4` this will create an array `@(4,4,4,4)`. Those array elements are then piped into `Get-Random` which will pluck out one of the elements with (pseudo) equal probability. Since, e.g., for `@(4,1,5)` this gives us `@(4,4,4,4,1,5,5,5,5,5)` this satisfies the probability requirements.
> 2 votes

# Answer
# Japt, 7 bytes

```
ËÆD
c ö

```

Test it here

---

## Explanation

Implicit input of array `U`.

```
Ë

```

Map over the array passing each element through a function where `D` is the current element.

```
ÆD

```

Generate an array of length `D` and fill it with `D`.

```
c

```

Flatten.

```
ö

```

Get a random element.
> 2 votes

# Answer
# C# (.NET Core), 93 89 87 76+18 = 94 bytes

```
a=>{int i=-1,r=new Random().Next(a.Sum());while(r>=0)r-=a[++i];return a[i];}

```

Try it online!

An extra 18 bytes for `using System.Linq;`

### Acknowledgements

11 bytes saved thanks to Nevay, whose random number implementation was a lot more concise (as well as being an `int` instead of a `double`).

### Degolfed

```
a=>{
    int i=-1,
    r=new Random().Next(a.Sum());
    while(r>=0)
        r-=a[++i];
    return a[i];
}

```

### Explanation

Get a random number, `r`, between 0 and sum of elements. Then at each iteration subtract the current element from `r`. If `r` is less than `0`, then return this element. The idea is that there are bigger portions of the random number for the larger numbers in the array.
> 2 votes

# Answer
# CJam, 5 bytes

```
lS/mR

```

Try it online! Note: seperate numbers by a space
> 2 votes

# Answer
# Perl, 31 bytes

```
@a=map{($_)x$_}@ARGV;$a[rand@a]

```

This assumes the input to be command line arguments. Note that it may run out of memory if the numbers are large.
> 1 votes

# Answer
# Perl 5, 31 + 1 (-a) = 32 bytes

```
@p=map{($_)x$_}@F;say$p[rand@p]

```

Try it online!
> 1 votes

# Answer
# GolfScript, 17 bytes

```
~{.({.}*}%.,rand=

```

Try it online!
> 1 votes

# Answer
# Charcoal, 12 bytes

```
Ｆ⪪θ;ＦＩι⊞υι‽υ

```

Try it online! Link is to verbose version of code. Since Charcoal tries to be too clever, I'm having to use semicolon-delimited input for the array. Explanation:

```
  θ             Input variable as string
 ⪪ ;            Split on semicolons
Ｆ               Loop i over each string
     Ｉι         Cast i to integer
    Ｆ           Repeat that many times
       ⊞υι      Push i to (originally empty) list
          ‽υ    Random selection from list
                Implicitly print

```
> 1 votes

# Answer
# Javascript (ES6), ~~61~~ 54 bytes

-7 bytes thanks to @Justin Mariner

```
a=>a.find(m=>(n-=m)<0,n=Math.random()*eval(a.join`+`))

```

## Example code snippet

```
f=
a=>a.find(m=>(n-=m)<0,n=Math.random()*eval(a.join`+`))
console.log(f([4,1,5]))
```
> 1 votes

# Answer
# Haskell, 87 bytes

```
import System.Random
f l|m<-[x<$[1..x]|x<-l]>>=id=randomRIO(0,length m-1)>>=print.(m!!)

```

Try it online!
> 1 votes

# Answer
# Haskell, ~~78~~ 77 bytes

```
import System.Random
f l=randomRIO(0,sum l-1)>>=pure.((l>>= \n->n<$[1..n])!!)

```

Try it online! Usage example: `f [1,99]` probably yields `99`.

### Explanation:

* `f` takes a list of integers `l` and returns the randomly selected integer as `IO Int`.
* `l>>= \n->n<$[1..n]` constructs a list with each element `n` repeated `n` times.
* `randomRIO(0,sum l-1)` yields an integer in the range from 0 to the length of the list of repeated elements, which is exactly the sum of all elements, minus one to avoid a out of bound exception.

---

**Bonus:** 85 byte point-free version

```
import System.Random
(>>=).randomRIO.(,)0.pred.sum<*>(pure.).(!!).(>>= \n->n<$[1..n])

```

Try it online!
> 1 votes

# Answer
# Bash, 51 bytes

```
for n in $@;{ printf $n\\n%.s `seq $n`;}|shuf|sed q

```

Takes space-separated or newline-separated input in one argument or multiple arguments.

Try it online!

Validate the random frequencies with a more complicated test case.
> 1 votes

# Answer
# Perl 6, 21 bytes

```
{flat($_ Zxx$_).pick}

```

Try it online!

`$_ Zxx $_` zips the input list with itself using the `xx` replication operator, turning (for example) `(1, 2, 3)` into `((1), (2, 2), (3, 3, 3))`. `flat` flattens that into a list of integers, and finally `pick` picks one at random.
> 1 votes

# Answer
# Java 8, ~~127~~ ~~122~~ 121 bytes

```
import java.util.*;a->{List l=new Stack();for(int i:a)for(int j=i;j-->0;Collections.shuffle(l))l.add(i);return l.get(0);}

```

-1 byte thanks to *@Nevay*.

Uses a similar approach as *@ErikTheOutgolfer*'s Jelly answer, by adding `n` times the item `n` to the list, and then select one randomly from that list.

**Explanation:**

Try it here.

```
import java.util.*;        // Required import for List, Stack and Collections
a->{                       // Method with integer-array parameter and integer return-type
  List l=new Stack();      //  Create a List
  for(int i:a)             //  Loop (1) over the input array
    for(int j=i;j-->0;     //   Inner loop (2) from `i` down to 0
        Collections.shuffle(l))
                           //   and shuffle the List randomly after every iteration
      l.add(i);            //    Add `i` that many times to List `l`
                           //   End of inner loop (2) (implicit / single-line body)
                           //  End of loop (1) (implicit / single-line body)
  return l.get(0);         //  And then return the first item of the list
}                          // End of method

```
> 1 votes

# Answer
# GNU APL 1.2, 26 23 bytes; 1.7 21 19 bytes

Approach inspired by Erik the Outgolfer's Jelly answer. Relies on `⎕IO` being 0 instead of 1, which is the default for GNU APL (sort of +5 bytes for `⎕IO←0`).

-3, -2 bytes thanks to @Zacharý

function form

```
∇f R
S[?⍴S←∊0 0⍉R∘.⍴R]∇

```

Anonymous lambda form

```
{S[?⍴S←∊0 0⍉⍵∘.⍴⍵]}

```

For the explanation, I will use  to represent the argument passed to the function, but it is equivalent to `R` in the  form.

`⍵∘.⍴⍵` computes the outer product on the list using the reshape () operator. Effectively, this creates a table (like a multiplication table) but instead of multiplying, it repeats the element in the column a number of times equal to the element in the row. For the example given in the question, this is:

```
4 4 4 4    1 1 1 1    5 5 5 5
4          1          5
4 4 4 4 4  1 1 1 1 1  5 5 5 5 5

```

`0 0⍉⍵∘.⍴⍵` transposes the matrix and returns just the main diagonal. This gives us just the parts where the row and column in `⍵∘.⍴⍵` were the same i.e. we repeated the number a number of times equal to its value. For the example, this is:

```
4 4 4 4  1  5 5 5 5 5

```

turns its argument into a list. Using the transpose () operator, we got a vector containing 3 vectors. Enlist () turns it into a single vector containing all the elements.

`S←...` assigns this new vector to vector `S`. `⍴S` gives us the length of that list. `?` is the random operator, so `?⍴S` gives us a random number between 0 and the length of the list (exclusive) (this is why it relies on `⎕IO` being 0; otherwise it's between 1 and the length, inclusive). `S[...]` returns the element at the given index.
> 1 votes

# Answer
# Dyalog APL, 8 bytes

```
/⍨⌷⍨1?+/

```

Try it online!

## How?

* `/⍨`, `n` copies of `n` for each `n` in the argument.
* `⌷⍨`, at the index of
* `1?`, a random value between `1` and
* `+/`, the sum of the argument
> 1 votes

# Answer
# MATLAB, 30 bytes

```
@(a)datasample(repelem(n,n),1)

```

This assumes MATLAB R2015a or newer and with the Statistics & Machine Learning toolbox installed.

See the explanation below for how `repelem` is used. The difference between this shorter one and the one below is that the S&ML toolbox includes the function `datasample` which can be used to take one or more elements from an array at random (with uniform probability) which allows an anonymous function to be used, stripping away the `input/disp` calls.

# MATLAB, 49 bytes

```
n=input('');a=repelem(n,n);disp(a(randi(nnz(a))))

```

This code assumes that MATLAB R2015a or newer is used as that is when the `repelem` function was introduced. `repelem` is a function which takes two parameters, the first is an array of numbers to be replicated, and the second is an array of how many times the corresponding element should be replicated. Essentially the function performs run-length decoding by providing the number and the run-length.

By providing the same input to both inputs of `repelem` we end up with an array which consists of n times more of element n if that makes sense. If you provided `[1 2 3]` you would get `[1 2 2 3 3 3]`. If you provided `[1 2 4 2]` you would get `[1 2 2 4 4 4 4 2 2]`. By doing this it means that if we select an element with uniform probability (`randi(m)` gives a random integer from 1 to m with uniform probability), each element n has an n times higher probability of being selected. In the first example of `[1 2 3]`, `1` would have a 1/6 chance, `2` would have a 2/6 chance and `3` would have a 3/6 chance.

---

As a side note, because `repelem` is not available yet for Octave, I can't give a TIO link. Additionally because Octave can't be used there is a big character penalty as `input()` and `disp()` need to be used as an anonymous function is not possible. If Octave supported `repelem`, the following could be used:

```
@(n)a(randi(nnz(a=repelem(n,n))))

```

That would have saved 16 bytes, but it was not to be.
> 1 votes

# Answer
# Vyxal, 3 bytes

```
ẋf℅

```

Try it Online!

```
  ℅ # Choose a random element of
ẋ   # Each element n in the array repeated n times
 f  # Flattened

```
> 1 votes

# Answer
# Uiua SBCS, 8 bytes

```
⊡⌊×⚂⧻.▽.

```

Try it!

```
⊡⌊×⚂⧻.▽.
      ▽.  # repeat each array item <itself> times
    ⧻.    # length
  ×⚂      # times random unit
 ⌊        # floor
⊡         # pick

```
> 1 votes

# Answer
# Go (1.22+ only), 116 bytes

```
import."math/rand"
func f(s[]int)int{A:=[]int{}
for _,e:=range s{for range e{A=append(A,e)}}
return A[Intn(len(A))]}

```

Attempt This Online!

### Go (all versions), 121 bytes

```
import."math/rand"
func f(s[]int)int{A:=[]int{}
for _,e:=range s{for i:=0;i<e;i++{A=append(A,e)}}
return A[Intn(len(A))]}

```

Attempt This Online!

### Explanation

```
import."math/rand"
func f(s[]int)int{
// construct a slice with each element `n` repeated `n` times
A:=[]int{}
for _,e:=range s{for i:=0;i<e;i++{A=append(A,e)}}
// actually select the element
return A[Intn(len(A))]
}

```

Attempt This Online!
> 1 votes

# Answer
# Clojure, 64 bytes

```
(defn a[i](rand-nth(reduce #(concat %(take %2(repeat %2)))[]i)))

```

Appends each item item number of times to a new list, then takes a random element.

Finally a clojure answer that's not incredibly much longer than other answers :D
> 0 votes

# Answer
# 05AB1E, 21 bytes

```
O/ždT6m/svy-D0‹s})1kè

```

Try it online!

---

Here's a weird implementation for you, uses microseconds on the system's CPU for the randomized seed.

```
O/                     # [.4,.1,.5] | Push prob distribution.
  ždT6m/               # ?????????? | 0 < x < 100000 divided by 100000.
        s              # [.4,.1,.5] | Swap...
         v             # For each prob in distribution...
          y-           # Remove from random number b/w 0 and 1.
            D0‹        # Dupe each, find if this number made the random number less than 0.
               s})     # Continue loop, swapping current random diff to the front of the stack.
                  1kè  # First instance of the random number going negative is our random return.

```
> 0 votes

# Answer
# Clojure, 46 bytes

```
(fn[s](rand-nth(flatten(map #(repeat % %)s))))

```

Try it online!

The usual Clojure pain: simple idea, long-ass (for golfing) function names.
> 0 votes

# Answer
# TI-BASIC, 20 bytes

```
Ans→L₁
SortD(L₁
L₁(1+int(rand²dim(L₁

```

Input and output are stored in `Ans`. If you see a box, `L₁` is L1. Same algorithm as my JavaScript answer.
> 0 votes

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


# Question
Title: Distance between two points in n-dimensional space
Here is another simple one:

# The Challenge

Given two points in an n-dimensional space, output the distance between them, also called the Euclidean distance.

* The coordinates will be rational numbers; the only limits are the restrictions of your language.
* Lowest dimension is 1, highest is whatever your language can handle
* You may assume that the two points are of the same dimension and that there will be no empty input.
* The distance has to be correct to at least 3 decimal places. If your language does not support floating point numbers, output the nearest whole number.

# Rules

* As usual, function or full program allowed.
* Input may be taken from STDIN, command line- or function arguments.
* Input format is up to you, specify which one you used in your answer.
* Output may be provided by printing to stdout or return value.
* This is so lowest byte-count wins! In case of a tie, the earlier answer wins.

# Test cases

Each point is represented by a list of length n.

```
[1], [3] -> 2
[1,1], [1,1] -> 0
[1,2], [3,4] -> 2.82842712475
[1,2,3,4], [5,6,7,8] -> 8
[1.5,2,-5], [-3.45,-13,145] -> 150.829382085
[13.37,2,6,-7], [1.2,3.4,-5.6,7.89] -> 22.5020221314

```

**Happy Coding!**

# Answer
> 28 votes
# MATL, 2 bytes

```
ZP

```

**Try it online**!

The `ZP` function (corresponding to MATLAB's `pdist2`) computes all pairwise distances between two sets of points, using Euclidean distance by default. Each set of points is a matrix, and each point is a row. In this case it produces a single result, which is the distance between the two points.

# Answer
> 16 votes
# MATL, ~~~~4.0~~~~ 3 bytes

Thanks for -1 by @AndrasDeak!

```
-Zn

```

Reads two vectors (via implicit input that is requested by `-`) then substracts those and calculates the norm of their difference with `Zn`.

Try it Online!

# Answer
> 12 votes
# Pyth, 2 bytes

```
.a

```

> `.a` \- L2 norm of vector difference of A\[0\] and A\[1\].

Literally a function that does this problem

Try it here.

# Answer
> 10 votes
# Jelly, 4 bytes

```
_²S½

```

Try it online!

### How it works

```
_²S½    Main link. Left input: A (list). Right input: B (list).

_       Subtract B from A, element by element.
 ²      Square all differences.
  S     Add all squares.
   ½    Take the square root of the sum.

```

# Answer
> 9 votes
## Mathematica, 11 bytes

```
Norm[#-#2]&

```

Input as two lists, output as a number. If the input is exact (integers, rationals, etc.) the output will be exact as well. If the input contains a floating-point number, the output will be a float as well.

# Answer
> 6 votes
## CJam, ~~11~~ 8 bytes

*Thanks to Dennis for saving 3 bytes.*

```
q~.-:mhz

```

Run all test cases.

### Explanation

```
q~   e# Read and evaluate input.
.-   e# Vectorised difference.
:mh  e# Reduce √(x²+y²) over the list.
z    e# Take abs() to handle 1D input.

```

See this tip for why `:mh` works.

# Answer
> 6 votes
# Haskell, 46 bytes

```
d :: Floating c => [c] -> [c] -> c
d a=sqrt.sum.map((^2).uncurry(flip(-))).zip a

```

# Haskell, 35 bytes (By @nimi)

```
d :: Float c => [c] -> [c] -> c
d a=sqrt.sum.zipWith(((^2).).(-))a

```

# Haskell, 31 bytes

> Like this Scala answer, takes input as a sequence of tuples

\<hack\>

```
d :: Float c => [(c,c)] -> c
d=sqrt.sum.map$(^2).uncurry(-)

```

\</hack\>

## Examples:

```
Prelude> d [1] [3]
2.0
Prelude> d [1,1] [1,1]
0.0
Prelude> d [1,2,3,4] [5,6,7,8]
8.0
Prelude> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
Prelude> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522

```

# Answer
> 6 votes
# Octave, 15 bytes

```
@(x,y)norm(x-y)

```

Example:

```
octave:1> d=@(x,y)norm(x-y);
octave:2> d([13.37,2,6,-7], [1.2,3.4,-5.6,7.89])
ans =  22.502

```

# Answer
> 5 votes
# APL, ~~14~~ 11 bytes

```
.5*⍨(+/-×-)

```

This is dyadic function train that takes the vectors on the left and right and returns the Euclidean norm of their difference.

Explanation:

```
       -×-)  ⍝ Squared differences
    (+/      ⍝ Sum them
.5*⍨         ⍝ Take the square root

```

Try it here

Saved 3 bytes thanks to Dennis!

# Answer
> 4 votes
# Julia, 16 bytes

```
N(x,y)=norm(x-y)

```

This is a function that accepts two arrays and returns the Euclidean norm of their difference as a float.

You can verify all test cases at once online here.

# Answer
> 4 votes
# Java, ~~130~~ ~~117~~ ~~114~~ ~~107~~ 105 bytes

This is the obvious solution. I don't usually golf in Java, but I was curious to see if Java could beat the Brainfuck version. Doesn't seem like I did a good job then.. Maybe one could use the new Map/Reduce from Java 8 to save some bytes.

Thanks to @flawr (13 bytes), @KevinCruijssen (9 bytes) and @DarrelHoffman (3 bytes)!

Golfed:

```
double d(float[]a,float[]b){float x=0,s;for(int i=0;i<a.length;x+=s*s)s=a[i]-b[i++];return Math.sqrt(x);}

```

Ungolfed:

```
double d(float[] a, float[] b) {
  float x=0,s;

  for(int i=0; i<a.length; x+=s*s)
    s = a[i] - b[i++];

  return Math.sqrt(x);
}

```

# Answer
> 4 votes
# J, 9 bytes

```
+&.*:/-/>

```

This is a function that takes one set of coordinates from the other (`-/>`), and then performs a sum `+` under `&.` square `*:`.

The input should be in the format `x y z;a b c` where `x y z` is your first set of co-ordinates and `a b c` is the other.

# Answer
> 3 votes
# Python 2, 47 bytes

A straight forward solution. The function expects 2 points as sequences of numbers, and returns the distance between them.

```
lambda a,b:sum((d-e)**2for d,e in zip(a,b))**.5

```

Example:

```
>>> f([13.37, 2, 6, -7], [1.2, 3.4, -5.6, 7.89])
22.50202213135522

```

# Answer
> 3 votes
# golflua, 43 chars

```
\d(x,y)s=0~@i,v i(x)s=s+(v-y[i])^2$~M.q(s)$

```

Works by calling it as

```
> w(d({1,1},{1,1}))
0
> w(d({1,2},{3,4}))
2.82842712475
> w (d({1,2,3,4},{5,6,7,8}))
8

```

A Lua equivalent would be

```
function dist(x, y)
    s = 0
    for index,value in ipairs(x)
       s = s + (value - y[index])^2
    end
    return math.sqrt(s)
end

```

# Answer
> 3 votes
## Seriously, 12 bytes

```
,iZ`i-ª`MΣ√A

```

Try it online!

Explanation:

```
,iZ`i-ª`MΣ√A
,iZ           get input, flatten, zip
   `   `M     map:
    i-ª         flatten, subtract, square
         Σ√A  sum, sqrt, abs

```

# Answer
> 3 votes
# Perl 6, ~~30~~ ~~29~~ ~~26~~ 24 bytes

```
{sqrt [+] ([Z-] $_)»²}

```

(Thanks @b2gills for 2 more bytes lost)

**usage**

```
my &f = {sqrt [+] (@^a Z-@^b)»²};

say f([1], [3]); # 2
say f([1,1], [1,1]); # 0
say f([1,2], [3,4]); # 2.82842712474619
say f([1,2,3,4], [5,6,7,8]); # 8
say f([1.5,2,-5], [-3.45,-13,145]); # 150.829382084526
say f([13.37,2,6,-7], [1.2,3.4,-5.6,7.89]); # 22.5020221313552

```

# Answer
> 2 votes
## JavaScript ~~ES7, 45~~ ES6, 37 bytes

```
a=>Math.hypot(...a.map(([b,c])=>b-c))

```

Expects an array of pairs of coordinates, one from each vector, e.g. `[[1, 5], [2, 6], [3, 7], [4, 8]]`. If that is unacceptable, then for 42 bytes:

```
(a,b)=>Math.hypot(...a.map((e,i)=>e-b[i]))

```

Expects two arrays of equal length corresponding to the two N-dimensional vectors, e.g. `[1, 2, 3, 4], [5, 6, 7, 8]`. Edit: Saved 3 bytes thanks to @l4m2. (Also, did nobody notice my typo?)

# Answer
> 2 votes
# Ruby, 52

```
->p,q{t=0;p.size.times{|i|t+=(p[i]-q[i])**2}
t**0.5}

```

**In test program**

```
f=->p,q{t=0;p.size.times{|i|t+=(p[i]-q[i])**2}
t**0.5}

p f[[1], [3]] # 2
p f[[1,1], [1,1]] # 0
p f[[1,2], [3,4]] # 2.82842712475
p f[[1,2,3,4], [5,6,7,8]] # 8
p f[[1.5,2,-5], [-3.45,-13,145]] # 150.829382085
p f[[13.37,2,6,-7], [1.2,3.4,-5.6,7.89]] # 22.5020221314

```

# Answer
> 2 votes
# AppleScript, ~~241~~ 239 bytes

This is golfed code, but I've put comments in in the form `--`.

```
on a()    -- Calling for getting input
set v to{1}          -- Arbitrary placeholder
repeat until v's item-1=""       -- Repeat until no input is gathered
set v to v&(display dialog""default answer"")'s text returned   -- Add input to list
end      -- End the repeat
end      -- End the method
set x to a()   -- Set the array inputs
set y to a()
set z to 0     -- Sum placeholder
set r to 2     -- 2 is the first significant array index
repeat(count of items in x)-2     -- Loop through all but first and last of the array
set z to z+(x's item r-y's item r)^2    -- Add the square of the difference
end   -- End the repeat
z^.5  -- Return the square root of the sum
```

This uses the same algorithm as most of the other programs here.

# Answer
> 2 votes
## Haskell, 32 bytes

```
((sqrt.sum.map(^2)).).zipWith(-)

```

---

```
λ> let d = ((sqrt.sum.map(^2)).).zipWith(-)
λ> d [1] [3]
2.0
λ> d [1,1] [1,1]
0.0
λ> d [1,2] [3,4]
2.8284271247461903
λ> d [1..4] [5..8]
8.0
λ> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
λ> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522

```

# Answer
> 2 votes
# C (gcc), ~~79~~ 77 bytes

-2 bytes thanks to ceilingcat.

TIO requires compiler flag `-lm`. GCC of MinGW (that I use) does not.

```
f(p,q,d,s)float*p,*q,s;{for(s=0;d--;)s+=*p++*=*p-=*q++;printf("%f",sqrt(s));}

```

Try it online!

# Answer
> 2 votes
# Vyxal, 2 bytes

```
∆d

```

Try it Online!

Laughs in built-in. Generalised euclidian distance do be like that sometimes.

# Answer
> 2 votes
# R, 38 bytes and 25 bytes

Sure, it is impossible to compete with the shortest 4 bytes answer, but I wanted to share anyway a hopefully interesting solution (38 bytes):

```
f=\(x,y)sd(c(x-y,y-x))*(nrow(x)-.5)^.5

```

How does it work? Standard deviation of a sample is calculated as a square root of the sum of squares of deviation scores divided by sample size minus one.

The trick is to add to the sample a second set of the same numbers with the opposite sign (like `c(1,2,-1,-2)`). This way we get rid of mean (=0) out of the formula, but also we are getting each number twice. To obtain the sum of squares we only need to "neutralize" the term `sqrt(2/(N-1))`, whereby the sample size N is 2\*N\_dimensions.

...but unfortunately this bright =) solution sucks to the old good straightforward formula (25 bytes):

```
g=\(x,y)(sum((x-y)^2))^.5

```

Here is the result:

```
> list.x <- list(matrix(1),
+                matrix(c(1,1),2),
+                matrix(c(1,2),2),
+                matrix(c(1,2,3,4), 4),
+                matrix(c(1.5,2,-5), 3),
+                matrix(c(13.37,2,6,-7),4))
>
> list.y <- list(matrix(3),
+                matrix(c(1,1), 2),
+                matrix(c(3,4),2),
+                matrix(c(5,6,7,8),4),
+                matrix(c(-3.45,-13,145),3),
+                matrix(c(1.2,3.4,-5.6,7.89),4))
>
> correct = list(2,0,2.82842712475,8,150.829382085,22.5020221314)
>
> do.call(rbind, Map(\(x,y,z)c(f(x,y),g(x,y),z),list.x,list.y,correct))
           [,1]       [,2]       [,3]
[1,]   2.000000   2.000000   2.000000
[2,]   0.000000   0.000000   0.000000
[3,]   2.828427   2.828427   2.828427
[4,]   8.000000   8.000000   8.000000
[5,] 150.829382 150.829382 150.829382
[6,]  22.502022  22.502022  22.502022

```

# Answer
> 1 votes
# Scala, 67 62 bytes

```
def e(a:(Int,Int)*)=math.sqrt(a map(x=>x._2-x._1)map(x=>x*x)sum)

```

Requires input as a sequence/vector of var-arg tuples
Example:

```
scala> e((1, 5), (2, 6), (3, 7), (4, 8))
res1: Double = 8.0

```

# Answer
> 1 votes
# , 6 chars / 13 bytes

```
МŰМŷ…ï

```

`Try it here (Firefox only).`

Calculates norm of difference of input arrays.

# Answer
> 1 votes
# C#, 72 bytes

```
(float[]i,float[]n)=>System.Math.Sqrt(i.Zip(n,(x,y)=>(x-y)*(x-y)).Sum())

```

A simple solution using Linq.

# Answer
> 1 votes
## Sage, 35 bytes

```
lambda a,b,v=vector:norm(v(a)-v(b))

```

This function takes 2 lists as input and returns a symbolic expression. The distance is calculated by performing vector subtraction on the lists and computing the Euclidean norm of the resultant vector.

Try it online

# Answer
> 1 votes
## Clojure, 48 bytes

```
#(Math/sqrt(apply +(for[d(map - % %2)](* d d))))

```

# Answer
> 1 votes
# 05AB1E, 4 bytes

```
-nOt

```

Try it online!

Negative not y'all!

```
-    # a-b
 n   # (a-b)**2
  O  # sum((a-b)**2) for all a,b
   t # sqrt(sum((a-b)**2) for all a,b)

```

# Answer
> 1 votes
# R, 4 bytes

```
dist

```

This is a built-in function to calculate the distance matrix of any input matrix. Defaults to euclidean distance.

Example usage:

```
> x=matrix(c(1.5,-3.45,2,-13,-5,145),2)
> x
      [,1] [,2] [,3]
[1,]  1.50    2   -5
[2,] -3.45  -13  145
> dist(x)
         1
2 150.8294

```

If you're feeling disappointed because it's a built-in, then here's a non-built-in (or at least, it's *less* built-in...) version for **22 bytes** (with thanks to Giuseppe):

```
pryr::f(norm(x-y,"F"))

```

This is an anonymous function that takes two vectors as input.

# Answer
> 1 votes
# Elixir, 74 bytes

```
:math.sqrt Enum.reduce Enum.zip(p,q),0,fn({a,b},c)->:math.pow(a-b,2)+c end

```

**You can try it online**

# Answer
> 1 votes
# TI-Basic (TI-84 Plus CE), 15 bytes

```
Prompt A,B
√(sum((<sub>L</sub>A-<sub>L</sub>B)<sup>2</sup>
```

TI-Basic is a tokenized language.

Prompts for input as two lists, and returns the Euclidian distance betwrrn them in `Ans`

Explanation:

```
Prompt A,B    # 5 bytes, Prompts for two inputs; if the user inputs lists:
           # they are stored in <sub>L</sub>A and <sub>L</sub>B
√(sum((<sub>L</sub>A-<sub>L</sub>B)<sup>2</sup> # 10 bytes, Euclidian distance between points
           #(square root of (sum of (squares of (differences of coordinates))))

```

# Answer
> 1 votes
# Python 3, 44 bytes

```
lambda*a:sum((x-y)**2for x,y in zip(*a))**.5

```

Try it online!

**Ungolfed version:**

```
      ₙ
sqrt( ∑(xᵢ - yᵢ)² )
     ⁱ⁼¹

def d(a, b):                    # two points (lists or tuples)
    return sum(                 # sum of...
        (x - y) ** 2            # (xᵢ - yᵢ)²
        for x,y in zip(a, b)    #
    ) ** 0.5                    # square root of sum

```

# Answer
> 1 votes
# Stax, 8 bytes

```
äÖ╙í▼=╬b

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
\       zip the coordinates into pairs
{       for each pair,
  :s    compute the absolute span
  J+    square and add to total
F
|Q      square root result

```

Run this one

# Answer
> 1 votes
# Desmos, 26 bytes

```
f(a,b)=total((a-b)^2)^{.5}

```

The function \\$f(a,b)\\$ takes in two lists, \\$a\\$ and \\$b\\$, representing the two points, and returns the distance between them.

I think the code is pretty self explanatory, even for someone unfamiliar with Desmos.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Husk, 6 bytes

```
√Σzo□-

```

Try it online!

### Explanation

```
√Σzo□-
  z     zip input arguments
   o    with composed function
     -  difference
    □   squared
 Σ      sum
√       sqrt

```

# Answer
> 0 votes
# Python 3, 70 Chars

Loops through, finding the square of the difference and then the root of the sum:

```
a=input()
b=input()
x=sum([(a[i]-b[i])**2 for i in range(len(a))])**.5

```

# Answer
> 0 votes
## Mathcad, bytes

Uses the built-in vector magnitude (absolute value) operator to calculate the size of the difference between the two points (expressed as vectors).

---

Mathcad golf size on hold until I get (or somebody else gets) round to opening up the discussion on meta. However, the shortest way (assuming that input of the point vectors doesn't contribute to the score) is 3 "bytes" , with 14 bytes for the functional version.

# Answer
> 0 votes
## Pyke, 7 bytes

```
,A-MXs,

```

Try it here!

Transpose, apply subtract, map square, sum, sqrt.

# Answer
> 0 votes
# Ruby, 50 bytes

Zip, then map/reduce. Barely edges out the other Ruby answer from @LevelRiverSt by 2 bytes...

```
->p,q{p.zip(q).map{|a,b|(a-b)**2}.reduce(:+)**0.5}

```

Try it online

# Answer
> 0 votes
## C 276 bytes

```
f(){*a,*b,d=0;l=1;a=malloc(sizeof(float)*50);b=malloc(sizeof(float)*50);scanf("%f",&a[0]);while(getchar()!='\n'){scanf("%f",&a[l]);l++;}l=1;scanf("%f",&b[0]);while(getchar()!='\n'){scanf("%f",&b[l]);l++;}for(int i=0;i<l;i++){d+=pow((a[i]-b[i]),2);}printf("%.5f",pow(d,0.5));}

```

Ungolfed version:

```
void f()
{

  float *a,*b,d=0;
  int l=1;

   a=malloc(sizeof(float)*50);
   b=malloc(sizeof(float)*50);

   //Accept p1,p2,p3.....pn
   scanf("%f",&a[0]);

   while(getchar()!='\n')
   {
     scanf("%f",&a[l]);
     l++;
   }
   l=1;

   //Accept q1,q2,q3.....qn
   scanf("%f",&b[0]);
   while(getchar()!='\n')
  {
    scanf("%f",&b[l]);
    l++;
  }

  for(int i=0;i<l;i++)
  {
    d+=pow((a[i]-b[i]),2);
  }

  printf("\n%.5f",pow(d,0.5));
}

```

Pretty straightforward. This solution lets you measure distance between 2 points in upto 50 dimensions (can be increased).

In Cartesian coordinates, input the position of first point of `n` dimensions. (`p1 p2 p3 ...pn`) and press `Enter`.

Next, input the position of second point of `n` dimensions. (`q1 q2 q3 ...qn`) and press `Enter` to get the Euclidean Distance.

# Answer
> 0 votes
# Excel VBA, 36 Bytes

Anonymous VBE immediate window function that takes input as two vectors, which are projected unto the range `1:2`, and outputs to the VBE immediate window

```
[3:3]="=(A1-A2)^2":?[Sqrt(Sum(3:3))]

```

# Answer
> 0 votes
# Factor \+ `math.distances`, 18 bytes

```
euclidian-distance

```

Try it online!

Built-in.

# Answer
> 0 votes
# J-uby, 35 bytes

```
+:zip|:*&(+:-|~:**&2)|:sum|~:**&0.5

```

Attempt This Online!

```
+:zip | :* & (+:- | ~:** & 2) | :sum | ~:** & 0.5

+:zip |                                            # Zip input arrays, then
        :* & (              )                      # map with
              +:- | ~:** & 2                       #   Difference, then square
                              | :sum |             # then sum, then
                                       ~:** & 0.5  # square root

```

# Answer
> 0 votes
# Fortran (GFortran), ~~85~~ 80 bytes

```
function d(A,n);real A(n,2);s=0;do5 i=1,n;s=s+(A(i,1)-A(i,2))**2
5 d=sqrt(s);end

```

Try it online! <sub>~~85 bytes~~</sub>

Instead of two vectors, I read all the data into two rows of array `A`. But Fortran 'helpfully' stores matrices by *column* so when I call the procedure `A` is transposed. <sub>
Using line number `5` instead of `enddo` saves 2 bytes :)
Saved 5 bytes using `function` instead of `subroutine`</sub>

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
-²Sƭ

```

Try it online!

#### Explanation

```
-²Sƭ  # Implicit input
-     # Subtract
 ²    # Square
  S   # Sum
   ƭ  # Square root
      # Implicit output

```

# Answer
> 0 votes
# Swift 5.9, 86 bytes

```
import Foundation
let f={(p:[(Double,_)])in
sqrt(p.map{pow($0.1-$0.0,2)}.reduce(0,+))}

```

Don't Try It Online, because TIO is too old. Here's a JDoodle link instead.

`f` is of type `([(Double, Double)]) -> Double` -- it takes an array of pairs of coordinates, one per vector.

I just used the *subtract*-*square*-*sum*-*squareRoot* trick borrowed from other answers.

---
Tags: code-golf, number, arithmetic, geometry
---


title: Fibonacci + Fizz Buzz = Fibo Nacci!

text:
# Question
Title: Fibonacci + Fizz Buzz = Fibo Nacci!
Fibonacci + FizzBuzz = Fibo Nacci!

---

# Your challenge is to create a Fibo Nacci program!

* A Fibo Nacci program outputs the first **100** Fibonacci numbers (starting from 1).
* If the Fibonacci number is divisible by both 2 **and** 3 (i.e. it is divisible by 6), then output FiboNacci instead of the number.
* Otherwise, if the Fibonacci number is divisible by 2, then output Fibo instead of the number.
* Otherwise, if the Fibonacci number is divisible by 3, then output Nacci instead of the number.

# Rules

* The program should take no input.
* The program should output a new line (`\n`) after every entry.
* The program should **not** print anything to STDERR.
* The program **must** output the first **100** Fibo Nacci entries (starting from 1).
* Standard loopholes are not allowed (by default).
* This is so shortest code in bytes wins!

Here is the expected output:

```
1
1
Fibo
Nacci
5
Fibo
13
Nacci
Fibo
55
89
FiboNacci
233
377
Fibo
Nacci
1597
Fibo
4181
Nacci
Fibo
17711
28657
FiboNacci
75025
121393
Fibo
Nacci
514229
Fibo
1346269
Nacci
Fibo
5702887
9227465
FiboNacci
24157817
39088169
Fibo
Nacci
165580141
Fibo
433494437
Nacci
Fibo
1836311903
2971215073
FiboNacci
7778742049
12586269025
Fibo
Nacci
53316291173
Fibo
139583862445
Nacci
Fibo
591286729879
956722026041
FiboNacci
2504730781961
4052739537881
Fibo
Nacci
17167680177565
Fibo
44945570212853
Nacci
Fibo
190392490709135
308061521170129
FiboNacci
806515533049393
1304969544928657
Fibo
Nacci
5527939700884757
Fibo
14472334024676221
Nacci
Fibo
61305790721611591
99194853094755497
FiboNacci
259695496911122585
420196140727489673
Fibo
Nacci
1779979416004714189
Fibo
4660046610375530309
Nacci
Fibo
19740274219868223167
31940434634990099905
FiboNacci
83621143489848422977
135301852344706746049
Fibo
Nacci

```

## The Catalogue

The ~~Snack~~ Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
/* Configuration */

var QUESTION_ID = 63442; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41805; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
> 19 votes
# Pyth, 37 bytes

I loop through the Fibonacci numbers instead of generating them beforehand, since it's really short to do.

```
K1V100|+*"Fibo"!%=+Z~KZ2*"Nacci"!%Z3Z

```

Try it online.

# Answer
> 50 votes
## Python 2, 62 bytes

```
a=b=1;exec"print~a%2*'Fibo'+~a%3/2*'Nacci'or a;a,b=b,a+b;"*100

```

Not much different from the standard FizzBuzz, really.

# Answer
> 22 votes
# C++11 metaprogramming, 348 bytes

```
#include<iostream>
#define D static const unsigned long long v=
template<int L>struct F{D F<L-1>::v+F<L-2>::v;};template<>struct F<2>{D 1;};template<>struct F<1>{D 1;};template<int Z>struct S:S<Z-1>{S(){auto&s=std::cout;auto l=F<Z>::v;s<<(l%2?"":"Fibo")<<(l%3?"":"Nacci");(l%2&&l%3?s<<l:s)<<"\n";}};template<>struct S<0>{S(){}};int main(){S<100>s;}

```

Because, why not. It compiles with `warning C4307: '+': integral constant overflow`, runs fine, but 93+ th Fibonacci numbers are not shown correctly (due to overflow), so this is invalid entry (but I could not win it with that much of bytes though)

Ungolfed

```
#include <iostream>
#define D static const unsigned long long v =
template<int L>struct F { D F<L - 1>::v + F<L - 2>::v; };
template<>struct F<2> { D 1; };
template<>struct F<1> { D 1; };

template<int Z>struct S : S<Z - 1>
{
    S()
    {
        auto&s = std::cout;
        auto l = F<Z>::v;
        s << (l % 2 ? "" : "Fibo")
          << (l % 3 ? "" : "Nacci");
        (l % 2 && l % 3 ? s << l : s) << "\n";
    }
};

template<>struct S<0>
{
    S() { }
};

int main()
{
    S<100>s;
}

```

# Answer
> 14 votes
## C#, ~~175 171 152~~ 145 bytes

```
class c{static void Main(){for(dynamic a=1m,b=a,c=0;c++<100;b=a+(a=b))System.Console.WriteLine(a%6>0?a%2>0?a%3>0?a:"Nacci":"Fibo":"FiboNacci");}}

```

Uncompressed:

```
class c {
    static void Main()
    {
        for (dynamic a = 1m, b = a, c = 0; c++ < 100; b = a + (a = b))
            System.Console.WriteLine(a%6>0?a%2>0?a%3>0?a:"Nacci":"Fibo":"FiboNacci");
    }
}

```

# Answer
> 14 votes
## Oracle SQL, 212 bytes

Not a golfing language but I had to try...

Concatenating all the rows with `\n`:

```
WITH F(R,P,C)AS(SELECT 1,0,1 FROM DUAL UNION ALL SELECT R+1,C,P+C FROM F WHERE R<100)SELECT LISTAGG(NVL(DECODE(MOD(C,2),0,'Fibo')||DECODE(MOD(C,3),0,'Nacci'),''||C),CHR(13))WITHIN GROUP(ORDER BY R)||CHR(13)FROM F

```

SQLFIDDLE

Or with one entry from the sequence per row (162 bytes):

```
WITH F(R,P,C)AS(SELECT 1,0,1 FROM DUAL UNION ALL SELECT R+1,C,P+C FROM F WHERE R<100)SELECT NVL(DECODE(MOD(C,2),0,'Fibo')||DECODE(MOD(C,3),0,'Nacci'),''||C)FROM F

```

# Answer
> 11 votes
# ShapeScript, 83 bytes

```
11'1?1?+'77*2**!""'"%r
"@+@0?2%1<"Fibo"*1?3%1<"Nacci"*+0?_0>"@"*!#%'52*0?**!"'"$""~

```

Try it online!

# Answer
> 8 votes
## Mathematica, 80 bytes

```
a=b_/;#∣b&;Print/@(Fibonacci@Range@100/.{a@6->FiboNacci,a@2->Fibo,a@3->Nacci})

```

Adaptation of my older FizzBuzz solution.

# Answer
> 8 votes
# Java, ~~407~~ ~~398~~ ~~351~~ 308 bytes

Golfed it with help from @Geobits and @SamYonnou

Spread the word: `Verbose == Java`

```
import java.math.*;class A{public static void main(String[]w){BigInteger a=BigInteger.ZERO,b=a.flipBit(0),c,z=a,t=a.flipBit(1),h=t.flipBit(0),s=t.flipBit(2);for(int i=0;i<100;i++){System.out.println(b.mod(s).equals(z)?"FiboNacci":b.mod(t).equals(z)?"Fibo":b.mod(h).equals(z)?"Nacci":b);c=a;a=b;b=c.add(b);}}}

```

Ungolfed version:

```
import java.math.*;

class A
{
  public static void main(String[]w)
  {
    BigInteger a=BigInteger.ZERO,b=a.flipBit(0),c,z=a,t=a.flipBit(1),h=t.flipBit(0),s=t.flipBit(2);
    for(int i=1;i<=100;i++) {
      System.out.println(b.mod(s).equals(z)?"FiboNacci":b.mod(t).equals(z)?"Fibo":b.mod(h).equals(z)?"Nacci":b);
      c=a;a=b;b=c.add(b);
    }
  }
}

```

# Answer
> 7 votes
# Ruby, ~~71~~ 66 bytes

```
a=b=1;100.times{puts [b,f='Fibo',n='Nacci',f,b,f+n][~b%6];a=b+b=a}

```

### ungolfed:

```
a = b = 1 #starting values
100.times{
  # create an array, and selects a value depending on the current number
  puts([b, 'Fibo', 'Nacci', 'Fibo', b, 'FiboNacci'][~b%6])
  a=b+b=a # magic
}

```

# Answer
> 7 votes
# \>\<\>, 116 bytes

```
01:n1&61>.
ao:@+:v
vv?%2:<
">:3%?vv^16<
o>:3%?!v~v<&
bov"ci"< 6 ;
io"   n  6~?
Focv1&<   o=
"o">+:aa*!o^
>^>"aN"ooo^

```

Try it online!

# Answer
> 6 votes
## C#, ~~498~~ ~~392~~ 320 bytes

I just really wanted to do this with linq, too bad I had to write my own sum function for BigInteger that really killed it :-(

```
using System.Linq;using System.Numerics;using System.Collections.Generic;static class a{static void Main(){var f=new List<BigInteger>(){1,1};while(f.Count<100)f.Add(f.Skip(f.Count-2).Take(2).Aggregate((a,b)=>b+a));f.ForEach(x=>{System.Console.WriteLine(x%6==0?"FiboNacci":x%2==0?"Fibo":x%3==0?"Nacci":x.ToString());});}}

```

Ungolfed:

```
using System.Linq;
using System.Numerics;
using System.Collections.Generic;
static class a
{
    static void Main()
    {
        var f=new List<BigInteger>(){1,1};
        while(f.Count<100)
            f.Add(f.Skip(f.Count-2).Take(2).Aggregate((a,b)=>b+a));
        f.ForEach(x=>
        {
            System.Console.WriteLine(x%6==0?"FiboNacci":x%2==0?"Fibo":x%3==0?"Nacci":x.ToString());
        });
    }
}

```

Edit: Down to 320 bytes thanks to LegionMammal978 for the aggregate suggestion and thanks to olegz's C# answer for the x%6 shorthand for X%2 && x%3 as well as the use of ternary operators in a single WriteLine statement.

# Answer
> 5 votes
# Pyth, 39

```
Vtu+Gs>2G99U2|+*!%N2"Fibo"*!%N3"Nacci"N

```

Very similar to the standard fizzbuzz solution, just with a generator for the Fibonacci numbers.

Try it here

# Answer
> 5 votes
# Python 2, 171 121 bytes

"Brute force approach."

```
a=[1,1]
print 1
for _ in"q"*99:print[a[1],"Fibo","Nacci","FiboNacci"][a.append(a.pop(0)+a[0])or(1-a[0]%2)+(a[0]%3<1)*2]

```

# Answer
> 4 votes
## Python 2, 100 bytes

```
x=[1,1]
exec"x+=[x[-1]+x[-2]];"*98
print"\n".join(["Fibo"*(i%2==0)+"Nacci"*(i%3==0)or`i`for i in x])

```

For the large numbers, adds a `L` to the end showing it's a long number.

If that's a problem, here is a 104 byte solution

```
x=[1,1]
exec"x+=[x[-1]+x[-2]];"*98
print"\n".join(["Fibo"*(i%2==0)+"Nacci"*(i%3==0)or str(i)for i in x])

```

# Answer
> 4 votes
## Javascript, ~~93 90 86~~ 84 Bytes

```
for(a=0,b=1,i=100;i--;a=[b,b+=a][0])console.log((b%2?'':'Fibo')+(b%3?'':'Nacci')||b)

```

# Answer
> 2 votes
# Javascript(ES6), ~~137~~ 134 bytes

```
g=x=>(a=[1,1],f=(x)=>(a[x]=y=a[x-1]+a[x-2],(y%2&&y%3?y:(!(y%2)?'Fibo':'')+(!(y%3)?'Nacci':''))+'\n'+((++x<99)?f(x):'')),'1\n1\n'+f(2))

```

Recursive function that calculates fibonnacci, put it in an array then output Fibo,Nacci or the number and call itself to calculate next until 100.

It breaks at 73 because of javascript Number precision. Only way to get around that would be to add my own bit calculation.

# Answer
> 2 votes
# \>\<\>, ~~128~~ 119 bytes

```
111&v       >:3%0=?v>  v
?;ao>:2%0=?v :3%0=?v :n>:}+&:1+&aa*=
            ^oooo < ^ooooo <
           >"obiF"^>"iccaN"^

```

I ~~shamelessly stole~~ borrowed an existing program FizzBuzz program and modified it to work for the Fibo Nacci sequence. ~~It outputs numbers forever.~~ Now it is fixed, i.e. it only outputs 100 numbers. Try it here.

# Answer
> 2 votes
## dc, ~~100~~ ~~89~~ 79 bytes

```
[sG[]]sx[dn]s01df[sbdlb+lbrdd2%d[Fibo]r0!=xnr3%d[Nacci]r0!=xn*0!=0APzZ3>o]dsox

```

Inspired by http://c2.com/cgi/wiki?DeeCee

# Answer
> 2 votes
## Wolfram Language, 84 bytes

Kind of cheating of course, because of the built in `Fibonacci`.

```
t=Fibonacci@Range@100;g=(t[[#;;;;#]]=#2)&;g[3,Fibo]g[4,Nacci]g[12,FiboNacci]Print/@t

```

Example command to run the script

```
/Applications/Mathematica.app/Contents/MacOS/WolframKernel -script ~/Desktop/fibo.wl

```

# Answer
> 2 votes
# Perl, 74 bytes

```
map{print+(Fibo)[$_%2].(Nacci)[$_%3]||$_ for$a+=$b||1,$b+=$a}1..50

```

Requires the following command line option: `-lMbigint`, counted as 8.

---

**Sample Usage**

```
$ perl -lMbigint fibo-nacci.pl

```

---

**Perl, 79 bytes**

```
use bigint;map{print+(Fibo)[$_%2].(Nacci)[$_%3]||$_,$/for$a+=$b||1,$b+=$a}1..50

```

Same as above, without requiring any command line options.

# Answer
> 2 votes
# GolfScript, 47 bytes

```
100,{1.@{.@+}*;..2%!'Fibo'*\3%!'Nacci'*+\or}%n*

```

---

**Explanation**

```
100,            # push 0..99
{               # map
  1.@           # push 1 twice, rotate counting var to the top
  {             # apply that many times
    .@+         # copy the top, rotate and add
                # if the stack is [a b], this produces: [a b b] -> [b b a] -> [b b+a]
  }*
  ;..           # discard the top, duplicate twice
  2%!'Fibo'*\   # divisible by 2 ? 'Fibo' : ''
  3%!'Nacci'*   # divisible by 3 ? 'Nacci' : ''
  +\or          # concatenate, if empty use the numeric value instead
}%
n*              # join all with a newline

```

# Answer
> 2 votes
# PARI/GP, ~~76~~ 73 bytes

*Saved three bytes courtesy of Mitch Schwartz.*

```
for(n=b=!a=1,99,b=a+a=b;print(if(b%2,"",Fibo)if(b%3,if(b%2,b,""),Nacci)))

```

---

**Sample Usage**

```
$ gp -qf < fibo-nacci.gp

```

# Answer
> 2 votes
# 05AB1E, 29 bytes

```
тENÅfDÑ23SÃvá.•iÑ+FÌ;•™#yèJ},

```

Inspired by *@Grimmy*'s bottom answer of the *1, 2, Fizz, 4, Buzz* challenge (doesn't work in the legacy version with `S` removed, because there is a bug in the compressed string `.•iÑ+FÌ;•`; the compiler probably thinks there is an open if/loop block due to the `i`/`F`..).

Try it online.

**Explanation:**

```
тE                # Loop `N` in the range [1,100]:
  NÅf             #  Get the N'th Fibonacci number
     D            #  Duplicate it
      Ñ           #  Pop this copy, and push a list of its divisors
       23SÃ       #  Only keep the divisors [2,3]
 v                #  Inner loop over those remaining divisors (or not if none are left):
  á               #   Only leave the letters of the current top of the stack
                  #   (to get rid of the Fibonacci number that was still on the stack)
   .•iÑ+FÌ;•      #   Push compressed string "fibo nacci"
            ™     #   Titlecase each: "Fibo Nacci"
             #    #   Split it on spaces: ["Fibo","Nacci"]
              yè  #   Index the current divisor `y` into it (0-based and with wraparound,
                  #   so 2 will index into "Fibo" and 3 into "Nacci")
                J #   Join everything on the stack together
 },               #  After the inner loop: pop and print the top with trailing newline

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•iÑ+FÌ;•` is `"fibo nacci"`.

# Answer
> 2 votes
# Vyxal `j`, 21 bytes

```
ÞF₁Ẏƛ₍₂₃«-∇j€₌p«⌈ǐ*∑∴

```

Try it Online!

Basically the same as the standard 11 byte FizzBuzz with a few changes

## Explained

```
ÞF₁Ẏƛ₍₂₃«-∇j€₌p«⌈ǐ*∑∴
ÞF₁Ẏ                  # The first 100 fibonacci numbers
    ƛ                 # to each item n:
     ₍₂₃              #   push a list [n % 2 == 0, n % 3 == 0]
        «-∇j€₌p«      #   push the string "fibo nacci"
                ⌈ǐ    #   split on spaces and titlecase each
                  *∑  #   vectorised string multiply and sum - this is like writing way of writing ("Fibo" * (n % 2 == 0) + "Naci" * (n % 3 == 0))
                    ∴ #   choose the greatest of n and that string. A number will always be greater than an empty string, and a non-empty string will always be greater than a number
                      # Just like the standard fizzbuzz, the `j` flag joins on newlines

```

# Answer
> 1 votes
# Pyth, 51 bytes

```
V.Wn100lHaZ+@Z_1@Z_2[1 1)|+*"Fibo"}2JPN*"Nacci"}3JN

```

Generates the Fibonacci sequence then decides what to print.

```
                    [1 1)                           - H = [1,1]
  Wn100lH                                           - While len(H)!=100
         aZ+@Z_1@Z_2                                - H.append(H[-1]+H[-2])
V.                                                  - For N in H:
                                    JPN             - Set J to the prime factorization of H
                           *"Fibo"}2J               - If there is a 2 in the factorization, add "Fibo" to a string
                                       *"Nacci"}3J  - If there is a 3 in the factorization, add "Nacci" to a string
                          +                         - Join them together
                         |                        N - If the string isn't empty (If it isn't divisible by 2 or 3), print N
                                                    - Else print the string

```

To test, try this (only does the first 20 numbers)

```
V.Wn20lHaZ+@Z_1@Z_2[1 1)|+*"Fibo"}2JPN*"Nacci"}3JN

```

# Answer
> 1 votes
## QBasic, 144 141 bytes

Not particularly small, but it beats C++ and C#

```
r=1:FOR i=1 TO 046:a$="":q=p+r
IF q MOD 2=0 THEN a$="Fibo"
IF q MOD 3=0 THEN a$=a$+"Nacci"
IF a$="" THEN a$=STR$(q)
PRINT a$:r=p:p=q:NEXT

```

No declarations, used the `:` wherever possible because it's 1 byte cheaper than `CRLF`. Prefixed a 0 to the loop counter: Basic will overflow on the 47th Fibonacci character, so compensated for the extra byte that should be there.

EDIT: Neil saved me 3 bytes: 141 bytes.

# Answer
> 1 votes
# Clojure, 127 bytes

```
(def f(lazy-cat[1 1](map +' f(rest f))))(doseq[x(take 100 f)](println(str(if(even? x)'Fibo)({0'Nacci}(mod x 3)(if(odd? x)x)))))

```

Ungolfed:

```
(def fib (lazy-cat [1 1] (map +' fib (rest fib))))

(doseq [x (take 100 fib)]
  (println (str (if (even? x) 'Fibo)
                ({0 'Nacci}
                 (mod x 3)
                 (if (odd? x) x)))))

```

Some tricks used:

* That pretty little `def` that gives the Fibonacci sequence itself is stolen shamelessly from Konrad Garus.
* `str` can take symbols as input. Crazy, right?
* Maps and default values are the shortest way to write `if` in some cases.

# Answer
> 1 votes
# CJam, 44 bytes

```
XX{_2$+}98*]{_B4bf%:!"Fibo Nacci"S/.*s\e|N}/

```

Try it online in the CJam interpreter.

# Answer
> 1 votes
## Haskell, ~~150~~ ~~143~~ ~~126~~ 118 bytes

```
main=putStr.unlines.take 100$0!1
x!y=d 3"Nacci"(d 2"Fibo"id)(show y):y!(x+y) where d z a f b|mod y z>0=f b|1>0=f""++a

```

ungolfed:

```
    main =
      putStr . unlines . take 100 $ f 0 1
    f x y
      = d 3 "Nacci" (d 2 "Fibo" id) (show y) : f y (x+y)
      where
        d z a g b
          | mod y z > 0 = g b
          | otherwise   = g "" ++ a

```

# Answer
> 1 votes
## F#, ~~202 163~~ 149 bytes

```
Seq.unfold(fun(a,b)->printfn"%s"(a%6m|>function|0m->"FiboNacci"|2m|4m->"Fibo"|3m->"Nacci"|_->string a);Some(1,(b,a+b)))(1m,1m)|>Seq.take 100|>Seq.sum

```

This is an FSX (F# script) file

# Answer
> 1 votes
# PHP, 75 bytes

```
<?for(;4e20>$b=bcadd($a,$a=$b)?:1;)echo[Fibo][++$i%3].[Nacci][$i%4]?:$b,~õ;

```

Surpisingly competitive. Requres PHP v5.5 or higher. I assume default settings, as they are without an .ini (you may disable your local .ini with the `-n` option).

---

**Sample Usage**

```
$ php -n fibo-nacci.php

```

# Answer
> 1 votes
## Javascript (ES6), ~~117~~ 108 bytes

```
let s=[1,1],i;for(i=1;i<101;s[++i]=s[i-1]+s[i-2]);s.map(n=>console.log((n%2?"":"Fibo")+(n%3?"":"Nacci")||n))

```

Try it online here.

Sadly this breaks after the 77th number, because Javascript doesn't support numbers that high. I think this is still cool enough to warrant an answer, though.

It generates the entire range of numbers, then iterates with `map` to print out the appropriate string.

Takes advantage of the fact that `console.log` prints on a new line. Could also use `alert`, but that's more annoying.

# Answer
> 1 votes
# \>\<\>, 78 bytes

```
01:n0\oo~o'F0ibo'\
aa:+1<}[3rn?/!?%3\!?%2:::::+}:}oa;?=*
ooooo'Nacci'/
00$0o\.

```

Try it online!

# Answer
> 1 votes
## Python 3, ~~100~~ ~~94~~ 88 bytes

```
a,b=0,1
exec("print(f\"{''if b%2else'Fibo'}{''if b%3else'Nacci'}\"or b);a,b=b,a+b;"*100)

```

Try it online!

# Answer
> 1 votes
# JavaScript, ~~82~~ 78 bytes

-4 bytes thanks to xigio

```
for(n=a=b=1;n++n<102;b=a+(a=b))alert((a%2n?'':'Fibo')+(a%3n?'':'Nacci')||a+'')

```

Uses JavaScript's BigInt (not supported in IE) to get to get all the way up to 100.

# Answer
> 0 votes
# Javascript ES6 112 bytes

```
var f=(a,b,c)=>{if(!(99<c)){var d=a%2?"":"Fibo",e=a%3?"":"Nacci";console.log(d||e?d+e:n);f(b,a+b,c+1)}};f(1,1,0)

```

As with other JS answers, fails after 73rd number because of js use of floats

# Answer
> 0 votes
## Perl, 146 Bytes

```
use bigint;$a=$b=1;for$i(0..99){$l=($a%2==0?2:0)+($a%3==0?1:0);print$a if$l==0;print"Fibo"if$l&2;print"Nacci"if$l&1;print"\n";($a,$b)=($b,$a+$b);}

```

Uncompressed:

```
#!/usr/bin/perl
use bigint;
$a=$b=1;
for$i(0..99) {
    $l=($a%2==0?2:0)+($a%3==0?1:0);
    print $a if $l == 0;
    print "Fibo" if $l & 2;
    print "Nacci" if $l & 1;
    print "\n";
    ($a,$b)=($b,$a+$b);
}

```

---

old version with 156 bytes...

```
use bigint;$a=$b=1;for$i(0..99){if($a%2==0){print"Fibo";print($a%3==0?"Nacci\n":"\n");}elsif($a%3==0){print"Nacci\n";}else{print"$a\n";}($a,$b)=($b,$a+$b);}

```

Uncompressed:

```
#!/usr/bin/perl
use bigint;
$a=$b=1;
for $i (0..99) {
    if($a%2 == 0) {
        print "Fibo";
        print ($a%3 == 0 ? "Nacci\n" : "\n");
    } elsif($a%3 == 0) {
        print "Nacci\n";
    } else {
        print "$a\n";
    }
    ($a,$b)=($b,$a+$b);
}

```

# Answer
> 0 votes
## Javascript, ~~157~~ 155 bytes

Golfed:

```
function g(n){a=!n%2;b=!n%3;a&&b?return "FiboNacci":;b?return "Nacci";a?return "Fibo";return n==1||n==2?1:f(n-1)+f(n-2)}for(n=100;n++>0;)console.log(f(n))

```

Ungolfed:

```
function fibonacci(n){
  if(n==1||n==2) return 1;
  return(fibonacci(n-1)+fibonacci(n-2));
}
function fibonacci2(n){
  a=!(n%2);
  b=!(n%3);
  if(a&&b) return "FiboNacci";
  if(a) return "Fibo";
  if(b) return "Nacci";
  return fibonacci(n);
}
for(n=100;n++>0;) console.log(fibonacci2(n));

```

Saved 3 bytes thanks to Cows Quack's comment

# Answer
> 0 votes
## Javascript (ES2015), 99 bytes

```
f=n=>n<3?1:f(n-1)+f(n-2);for(i=0;i<100;)console.log((f(++i)%2?'':'Fibo')+(f(i)%3?'':'Nacci')||f(i))

```

Ungolfed:

```
// fibonacci function
var fibonacci = (n) => n < 3 ? 1 : fibonacci(n-1) + fibonacci(n-2) // (implicit return)

for (var i = 0; i<100;) {
  var output = fibonacci(++i) % 2 !== 0 ? '' : 'Fibo';
  output += fibonacci(i) % 3 !== 0 ? '' : 'Nacci';
  console.log(output || fibonacci(i));
}

```

# Answer
> 0 votes
# C, 121 bytes

Had to go full `__int128_t` for this to work. `printf` doesn't know how to handle a 128bit integer, so the last four numeric values will be *printed* wrong. Still, it was fun to code, so here you go:

```
__int128_t a,b=1,c;i=100;main(){while(i--){c=b;b%=6;printf(b?b%2?b-3?"%lu\n":"Nacci\n":"Fibo\n":"FiboNacci\n",c);b=c+a;a=c;}}

```

compiled with `gcc-4.8 fibo.c` on x86\_64.

# Answer
> 0 votes
# Prolog, 182 bytes

```
f(A,B,X):-X<100,C is A+B,Z is X+1,(Y is B mod 6,Y=0->writeln('FiboNacci');(Y is B mod 2,Y=0->writeln('Fibo');(Y is B mod 3,Y=0->writeln('Nacci');writeln(B)))),f(B,C,Z).
p:-f(0,1,0).

```

Try it out online here
To run the program, use the query:

```
p.

```

# Answer
> 0 votes
**Python 3, 137 bytes**

Fun question with lots of new things I learnt in doing it. Python3 isn't a golfing language, but I suppose this isn't too bad

```
f=lambda n:n if n<2 else f(n-2)+f(n-1)
for n in range(100):t=f(-~n);x="Fibo"*(t%2==0)+"Nacci"*(t%3==0);print(x if t%2==0 or t%3==0 else t)

```

Hardest part was just to get it to only print the number

First line calculates the nth fib number. Second line joins Fibo and Nacci if it fits the rules an then it prints that string if it should else print the nth fib number.

# Answer
> 0 votes
# ///, 642 bytes

```
/A/
Fibo//B/
Nacci//*/ANacci
//^/AB
/1
1^5A
13BA
55
89*233
377^1597A
4181BA
17711
28657*75025
121393^514229A
1346269BA
5702887
9227465*24157817
39088169^165580141A
433494437BA
1836311903
2971215073*7778742049
12586269025^53316291173A
139583862445BA
591286729879
956722026041*2504730781961
4052739537881^17167680177565A
44945570212853BA
190392490709135
308061521170129*806515533049393
1304969544928657^5527939700884757A
14472334024676221BA
61305790721611591
99194853094755497*259695496911122585
420196140727489673^1779979416004714189A
4660046610375530309BA
19740274219868223167
31940434634990099905*83621143489848422977
135301852344706746049AB

```

# Answer
> 0 votes
## Perl6, ~~59~~ 58

```
say "Fibo"x$_%%2~"Nacci"x$_%%3||$_ for (1,1,*+*...*)[^100]

```

# Answer
> 0 votes
# F#, ~~153~~ 134 bytes

```
let rec L c n p=printfn"%s"(c%6m|>function|0m->"FiboNacci"|2m|4m->"Fibo"|3m->"Nacci"|_->string c);if n<100 then L(p+c)(n+1)c
L 1I 1 0I

```

Edit: Used `decimal` instead of `bigint` which allowed using pattern matching. Stole the internal logic from the other F# answer. My older filtering logic is in the below snippets.

One liner, same logic, 155 bytes:

```
let rec L c n p=printfn"%s"(if c%6I=0I then"FiboNacci"elif c%2I=0I then"Fibo"elif c%3I=0I then"Nacci"else string c);if n<100 then L(p+c)(n+1)c in L 1I 1 0I

```

Different logic, 168 bytes:

```
Seq.unfold(fun(p,c)->Some((if c%6I=0I then"FiboNacci"elif c%2I=0I then"Fibo"elif c%3I=0I then"Nacci"else string c),(c,c+p)))(0I,1I)|>Seq.take 100|>Seq.iter(printfn"%s")

```

# Answer
> 0 votes
# Swift 5.9, 129 bytes

```
let f={$0<3 ?1:f($0-UInt64(1))+f($0-2)},m="Fibo",n="Nacci"
for i in 1...30{print(i%12<1 ?m+n:i%3<1 ?m:i%4<1 ?n:"\(f(.init(i)))")}

```

---
Tags: code-golf, kolmogorov-complexity, sequence, fibonacci
---


title: Zip uneven lists

text:
# Question
Title: Zip uneven lists
In this challenge you will take two lists as input and you will *zip* them. The zip can be defined with this recursive expression:

\\$ \mathrm{zip}(a,b) = \begin{cases} \left\[\\,\\,\right\] & a = \left\[\\,\\,\right\] \\ \[a\_0\]\mid\mid\mathrm{zip}(b, t) & a = \[a\_0\] \mid\mid t \end{cases} \\$

or this Haskell program if you would like:

```
zip [] _ = []
zip (x:xs) ys = x : zip ys xs

```

In simple terms you create a list which alternates between elements of the two input lists, starting with the first element of the first list, then the first element of the second list and so on, until one of the lists doesn't have the next element, then you stop.

For example if we zip `[1,2,3,4,5]` and `[11,12,13]` we get `[1,11,2,12,3,13,4]`. Every element appears in the output except `5`, which is missing because the second list ran out before we reached it.

## Task

As input you will take two lists of positive integers and output the result of *zipping* them as described above. I use the term "first" and "second" when referring to the inputs, but you may take the two lists in the opposite order (although this choice must be consistent, you cannot e.g. swap the order of the inputs depending on what they are).

This is so the goal is to minimize your source code as scored in bytes.

## Test cases

```
[] [] -> []
[] [1,2,3] -> []
[1,2,3] [] -> [1]
[1,2] [3] -> [1,3,2]
[1,2,3,4,5] [11, 12, 13] -> [1,11,2,12,3,13,4]
[9,9,9] [8,8,8] -> [9,8,9,8,9,8]
[1,2,3] [4,5,6,7] -> [1,4,2,5,3,6]

```

---

As a word of advice if your language has a built-in which solves the task try and solve the task without the builtin and post both solutions as a single answer. It's more interesting to read solutions like that and it will almost certainly be more fun for you to golf.

# Answer
# Python 2, 32 bytes

```
def f(X,Y):print X.pop(0);f(Y,X)
```

Attempt This Online!

Ends with an error.

## Python, 35 bytes

```
f=lambda X,Y:X and X[:1]+f(Y,X[1:])
```

Attempt This Online!

No error.

# Whython, 33 bytes

```
f=lambda X,Y:[X.pop(0)]+f(Y,X)?[]
```

Attempt This Online!
> 9 votes

# Answer
# 05AB1E, ~~6~~ 5 bytes

```
ζ˜#R`

```

Input-lists in reversed order.

1 byte is added to deal with the edge case of two empty input-lists, which otherwise would result in an empty string. Otherwise the two trailing bytes could have been `н` (pop and push first inner list) instead.

Try it online or verify all test cases.

**Explanation:**

```
ζ      # Zip/transpose the two (implicit) input-lists, with space " " as filler
 ˜     # Flatten this list of pairs
  #    # Split it on spaces
   R   # Reverse the list of lists
    `  # Pop and push the lists to the stack
       # (after which the top list is output implicitly,
       # or the (implicit) input-list if both lists were empty)

```
> 6 votes

# Answer
# Haskell, 19 bytes

```
(a:x)#y=a:y#x
o#_=o
```

Attempt This Online!
> 5 votes

# Answer
# Prolog (SWI), ~~37~~ 28 bytes

*-9 bytes thanks to @DLosc*

```
[H|T]+B+[H|Y]:-B+T+Y.
A+_+A.

```

Try it online!

Port of the Haskell solution.
> 5 votes

# Answer
# , 36 bytes

```
f=\(a,b)if(sum(a))c(a[1],f(b,a[-1]))
```

Attempt This Online!

---

Slightly longer, but without recursion:

### , 43 bytes

```
\(a,b,x=rbind(c(a,0),c(b,0)))x[!cumsum(!x)]
```

Attempt This Online!
> 4 votes

# Answer
# , 19 18 17 16 bytes

```
0(i.~{.]),@|:@,:

```

Try it online!

*-1 thanks to ovs!*

Consider `1 2 3 4 f 8 9`:

* `,:` Laminate with 0-fill:

```
1 2 3 4
8 9 0 0

```
* `|:@` Transpose:

```
1 8
2 9
3 0
4 0

```
* `,@` Flatten:

```
1 8 2 9 3 0 4 0

```
* `0(i.~{.[)` Take everything up to the first 0:

```
1 8 2 9 3

```
> 3 votes

# Answer
# Retina 0.8.2, 40 bytes

```
^
;
+`;(\d+),?(.*);(.*)
$1,;$3;$2
,?;.*

```

Try it online! Link includes test cases. Explanation:

```
^
;

```

Start with an empty output list.

```
+`

```

Until the first input list is empty, ...

```
;(\d+),?(.*);(.*)

```

... match the first element of the first input list, the rest of the first input list and the second input list, and...

```
$1,;$3;$2

```

... move the first element of the input list to the output list and swap the rest of the first input list with the second list.

```
,?;.*

```

Delete the input lists.
> 2 votes

# Answer
# APL (Dyalog Unicode), 16 bytes

Anonymous tacit prefix function taking a list of two lists.

```
((>+2×⌊)/≢¨)⍴⍉∘↑

```

Try it online!
> 2 votes

# Answer
# Perl 6, 51 bytes

```
sub f(@a,@b){if @a {@a[0],|f(@b,@a[1..*])}else{()}}

```

Try it online!
> 2 votes

# Answer
# HBL, 6.5 bytes

```
?.(211.'?,(2.

```

The `branch` macro isn't implemented in the online interpreter at the moment, so here's a 7.5-byte equivalent without it:

```
?.(1(1.)('?,(2.

```

Try it!

### Explanation

The longer version implements the spec directly:

```
?.(1(1.)('?,(2.
?                If
 .               The first argument is truthy:
  (1               Cons
    (1.)           The head of the first argument to
        ('?        A recursive call with
           ,       The second argument and
            (2.    The tail of the first argument
                 Otherwise, return the first argument (empty list)

```

The `branch` macro (`2`, in golfed HBL) takes several expressions and restructures them into a function call with two arguments. With six expressions, it works like this:

```
(2 a b c d e f)  ->  (a (b c) (d e f))

```

In this case, we have:

```
2 1 1 . '? , (2.)  ->  (1 (1 .) ('? , (2.)))

```
> 2 votes

# Answer
# Ruby, 32 bytes

```
f=->a,b{r,*a=a;r ?[r,*f[b,a]]:a}

```

Try it online!
> 2 votes

# Answer
# Desmos, 139 bytes

```
l=[1...a.length+b.length]
g(A)=join(A,0l)[ceil(l/2)]
L=\{\mod(l,2)=1:g(a),g(b)\}
f(a,b)=\{a.\length=0:a,L[1...\min(\{L=0:l,l.\max+1\})-1]\}

```

Holy crap, it took me forever for me to get an actually working solution for this challenge in Desmos. I don't know if I'm severely overcomplicating this or what, but I got it to work so...

¯\\\_(ツ)\_/¯

I'll see if I can golf this some more later, too tired to think about this right now :P

Try It On Desmos!

Try It On Desmos! - Prettified
> 2 votes

# Answer
# Curry (PAKCS), 21 bytes

```
(a:b)#c=a:c#b
[]#_=[]

```

Try it online!

The Haskell answer almost works in Curry, but because of non-determinism it matches any prefix of the result. We can restrain it by adding two more bytes.
> 2 votes

# Answer
# Japt `-g`, 7 bytes

```
íV c óÏ

```

Try it

```
íV c óÏ     :Implicit input of arrays U & V
íV          :Interleave U with V, padding V with null
   c        :Flatten
     ó      :Partition before elements
      Ï     :That are falsey
            :Implicit input of first element

```

## 5 bytes

By taking input as a 2D array, with the order reversed.

```
ÕcÔóÏ

```

Try it

```
ÕcÔóÏ     :Implicit input of 2D array
Õ         :Transpose, padding the first array with null
 c        :Flat map
  Ô       :Reverse
   óÏ     :As above
          :Implicit input of first element

```
> 2 votes

# Answer
# APL+WIN, 27 bytes

Prompts for two lists as a nested vector

```
(^\0≠v)/v←,⍉⊃(⌈/⍴¨v)↑¨v←,¨⎕

```

Try it online! Thanks to Dyalog APL Classic
> 1 votes

# Answer
# Charcoal, 13 bytes

```
ＵＭθ⮌ιＷ§θⅉ⟦Ｉ⊟ι

```

Try it online! Takes input as a pair of lists. Explanation:

```
ＵＭθ⮌ι

```

Reverse each of the two lists.

```
Ｗ§θⅉ

```

Cyclically index the lists according to the number of values already output and repeat until that list is empty.

```
⟦Ｉ⊟ι

```

Output the "next" value from that list on its own line.
> 1 votes

# Answer
# Jelly, 5 bytes

Uses Kevin Cruijssen's method from their 05AB1E answer.

```
z⁶FḲḢ

```

A monadic Link that accepts a pair of lists, `[a, b]`, and yields a zipped list.

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

### How?

```
z⁶FḲḢ - Link: pair of lists [a,b]
 ⁶    - space character
z     - transpose [a,b] with space-filler
  F   - flatten
   Ḳ  - split at spaces
    Ḣ - head

```
> 1 votes

# Answer
# Factor, ~~43~~ 39 bytes

```
[ f pad-longest vmerge { f } split1 . ]

```

Try it online!

## Explanation

```
                ! { 1 2 3 4 5 } { 11 12 13 }
f               ! { 1 2 3 4 5 } { 11 12 13 } f
pad-longest     ! { 1 2 3 4 5 } { 11 12 13 f f }
vmerge          ! { 1 11 2 12 3 13 4 f 5 f }
{ f }           ! { 1 11 2 12 3 13 4 f 5 f } { f }
split1          ! { 1 11 2 12 3 13 4 } { 5 f }
.               ! { 1 11 2 12 3 13 4 }

```
> 1 votes

# Answer
# Husk, 5 bytes

```
↑_ΣT0

```

Try it online!

Input is list of the two lists.

`T`ransposes using `0` to fill shorter rows, flattens (`Σ`) the result, and  takes the longest prefix with all elements that are truthy using the function `_` (=negate; it would have been more-intuitive to use the `I`dentity function here, but for reasons that I don't understand this doesn't seem to work).

Pretty-much the same approach as Kevin Cruijssen's answer but independently found.

Note that the Husk interpreter will not accept input consisting of only empty lists, presumably since it's unable to infer their type. The TIO link above successfully runs all the test cases (including the first, only-empty-lists one), since these are grouped together and run side-by-side, allowing the interpreter to infer that all lists are of numbers; but it fails when given the first test case on its own. I can't currently see a way to avoid this.
> 1 votes

# Answer
# JavaScript (ES6), 33 bytes

```
f=([v,...a],b)=>v?[v,...f(b,a)]:a

```

Try it online!
> 1 votes

# Answer
# x86 machine code (32-bit), 39 bytes

```
\x31\xC0\x89\xC5\x55\x87\x2C\x24\x39\xCD\x74\x19\xFF\x34\xAE\x8F\x04\x87
\x45\x40\x87\x2C\x24\x39\xD5\x74\x0A\xFF\x34\xAB\x8F\x04\x87\x45\x40\xEB
\xE0\x5D\xC3

```

Try it online!

The algorithm is quite straightforward, but 32-bit x86 *really* needs more registers. Some ugly stack hacks are used to cope with the lack of registers.

The test cases in TIO relies on a GCC extension supporting C arrays of length 0. ISO C and C++ forbid 0-length arrays.

Since OP didn't specify the upper bound of integers, I tried to find some clever way using an array of bytes, and interleaving them with `pdep` or some SSE shuffle instruction, but that ended up using too many bytes.

```
# edi: dst, esi: arr0, ecx: len0, ebx: arr1, edx: len1
# eax: return, ebp: clobber

0:  31 c0                   xor    eax,eax
2:  89 c5                   mov    ebp,eax
4:  55                      push   ebp
5:  87 2c 24                xchg   DWORD PTR [esp],ebp
8:  39 cd                   cmp    ebp,ecx
a:  74 19                   je     0x25
c:  ff 34 ae                push   DWORD PTR [esi+ebp*4]
f:  8f 04 87                pop    DWORD PTR [edi+eax*4]
12: 45                      inc    ebp
13: 40                      inc    eax
14: 87 2c 24                xchg   DWORD PTR [esp],ebp
17: 39 d5                   cmp    ebp,edx
19: 74 0a                   je     0x25
1b: ff 34 ab                push   DWORD PTR [ebx+ebp*4]
1e: 8f 04 87                pop    DWORD PTR [edi+eax*4]
21: 45                      inc    ebp
22: 40                      inc    eax
23: eb e0                   jmp    0x5
25: 5d                      pop    ebp
26: c3                      ret

```
> 1 votes

# Answer
# PowerShell Core, 45 bytes

```
param($a,$b)for(;$a){$h,$t=$a
$a,$b=$b,$t
$h}

```

Try it online!

One test case returns `1` instead of `[1]` as PowerShell tends to flatten arrays

*-1 byte thanks to mazzy*
> 1 votes

# Answer
# PARI/GP, 38 bytes

```
f(a,b)=if(a,concat(a[1],f(b,a[^1])),a)
```

Attempt This Online!

`a[^1]` means skiping the first item in `a`.
> 1 votes

# Answer
# Bash, 27 bytes

```
read x<$1&&echo $x&&f $2 $1

```

Try it online!

Port of pxeger's python solution to Bash.

Input lists are taken as files (one entry per line). Output is one entry per line. Output contains extra blanks, which may be illegal and could be fixed at the price of some bytes, but I liked the simplicity of the translation.
> 1 votes

# Answer
# Julia 1.0, 25 bytes

```
a^b=@show(a[1])b^a[2:end]

```

Try it online!

prints the values and ends with an error

# Julia 1.0, 30 bytes

```
>(b)=[]
>(b,a,A...)=[a;A>b...]

```

Try it online!

expects `b>a...`, returns an actual list
> 1 votes

# Answer
# C (gcc), 68 bytes

Takes `0`-terminated arrays as input.

```
f(a,b)int*a,*b;{for(;*a;!*b?a=b:b++)printf("%d %d "+3*!*b,*a++,*b);}

```

Try it online!
> 1 votes

# Answer
# Vyxal, 6 bytes

```
Zf0€÷^

```

Try it Online!

Looks like 05AB1E beats Vyxal this time. Takes input in reversed order.

```
Zf0€÷^ # Leaving out this comment makes the explanation kinda feel empty
Z      # Zip the lists
 f     # Flatten
  0€   # Split on 0
    ÷  # Push every item
     ^ # Reverse the stack

```

# Vyxal, 6 bytes

```
Zf:0ḟẎ

```

Try it Online!

A slightly different approach. Still 6 bytes.

```
Zf:0ḟẎ # Leaving out this comment makes the explanation kinda feel empty
Z      # Zip the lists
 f     # Flatten
  :    # Duplicate the top of the stack
   0ḟ  # Index of the first 0
     Ẏ # Take everything up until that index

```

# Vyxal, 5 bytes

```
Zf0€h

```

Try it Online!

Takes input in reversed order. Returns 0 for the case of 2 empty lists, so does not meet the spec.

```
Zf0€h # Leaving out this comment makes the explanation kinda feel empty
Z     # Zip the 2 lists
 f    # Flatten them
  0€  # Split on 0
    h # Get the first item

```
> 1 votes

# Answer
# Uiua, 9 bytes SBCS

```
↙⊗0.♭⍉⬚0⊟

```

Try it!

Port of Jonah's J answer.
> 1 votes

# Answer
# Vyxal 3, 5 bytes

```
Zf0sh

```

Try it Online!

takes input in reverse order
> 1 votes

# Answer
# Perl 5 `-MList::Util=min`, 65 bytes

```
sub{($a,$b)=@_;grep/./,map{$_,shift@$b}@$a[0..min(@$b+0,$#{$a})]}

```

Try it online!
> 1 votes

# Answer
# Pip `-x`, 9 bytes

```
Wb::aPPOb

```

Takes two Pip lists as command-line arguments; outputs to stdout, one number per line. Attempt This Online!

### Explanation

```
Wb::aPPOb
           ; a and b are command-line args
W          ; Loop while
 b::a      ; b, after being swapped with a, is truthy (nonempty):
      POb  ;   Pop the first element from b
     P     ;   and print it

```
> 1 votes

# Answer
# Pip `-xp`, 10 bytes

Only works on Pip 1.2, currently available in alpha at DSO.

```
FI\$&FLZDg

```

Takes two Pip lists as command-line arguments; outputs a Pip list to stdout. Try It Online!

### Explanation

Port of Jonah's J answer, among others:

```
FI\$&FLZDg
         g  ; List of command-line args (i.e. list of lists of numbers)
       ZD   ; Zip (transpose), filling with a default value of "" (which is falsey)
     FL     ; Flatten
  \$&       ; Scan on logical AND, making everything after the first falsey value falsey
FI          ; Filter, keeping only truthy values

```
> 1 votes

# Answer
# Arturo, 42 bytes

```
f:$[a,b][([]=a)?->a->@[a\0]++f b drop a 1]

```

Try it

```
f:$[a,b][          ; a function f taking two lists a and b
  ([]=a)?          ; is a empty?
  ->a              ; if so, return a
  ->               ; otherwise,
    @[a\0]         ; the first element of a as a list
    ++             ; concatenated with
    f b drop a 1   ; the result of calling f with b and a without its first element
]                  ; end function

```
> 0 votes

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