title: Wind me a number snake!

text:
# Question
Title: Wind me a number snake!
Given an input integer `n`, draw a number snake, that is, a grid measuring `n x n` consisting of the numbers `1` through `n^2` that are wound around each other in the following fashion:

Input `n = 3`:

```
7 8 9
6 1 2
5 4 3

```

Input `n = 4`:

```
 7  8  9 10
 6  1  2 11
 5  4  3 12
16 15 14 13

```

Input `n = 5`:

```
21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

```

(Inspired by this problem from Project Euler.)

This is , the shortest answer in bytes wins!

# Answer
> 44 votes
# MATL, 3 bytes

```
1YL

```

Try it online!

### Explanation

Built-in... ¯\\\_(ツ)\_/¯

# Answer
> 18 votes
# C#, ~~203~~ ~~202~~ ~~196~~ ~~193~~ 178 bytes

```
n=>{var r=new int[n,n];for(int o=n-2+n%2>>1,i=r[o,o]=1,c=2,w=o,h=o,b=1-2*(i%2),j;n>i++;){r[h,w+=b]=c++;for(j=0;j<i-1;++j)r[h+=b,w]=c++;for(j=0;j<i-1;++j)r[h,w-=b]=c++;}return r;}

```

*Saved a byte thanks to @StefanDelport.*
*Saved 22 bytes thanks to @FelipeNardiBatista.*

This works by the following observation of how the squares are built up:

As you can see each bit is added on to the previous square. For even numbers we go right of where we were, down till were one lower than where the square was and then left to the end. Odd numbers are essentially the opposite, we go left one, up till were one above the current height and then right to the end.

Full/Formatted version:

```
using System;
using System.Linq;

class P
{
    static void Main()
    {
        Func<int, int[,]> f = n =>
        {
            var r = new int[n, n];
            for (int o = n - 2 + n % 2 >> 1, i = r[o, o] = 1, c = 2, w = o, h = o, b = 1 - 2 * (i % 2), j; n > i++;)
            {
                r[h, w += b] = c++;

                for (j = 0; j < i - 1; ++j)
                    r[h += b, w] = c++;

                for (j = 0; j < i - 1; ++j)
                    r[h, w -= b] = c++;
            }

            return r;
        };

        Console.WriteLine(String.Join("\n", f(3).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
        Console.WriteLine(String.Join("\n", f(4).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
        Console.WriteLine(String.Join("\n", f(5).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");

        Console.ReadLine();
    }
}

public static class ArrayExtensions
{
    public static T[][] ToJagged<T>(this T[,] value)
    {
        T[][] result = new T[value.GetLength(0)][];

        for (int i = 0; i < value.GetLength(0); ++i)
            result[i] = new T[value.GetLength(1)];

        for (int i = 0; i < value.GetLength(0); ++i)
            for (int j = 0; j < value.GetLength(1); ++j)
                result[i][j] = value[i, j];

        return result;
    }
}

```

# Answer
> 15 votes
# Dyalog APL, ~~70~~ ~~56~~ ~~45~~ 41 bytes

```
,⍨⍴∘(⍋+\)×⍨↑(⌈2÷⍨×⍨),(+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳

```

Try it online!

**How?**

```
(+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳

```

calculates the differences between the indices; `1` and `¯1` for right and left, `¯⍵` and  for up and down.

`1,⊢,¯1,-` comes as `1 ⍵ ¯1 ¯⍵`, `+⍨⍴` stretches this array to the length of `⍵×2`, so the final `2/⍳` can repeat each of them, with a repetition count increasing every second element:

```
      (1,⊢,¯1,-) 4
1 4 ¯1 ¯4
      (+⍨⍴1,⊢,¯1,-) 4
1 4 ¯1 ¯4 1 4 ¯1 ¯4
      (2/⍳) 4
1 1 2 2 3 3 4 4
      ((+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳) 4
1 4 ¯1 ¯1 ¯4 ¯4 1 1 1 4 4 4 ¯1 ¯1 ¯1 ¯1 ¯4 ¯4 ¯4 ¯4

```

then,

```
(⌈2÷⍨×⍨),

```

prepends the top-left element of the spiral,

```
×⍨↑

```

limit the first ⍵2 elements of this distances list,

```
+\

```

performs cumulative sum,

grades up the indices (`⍵[i] = ⍵[⍵[i]]`), to translate the original matrix with the indices of every element, and finally

```
,⍨⍴

```

shapes as a `⍵×⍵` matrix.

# Answer
> 9 votes
# C, ~~321~~ ~~307~~ ~~295~~ ~~284~~ ~~283~~ 282 bytes

*Thanks to both @Zachary T and @Jonathan Frech for golfing a byte!*

```
#define F for(b=a;b--;)l
i,j,k,a,b,m;**l;f(n){n*=n;l=calloc(a=m=3*n,4);F[b]=calloc(m,4);for(l[i=j=n][j]=a=k=1;n>k;++a){F[i][++j]=++k;F[++i][j]=++k;++a;F[i][--j]=++k;F[--i][j]=++k;}for(i=0;i<m;++i,k&&puts(""))for(j=k=0;j<m;)(a=l[i][j++])>0&&a<=n&&printf("%*d ",(int)log10(n)+1,k=a);}

```

Allocates a two-dimensional array of zeroes, then starts filling it from somewhere in the middle. Lastly the values that are larger than zero but smaller than or equal to the square of the input are printed.

Try it online!

**Formatted:**

```
#define F for(b=a; b--;)l
i, j, k, a, b, m; **l;
f(n)
{
    n *= n;
    l = calloc(a=m=3*n, 4);

    F[b] = calloc(m, 4);

    for(l[i=j=n][j]=a=k=1; n>k; ++a)
    {
        F[i][++j] = ++k;
        F[++i][j] = ++k;
        ++a;

        F[i][--j] = ++k;
        F[--i][j] = ++k;
    }

    for(i=0; i<m; ++i, k&&puts(""))
        for(j=k=0; j<m;)
            (a=l[i][j++])>0 && a<=n && printf("%*d ", (int)log10(n)+1, k=a);
}

```

# Answer
> 7 votes
# APL (Dyalog Classic), ~~32~~ 29 bytes

```
1+×⍨-{⊖∘⌽⍣⍵⌽{⌽⍉,⌸⍵+≢⍵}⍣2⍣⍵⍪⍬}

```

Try it online!

Uses `⎕io←1`. Starts with a 0-by-1 matrix (`⍪⍬`). 2N times (`⍣2⍣⍵`) adds the height of the matrix (`≢⍵`) to each of its elements, puts `1 2...height` on its right (`,⌸`), and rotates (`⌽⍉`). When that's finished, corrects the orientation of the result (`⊖∘⌽⍣⍵⌽`) and reverses the numbers by subtracting them from N2+1 (`1+×⍨-`).

# Answer
> 6 votes
# PHP, 192 bytes

```
for($l=strlen($q=($a=$argn)**2)+$d=1,$x=$y=$a/2^$w=0;$i++<$q;${yx[$w%2]}+=$d&1?:-1,$i%$d?:$d+=$w++&1)$e[$x-!($a&1)][$y]=sprintf("%$l".d,$i);for(;$k<$a;print join($o)."\n")ksort($o=&$e[+$k++]);

```

Try it online!

Same way build a string instead of an array

PHP, 217 bytes

```
for($l=strlen($q=($a=$argn)**2)+$d=1,$x=$y=($a/2^$w=0)-!($a&1),$s=str_pad(_,$q*$l);$i++<$q;${yx[$w%2]}+=$d&1?:-1,$i%$d?:$d+=$w++&1)$s=substr_replace($s,sprintf("%$l".d,$i),($x*$a+$y)*$l,$l);echo chunk_split($s,$a*$l);

```

Try it online!

# Answer
> 6 votes
# PHP, ~~185 176~~ 174 bytes

```
for(;$n++<$argn**2;${xy[$m&1]}+=$m&2?-1:1,$k++<$p?:$p+=$m++%2+$k=0)$r[+$y][+$x]=$n;ksort($r);foreach($r as$o){ksort($o);foreach($o as$i)printf(" %".strlen($n).d,$i);echo"
";}

```

Run as pipe with `-nR` or test it online.

**breakdown**

```
for(;$n++<$argn**2;     # loop $n from 1 to N squared
    ${xy[$m&1]}+=$m&2?-1:1, # 2. move cursor
    $k++<$p?:               # 3. if $p+1 numbers have been printed in that direction:
        $p+=$m++%2+             # increment direction $m, every two directions increment $p
        $k=0                    # reset $k
)$r[+$y][+$x]=$n;           # 1. paint current number at current coordinates

ksort($r);              # sort grid by indexes
foreach($r as$o){       # and loop through it
    ksort($o);              # sort row by indexes
    foreach($o as$i)        # and loop through it
        printf(" %".strlen($n).d,$i);   # print formatted number
    echo"\n";               # print newline
}

```

# Answer
> 5 votes
# Mathematica, 177 bytes

```
(n=#;i=j=Floor[(n+1)/2];c=1;d=0;v={{1,0},{0,-1},{-1,0},{0,1}};a=Table[j+n(i-1),{i,n},{j,n}];Do[Do[Do[a[[j,i]]=c++;{i,j}+=v[[d+1]], {k,l}];d=Mod[d+1,4],{p,0,1}],{l,n-1}];Grid@a)&

```

# Answer
> 5 votes
# Python 3, ~~249~~ 247 bytes

I initialize an 2D array and find the starting point, which is the center for odd n or offset (-1,-1) for even n, then scale the fill/cursor pattern with the current 'ring' number. I feel like I'm missing a trick for interpreting the directions but I haven't come up with anything cheaper.

```
def f(n):
 M=[n*[0]for a in range(n)]
 x=y=n//2-1+n%2
 M[x][y]=i=s=1
 while 1:
  t=s*2
  for d in'R'+'D'*(t-1)+'L'*t+'U'*t+'R'*t:
   if i==n*n:print(*M,sep='\n');return
   v=[1,-1][d in'LU']
   if d in'UD':x+=v
   else:y+=v
   M[x][y]=i=i+1
  s+=1

```

Try it online!

-2 thanks to Zachary T!

# Answer
> 5 votes
# C++, ~~245~~ 228 bytes

```
void f(){for(int i=0,j=-1,v,x,y,a,b;i<n;i++,j=-1,cout<<endl)while(++j<n){x=(a=n%2)?j:n-j-1;y=a?i:n-i-1;v=(b=y<n-x)?n-1-2*(x<y?x:y):2*(x>y?x:y)-n;v=v*v+(b?n-y-(y>x?x:y*2-x):y+1-n+(x>y?x:2*y-x));cout<<setw(log10(n*n)+1)<<v<<' ';}}

```

Try it online!

The function calculates and prints the value of each number of the matrix depending on its *x, y* position by applying this logic:

**Formatted version**:

```
#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;

void f(int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            int value = 0;

            // Invert x and y when n is even
            int x = n % 2 == 0 ? n - j - 1 : j;
            int y = n % 2 == 0 ? n - i - 1 : i;
            if (y < (n - x))
            {
                // Left-top part of the matrix
                int padding = x < y ? x : y;
                value = n - 1 - padding * 2;
                value *= value;
                value += y >= x ? n - x - y : n + x - y - (y * 2);
            }
            else
            {
                // Right-bottom part of the matrix
                int padding = x > y ? n - x : n - y;
                value = n - padding * 2;
                value *= value;
                value += x > y ? y - padding + 1 : n + y - x - (padding * 2) + 1;
            }

            cout << setw(log10(n * n) + 1);
            cout << value << ' ';
        }

        cout << endl;
    }
}

int main()
{
    int n;
    while (cin >> n && n > 0)
    {
        f(n);
        cout << endl;
    }
}

```

# Answer
> 5 votes
# Wolfram Language (Mathematica), ~~(...)~~ 83 bytes

Byte measured in UTF8, `\[LeftFloor]` () and `\[RightFloor]` () cost 3 bytes each. Mathematica doesn't have any special byte character set.

```
Table[Max[4x^2-Max[x+y,3x-y],4y
y-{x+y,3y-x}]+1,{y,b+1-#,b=⌊#/2⌋},{x,b+1-#,b}]&

```

Try it online!

---

Uses the closed form for each of the 4 cases, then takes the maximum carefully to get the desired result.

Returns a 2D array of integers. I'm not sure if this is allowed, and although it has been asked in the comments, the OP didn't reply.

# Answer
> 4 votes
## Clojure, 206 bytes

```
(defmacro F[s]`(if(~'r(+ ~'p ~'v ~s))~'v ~s))
#(loop[i 1 p(*(quot(dec %)2)(inc %))v 1 r{}](if(<(* % %)i)(partition %(map r(range i)))(recur(inc i)(+ p v)({1(F %)-1(F(- %))%(F -1)(- %)(F 1)}v)(assoc r p i))))

```

I guess this is a decent start, builds the board in sequence to a hash-map and then partitions it into `n x n` lists. That `defmacro` ended up being quite long, but the code is still shorter with it than without. Is there a more succint syntax to describe it?

Bulk of bytes calculate the starting point, and build the look-up logic of the next velocity `v`. Perhaps a nested `vec` would be better, but then you've got two indexes and velocities to keep track of.

# Answer
> 3 votes
# , 41 bytes

```
(]|.@|:@[&0](|.@|:@,.*/@$+#\)@]^:[1:)2*<:

```

Try it online!

Does the same thing as ngn’s APL submission but starts with a 1-by-1 matrix and repeats 2×N−2 times.

# Answer
> 1 votes
# Python 165 (or 144)

```
from pylab import *
def S(n):
 a=r_[[[1]]];r=rot90;i=2
 while any(array(a.shape)<n):
  q=a.shape[0];a=vstack([range(i,i+q),r(a)]);i+=q
 if n%2==0:a=r(r(a))
 print(a)

```

This creates a numpy array, then rotates it and adds a side until the correct size is reached. The question didn't specify if the same start point needs to be used for even and odd numbers, if that's not the case the line `if n%2==0:a=r(r(a))` can be removed, saving 21 bytes.

# Answer
> 1 votes
# , 41 bytes

```
,~$[:/:[:+/\_1|.1&,(]##@]$[,-@[)2}:@#1+i.

```

## standard formatting

```
,~ $ [: /: [: +/\ _1 |. 1&, (] # #@] $ [ , -@[) 2 }:@# 1 + i.

```

This approach is based off *At Play With J Volutes* (Uriel's APL uses a similar technique).

It's unexpected and elegant enough to justify a 2nd J answer, I thought.

Essentially, we don't do anything procedural or even geometric. Instead, we arithmetically create a simple sequence that, when scan summed and graded up, gives the correct order of the spiraled number from left to right, top to bottom. We then shape that into a matrix and are done.

I'll add a more detailed explanation when time permits, but the linked article explains it in depth.

Try it online!

# Answer
> 1 votes
# K (ngn/k), 38 bytes

```
{(x,x)#<0,+\(,/-:\1,x)4!-1_&1+-1_&x#2}

```

Attempt This Online!

# Answer
> 0 votes
# Python 3 (Stackless), ~~192~~ ~~188~~ ~~179~~ 150 bytes

```
lambda n:[list(map(v,list(range(t-n,t)),[y]*n))for t in[1+n//2]for y in range(n-t,-t,-1)]
v=lambda x,y,r=0:y>=abs(x)and(3-2*r+4*y)*y+x+1or v(y,-x,r+1)

```

Try it online!

The algorithm here is to form a phasor for each coordinate in the grid, and then rotate it 90-degrees clockwise until the phasor lies between the upper diagonals. A simple formula can be used to calculate the value based on the coordinates and the number of clockwise rotations: $$ (2y+1)^2-(y-x)-2yr $$

Saved 4-bytes since 90-degree phasor rotation is easily done without complex numbers

# Answer
> 0 votes
# , 183 bytes

```
x=scan()
b=t(d<-1)
while(2*x-1-d){m=max(b)
y=(m+1):(m+sum(1:dim(b)[2]|1))
z=d%%4
if(z==1)b=cbind(b,y)
if(z==2)b=rbind(b,rev(y))
if(z==3)b=cbind(rev(y),b)
if(z==0)b=rbind(y,b)
d=d+1}
b

```

Try it online!

Output is a matrix snake (or snake matrix, whatever). It's probably not the most efficient method, and it could likely be golfed, but I thought it was worth showing. I'm rather proud of this actually!

The method builds the matrix from the inside out, always appending an additional number of integers equal to the number of columns in the matrix before appending. The pattern that follows is either binding by columns or by rows, while also reversing some values so they are appended in the correct order.

# 193 bytes

Exact same as above, but final `b` is

```
matrix(b,x)

```

Try it online!

which gives slightly cleaner output, but I didn't see any special criteria for output, so the first answer should work if I'm not mistaken.

---
Tags: code-golf
---


title: Turn strings into hexagonal spirals!

text:
# Question
Title: Turn strings into hexagonal spirals!
## Goal

Write a function or a program that when given a string, for example `"The quick brown fox jumps over the lazy dog"`, outputs:

```
     T h e   q u
                i
   e r   t h e   c
  v               k
 o             l
                a   b
 s             z   r
  p           y   o
   m   g o d     w
    u           n
     j   x o f

```

## Rules

1. You may not truncate the input!
2. The output must be text and formatted as above.
3. The hexagons must have the shortest possible side length. This is wrong for example:

```
      T h e   q u i
                   c
      l a z y   d   k
   e             o
  h               g   b
 t                     r
                        o
 r                     w
  e                   n
   v
    o               f
                   o
      s p m u j   x

```

The outer hexagon above has a side of 7 characters, but clearly it is not optimal. A spiral with an outer hexagon with a side of 6 characters would be able to store all the characters of the string too (as shown previously).
4. The spiral must look *like* an Archimedean spiral:

* This is **not** correct:
    ```
         T h e   q u
                    i
       e r   t h e   c
      v               k
     o             l
        g         a     b
     s   o d   y z     r
      p               o
       m             w
        u           n
         j   x o f

    ```
5. You may start the spiral at any point you like and even go anti-clockwise. Any of these would be valid:

```
     . . . . . .              . . . . . .              u q   e h T
    .           .            .           .            i
   x   j u m p   .          j u m p s     .          c   e h t   r e
  o           s   .                    o   T        k               v
 f   a z y         .      x   y   d o   v   h          l   . . . .   o
    l       d   o   T    o   z       g   e   e    b   a   .       .
 n       g o   v   h      f   a   . .   r          r   z   . .   .   s
  w   e       e   e            l           q        o   y       .   p
   o   h t   r              n     e h t   u          w     d o g   m
    r           q            w           i            n           u
     b   k c i u              o r b   k c                f o x   j

```

The dots (`'.'`) indicate "cells" that weren't used. You **don't** have to include them.
6. It does not matter if the string is not long enough to form a complete spiral, but the rules above must still hold.

This is (no loopholes!), so the shortest answer in terms of bytes wins!

---

## More examples

Note that there are more than one valid outputs due to rule 5.

`ABCDE` \\$\rightarrow\\$

```
 A B
    C
 E D

```

`#####################################################` \\$\rightarrow\\$

```
     # # # # # #
                #
   # # # # # #   #
  #           #   #
 #   # # # #   #   #
#   #       #   #   #
 #   #   # #   #   #
  #   #       #   #
   #   # # # #   #
    #           #
     # # # # # #

```

`0123456789ABCDEF` \\$\rightarrow\\$

```
   0 1 2 3
          4
           5
F           6
 E         7
  D       8
   C B A 9

```

`-\\\|///-----\\\|/-----\|/---\---` \\$\rightarrow\\$

```
            -
             \
  - - - - -   \
 /         \   \
|   - - -   |   |
 \   \     /   /
  \   - - -   /
   \         /
    - - - - -

```

`Racecar, racecar!` \\$\rightarrow\\$

```
      c e c a
 R   a       r
  a   r !
   c       ,
    e c a r

```

`0123456789AB` \\$\rightarrow\\$

```
  0 1 2
       3
A B     4
 9     5
  8 7 6

```

# Answer
# Charcoal, 61 bytes

```
Ｗφ«⎚≔⪪⮌θ¹φ⊞υＬυＦ⁺⭆Φ⮌υ﹪λ²⮌⭆⭆134570×μκ⎇›ν¹μ∧⁼κ¹ω0¿φ«Ｐ⊟φＭ⊕№04κ✳Ｉκ

```

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

```
Ｗφ«

```

Repeat until the string is successfully turned into a spiral. (`φ` is actually a predefined variable here, which is why the loop succeeds at least once.)

Start by clearing any output from the previous loop.

```
≔⪪⮌θ¹φ

```

Reset the variable to the input, split into characters and reversed to that its characters can be consumed more easily.

```
⊞υＬυ

```

Build up a list of integers for each pass. (The zero entry is useless and serves only to save bytes.)

```
Ｆ⁺⭆Φ⮌υ﹪λ²⮌⭆⭆134570×μκ⎇›ν¹μ∧⁼κ¹ω0«

```

Loop over a list of directions for the spiral. This starts with the list of integers, which is reversed and then alternating elements are picked out (again in a byte-saving manner, requiring a further pass through the loop). For each integer, the characters `075431` (representing the directions) are each repeated that many times, except that the last two `11` are replaced with `00` unless they are `31` in which case they are deleted. (This is actually done on the reverse of the strings as that's golfier.) A final `0` is appended before the list is looped over.

```
¿φ«

```

If there are still more characters to print, then:

```
Ｐ⊟φ

```

Output the next character without moving the cursor.

```
Ｍ⊕№04κ✳Ｉκ

```

Move two steps horizontally or one step diagonally.
> 5 votes

# Answer
# Jelly, 63 bytes

```
JḂḤØ-;+2ÄÄ<LS‘RṚm2x6IŻN+Ɗ+Ɗ’Jx$Żị“¬½®‘d4¤’;C¤+\_«/$‘ŒṬ€ṁa"⁸o/o⁶

```

A monadic Link that accepts a list of characters and yields a list of lines.

Starts at the top-left of the smallest outer hexagon and spirals inwards, clockwise.

**Try it online!** Or see a test series.

### How?

Split into two parts, for ease of reading...

```
JḂḤØ-;+2ÄÄ<LS‘RṚm2x6IŻN+Ɗ+Ɗ’Jx$Ż   - Link: list of characters, "Chars"
J                                  - 1-indexed indices -> [1,2,...,len(Chars)]
 Ḃ                                 - mod two -> [1,0,1,0,1,0,...]
  Ḥ                                - double -> [2,0,2,0,2,0,...]
   Ø-;                             - prefix with [-1,1] -> [-1,1,2,0,2,0,2,0,...]
      +2                           - add two -> [1,3,4,2,4,2,4,2,...]
        Ä                          - cumulative sums -> [1,4,8,10,14,16,20,24,...]
         Ä                         - cumulative sums -> [1,5,13,23,37,53,73,95,...]
          <L                       - less than length(Chars)?
                                       e.g. L=9 -> [1,1,0,0,0,0,0,0,0,0,0]
            S                      - sum -> outer hexagon side length
             ‘                     - increment
              R                    - range -> [1,2,3,...,side-1,side,side+1]
               Ṛ                   - reverse -> [side+1,side,side-1,...,3,2,1]
                m2                 - modulo-2 slice -> [side+1,side-1,side-3,...]
                  x6               - repeat each element six times
                          Ɗ        - last three links as a monad - f(X):
                    I              -   deltas of X
                        Ɗ          -   last three links as a monad - f(Y):
                     Ż             -     prepend a zero to Y
                      N            -     negate
                       +           -     add Y (vectorises)
                         +         -   add X
                           ’       - decrement (vectorises)
                                       -> number of steps to take in each direction
                                          - has excess such instructions
                              $    - last two links as a monad f(Z):
                            J      -   1-indexed indices
                             x     -   repeat (vectorises)
                                         -> 1, 7, 13, ... represent East
                                            2, 8, 14, ... represent South-East
                                            etc...
                               Ż   - prefix a zero (to have a starting point)
                                       -> "Instructions"

```

```
ị“¬½®‘d4¤’;C¤+\_«/$‘ŒṬ€ṁa"⁸o/o⁶ - ...continued...
            ¤                    - nilad followed by links as a nilad:
        ¤                        -   nilad followed by links as a nilad:
 “¬½®‘                           -     code-page indices -> [7, 10, 8]
      d4                         -     div-mod four -> X = [[1,3],[2,2],[2,0]]
         ’                       -   decrement X        -> [[0,2],[1,1],[1,-1]]
           C                     -   complement X       -> [[0,-2],[-1,-1],[-1,1]]
          ;                      -   concatenate -> [[0,2],[1,1],[1,-1],[0,-2],[-1,-1],[-1,1]]
                                                    -> "Directions"
ị                                - {Instructions} index into {Directions}
              \                  - cumulative reduce by:
             +                   -   addition (vectorises)
                  $              - last two links as a monad:
                 /               -   reduce by:
                «                -     minimum (vectorises)
               _                 -   subtract -> normalises the minimal values to 0
                   ‘             - increment -> make them 1-indexed
                    ŒṬ€          - for each: 2d array of zeros with a one
                                             at the given 2d index
                       ṁ         - mould like Chars (keep first length(Chars))
                        a"⁸      - zipped logical AND (vectorises) Chars
                            /    - reduce by:
                           o     -   logical OR (i.e. layer these together)
                             o⁶  - logical OR (vectorise) with a space character
                                     (replaces remaining zeros with spaces)

```
> 3 votes

# Answer
# Haskell, 360 bytes

```
import Data.Array
t(a,b)(c,d)=(a+c,b+d)
s i=[[a!(r,c)|c<-[b..d]]|((p,b),(q,d))<-[b],r<-[p..q]]where
 d=zip(scanl t(0,0)$concat$zipWith replicate(concat$iterate(map(2+))[1,1,1,3,1,3])$cycle[(0,2),(-1,1),(-1,-1),(0,-2),(1,-1),(1,1)])$reverse i
 b=foldl(\((p,b),(q,d))((r,c),e)->((min p r,min b c),(max q r,max d c)))((0,0),(0,0))d
 a=accumArray(flip const)' 'b d

```

Try it online!

```
    o u n d   l
   r           i
      ,   b a   k
 g   d       b   e
n   r   ! y
 i   o       a
  n   c e r
   n           I
    i p s   m '

```
> 2 votes

# Answer
# K (ngn/k), 127 119 115 bytes

```
{(0N,w)#@[""@!4*s*w;(#x)#+\(2*s),(|2,,/--:\(-1 1+w:-2+8*s),2)7!&-2_,/+|2,(-2*|&5 1)+6#,|-1+2*1+!s:-_-%-6!1+#x;:;x]}

```

-8 : squeezed
-4 : and again

Attempt This Online!
> 2 votes

# Answer
## Javascript, 365 bytes

```
f=s=>(b=Math.abs,m=Math.max,w=h=3,x=-2,y=0,l=[...s].reverse().map(n=>(c=y>0?b(x)<y||-x==y?[x+=2,y]:x>0?[++x,--y]:[++x,++y]:y<0?b(x)<-y||(x<0&&x>y-4)||x==-y?[x-=2,y]:x<0?[--x,++y]:[--x,--y]:x>0?[--x,--y]:[++x,++y],w=m(w,b(x)),h=m(h,b(y)),c.push(n),c)),d=Array.from(Array(2*h+1),r=>Array(2*w).fill(' ')),l.map(([x,y,n])=>d[y+h][x+w]=n),d.map(r=>r.join('')).join(`
`))

```

Depending on the length of the string, there might be some extra whitespace surrounding the spiral on each side.

### Ungolfed

From an (empty) start position of `(-2, 0)` a two-dimensional array gets filled by assigning each consecutive letter to a new position computed from the last. It is not optimal to condense this to six conditions for six directions, for my solution I used eight.

As the spiral is constructed inward-out, its final size is only apparent after completing the assignment.

```
f = s => {
  b = Math.abs, m = Math.max
  w = h = 3, x = -2, y = 0
  l=[...s].reverse().map(n => {    // map letter n to [x, y, n]
    if(y > 0) {                    // lower half
      if(b(x) < y || -x == y) {    // between the lower corners, left included
        c = [x+=2,y]               // go right
      } else if(x > 0) {           // right lower quadrant
        c = [++x,--y]              // go right and up
      } else {                     // left lower quadrant
        c=[++x,++y]                // go right and down
      }
    } else if(y < 0) {            // upper half
      if(b(x) < -y || (x < 0 && x > y - 4) || x == -y) {
                                  // between the upper corners, right included,
                                  // on the left going two steps further out
        c = [x-=2,y]              // go left
      } else if(x < 0) {          // upper left quadrant
        c = [--x,++y]             // go left and down
      } else {                    // upper right quadrant
        c = [--x,--y]             // go left and up
      }
    } else if(x > 0) {           // right corner
      c = [--x,--y]              // go left and up
    } else {                     // left corner
      c = [++x,++y]              // go right and down
    }
    w=m(w,b(x)),h=m(h,b(y))
    c.push(n)
    return c
  })
  d=Array.from(Array(2*h + 1),r => Array(2*w).fill(' '))
  l.map(([x,y,n]) => {
    d[y+h][x+w] = n              // place letters in array, origin in the middle
  })
  return d.map(r => r.join('')).join('\n')
}

```
> 1 votes

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


title: Create chunks from an array

text:
# Question
Title: Create chunks from an array
Your task is to write a program which given an array and a number, you need to split the array into chunks with size is number.

## Rules

Your program will receive an array `A` , as well as a positive integer `n`. The array should then be split into chunks of length `n`, if the length of the string isn't divisible by `n` any leftover at the end should be considered its own chunk.

* If `n` is greater than length of array `A`, you will need to return array `A`, for example: if `n = 4` and `array A = [1,2,3]`, you should return `[1,2,3]`
* The array can contain any type rather than number.
* You should not change order (or direction) of any item from left to right. For example `if n = 2` and `A= [1,2,3]`. Any result rather than `[[1,2],[3]]` will be invalid.

## Test Cases

```
n   A               Output

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

```

This is , so you the shortest bytes of each language will be the winner.

# Answer
> 15 votes
# 05AB1E, 1 byte

```
ô

```

Try it online or verify all test cases.

Builtins ftw. :)

# Answer
> 9 votes
# JavaScript (ES6), 36 bytes

Takes input as `(n)(array)`.

```
n=>g=a=>a+a&&[a.splice(0,n),...g(a)]

```

Try it online!

### Commented

```
n =>                  // n = chunk size
  g = a =>            // g = recursive function taking the array a[]
    a + a             // if a[] is empty, stop recursion and return an empty string
    &&                // otherwise, return an array made of:
    [ a.splice(0, n), //   the next chunk
      ...g(a)         //   followed by the result of a recursive call
    ]                 //   (the last call leads to ...'', which adds nothing)

```

# Answer
> 9 votes
# APL (Dyalog Unicode), 12 bytesSBCS

```
⊢⊂⍨(⍴⊢)⍴1↑⍨⊣

```

Big thanks to Adám for basically doing basically all the golfing (and for basically all the APL knowledge I have currently \>\_\>).

### Explanation

```
 ⊂⍨           Partitioned enclose (commuted, i.e. left and right switched) - for each ⍵ in left, ⍺ in right, if ⍺ = 0, create a new sub-array, push ⍵ to latest sub-array
⊢             Right argument of entire expression
       ⍴      Reshape - Change size of right into dimensions specified by left
   (⍴ )       Shape of (here, there is only one dimension - length)
     ⊢        Right argument of entire expression
         ↑⍨   Take (commuted) - takes ⍺ elements from left where ⍺ is right. Extra elements (zeroes here) are automatically added
        1     1
           ⊣  Left argument of entire expression

```

### Execution

Arguments `2`, `1 2 3 4 5 6 7`. Note that APL arrays are of the form `a b c`, with optional surrounding parentheses.

```
           ⊣  2
        1     1
         ↑⍨   1↑2 = 1 0
     ⊢        1 2 3 4 5 6 7
   (⍴ )       ⍴1 2 3 4 5 6 7 = 7
       ⍴      7⍴1 0 = 1 0 1 0 1 0 1
⊢             1 2 3 4 5 6 7
 ⊂⍨           1 0 1 0 1 0 1⊂1 2 3 4 5 6 7 = (1 2)(3 4)(5 6)(7)

```

Try it online!

# Answer
> 9 votes
# Python 3, 61 bytes

```
lambda A,n:[A,[A[x:x+n]for x in range(0,len(A),n)]][n<len(A)]

```

Try it online!

Modifies Henry T's existing Python 3 solution to produce valid output for n \>= len(A).
Posting as its own answer due to lack of commenting privileges.

# Answer
> 8 votes
# Prolog (SWI), ~~90~~ ~~84~~ 61 bytes

### Code:

```
[]*_*[].
L*N*[P|R]:-length(P,N),append(P,T,L),T*N*R;P=L,R=[].

```

The input format might be a bit weird, but it is:

```
A * n * Result.

```

For example, for the input:

```
**n** = 2
**A** = [1, 2, 3, 4, 5, 6]
```

You would need to use `[1, 2, 3, 4, 5, 6] * 2 * Result.`.

Try it online!

### Ungolfed version:

```
divide([], _, []).
divide(List, N, [Prefix | Result]) :-
    length(Prefix, N), append(Prefix, Remaining, List), divide(Remaining, N, Result)
  ; Prefix = List, Result = [].

```

Try it online!.

# Answer
> 6 votes
# PHP, 15 bytes

```
$f=array_chunk;

```

requires PHP 7. Call with `$f(ARRAY, N)`.

# Answer
> 6 votes
# Perl 6, 13 bytes

```
{*.batch($_)}

```

Try it online!

Curried function wrapping the `batch` built-in.

# Answer
> 5 votes
# Clean, 54 bytes

```
import StdEnv
$n l=[l%(i,i+n-1)\\i<-[0,n..length l-1]]

```

Try it online!

# Answer
> 5 votes
# Python 3, 46 chars

```
lambda A,n:[A[:n],*(f(A[n:],n)if A[n:]else[])]

```

-1 thanks to @Collin Phillips.

Try it online!

# Answer
> 5 votes
# Python 2, 39 bytes

```
i,j=input()
while j:print j[:i];j=j[i:]

```

Try it online!

Assumes that 1 chunk per line is acceptable output.

# Answer
> 5 votes
# Brainfuck, 71 bytes

```
,[>+>+<<-]>>>,[<[>.,<-]>>>++++[<++++++++>-]<.[-]<<<[<+>>+<-]<[->+<]>>>]

```

Dunno if this counts or not... input format:

```
<character whose ascii is n>AAAAAAAAAAAAA
For example, in the input:
 1234567890123492034
n is 32 since the ASCII value of space is 32

```

Takes the input and puts in a space every time `n` characters pass

Explanation (no commas because that would break the program):

```
, take n
[>+>+<<-] copy into next two cells (destroys original)
>>>, take first of A into next cell
[ while that input exists
<[>.,<-] if n is nonzero output take next of A subtract one from n
>>>++++[<++++++++>-]<.[-]< n is zero so put a space
<<[<+>>+<-] copy the old n into surrounding cells
<[->+<] move from first cell to second
>>>] take input, do again

```

# Answer
> 4 votes
# CJam, 3 bytes

```
{/}

```

This is an anonymous block that takes an array of numbers and a number from the stack, and replaces them by an array of arrays.

Try it online!

# Answer
> 4 votes
# Brachylog, 2 bytes

```
ġ₎

```

Try it online!

# Answer
> 4 votes
# Elixir, 16 bytes

```
Enum.chunk_every

```

Try it online!

# Answer
> 4 votes
# Charcoal, 1 byte

Try it online! Charcoal's default I/O makes it difficult to demonstrate using anything except strings. If you want a full program that takes numeric lists and outputs formatted lists then this can be done as follows:

```
Ｅ⪪ＡＮ⪫ι,

```

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

```
  Ａ      Input array
 ⪪       Split into chunks of
   Ｎ     Input number
Ｅ       Map over chunks
     ι  Current chunk
    ⪫   Joined with
      , Literal `,`
        Implicitly print each chunk on its own line

```

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), ~~78~~ ~~77~~ 43 bytes

```
a=>b=>{int i=0;return a.GroupBy(_=>i++/b);}

```

Try it online!

I think we should be able to just write `int i;` because 0 is the default of int. I let it to avoid the error: `error CS0165: Use of unassigned local variable 'i'`.

# Answer
> 4 votes
# F# (.NET Core), 15 bytes

```
Seq.chunkBySize

```

Try it online!

Well F# has a builtin...

# Answer
> 4 votes
# , 4 bytes

```
<\~-

```

Try it online!

Takes the array as left arg and chunk size as right arg.

Uses a dyadic hook and the infix adverb with a negative argument, which does what we want by definition.

Note: The return type *must* be boxed because J only allows tables of equal sized items.

# Answer
> 3 votes
# Japt, 2 bytes

```
òV

```

Try it online!

# Answer
> 3 votes
# Java 10, ~~106~~ 80 bytes

```
L->n->{for(int l=L.size(),i=0;i<l;)System.out.print(L.subList(i,(i+=n)<l?i:l));}

```

Prints the chunks without delimiter.

Try it online.

### 106 bytes:

```
L->n->{var r=new java.util.Stack();for(int l=L.size(),i=0;i<l;)r.add(L.subList(i,(i+=n)<l?i:l));return r;}

```

Actually returns a list of lists.

Try it online.

**Explanation:**

```
L->n->{                       // Method with List and integer parameters and List return-type
  var r=new java.util.Stack();//  Create an empty List
  for(int l=L.size(),         //  Determine the size of the input-List
      i=0;i<l;)               //  Loop `i` in the range [0, size):
    r.add(                    //   Add to the result-List:
      L.subList(i,            //    A sublist of the input-list in the range from `i`
        Math.min(i+=n,l)));   //    to the minimum of: `i` + input-integer or the size
                              //    (and increase `i` by the input-integer at the same)
  return r;}                  //  Return the List of Lists of integers as result

```

# Answer
> 3 votes
# PHP, 45 bytes

```
function f($a,$b){return array_chunk($a,$b);}

```

Try it online!

# Answer
> 3 votes
# Jelly, 1 byte

```
s

```

Try it online!

While the printer makes it look like single-element splits are not wrapped into lists, they actually are.

# Answer
> 3 votes
# K (oK), 10 bytes

```
{(0N,x)#y}

```

Try it online!

# Answer
> 3 votes
# Ruby, 25 bytes

```
->n,a{[*a.each_slice(n)]}

```

Try it online!

If we can return enumerators instead of arrays, then it becomes simply:

# Ruby, 21 bytes

```
->n,a{a.each_slice n}

```

Try it online!

# Answer
> 3 votes
# PicoLisp, ~~75~~ 74 bytes

```
(de f(n l)(if(>= n(length l))(list l)(cons(head n l)(f n(tail(- 0 n)l)))))

```

Try it online!

# Answer
> 3 votes
# Coconut, 8 bytes

```
groupsof

```

Try it online!

# Answer
> 3 votes
# PowerShell, ~~67~~ 65 bytes

*-2 bytes thanks AdmBorkBork*

```
param($n,$a)$a|%{$b+=,$_
if($b.Count-ge$n){,$b;rv b}}
if($b){,$b}

```

Try it online!

# Answer
> 3 votes
# , 6 bytes

```
òÀf,r

```

Try it online!

Hexdump:

```
00000000: f2c0 662c 720a                           ..f,r.

```

Explanation:

```
ò           " Until an error happens:
  f         "   (f)ind the...
 À          "     n'th...
   ,        "     ","
            "   (If there are less than n commas after the cursor, throw an error)
    r       "   Replace the char under the cursor with...
     <cr>   "     A newline

```

# Answer
> 3 votes
# Clojure, 14 bytes

```
#(partition %)

```

builtins I guess

# Answer
> 3 votes
# Haskell, 26 bytes

```
import Data.Lists
chunksOf

```

Here's a more interesting version, with just a few more bytes (thanks to nimi for five bytes in each solution):

# Haskell, 31 bytes

```
n![]=[]
n!x=take n x:n!drop n x

```

Try it online!

# Answer
> 3 votes
# , ~~49~~ 36 bytes

```
function(A,n)split(A,(seq(A)-1)%/%n)

```

Try it online!

Thanks to Kirill L. for the golf.

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

```
#2~Partition~UpTo@#&

```

Try it online!

# Answer
> 2 votes
# Perl 5, 42 bytes

```
$p=<>-1;s/(,.*?){$p}\K,/],[/g&&($_="[$_]")

```

Try it online!

# Answer
> 2 votes
# Red, 46 bytes

```
func[n l][until[print take/part l n empty? l]]

```

Try it online!

# Answer
> 2 votes
# Ahead, 38 bytes

Input is a series of numbers on stdin. The first number is `n`, and the rest of the numbers make up the array. Output consists of `n` comma-separated numbers per line, so each line is a chunk.

```
~Ilj~#l,'H!t<
vuj{ oN @j<c
>:&}>d2(nOl

```

# Example

```
In: 2 1 2 3 4 5 6
Out:
1,2
3,4
5,6

In: 4 1 2 3 4 5 6
Out:
1,2,3,4
5,6,

```

Note there will be a trailing comma if the last chunk is not the right size. Hopefully this is ok.

Try it online!

# Answer
> 2 votes
# Factor, 5 bytes

```
group

```

Try it online!

# Answer
> 2 votes
# Vyxal, 1 byte

Try it Online!

# Answer
> 2 votes
# Ruby, 17 bytes

```
proc &:each_slice

```

Try it online!

# Answer
> 1 votes
# APL(NARS), 55 char, 110 bytes

```
{⍺≤1:,¨⍵⋄z←¯1↓v←,/(k←1+⌊⍺÷⍨≢⍵)⍺⍴⍵⋄0=r←⍺∣≢⍵:z⋄z,⊂r↑↑k⌷v}

```

this appear to return the right results... test:

```
  f←{⍺≤1:,¨⍵⋄z←¯1↓v←,/(k←1+⌊⍺÷⍨≢⍵)⍺⍴⍵⋄0=r←⍺∣≢⍵:z⋄z,⊂r↑↑k⌷v}
  o 1 f 1 2 3 4 5 6
┌6────────────────────────────┐
│┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐│
││ 1│ │ 2│ │ 3│ │ 4│ │ 5│ │ 6││
│└~─┘ └~─┘ └~─┘ └~─┘ └~─┘ └~─┘2
└∊────────────────────────────┘
  2 f 1 2 3 4 5 6
 1 2  3 4  5 6
  3 f 1 2 3 4 5 6
 1 2 3  4 5 6
  4 f 1 2 3 4 5 6
 1 2 3 4  5 6
  5 f 1 2 3 4 5 6
 1 2 3 4 5  6
  6 f 1 2 3 4 5 6
 1 2 3 4 5 6
  7 f 1 2 3 4 5 6
 1 2 3 4 5 6

```

# Answer
> 1 votes
# Python 3, 49 bytes

```
f=lambda x,n:[x[i:i+n]for i in range(0,len(x),n)]

```

Simple anonymous function implementation with a list comprehension. 47 bytes if you don't count the `f=` assignment.

Try it online!

# Answer
> 1 votes
# Kotlin, 19 bytes

```
{a,n->a.chunked(n)}

```

o/ built-ins

Try it online!

# Answer
> 1 votes
# GolfScript, 2 bytes

GS has a built-in. Unfortunately the implicit input got in the way.

```
~/

```

Try it online!

# Answer
> 1 votes
# Thunno 2, 1 byte

Try it online!

Yeah, another built-in :p

Polyglots with Vyxal apparently...

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


# Question
Title: Shortest code to produce infinite non-periodic output
<sup>**Not a dupe to this. That question asks *specifically* for counting up forever, while this question allows many other approaches.**</sup>

Write a program or function which, given infinite time and memory, would print an infinite non-periodic output.

## Clarifications

* 'Infinite' means the solution keeps outputting something without any further inputs or operations after successfully started the program or function.
* 'Non-periodic' means the output has **no** possibility of eventually repeating the same section forever (regardless of how long that period is). An example of a valid solution would be printing the digits of an irrational number.
* Random solutions would **not** count unless you can prove that it fits the requirements. Date/time-based solutions may also be invalid if they are not stored with arbitrary precision.

## Winner

Shortest code (in bytes) wins.

# Answer
## Hexagony, 2 bytes

```
(!

```

Try it online!

The unfolded source code looks like:

```
 ( !
. . .
 . .

```

This just runs these two commands in a loop, which are decrement (`(`) and print (`!`). Hence, the output is:

```
-1-2-3-4-5-6-7-8-9-10-11-12...

```

We need to use decrement instead of increment to ensure that the program loops back to the first line (if the memory value was positive, Hexagony would loop between then second and third line, and end up in an infinite loop without doing anything).
> 14 votes

# Answer
# Python 2, 23 bytes

```
while 1:print id;id=id,

```

Try it online!

Prints

```
<built-in function id>
(<built-in function id>,)
((<built-in function id>,),)
(((<built-in function id>,),),)
((((<built-in function id>,),),),)

```

and so on. Starts with the built-in function `id`, the shortest pre-initialized variable name, and repeatedly turns it into a tuple of itself.

In Python 3, this solution is one byte longer because of `print()`, but the byte can be recovered from `print` outputting `None`:

```
while 1:id=print(id),id

```

or

```
while[print(id)]:id=id,

```
> 16 votes

# Answer
# Brachylog, 2 bytes

```
ẉ⊥

```

Try it online!

This prints all integers ordered by magnitude. This will never overflow and print already seen integers since Brachylog uses unbounded integers by default.

### Explanation

```
ẉ      Writeln: the Input is anything, so we label it implicitely to an integer and write it
 ⊥     False: backtrack and try another integer value for the Input

```
> 6 votes

# Answer
## Labyrinth, 3 bytes

```
#:!

```

Try it online!

Prints all non-negative even integers without separator:

```
024681012141618202224262830323436384042...

```

The IP bounces back and forth on the code, so this is really `#:!:` in a loop:

```
#  Push stack depth.
:  Duplicate.
!  Print.
:  Duplicate.

```

A bunch of alternatives:

```
:#!     Prints all positive odd integers.
:)!     Prints all positive integers.
):!     Prints all positive integers.
:(!     Prints all negative integers.
(:!     Prints all negative integers.

```
> 5 votes

# Answer
# Bash \+ coreutils, 6 bytes

```
yes|sh

```

Try it online!

## Explanation

`yes` produces an infinite stream of newline-separated `y`s. `|` sends the output to `sh`, which tries to execute it line by line as it arrives. The first `y` is not valid code, so it produces the error message `sh: line 1: y: command not found`. The second `y` is also invalid, but it's part of the same stream (the output from `yes`), so it's treated as "line 2", making the error message `sh: line 2: y: command not found`. This continues forever, producing a different error message each time:

```
sh: line 1: y: command not found
sh: line 2: y: command not found
sh: line 3: y: command not found
sh: line 4: y: command not found
sh: line 5: y: command not found
...

```
> 5 votes

# Answer
# Haskell - 10 bytes

```
print[1..]

```

Although in ghci you could just type \[1..\] and that would automatically start printing.
> 3 votes

# Answer
## \>\<\>, 3 bytes

`l:n`

Outputs a stream of numbers, counting from 0.

I believe incrementing numbers don't cycle...

Explanation:

`l` pushes stack length onto stack

`:` duplicates top stack value on top of stack

`n` outputs value as number

When the line is finished it goes back to the beginning, so it does it again, but now the stack is longer...

online
> 2 votes

# Answer
# JavaScript, 26 22 20 bytes

```
for(;;)alert(Date())
```

(Warning: it's evil)
> 2 votes

# Answer
# Befunge, 4 bytes

```
1+:.

```

Try it online!

In Befunge, the stack is bottomless and has infinite zeros. That said:

`1+` adds one to the top of the stack

`:` duplicates the top of the stack

`.` prints the ascii value of the top of the stack as a number

And it continues infinitely, because there's no `@` to stop execution. This is actually one of those problems made easier to solve by the way befunge works... weird.
> 2 votes

# Answer
# PHP, 20 bytes

```
for(;;)echo$argc.=0;

```

Outputs this:

```
101001000100001000001000000100000001000000001000000000...

```

If command line arguments are provided, the output will be different, but still non-periodic.

As far as I understand the documentation, the language itself doesn't restrict length of strings.
> 2 votes

# Answer
# , 2 bytes

The characters that make up this program are:

```
240223

```

When viewing the file in an editor, it'll likely try to interpret it as ASCII, in which case it looks like this:

```
P$

```

Try it online!

The program takes input. I've assumed here that the input is at EOF; if you provide it input, it's possible it will crash.

## Explanation

**Zeroth iteration**

```
240223
240223  Append **240223** to the top stack element

```

The entire program here is passive, so it'll append an active version of itself to the top stack element (which is initially empty). The program's in an implicit loop, which evaluates the top stack element (while leaving it on the stack) every iteration. So the active version will run. (Pretty much all 7 programs start like this.)

**First iteration**

```
**240223**
**2**       Copy the top stack element
 **40**     Escape the second stack element, swapping it to the top
   **2**    Copy the top stack element
    **23**  Output the top stack element

```

Before the output command, the stack contains two copies of `240223` (i.e. passive). The top one gets output (with no observable effect other than selecting output format 2, "numbers"), the one below stays and becomes the program for the next iteration.

**Second iteration**

```
240223
240223  Append **240223** to the top stack element

```

The same as the zeroth iteration, right? Not quite; the stack had different contents. The stack is now **`240223`** below `240223**240223**`.

**Third iteration**

```
240223**240223**
240223  Append **240223** to the top stack element
      **2**   Copy the top stack element
       **40**   Escape the second stack element, swapping it to the top
       **2**   Copy the top stack element
       **23**  Output the top stack element

```

This outputs a stack element that has three more 6s-and-0s than it does 7s-and-1s. Output format 2 interprets this as a request to *input* a number. We read EOF, with the consequence that the next element on the stack is reduced to a zero-length string. However, due to a bug (which seems mildly useful and may be promoted to a feature?), this only happens *after* it starts executing. The stack once again has two elements, **`240223`** below `240223**240223240223**`, but the escaped version of this top element, `**7**240223**6**240223240223`, is now executing.

**Fourth iteration**

```
**7**240223**6**240223240223
**7**240223**6**240223240223  Append 240223**240223240223** to the top of stack

```

The top of stack was a zero-length string, so we're basically just unescaping the program that ended up there.

**Fifth iteration**

```
240223**240223240223**
240223        Append **240223** to the top stack element
      **2**         Copy the top stack element
       **40**         Escape the second stack element, swapping it to the top
       **2**         Copy the top stack element
       **23**        Output the top stack element
      **2**   Copy the top stack element
       **40**   Escape the second stack element, swapping it to the top
       **2**   Copy the top stack element
       **23**  Output the top stack element

```

This is very similar to the third iteration. There are two changes, though. First, there are now 4 more 0s-and-6s than there are 1s-and-7s, so we'll try to input a character from standard input rather than a number. We still get EOF, though, and still end up reducing the top of stack to a zero-length string as a result. Next, there's code running *after* the reduction, so the next iteration doesn't start immediately. Rather, we do a bunch of operations on that zero-length element, ending up with three zero-length elements. We output one, the other two disappear (because it's the end of an iteration), and we end up basically where we were at the end of the third iteration.

**Sixth iteration**

The program we copy from the top of stack is now `240223**240223240223240223**`. Everything works like in the previous iteration until we reach the first output instruction (the first **`23`**). This now has five more 0s-and-6s than there are 1s-and-7s, so it sets a mode in which the next output instruction will be interpretted as a request to change the output format. This also leads to a notable change in behaviour; as there was no input request, we didn't read EOF, and thus didn't trigger the consequence of reading EOF (the new top stack element being blanked), and as such the escaped version of the original stack element stays rather than being removed. This means that the next **`2402`** is no longer a no-op, creating two escaped copies of the escaped stack element (i.e. they're now double-escaped). We output one, setting the output format to 7 ("same as the input"); this output format has no I/O commands, and no commands to change the format, so we'll stay in it for the rest of the program. We also output `724022362402232402232402232402236` (in the same encoding as the input) to standard output.

Anyway, it's fairly clear what the program's going to be doing from this point onwards: it's a combination of appending various number of copies of variously escaped `240223` to the top of the stack, escaping the top of the stack, and outputting copies of the top of the stack. From this point onwards, the top stack element is never cleared (because we never read EOF), so it just grows and grows and grows. The periodic escaping ensures that the output never repeats (because it means that each iteration, the first output starts with at least one more `7` than it did on the previous iteration).
> 2 votes

# Answer
# Brainfuck, 13 Bytes, assuming no upperbound but output mod 256

```
+[[->+++.<]>]

```

output char code 2 2 4 6 2 4 6 8 10 12 14 16 18 ...

sorry that the old code print loop 0 2 4 6 ... 254,

# Brainfuck, ~~13~~ 12 Bytes (-1 from Jo King)

```
+[[>.]<[<]+]

```

output char code 0 1 0 1 1 0 1 1 1 0 ...
> 2 votes

# Answer
# Jelly, 3 bytes

```
‘Ȯß

```

**Try it online!** \- truncates the output and raises an error, but will go far longer locally (until memory runs out).

With an implicit input of zero this program consists of a single link which increments, , prints `Ȯ`, and then calls itself with the new value, `ß`.
> 1 votes

# Answer
# Ohm, 4 bytes (CP437)

```
¼,¡∞

```

Prints the counter variable, increments it, and goes into an infinite loop! Simple enough.

**EDIT** (Mar 1 '17): While I was in the process of doing some other updates (after I posted this answer), I changed the behavior of . The updated answer would be `∞^,`.
> 1 votes

# Answer
# MATL, 4 bytes

```
`@tD

```

This solution creates a `while` loop which pushes the index of the loop to the stack, duplicates it, prints the value and then checks that the loop index is non-zero to repeat again.

Try it Online!
> 1 votes

# Answer
# "modern" DC, 9 bytes

Infinite memory?
Then a continuously growing stack is ok?
\]:-)

```
[zprdx]dx

```

Commented:

```
[         # start string constant
 z        #   push current stack depth
  p       #   print TOS without removing
   r      #   swap TOS and NOS
    d     #   duplicate TOS
     x    #   pop TOS and interprete it
      ]   # end string constant, push it
       d  # duplicate TOS
        x # pop TOS and interprete it

```

Because of using the `r` command, this will not run on some anicent DCs.
> 1 votes

# Answer
# RProgN 2, 13 bytes

```
2{22.`2=2p2}:

```

There are many twos in the output, separated by progressively more sparce newlines.

```
2{22.`2=2p2}:
2               # Push a two to the stack
 {         }:   # While the top of the stack is truthy
  22.           # Push the value of "2" twice, and concatenate them together.
     `2=        # Set the value of "2" to this.
        2p      # Print the value of "2"
          2     # And push the value of "2"

```

Which prints 2^n 2s followed by a newline for each iteration.

Try it online!
> 1 votes

# Answer
# C (gcc), ~~83~~ 81 bytes

```
*p,*t,*g;f(){for(t=p=malloc(1),g=--t;t<p?putchar(55):(t=g,*p++,putchar(9));t++);}

```

First allocating a pointer on the heap, the function then counts off into the memory addresses ahead until a segfault from `*p++`, therefore is limited by the amount of memory in the system rather than the data types used which would otherwise eventually overflow and repeat the series. Given infinite memory with infinite addressing capability it would go on forever.

Try it online!
> 1 votes

# Answer
# APL (Dyalog APL), 8 bytes

```
{∇⎕←0⍵}1
```

`{`emsp;an anonymous function...

recurse on

`⎕ ←` output to STDOUT

`0 ⍵` the two element list consisting of a zero and the argument

`}` applied to the number one

This outputs (on separate lines) `[0,1]`, `[0,[0,1]]`, `[0,[0,[0,1]]]`, etc.
> 1 votes

# Answer
# Processing, ~~30~~ 29 bytes

*1 byte saved thanks to QwerpDerp for using `millis()` instead of `frameRate`*

```
void draw(){print(millis());}

```

Continuously prints the number of milliseconds since the start of the program.

Sample output:

```
3573743914054244404574734925085205375585755916...

```
> 1 votes

# Answer
## Bourne Shell, 11 bytes

```
yes date|sh

```
> 1 votes

# Answer
## Ruby, ~~21~~ 12 bytes

```
loop{p$.+=1}

```

Print all natural numbers. As far as I understand the problem description, this should be ok.
> 0 votes

# Answer
# PHP, 21 bytes

```
for(;;)echo uniqid();

```

Usage: `php -r "for(;;)echo uniqid();"`

Outputs unique IDs based on the current time in microseconds: `58b3e065e4b4c58b3e065e4b6358b3e065e4b7b58b3e065e4b9458b3e065e4bac58b3e065e4bc458b3e065e4bdc58b3e065e4bf558b3e065e4c0e58b3e065e4c2658b3e065e4c3e58b3e065e4c5658b3e065e4c6f58b3e065e4c8758b3e065e4c9f...`

as a continuous sequence of: `58b3e09390617` `58b3e09390651` `58b3e0939068a` `58b3e093906c3` `58b3e093906fc` `...`
> 0 votes

# Answer
# Perl 6, 11 bytes

```
say($++)xx*

```

Prints the natural numbers.

Try it online!
> 0 votes

# Answer
# Python 2, 24 bytes

Prints 9 times each power of 2.

```
n=9
while 1:print n;n+=n

```

**Try it online**
> 0 votes

# Answer
# Batch, 7 bytes

```
time|%0

```

Or:

```
%random%|%0

```
> 0 votes

# Answer
# Powershell, 19 Bytes

Boring counting up answer.

```
for(){[bigint]$i++}

```

Improved version of answer from Count Up Forever
> 0 votes

# Answer
# stacked, 9 bytes

```
$out0 ani

```

Try it online! Similar to my Count up forever answer, this outputs natural numbers from `0`, the counter.
> 0 votes

# Answer
## GNU sed, 13 bytes

This is an arbitrary precision counter in unary. That's a fancy way of saying that I append one `0` to the pattern space and print it on every iteration (infinite loop).

```
:
s:0*:&0:p
b

```

After some time this would normally run into a memory allocation error and stop printing, because it can't store anymore the ever growing pattern space. That's not a problem for this challenge, since the memory is assumed to be infinite.

**Try it online!** (this interpreter further limits the available resources by design)

**Output preview:** only the first 5 lines

```
me@LCARS:/PPCG$ echo | sed -f infinite_non_periodic.sed | head -5
0
00
000
0000
00000

```
> 0 votes

# Answer
# OIL, ~~11~~ 9 bytes

```
4
6
8
6
6

```

First prints what's in cell 6 (0), then increments cell 6 and jumps to the beginning. The reference implementation of OIL uses arbitrary precision integers, so this will (in theory) run forever. This is probably the shortest possible such program in OIL.

*edit: Realized I can remove the final zero and it will still work.*
> 0 votes

# Answer
# TI-Basic, 11 Bytes

```
While 1
Ans+1
Disp Ans
End

```
> 0 votes

# Answer
# Sesos, 2 bytes

### SASM

```
set numout
jmp, put, add 1

```

### SBIN

```
00000000: c40a                                              ..

```

Prints all non-negative integers in order.

Try it online!
> 0 votes

# Answer
# Tcl, 23 bytes

```
while 1 {puts [incr i]}

```

Try it online!
> 0 votes

# Answer
# Aceto, 5 bytes

```
dp
I<

```

Increments the top element (initially zero), duplicates the resulting element, pops and prints it, and goes back to the start.
> 0 votes

# Answer
## Mathematica, 17 bytes

```
i=0;#0@Print@++i&

```

or (more interesting version, 1 byte longer)

```
#0@Print@Unique[]&

```

Recursive forever (assuming `$MaxRecursionLimit = Infinity`)

This version is 24 byte.

```
i=0;While[1>0,Print@++i]

```
> 0 votes

# Answer
# Triangular, 6 bytes

```
(.i]%<

```

Formats into this triangle:

```
  (
 . i
] % <

```

Prints an infinite stream of numbers starting from 0. The code that is executed (after removing directionals and no-ops) is `(i%]` \- basically, starts a loop, increments the top of stack, prints it, and jumps back to the loop.

Try it online!
> 0 votes

# Answer
# 05AB1E, 3 bytes

```
[N,

```

Counts up forever.

Try it online!
> 0 votes

# Answer
# PHP, 19 bytes

```
for(;;)echo$s.=0,1;

```

Run with `-r` or `-R`.
> 0 votes

# Answer
# Java 8, 82 bytes

```
o->{java.math.BigDecimal t=null;for(t=t.ONE;;System.out.println(t=t.add(t.ONE)));}

```

Perhaps a bit boring considering the other challenge, but this loops up forever, starting at 2.

Has an unused `Object` parameter (which is `null`), since the challenge doesn't specifically ask for "*no input*".

**Explanation:**

Try it here. (It's a cache after it has timed out after 60 seconds the first time.)

```
o->{                            // Method with empty Object parameter and no return-type
  java.math.BigDecimal t=null;  //  Create BigDecimal once so we can use it's static fields
  for(t=t.ONE;                  //  Start at 1
      ;                         //  Loop infinitely
      System.out.println(       //   And print `t`
        t=t.add(t.ONE)          //    after we've raised `t` by 1
      )
  );                            // End of loop
}                               // End of method

```
> 0 votes

# Answer
# Pushy, 3 bytes

```
[H"

```

**Try it online!**

```
[     \ Infinitely:
 H    \  Push 100 ('d')
  "   \  Print whole stack (with trailing newline)

```
> 0 votes

# Answer
# Husk, 1 byte

```
N

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 1 byte

Try it online!

```
∞  # [1, 2, ..., ∞]
   # implicit output

```
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
1Ƙ£

```

Attempt This Online!

Prints the infinite list of positive integers.
> 0 votes

---
Tags: code-golf
---


# Question
Title: La La Land... no wait, Moo Moo Moonlight
This challenge is a tribute to the winner of Best Picture at the Oscars 2017, ~~La La Land~~ Moonlight!

---

Write a function/program that takes a string containing only letters `[A-Za-z]`, the four symbols that are common in every day sentences `.,'?` and spaces, and outputs the string in the style of La La Land.

To be more specific, take the letters up to, and including, the first vowel group, and print/output it twice adding a space each time, then print/output the whole string. *y is a vowel* in this challenge. Punctuation and capitalization should be kept.

You may assume that all strings contain at least one vowel, and that all strings start with a letter.

**Test cases:**

```
Land
La La Land

Moonlight
Moo Moo Moonlight

quEueIng
quEueI quEueI quEueIng

This isn't a single word.
Thi Thi This isn't a single word.

It's fun to play golf
I I It's fun to play golf

Ooo
Ooo Ooo Ooo

I'm okay
I I I'm okay

Hmm, no. There will be at least one vowel, but it can be anywhere.
Hmm, no Hmm, no Hmm, no. There will be at least one vowel, but it can be anywhere.

Why is y a vowel?
Why Why Why is y a vowel?

```

This is so the shortest code in each language wins. **Explanations are encouraged**, also in mainstream languages.

# Answer
> 56 votes
## Sed 30 bytes

```
s/[^aeiouy]*[aeiouy]\+/& & &/i

```

# Answer
> 30 votes
# 05AB1E, ~~23~~ ~~19~~ 18 bytes

Saved 1 byte thanks to *Okx*.

```
Dlð«žOsSåJTk>£D¹ðý

```

Try it online! or as a Test suite

**Explanation**

```
 Dl                  # create a lowercase copy of implicit input
   ð«                # append a space
     žO              # push the vowels
       s             # swap lowercase input to the top of the stack
        S            # split into a list of chars
         å           # check each char for membership in the vowel-string
                     # (creates a list with 1 at the index of vowels and 0 for non-vowels)
          J          # join to string
           Tk        # find the index of 10
             >       # increment
              £      # take that many items from input
               D     # duplicate this string
                ¹    # push input
                 ðý  # join the strings by space

```

# Answer
> 24 votes
# Jelly, ~~24 22 20 19~~ 14 bytes

-5 bytes by utilising a trick from Emigna's brilliant answer (look for 10 in the isVowel list)

```
;⁶e€Øyw⁵ḣ@;⁶Ȯ;

```

**Try it online!** (not quite sure how to make a test suite for this full program)

---

**15** byte alternative:

```
;⁶e€Øyw⁵ḣ@;⁶ẋ2;

```

**Here** is full test suite.

### How?

```
;⁶e€Øyw⁵ḣ@;⁶Ȯ; - Main link: string s
 ⁶             - space character
;              - concatenate to s (for all vowel edge case)
    Øy         - vowels + y yield
  e€           - exists in? for €ach (gives a list of isVowel identifiers)
       ⁵       - 10
      w        - index of first sublist (with implicit decimalisation of 10 to [1,0])
        ḣ@     - head with reversed @rguments (start of word up to & including vowel group)
           ⁶   - space character
          ;    - concatenate (start of word up to & including vowel group plus a space)
            Ȯ  - print and yield (hence a full program...
               -     ...the alternative ẋ2 repeats instead in order to return the result)
             ; - join with the input, s
               - implicit print (of the second repetition and input string)

```

# Answer
> 19 votes
# Python, 61 bytes

```
import re;lambda x:re.sub('(.*?[aeiouy]+)',r'\1 \1 \1',x,1,2)

```

Here comes the first non-regex-based language (using regex).

Saved 1 byte thanks to Neil.

# Answer
> 18 votes
# JavaScript (ES6), 40 ~~46~~

**Edit** 5+1 bytes saved thx @Arnauld

Overly long compared to other using the same trick (as usual)

```
x=>x.replace(/.*?[aeiouy]+/i,'$& $& $&')

```

```
let f=
x=>x.replace(/.*?[aeiouy]+/i,'$& $& $&')

test=`Land
La La Land

Moonlight
Moo Moo Moonlight

queueing
queuei queuei queueing

This isn't a single word.
Thi Thi This isn't a single word.

It's fun to play golf
I I It's fun to play golf

Ooo
Ooo Ooo Ooo

I'm okay
I I I'm okay

Hmm, no. There will be at least one vowel, but it can be anywhere.
Hmm, no Hmm, no Hmm, no. There will be at least one vowel, but it can be anywhere.`
test.split(`\n\n`).forEach(z=>{
  var [i,k]=z.split(`\n`),x=f(i);
  console.log(k==x ? 'OK':'KO',i+'\n'+x);
})
```

# Answer
> 16 votes
## Retina, 24 bytes

```
i`^.*?[aeiouy]+
$& $& $&

```

Try it online!

# Answer
> 12 votes
## Batch, 180 bytes

```
@echo off
set/ps=
set v=aeiouy
set g=c
set t=
:l
call set w=%%v:%s:~,1%=%%
if %v%==%w% goto %g%
set g=o
:c
set t=%t%%s:~,1%
set s=%s:~1%
goto l
:o
echo %t% %t% %t%%s%

```

Implements a state machine. `g` keeps track of whether we've ever seen a vowel, so if the current letter isn't a vowel we know whether to output or continue with the next letter.

# Answer
> 12 votes
# PowerShell, ~~46~~ ~~47~~ ~~41~~ ~~39~~ 38 bytes

```
$args-replace"^.*?[aeiouy]+",(,'$&'*3)

```

Try it online!

Thanks to Maarten Bamelis for the bugfix

Saved 6 bytes thanks to Rynant

Saved ~~2~~ 3 bytes thanks to Joey

# Answer
> 8 votes
# Ruby, ~~31~~ ~~32~~ 30 Bytes

```
->s{(s[/.*?[aeiouy]+/i]+' ')*2+s}

```

Two bytes saved thanks to G B and Cyoce.

# Answer
> 6 votes
# Perl, 25 + 1 (`-p` flag)

```
s/.*?[aeiouy]+/$& $& $&/i

```

# Answer
> 6 votes
# PHP, ~~55~~ 54 bytes

Note: encoded version uses IBM-850 encoding.

```
echo preg_filter("/^(.*?[aeiouy]+)/i","$1 $1 $0",$argn);
echo preg_filter(~ðíÎÐı└ñ×ÜûÉèåóÈÍðû,~█╬▀█╬▀█¤,$argn);     # Encoded

```

Run like this:

```
echo "This isn't a single word." | php -nR 'echo preg_filter(~ðíÎÐı└ñ×ÜûÉèåóÈÍðû,~█╬▀█╬▀█¤,$argn);'

```

# Explanation

Just a regex replace with non-eager matching any character at the start of the string, followed by any amount of vowels (use `i` option for case insensitivity). That capture group is then printed twice, followed by the entire string.

# Tweaks

* Saved a byte by using `-R` to make `$argn` available (Thx Titus)

# Answer
> 6 votes
# Javascript (ES6), 38 bytes

```
x=>(y=/.*?[aeiouy]+/i.exec(x)+' ')+y+x

```

```
f=
x=>(y=/.*?[aeiouy]+/i.exec(x)+' ')+y+x
```

```
<!-- snippet demo: -->
<input list=l oninput=console.log(f(this.value))>
<datalist id=l><option value=Land>
<option value=Moonlight>
<option value=queueing>
<option value="This isn't a single word.">
<option value="It's fun to play golf">
<option value=Ooo>
<option value="I'm okay.">
<option value="Hmm, no. There will be at least one vowel, but it can be anywhere.">
<option value="Why is y a vowel?">
```

# Answer
> 5 votes
# Perl 6, 30 bytes

```
{S:i/.*?<[aeiouy]>+/{$/xx 3}/}

```

Try it online!

# Answer
> 5 votes
# C, ~~202~~ ~~196~~ ~~195~~ ~~193~~ ~~190~~ 180

`i,j,k,m,n;f(char*a){if((a[i/12]-"AEIOUY"[i++%6])%32==0)k=n=24-(i%12);else if(k&&!n--){m=j=(i-13)/12;for(i=0;i<j*2;)printf("%c%c",a[i%j],(i==j-1)*32),i++;printf(" %s", a);}m?:f(a);}`

Try it online!

---

Thing left to golf:
•Collapse two printf into one.

•Printing my space char can be changed into `%*c` logic I'm sure.

•I'm using conditionals which can be removed somehow

`j=(i-13)/12` can likely be shortened.

•\[A-Y\] conditional checks if `==0` which is usually un-necessary, though I'm currently stuck on that one (tried switching if-else and ditching the `==0` altogether but that requires adding more {brackets} and increase byte size)

---

Tricks I've used to golf this down:

•Combined a double for loop string search by using modulo for x-axis and integer-division for y-axis (input string vs vowel string). (X-axis is looped twice before iterating once on y-axis; the first time with \[A-Z\] and the second time with \[a-z\] using character value 32 differential.

•Bypassed having to use "\[A-Y\] and \[a-y\]" by just taking the distance between character sets and modulo 32. That way if the distance is 0 (A-A) or if the distance is 32 (a-A)

•Re-using integer variables that are no longer in use as boolean variables.

•Recursively calling a function with the same string to process through it and avoid a second for-loop.

•Set BOOL values to the logic of setting another variable. (e.g. bool = i=5;) to knock out both with one stone.

•Ternary empty-true exploit abuse. (GCC)

---

Readable Format:

```
i,j,k,m,n;
f(char*a){
    if((a[i/12]-"AEIOUY"[i++%6])%32==0)
        k=n=24-(i%12);
    else
        if(k&&!n--){
            m=j=(i-13)/12;
            i=0;
            for(;i<j*2;)
               printf("%c%c",a[i%j],(i==j-1)?32:0),i++;
            printf(" %s", a);
        }
    m?:f(a);
}

```

---

Knocked off 10 bytes thanks to Keyu Gan (in comments)

# Answer
> 4 votes
# PHP, ~~69 65~~ 53 bytes

```
<?=preg_filter("#.*?[aeiouy]+#i","$0 $0 $0",$argn,1);

```

requires PHP 5.3 or later. Run as pipe with `-F` or try some versions online.

Saved 4 bytes (and fixed the code) with regex stolen from @aross;
10 more with `preg_filter` instead of `preg_match` and `-F`
and another two with an improved regex.

**~~75~~ 81 bytes** for a non-regex version:

```
for(;$c=$argn[$i++];)($k+=$k^!trim($c,aeiouyAEIOUY))>1?:$w.=$c;echo"$w $w $argn";

```

requires PHP 5 or later; replace `?:` with `?1:` for older PHP. Run with `-nR`

**Breakdown**

```
for(;$c=$argn[$i++];)       // loop $c through input characters
    ($k+=$k^!                   // 2. !$k and vowel or $k and not vowel: increment $k
        trim($c,aeiouyAEIOUY)   // 1. strip vowels -> vowel=false, non-vowel=true
    )>1                         // 3. if $k>1
    ?                           // do nothing
    :$w.=$c;                    // else append $c to $w
echo"$w $w $argn";          // output

```

# Answer
> 4 votes
# Python 3, ~~101~~ 96 bytes

```
s=input()
v=i=0
for c in s:
 w=c in'aAeEiIoOuUyY'
 if v*~-w:break
 v=w;i+=1
print(s[:i],s[:i],s)

```

Try it online!

a non-regex solution

---

Commented:

```
s=input()
a='aAeEiIoOuUyY'
v=i=0
for c in s:          # for each character in the string
 w=c in a            # w = True if the character is a vowel, else false
                     # true is equivalent to 1  and false to zero
                     # v*(w-1) evaluates only to true (-1 in this case) if v=1 (last character was a vowel) and w=0 (current character is not a vowel)
 if v*(w-1):break    # if so, break the loop
 v=w;i+=1            # increase the counter and set v to w
print(s[:i],s[:i],s)

```

# Answer
> 4 votes
# Ohm, 19 bytes (CP437)

```
≡┬üC▓αy_ε;TF«u├DQüj

```

Explanation:

```
≡┬üC▓αy_ε;TF«u├DQüj     Main wire, arguments: s

≡                       Triplicate input
 ┬üC                    Push input, all lowercase with concatenated space character
    ▓    ;              Map string into an array with...
     αy_ε                 Boolean: is element a vowel?
          TF«u          Find first occurrence of [true, false]
              ├D        Slice input up to that index and duplicate it
                Q       Reverse stack
                 üj     Join on spaces, implicitly print

```

# Answer
> 4 votes
# Python 3, ~~75~~ 68 bytes

```
lambda s:(s[:[x in"aAeEiIoOuUyY"for x in s][1:].index(0)+1]+" ")*2+s

```

Try it online!

Explanation:

Works by generating a boolean value for every character in the input string based on whether or not it is a vowel, and finding the lowest index of `0`, the first non-vowel (excluding the first character). It returns the substring to this index twice,separated by spaces, and the original string.

# Answer
> 4 votes
# MATL, 33 bytes

```
'(^.*?[yY%s]+)'13Y2YD'$1 $1 $1'YX

```

Try it at **MATL Online**

**Explanation**

```
                % Implicitly grab input as a string
'(^.*?[yY%s]+)' % Push this string literal (regex pattern)
13Y2            % Push the string literal 'AEIUOaeiuo'
YD              % Replace the '%s' in the string with 'AEIUOaeiuo'
'$1 $1 $1'     % Push the string literal to use for replacement which repeats
                % the first match 3 times
YX              % Perform regular expression matching and replacement
                % Implicitly display the result

```

# Answer
> 4 votes
# , ~~21~~, 20 bytes

```
é /ã[aeiouy]«“.
3ä|<

```

Try it online!

Explanation:

```
é               " Insert a space
  /             " Jump forward too...
   ã[aeiouy]«. "   The first non-vowel after a vowel
3ä              " Make three copies of
  |             " Everything from the cursor to the first character
   <            " Delete the space we inserted

```

Hexdump:

```
00000000: e920 2fe3 5b61 6569 6f75 795d ab93 2e0a  . /.[aeiouy]....
00000010: 33e4 7c3c                                3.|<

```

Alternate version (21 bytes):

```
Íã¨ƒ[aeiouy]«©/± ± &

```

Try it online!

This uses ridiculous regex compression, and it still manages to get it's butt kicked by the other golfing languages. For reference, this is about two/thirds the length of the regular "uncompressed" version, namely:

```
:%s/\v\c(.{-}[aeiou]).*/\1 \1 &

```

Explanation:

```
Í                               " Replace on every line:
 ã                              "   Case-insensitive
  ¨              ©              "   Capture-group 1
   <131>                        "   Any character, any number of times (non-greedy)
        [aeiouy]«               "   A vowel, repeated once or more
                  <129>         "   Followed by anything
                       /        " Replaced with:
                        ± ±     "   Capture group one twice, with spaces between
                            &   "   The whole matched pattern

```

Here is a hexdump:

```
00000000: cde3 a883 5b61 6569 6f75 795d aba9 812f  ....[aeiouy].../
00000010: b120 b120 26                             . . &

```

# Answer
> 4 votes
# Clojure, ~~192~~ ~~188~~ 181 bytes

```
(fn[p](let[[f] p v #(#{\a \e \i \o \u \y}(Character/toLowerCase %))[q r](split-with(if(v f)v #(not(v %)))p)[w _](split-with v r)as #(apply str %)](str(as(repeat 2(str(as q)(as w) \ )))p)))

```

-4 bytes by inlining `first-sp-pred` (whoops).

-7 bytes by removing some missed spaces

This was far more challenging than I thought it would be going in! I'm manually parsing the string...since I still haven't gotten around to learning regex :/

See pre-golfed code for breakdown:

```
(defn repeat-prefix-cons [phrase]
  (let [[first-letter] phrase ; Get first letter

        ; Function that checks if a lowercased character is a part of the vowel set
        vowel? #(#{\a \e \i \o \u \y} (Character/toLowerCase %))

        ; cons(onant)? Negation of above
        cons? #(not (vowel? %))

        ; Decide how to split it depending on if the first character is a vowel
        first-sp-pred (if (vowel? first-letter) vowel? cons?)

        ; Split off the first chunk of cons/vowels
        [pre1 r] (split-with first-sp-pred phrase)

        ; Split off the rest of the vowels
        [pre2 r2] (split-with vowel? r)

        ; Shortcut function that turns a list into a string (Basically (join "" some-list-of-strings) )
        as #(apply str %)]

    (str ; ... then concat the prefix in front of the original phrase, and return
      (as ; ...then turn it back into a string since "repeat" returns a list... ^
        (repeat 2 ; ... then repeat it twice (shame Clojure doesn't have string multiplication)... ^
                (str (as pre1) (as pre2) \ ))) ; Concat the 2 prefix parts together with an space at the end... ^
      phrase)))

```

# Answer
> 4 votes
## R, 49bytes

`sub("(.*?[aeiouy]+)","\\1 \\1 \\1",scan(,""),T,T)`

Regex based replace, match everything until not a vowel, capture and replace it by itself 3 times.

`scan` wait for a `double` type input, to tell it to use `character` type we have to give it two arguments, first is the default , emtpy string for stdin, and for the second the R evaluation allow to use only `c` as it's not ambiguous for `character` in this context.

`T` stands for `TRUE` and save some char as 4th and 5th parameter to sub to tell it to ignore case and use PCRE (the greedyness is not the same with R regex syntax)

4 bytes saved courtesy of Sumner18 along with the Tio link to running code

# Answer
> 3 votes
# Java 8, 147 140 bytes

Golfed:

```
import java.util.regex.*;s->{Matcher m=Pattern.compile("([^aeiouy]*[aeiouy]+)",2).matcher(s);m.find();return m.group()+" "+m.group()+" "+s;}

```

Ungolfed:

```
import java.util.regex.*;

public class LaLaLandNoWaitMooMooMoonlight {

  public static void main(String[] args) {
    for (String[] strings : new String[][] { { "Land", "La La Land" }, { "Moonlight", "Moo Moo Moonlight" },
        { "queueing", "queuei queuei queueing" }, { "This isn't a single word.", "Thi Thi This isn't a single word." },
        { "It's fun to play golf", "I I It's fun to play golf" }, { "Ooo", "Ooo Ooo Ooo" },
        { "I'm okay", "I I I'm okay" }, { "Hmm, no. There will be at least one vowel, but it can be anywhere.",
            "Hmm, no Hmm, no Hmm, no. There will be at least one vowel, but it can be anywhere." } }) {
      final String input = strings[0];
      final String expected = strings[1];
      final String actual = f(s -> {
        java.util.regex.Matcher m = java.util.regex.Pattern.compile("([^aeiouy]*[aeiouy]+)", 2).matcher(s);
        m.find();
        return m.group() + " " + m.group() + " " + s;
      } , input);
      System.out.println("Input:    " + input);
      System.out.println("Expected: " + expected);
      System.out.println("Actual:   " + actual);
      System.out.println();
    }

  }

  private static String f(java.util.function.Function<String, String> function, String input) {
    return function.apply(input);
  }
}

```

Note: the literal `2` in the code is the value of `java.util.regex.Pattern.CASE_INSENSITIVE`.

# Answer
> 3 votes
# C, 123 bytes

```
#define v(x)while(x strchr("AEIOUY",*s&95))++s;
a;f(s,t)char*s,*t;{t=s;v(!)v()a=*s;*s=0;printf("%s %s ",t,t);*s=a;puts(t);}

```

Call as:

```
main(){char s[] = "queueing"; f(s);}

```

# Answer
> 2 votes
# Pyke, 22 bytes

```
l1~V\y+L{$0R+f2<ssDQdJ

```

Try it online!

This is 4 bytes longer than it should really be had I implemented a shorter way of getting vowels including `y`.

# Answer
> 2 votes
# Retina, 24 bytes

```
i1`.*?[aeiouy]+
$0 $0 $0

```

**Try it online**

# Answer
> 2 votes
# MATLAB / Octave, ~~58~~ 51 bytes

*7 Bytes saved thanks to @HughNolan*

```
@(x)regexprep(x,'(^.*?[aeiouyAEIOUY]+)','$1 $1 $1')

```

Creates an anonymous function named `ans` which can be called by passing a string to it: `ans('Land')`

Online Demo

For MATLAB compatibility, `$0` should be used in place of `$1` in the above function.

# Answer
> 2 votes
# Python 3, ~~130~~ 102 bytes

```
w=input();a='';v=0
for i in w:
	if i in 'aeiouyAEIOUY': v=1
	elif v:
		break
	a+=i
a+=' ';print(a*2+w)

```

Try it online!

Uses no function of any kind and no external libraries! (Unless print and input count as functions, which they do).

Works by seeing if it gets out of the consonants in the start of the title into the 'vowel zone'. If it is in the 'vowel zone' and detects a consonant, then it prints the title.

Saved 28 bytes thanks to @LliwTelracs

# Answer
> 2 votes
# APL (Dyalog), 28 bytes

### `'(?i)^.*?[aeiouy]+'⎕R'& & &'` or 29 chars: `'^.*?[aeiouy]+'⎕R'& & &'⍠1`

Simply a (`(?i)` or `⍠1`) case-insensitive PCRE **R**eplace of

`^` the beginning
`.*?` zero or more characters (lazy)
`[aeiouy]+` one or more vowels

with

`& & &` the entire match thrice with spaces inbetween

---

### Version without RegEx, 43 bytes

`⊢(↑,' ',↑,' ',⊢)⍨1⍳⍨1 0⍷'aeiouy'∊⍨' ',⍨819⌶`

`819⌶` lowercase

`' ',⍨` append a space

`'aeiouy'∊⍨` which letters are vowels

`1 0⍷` vowels that are followed by a non-vowel

`1⍳⍨` index of first one

`⊢(``)⍨` apply the following tacit function with the string as right argument, and the above index as left argument

that many characters taken from the string

`,` followed by

that many characters taken from the string

`,` followed by

the string

# Answer
> 2 votes
# C (gcc), ~~111~~ 110 bytes

```
*d="AEIOUYaeiouy";b;f(char*a){b=strcspn(a,d);write(printf(" "),a,write(1,a,b+strspn(a+b,d)));printf(" %s",a);}

```

Try it online!

This just uses library functions `strspn()` and `strcspn()` and exploits the order in which gcc evaluates function parameters. Slightly less golfed

```
*d="AEIOUYaeiouy";b;
f(char*a){
  b=strcspn(a,d);
  write(printf(" "),a,write(1,a,b+strspn(a+b,d)));
  printf(" %s",a);
}

```

Thanks to @gastropner for -1.

# Answer
> 1 votes
# Pyth - 24 bytes

```
jd[Ke:Q"^.*?[aeiou]+"1KQ

```

Test Suite.

# Answer
> 1 votes
# Python 3, ~~102~~ 99 bytes

```
def l(s,v=0):
 for l in range(len(s)):
  if s[l]in"aeiouyAEIOUY":v=1
  elif v:return(s[:l]+" ")*2+s

```

Running on IDLE, so the `Print/output` part stands

```
>>> l("Land")
'La La Land'

```

Managed to shave off a space or two, and replace `.lower()` with simply adding uppercase vowels to the check.

# Answer
> 1 votes
# C, ~~150~~ 146 bytes

```
f(char*s){char*v="aeiouyAEIOUY",*p=strpbrk(s,v);int i=strspn(p,v),f=i+(p-s),d=0,j=2;while(j--)while(d<f)putchar(s[d++]);d=0,putchar(' ');puts(s);}

```

### Ungolfed:

```
#include <stdio.h>
#include <string.h>

int main(void)
{
    char *s = "Land";  // change this

    char *p = strpbrk(s, "aeiouyAEIOUY");
    int count = strspn(p, "aeiouyAEIOUY");

    int idx = count + (p - s);

    int i, j = 2;

    while (j--)
    {
        while (i < idx)
            putchar(s[i++]);

        i = 0;
        putchar(' ');
    }

    puts(s);
}

```

### How it works:

* `strpbrk` finds the first vowel and returns a pointer `p`.
* `strspn` finds how many vowels there are in a row in `p` and returns an integer `count`.
* The index `idx` of the last vowel equals `count` (# of vowels) + `p - s` (index of first vowel).
* Print the first `idx` characters in `s`, twice.

# Answer
> 1 votes
# Japt v2.0a0, 17 bytes

```
r/^.*?\y+/@[XXX]¸

```

Try it | Check all test cases

---

## Explanation

```
                      :Implicit input of string
r/^.*?\y+/            :RegEx replace
                      :  ^ is required to save the extra bytes disabling the g flag
                      :  \y is the class for [AEIOUYaeiouy]
          @[XXX]      :An array containing three copies of the match
                ¸     :Joined to a string with spaces
                      :Implicit output of result

```

# Answer
> 1 votes
# Jelly, 13 bytes

```
e€ØyIi-⁸ḣ;⁶Ȯ;

```

Try it online!

Full program.

# Answer
> 1 votes
# Julia 0.6, 45 bytes

```
s->(match(r"^.*?[aeiouy]+"i,s).match*" ")^2*s

```

Try it online!

A pretty straightforward regex-based solution (for now at least). `*` is a concatenation operator when applied to strings, and `^` is a self-concatenation operator - `"Moo "^2 == "Moo "*"Moo " == "Moo Moo "`.

# Answer
> 1 votes
# Java 8, 49 bytes

Lambda from `String` to `String`.

```
s->s.replaceAll("(?i)^(.*?[aeiouy]+)","$1 $1 $1")

```

Try It Online

The same regular expression approach many are using. `(?i)` turns on case insensitivity, the capture group is substituted for each `$1` in the replacement string, and `.*?` is lazy so that it doesn't match vowels.

# Answer
> 1 votes
# Vyxal `r`, 16 bytes

```
k∩c)M¯uḟ₌iẎ+:"JṄ

```

Try it online!

Explanation:

```
   )              # Lambda from the beginning of the line
k∩                #   Does "aeiouyAEIOUY"
  c               #   Contain the lambdas argument
    M             # Map that lambda over the input string returning a list of 1s and 0s (1 if a vowel and 0 if not)
     ¯            # Differences between each
      u           # Negative 1
       ḟ          # In the list of the differences, find the first index of that
                  # (this will be the length of the string to prepend twice (let's call that s), minus 1. Let's call that number l)
        ₌         # Apply the next two elements to the top of the stack
         i        #   Index; get the lth character from the input (0-indexed)
          Ẏ       #   Get the first l characters from the input
           +      # Add (r flag flips argument order).
                  # Now we have s, but found in a way that if l is -1 (i.e. -1 isn't in the deltas) s isn't just an empty string
            :     # Duplicate
             "    # Pair (resulting in [s, s])
              J   # Prepend (not append because of r flag) that to the input
               Ṅ  # Join by spaces

```

# Answer
> 1 votes
# Thunno 2 `J`, 16 bytes

```
ð+k.s€ƇJTȮ⁺ɱð+ḌƤ

```

Try it online!

#### Explanation

```
ð+k.s€ƇJTȮ⁺ɱð+ḌƤ  # Implicit input
ð+                # Append a space to the input string
  k.s€Ƈ           # Check if each character is in the string "AEIOUYaeiouy"
       JTȮ⁺       # Find the first one-based index of [1, 0]
           ɱ      # Take this many characters from the start of the input
            ð+    # Append a space to this string
              ḌƤ  # Double it and append the input string
                  # Implicit output

```

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 70 bytes

```
	T =INPUT
	T (ARB SPAN('AEIOUYaeiouy')) . X
	OUTPUT =X ' ' X ' ' T
END

```

Try it online!

# Answer
> 0 votes
# Node.JS, 64 bytes

```
console.log(process.argv[2].replace(/.*?[aeiouy]+/i,"$& $& $&"))

```

# Answer
> 0 votes
## C# (Visual C# Interactive Compiler), ~~79~~ 75 bytes

Since it hasn't been posted yet...

```
f=>{var v=new Regex(".*?[aeiouyAEIOUY]+").Match(f).Value+" ";return v+v+f;}

```

Try it online!

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


title: Simplify a fraction

text:
# Question
Title: Simplify a fraction
# Winner: Ian D. Scott's answer, by one byte (48 bytes)! Superb!

Your program must accept input from a fraction that can be simplified, then simplify it.

Rules:

* If the fraction is already in its most simplified form, you must inform the user
* No built-in functions to do this
* The user must type the number at some point, however the method the program reads it does not matter. It can be with stdin, console.readline, etc. As long as the user types `9/18` (for example) at some point, it is valid
* Output must be done with stdout, console.writeline, etc...
* The fraction will be put in as `x/y`, and must output as `a/b`
* The fraction must output the most simplified form. For example, 8/12 -\> 6/9 is *not valid*, the only valid solution is 2/3.

---

* This contest ends on August 9th, 2014 (7 days from posting)
* This is a question, so the shortest code wins

# Answer
# Python - ~~69~~ 48

The first thing to do is to represent it in python's native format for storing fractions, namely the Fraction class.

```
print(__import__("fractions").Fraction(input()))

```

Now we simplify... but look! It's already simplified.

Does this count as using a built-in function? It is not intended specifically for simplifying, and Fraction is a class anyway, not a function.

I didn't call any simplifying function, so it's not my fault if python decides to do it itself.
> 1 votes

# Answer
# \>\<\> (92)

```
0v
+>>>>>>a*ic4*-:0(?v
v@:{:~^?=2l0  ,a~ <
>:?!v:@%
=1:~<;no-1*4c,n,@:/?
|oooo;!'simplest' /

```

I know I can get this lower, I'll golf it a bit more in the morning.

Basic explanation: First two lines, and the latter half of the third, are all for reading numbers. Sadly, \>\<\> has no way to do that, so the parsing takes up half the program.

4th line is a simple iterative gcd calculation. I'm surprised at how well \>\<\> did on byte count for the actual algorithm. If it wasn't for the terrible i/o, it could actually be a reasonable golf language.

Last two lines are just for printing the result and dividing the original numbers by the gcd.
> 5 votes

# Answer
### GolfScript, 49 characters

```
'/'/{~}%.~{.@\%.}do;:G({{G/}%'/'*}{;'simplest'}if

```

Run the two testcases here:

```
> 8/12
2/3

> 7/12
simplest

```
> 3 votes

# Answer
# JavaScript 101

For once, a solution not using EcmaScript 6

```
v=prompt().split('/');for(a=v[0]|0,b=v[1]|0;a-b;)a>b?a-=b:b-=a;
alert(a>1?v[0]/a+'/'+v[1]/a:'Reduced')

```

But with E6 could be 93

```
[n,d]=prompt().split('/');for(a=n|0,b=d|0;a-b;)a>b?a-=b:b-=a;
alert(a>1?n/a+'/'+d/a:'Reduced')

```
> 3 votes

# Answer
# PHP\>=7.1, 76 Bytes

```
for([$x,$y]=explode("/",$argn),$t=1+$x;$y%--$t||$x%$t;);echo$x/$t."/".$y/$t;

```

Online Version
> 3 votes

# Answer
# Python 2.7, 124

```
from fractions import gcd;x,y=map(int,raw_input().split('/'));g=gcd(x,y);print'%d/%d'%(x/g,y/g)if g!=1 else'Already reduced'

```

Very simple solution, though I know it would be shorter in many other languages.

I used an imported `gcd` but if it counts as a built-in fraction reducer it could be implemented directly.
> 2 votes

# Answer
# Python 2 (82)

```
A,B=a,b=map(int,raw_input().split("/"))
while b:a,b=b,a%b
print`A/a`+"/"+`B/a`,a<2

```

Prints a Boolean afterward to say whether the original was in simplest form. Just does the usual GCD algorithm. Most of the characters are spent on input/output.
> 2 votes

# Answer
**C, 94**

Just brute force guess and check, for GCD starting at a|b down to 1;

```
main(a,b,c){scanf("%d/%d",&a,&b);for(c=a|b;--c;)if(a%c+b%c<1)a/=c,b/=c;printf("%d/%d\n",a,b);}

```
> 1 votes

# Answer
# Vyxal, 0 bytes

```

```

Try it Online!

Yes. It really is 0 bytes. It doesn't use any built-in functions, as inputted fractions are simplified by default.

The benefits of using rational numbers internally!
> 1 votes

# Answer
# ARBLE, 54 bytes

```
(a/c.."/"..b/c)(a,b,index(range(a+b,1)&nt(a%c+b%c),1))

```

## Explained

```
(a/c.."/"..b/c)(a,b,index(range(a+b,1)&nt(a%c+b%c),1))
                          range(a+b,1)                  -- All numbers from (a+b) down to 1.
                                      &                 -- Filter
                                       nt(a%c+b%c)      -- Both a and b divisible by the iterator
                    index(                        ,1)   -- Get the first value (Naturally the highest)
(             )(a,b,                                 )  -- Pass a, b, and the gcd of a and b to the stringifier
 a/c.."/"..b/c                                          -- Format as a fraction.
                                                        -- Returns a two argument function.

```

Takes input as two numbers. Outputs as `1.0/2.0`. The trailing `.0` can be removed for +2 bytes by replacing `(a/c.."/"..b/c)` with `(a//c.."/"..b//c)`

Try it online!
> 1 votes

# Answer
# Rebmu (104 characters)

```
P"/"rSst[a b]paSp AtiA BtiB Ca DbFOiMNcD 1 -1[izADmdCiMDdI[CdvCi DdvDi]]QapAPtsCpTSdIa^e?aCe?bD[Q"Err"]Q

```

Unmushed:

```
P"/"
rS
; extract numerator to a, denominator to b
st [a b] pa s p
; convert a,b to integers
AtiA
BtiB
; set c=a, d=b
Ca Db
; loop from min(c,d) to 1
fo i mn c d 1 -1[
    ; check if (c mod i) + (d mod i) is 0
    iz ad md c i md d i [
        ; divide c, d by i
        Cdv c i
        Ddv d i
    ]
]
; set Q to c/d
Qap ap ts c p ts d
; check if a==c and b==d
i a^ e? a c e? b d[
    ; set q to "err"
    Q"err"
]
; print q
Q

```
> 0 votes

# Answer
# PHP 156

*meh.*

```
$f=$argv[1];$p=explode('/',$f);$m=max(array_map('abs',$p));for(;$m;$m--)if(!($p[0]%$m||$p[1]%$m)){$r=$p[0]/$m.'/'.$p[1]/$m;break;}echo $r===$f?'reduced':$r;

```

Run:

```
php -r "$f=$argv[1];$p...[code here]...:$r;" 9/18;
1/2

```
* prints "reduced" if the fraction is already in its simplest form
* works with negative fractions
* works with improper fractions (e.g. 150/100 gives 3/2)
* *kinda* works with decimals (e.g. 1.2/3.6 gives 0.75/2.25)
* 99/0 incorrectly gives 1/0 *?*
* won't reduce to a whole number (e.g. 100/100 gives 1/1)

Here's an ungolfed version with some testing (modified into function form):

```
<?php
$a = array(
    '9/18','8/12','50/100','82/100','100/100','150/100','99/100',
    '-5/10','-5/18','0.5/2.5','1.2/3.6','1/0','0/1','99/0'
);
print_r(array_map('r',array_combine(array_values($a),$a)));

function r($f) {
    $p = explode('/',$f);
    $m = max(array_map('abs',$p));
    for ( ; $m; $m-- )
        if ( !($p[0] % $m || $p[1] % $m) ) {
            $r = $p[0]/$m.'/'.$p[1]/$m;
            break;
        }
    return $r === $f ? 'reduced' : $r;
}
/*
Array(
    [9/18] => 1/2
    [8/12] => 2/3
    [50/100] => 1/2
    [82/100] => 41/50
    [100/100] => 1/1
    [150/100] => 3/2
    [99/100] => reduced
    [-5/10] => -1/2
    [-5/18] => reduced
    [0.5/2.5] => 0.2/1
    [1.2/3.6] => 0.75/2.25
    [1/0] => reduced
    [0/1] => reduced
    [99/0] => 1/0
)
*/
?>

```
> 0 votes

# Answer
**Java, 361 349 329 (thanks @Sieg for the `int` tip)**

```
class P{public static void main(String[]a){String[]e=a[0].split("/");String f="";int g=new Integer(e[0]),h=new Integer(e[1]);if(g>h){for(int i=h;i>=1;i--){if(g%i==0&&h%i==0){f=g/i+"/"+h/i;break;}}}else if(g<h){for(int i=g;i>=1;i--){if(g%i==0&&h%i==0){f=g/i+"/"+h/i;break;}}}else if(g.equals(h)){f="1/1";}System.out.println(f);}}

```

I know it's not short, but I'm just mesmerized of what I did.

To use it, compile the code and run it passing the arguments through the command-line.

* Integers only (I'm not into `doubles` and the task doesn't require it).
* If the fraction is already simplified, returns itself.
* Doesn't work with negative fractions.
* Dividing by zero? No cookie for you (Returns an empty string).

Ungolfed (if anyone wants to see this mess):

```
class P{
    public static void main(String[]a){
        String[]e=a[0].split("/");
        String f="";
        int g=new Integer(e[0]),h=new Integer(e[1]);
        if(g>h){
            for(int i=h;i>=1;i--){
                if(g%i==0&&h%i==0){
                    f=g/i+"/"+h/i;
                    break;
                }
            }
        }else if(g<h){
            for(int i=g;i>=1;i--){
                if(g%i==0&&h%i==0){
                    f=g/i+"/"+h/i;
                    break;
                }
            }
        }else if(g.equals(h)){
            f="1/1"; //no processing if the number is THAT obvious.
        }
        System.out.println(f);
    }
}

```
> 0 votes

# Answer
### Ruby — 112 characters

`g` is a helper lambda that calculates the GCD of two integers. `f` takes a fraction as a string, e.g. `'42/14'`, and outputs the reduced fraction or `simplest` if the numerator and denominator are relatively prime.

```
g=->a,b{(t=b;b=a%b;a=t)until b==0;a}
f=->z{a,b=z.split(?/).map &:to_i;y=g[a,b];puts y==1?:simplest:[a/y,b/y]*?/}

```

Some test cases:

```
test_cases = ['9/18', '8/12', '50/100', '82/100', '100/100',
              '150/100', '99/100', '-5/10', '-5/18', '0/1']

test_cases.map { |frac| f[frac] }

```

Output:

```
1/2
2/3
1/2
41/50
1/1
3/2
simplest
-1/2
simplest
simplest

```

Note, although against the rules, Ruby has `Rational` support baked in, so we could do

```
a=gets.chomp;b=a.to_r;puts b.to_s==a ?:simplest:b

```
> 0 votes

# Answer
# Lua - 130 115 characters

*10/10 i really tried*

```
a,b=io.read():match"(.+)/(.+)"u,v=a,b while v+0>0 do t=u u=v v=t%v end print(a+0==a/u and"reduced"or a/u.."/"..b/u)

```
* prints "reduced" if fraction is in simplest form
* works with negatives
* works with improper fractions
* presumably works with decimals (1.2/3.6 gives 5.4043195528446e+15/1.6212958658534e+16)
* any number/0 gives 1/0
* does not reduce to whole numbers

I fully took advantage of Lua's ability to auto convert a string to a number when doing arithmetic operations on a string. I had to add "+0" in place of tonumber for some comparison code.

Sorry, I don't have an ungolfed version, the above is actually how I wrote it
> 0 votes

# Answer
# JavaScript (91) (73)

Returns '/' when the fraction is already in it's simplest form. The function g calculates the gcd. BTW: Is there any shorter way for '1==something' where something is a non negative integer?

`function s(f){[n,m]=f.split(b='/');g=(u,v)=>v?g(v,u%v):u;return 1==(c=g(n,m))?b:n/c+b+m/c;}`

Thanks to @bebe for an even shorter version:

```
s=f=>([n,m]=f.split(b='/'),c=(g=(u,v)=>v?g(v,u%v):u)(n,m))-1?n/c+b+m/c:f;

```
> 0 votes

# Answer
# Batch - 198

```
for /f "tokens=1,2delims=/" %%a in ("%1")do set a=%%a&set b=%%b&set/ac=%%b
:1
set/ax=%a%%%%c%&set/ay=%b%%%%c%
if %x%%y%==00 set/aa/=%c%&set/ab/=%c%
if %c% GTR 0 set/ac=%c%-1&goto 1
echo %a%/%b%

```

Input is split as `a/b`, then for every `c` in `b,b-1,...1` we check if `a` and `b` are divisible by `c`, and divide them by `c` if they are. Then we return `a/b`
> 0 votes

# Answer
# Befunge 93 (192)

```
&04p~$&14p2       > :24p  v       >34g#v_0"tselpmiS">:#,_@
>134p 24g>        ^+1g42$<>04g`   |    >04g."/",14g.@
^p41/g42p40/g42<         |%g42:g41<
         #     |!%g42:g40<
   0     ^+1g42<

```
> 0 votes

# Answer
## C 135

Accepts input for 2 space-separated integers. Keeps dividing by minimum of a & b down to 1 to find GCD.

```
int a,b,m;
void main()
{
scanf("%d %d", &a, &b);
m=a<b?a:b;
for (;m>0;m--){if (a%m==0&&b%m==0)break;}
printf("%d/%d",a/m,b/m);
}

```
> 0 votes

# Answer
# Java (200)

The previous best solution in Java still had \>300 bytes, this one has 200:

```
class M {public static void main(String[]args){String[]s=args[0].split("/");int a=Integer.parseInt(s[0]),b=Integer.parseInt(s[1]),c=a,d=b;while(d>0){int g=c;c=d;d=g%d;}System.out.print(a/c+"/"+b/c);}}

```

This uses the (faster) modulo to determine the gcd instead of iterating all numbers.
> 0 votes

---
Tags: code-golf, rational-numbers
---