title: N-dimensional identity "matrix"

text:
# Question
Title: N-dimensional identity "matrix"
Given a positive integer `n`, output the `N`-dimensional identity "matrix", which is the `N^N` array with `1` where all the components of the indices are equal and `0` otherwise. `N^N` means N-by-N-by-N-by-...

```
1 -> [1]

2 -> [[1,0],[0,1]]

3 -> [[[1,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,1,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,1]]]

4 -> [[[[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]],[[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]],[[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]],[[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]]]]

```

For example, if `a` is the `4`-dimensional identity "matrix", then the only entries with `1` would be `a[0][0][0][0]`, `a[1][1][1][1]`, `a[2][2][2][2]`, and `a[3][3][3][3]`.

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
> 16 votes
# Octave, 29 bytes

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

```

Try it online!

# Answer
> 10 votes
# Jelly, 8 bytes

```
×=¥þ’¡`Ṡ

```

Try it online!

Ooh, looks like I get to outgolf @Dennis in his own language again :-)

This is a 1-argument function (because Jelly's default output format for nested lists is a little ambiguous, meaning that it arguably doesn't fulfil the spec as a full program).

## Explanation

```
×=¥þ’¡`Ṡ
     ¡    Repeatedly apply the following operation,
    ’     {input-1} times in total:
   þ        For each element of the current value {perhaps made into a range}
      `     and of {the range from 1 to the} {input}:
 =            Compare corresponding elements, giving 0 for equal or 1 for unequal
× ¥           then multiply by one of the elements
       Ṡ  then replace each element with its sign

```

In order to understand this, it helps to look at the intermediate steps. For an input of 3, we get the following intermediate steps:

1. `[1,2,3]` (input, made into a range implicitly by the `þ`)
2. `[[1,0,0],[0,2,0],[0,0,3]]` (make a table with `[1,2,3]`, compare for equality to get `[[1,0,0],[0,1,0],[0,0,1]]`, then multiply by one of the values we compared)
3. `[[[1,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,2,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,3]]]` (the same idea again)
4. `[[[1,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,1,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,1]]]` (replace each element with its sign using )

Note the fact that the input starts out 1-dimensional means that we have to loop (input-1) times in order to add (input-1) dimensions, producing an input-dimensional list.

Fun fact: this program contains five quicks in a row, `¥þ’¡``. (A quick is a modifier to a "link", or builtin, used to modify its behaviour or combine it with another link.)

# Answer
> 7 votes
## Mathematica, 30 bytes

```
Array[Boole@*Equal,#~Table~#]&

```

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

```
1=≢∘∪¨⍳⍴⍨⎕

```

Try it online!

`1=` \[is\] 1 equal to

the number

of

unique elements

`¨` in each of

the indices in an array with the dimensions of

`⍴⍨` the self-reshape (*N* copies of *N*) of

the input (*N*) \[?\]

# Answer
> 5 votes
# Jelly, 9 bytes

```
ðṗE€ṁ+þ’¡

```

Try it online!

### How it works

Achieving the task directly seems to be difficult (I haven't found a way), but contructing arrays of the same numbers and arrays of the same shape is quite easy.

`ð` makes the chain dyadic, and the integer input **n** serves as both left and right argument for the chain. It's possible to use a monadic chain instead, but the parsing rules for dyadic ones save three bytes here (two after accouting for `ð`).

The *Cartesian power* atom , with left and right argument equal to **n**, constructs the array of all vectors of length **n** that consist of elements of **\[1, ..., n\]**, sorted lexicographically.

When **n = 3**, this yields

```
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3, 1], [1, 3, 2], [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 3, 1], [3, 3, 2], [3, 3, 3]]

```

The *equal each* quicklink `E€` tests the elements of all constructed vectors for equality.

When **n = 3**, we get

```
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

```

which are the elements of the 3-dimensional identity matrix, in a flat array.

The dyadic quicklink `+þ’¡` is called with left argument and right argument **n**. The quick `¡` calls the decrement atom , which yields **n-1**, then calls the *add table* quicklink  **n-1** times.

Initially, the arguments of  are both **n**. After each call, the right argument is replaced by the left one, and the left one is replaced by the return value of the call.

The *table* quick calls the *add* atom `+` for each elements of its left argument and each element of its right argument, constructing a table/matrix of the return value. The initial integer arguments **n** are promoted to the ranges **\[1, ... n\]**.

When **n = 3**, after promotion but before the first iteration, both arguments are

```
[1, 2, 3]

```

Adding each integer in this array to each integer in this array yields

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

```

In the next invocation, we add each of these arrays to the integers in **\[1, 2, 3\]**. Addition vectorizes (adding an integer to an array adds it to each element), so we get

```
[[[3, 4, 5], [4, 5, 6], [5, 6, 7]],
 [[4, 5, 6], [5, 6, 7], [6, 7, 8]],
 [[5, 6, 7], [6, 7, 8], [7, 8, 9]]]

```

This array has the same shape as the 3-dimensional identity matrix, but not the correct elements.

Finally, the *mold* atom  discards the integer entries of the result to the right and replaces them in order with the elements in the result to the left.

# Answer
> 4 votes
# Python, 70 bytes

```
f=lambda n,l=[]:[f(n,l+[i])for i in(len(l)<n)*range(n)]or+(l==l[:1]*n)

```

Try it online!

A recursive solution. Thinking of the matrix as a list of matrices one dimension smaller, it iterates over that list to go down the tree. It remembers the indices picked in `l`, and when `n` indices have been picked, we assign a `1` or `0` depending on whether they are all the same.

---

# Python 2, 73 bytes

```
n=input();r=0
exec'r=eval(`[r]*n`);'*n+('n-=1;r'+'[n]'*n+'=1;')*n
print r

```

Try it online!

An improvement on totallyhuman's method of making a matrix of zeroes and then assigning ones to the diagonal.

---

# Python 2, 88 bytes

```
n=input()
t=tuple(range(n))
print eval('['*n+'+(i0'+'==i%d'*n%t+')'+'for i%d in t]'*n%t)

```

Try it online!

Some nonsense with `eval`, generating a nested list, and string-format substitution. The string to be evaluated looks like:

```
[[[+(i0==i0==i1==i2)for i0 in t]for i1 in t]for i2 in t]

```

# Answer
> 4 votes
# Python 2 + NumPy, ~~80~~ ~~72~~ 70 bytes

Now tied with the top Python answer!

```
from numpy import*
n=input()
a=zeros((n,)*n)
a[[range(n)]*n]=1
print a

```

**Try it online**

<sub>*Saved 8 bytes thanks to Andras Deak, and 2 by officialaimm*</sub>

# Answer
> 3 votes
# Python 2, ~~99~~ ~~93~~ 90 bytes

*Thanks to Rod for ~~some~~ even more help that got it working and also shaved 6 bytes off! -3 bytes thanks to xnor.*

```
n=input()
r=eval(`eval('['*n+'0'+']*n'*n)`)
for i in range(n):exec'r'+`[i]`*n+'=1'
print r

```

Try it online!

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

```
f=(n,d=n-1,i)=>[...Array(n)].map((_,j)=>d?f(n,d-1,j-i?n:j):j-i?0:1)

```

Explanation: `i` is used to keep track of whether the cell is on the main diagonal or not. Initially it's undefined, so on the first recursive call we always pass the first dimension, while on subsequent recursive calls we only pass it on if the current dimension index is equal to all previous dimensions, otherwise we pass an index of `n` which indicates that all of the recursive cells should be zero.

# Answer
> 2 votes
# , ~~64~~ 49 bytes

*-15 bytes thanks to Jarko Dubbeldam*

```
x=array(0,rep(n<-scan(),n));x[seq(1,n^n,l=n)]=1;x

```

Reads from stdin and returns an array, printing as matrices. `seq` generates a sequence evenly spaced from `1` to `n^n` with length `l=n`, which does the trick quite nicely to index where the 1s go.

Try it online!

### old version:

```
n=scan();x=rep(0,n^n);x=array(x,rep(n,n));x[matrix(1:n,n,n)]=1;x

```

Reads `n` from stdin; returns an array, printing the results as matrices. I struggled with this for a while until I read the docs for `[`, which indicate that a matrix can be used to index an array, where each row of the matrix represents the set of indices. Neat!

Try it online!

# Answer
> 2 votes
# Brainfuck, 61 bytes

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

```

## Ungolfed

The numbers after the angle brackets indicate the cell the head is over.

```
>,                   read n to 1
[->+>+<<]            move 1 to 2 and 3
>2[-<<+>>]>3         move 2 to 0
                     (tape: n 0 0 n 0)
-[                   while cell 3 {
    -                  dec 3
    >4+.-<3            print \x1
    <<<0[->+>+<<]      move 0 to 1 and 2
    >1[-<+>]>2         move 1 to 0
                       (tape: 0 0 n rows_left 0)
    [                  while cell 2 {
        -                dec 2
        >>4.<<           print \x0
    ]>3                }
]                    }
+.                   print \x1

```

Try it online!

Input is a binary number. Output is a matrix stored in row-major order.

# Answer
> 1 votes
# , ~~16~~ 15 bytes

```
i.@#~=i.*]#.#&1

```

Try it online!

# Answer
> 1 votes
# Common Lisp, ~~147~~ 133 bytes

```
(defun i(n)(flet((m(x)(fill(make-list n)x)))(let((a(make-array(m n):initial-element 0)))(dotimes(i n)(incf(apply #'aref a(m i))))a)))

```

Try it online!

The usual super-lengthy lisp. Reduced 12 bytes thank to @ceilingcat!

Explanation:

```
(defun i (n)
  (flet ((m (x) (fill (make-list n) x)))            ; function to build a list of n values x
    (let ((a (make-array (m n) :initial-element 0))); build the array with all 0
      (dotimes (i n)                                ; for i from 0 to n-1
        (incf (apply #'aref a (m i))))              ; add 1 to a[i]..[i]
      a)))                                          ; return the array

```

# Answer
> 1 votes
## Python 3 + numpy, ~~81~~ 77 bytes

```
from numpy import*
f=lambda n:all([a==range(n)for a in indices((n,)*n)],0)+0

```

I'm not *entirely* sure that the above fits all guidelines: it returns an ndarray with the given properties. I know anonymous functions are usually fine, but an interactive shell will actually print

```
>>> f(2)
array([[1, 0],
       [0, 1]])

```

If the array fluff makes the above invalid, I have to throw in a `print()` for something like 7 additional bytes.

Try it online!

# Answer
> 1 votes
# Pyth, 14 bytes

```
ucGQtQms!t{d^U

```

Test suite

Explanation: `^U`, which is implicitly `^UQQ`, where `Q` is the input, calculates all possible Q element lists of the range `0 ... n-1`. `ms!t{d` maps the ones with all elements equal to 1, and the rest to 0. This gives the flattened output

`ucGQtQ` executes the following, Q - 1 times: Chop the input into lists of size Q.

# Answer
> 1 votes
# C# (.NET Core), 166 bytes

```
n=>{var c=new int[n];int i=0,d;for(;i<n;c[i++]=n);var m=System.Array.CreateInstance(typeof(int),c);for(i=0;i<n;i++){for(d=0;d<n;c[d++]=i);m.SetValue(1,c);};return m;}

```

Try it online!

At first I thought it could not be done with a lambda expression in C#... ^\__^U

# Answer
> 1 votes
# Vyxal, 6 bytes

```
ẋÞm⁽≈€

```

Try it Online!

My first submission, thanks to emanresu for help with the lambda.

# Answer
> 0 votes
# SOGL V0.12, 22 bytes

```
.^κ.H/ 0* 1.H≤Οčr.H{.n

```

Try it Here!
Leaves the output on the stack, viewable in the console. If the numbers in the output were allowed to be strings, then the `r` could be removed.
Just as a fun test of how SOGL does in challenges it was completely not made for :p

```
input: x
.^                      push  x^x
  κ                     subtract x    (x^x)-x
   .H/                  divide by x   ((x^x) - x)/x
       0*               get that many zeroes
          1             push "1"
           .H           push x-1
             ≤          pull the first item from the stack to the top
              Ο         encase (x-1 times the zeroes, separated, started and ended with 1s)
               č        chop to a char-array
                r       convert each character to a number
                 .H{    repeat x-1 times:
                    .n    in the top array, for each group of x contents, encase that in an array

```

# Answer
> 0 votes
## Clojure, 92 bytes

```
#(reduce(fn[v i](assoc-in v(repeat % i)1))(nth(iterate(fn[v](vec(repeat % v)))0)%)(range %))

```

Nice that assoc-in works also with vectors, not only with hash-maps.

---
Tags: code-golf, math, array, integer, generation
---


title: Tips for restricted source in Haskell

text:
# Question
Title: Tips for restricted source in Haskell
I tested the waters on this sort of question with python, but now I get to the real question I want to ask.

challenges are uniquely rewarding in Haskell because of Haskell's strict rule set. Type coercion which is the bread and butter for other languages in these sort of challenges is arguably non-existent but when pushed to the limits Haskell provides some weird and interesting solutions.

What are some for solving challenges in Haskell?

Please only include 1 tip per answer. If your tip only works for a specific compiler, or version of Haskell please note that.

---

## What makes a good tip here?

There are a couple of criteria I think a good tip should have:

1. It should be (somewhat) non obvious.

Similar to the tips it should be something that someone who has golfed in python a bit and read the tips page would not immediately think of. For example "Replace `a + b` with `a+b` to avoid using spaces", is obvious to any golfer since it is already a way to make your code shorter and thus not a good tip for this question.
2. It should not be too specific.

Since there are many different types of source restrictions, answers here should be at least somewhat applicable to multiple source restrictions, or one common source restriction. For example tips of the form **How to X without using character(s) Y** are generally useful since banned characters is a common source restriction, or the byproduct of more unique restrictions. The thing your tip helps to do should also be somewhat general. For example tips of the form **How to create numbers with X restriction** are useful since many programs utilize numbers regardless of the challenge. Tips of the form **How to implement Shor's algorithm with X restriction** are basically just answers to a challenge you just invented and not very helpful to people solving other challenges.

# Answer
# Break tokens with comments

A neat fact I discovered a little while ago (and the impetus for this sort of tips question in the first place), is that a block comment allows you to split tokens apart without a space.

For example if you want to write

```
main=interact tail

```

Without using whitespace, parentheses or `$` you can do the following:

```
main=interact{--}tail

```

Here `{--}` is a block comment, which normally would do nothing, however here placed between `interact` and `tail` it serves to prevent the two as being parsed as a single token, `interacttail`.

This could also be used to split other kinds of tokens for example:

```
main=print${--}-3

```

Here we split the `$` and the `-` without using spaces or parentheses.

```
data{--}K=K

```

Here we split a keyword from a type declaration (which unlike the earlier example cannot be done with `$`).

Pretty much anywhere you would use a space outside a `String` or `Char` literal you can use a block comment instead.
> 11 votes

# Answer
## Anything can be an infix operator

While `(&)` is usually the "prefix form" of an infix function, it doesn't have to be defined as infix, or even a function. The following definition of a unary function `(#)` with argument `(&)`, a list of numbers, compiles and runs just fine:

```
(#)(&)=(&)!!0+(&)!!3

```

This could be useful if alphabetic characters are forbidden/restricted/penalized.
> 9 votes

# Answer
# Name your variables `__` and `_'`

Before you go naming things as infix operators if you need to avoid letters you can name things `__` and `_'`. These are only 2 bytes long whereas infix operators are 3. And once you run out of 1 character infix operators `___`, `__'`, `_'_` and `_''` are all available.

You can see this used here by Lynn.
> 1 votes

---
Tags: restricted-source, tips, haskell
---


title: Write "tut-tut-tut" without using "tut"

text:
# Question
Title: Write "tut-tut-tut" without using "tut"
Following this question: Tut-tut-tut-tut-tut

Write a program that writes "tut-tut-tut" **without** using the characters "t", "u" or "-" in the code itself.

This is code golf, shortest code in bytes wins.

# Answer
# Japt, 9 bytes

```
Bî`¡s,`cÄ

```

Test it

```
Bî`¡s,`cÄ
B             :11
 î            :Repeat to length B
  `¡s,`       :  Compressed string "sts,"
       c      :  Map charcodes
        Ä     :    Add 1

```
> 3 votes

# Answer
# Windows Batch, 169 115 bytes

No code points, but assuming capital letters are OK for the output, as this will produce TuT-TuT-TuT

```
@for /f %%a in ('sc^|find "CO"') do @se%OS:~9% q=%%a
@se%OS:~9% a=%q:~8,1%%OS:~9%%q:~6,1%%OS:~9%
@echo %a:~1%%a%%a%

```

Length calculated by using Unix/LF as EOL, without an EOL at the end of the last line.

Shaved of 54 bytes thanks to @jdt, who posted a solution using code points (which I wanted to avoid), but contained three `t`s. Thinking about ways to fix this made me have another go at mine as well.

The first issue with Batch is that you can't even `set` a variable without using a `t`.
But Batch will expand variables in a command first and then take the resulting line verbatim, so the forbidden characters can be picked from a variable. As luck would have it, there is a default environment variable with only two letters, and it even has the T at the last position (allowing to drop the substring length when extracting the T): `OS=Windows_NT`.
So a `T` in a command line can be replaced by `%OS:~9%`, which solves most of the problems; but no such luck for `U` or `-`.

`@for /f %%a in ('sc^|find "CO"') do @se%OS:~9% q=%%a`
This will use the help for sc.exe, find the line  `continue--------Sends a CONTINUE control request to a service.`, break it into tokens at spaces (discarding empty fields), and set the variable `q` to `continue--------Sends`, where `u` and `-` are at single-digit positions.

`@se%OS:~9% a=%q:~8,1%%OS:~9%%q:~6,1%%OS:~9%`
This sets `a` to `-TuT` by picking characters from `OS` and `q`.

`@echo %a:~1%%a%%a%`
This prints `a` three times, with the first instance `%a:~1%` starting with the second character to remove the leading `-`.

---

## Alternative answer by @jdt, 118 bytes

```
@for %%a in (84,85,84,45,84,85,84,45,84,85,84) do @(cmd /C exi%OS:~9% %%a&echo|se%OS:~9% /p=%%^=Exi%OS:~9%CodeAscii%%)

```

@jdt posted this in a comment for initially 110 bytes, but it used `exit`, `set`, and `ExitCodeAscii` in the original. Replacing the `t`s with `%OS:~9%` brought it to 128, some more golfing brought it down to a one-liner with 118 bytes.

---

---

## Previous version

```
@for /f %%a in ('help^|find "SE%OS:~9,1% "') do @%%a s=%%a
@for /f "delims=" %%a in ('wmic/?^|find "/E"') do @%s%q=%%a
@%s%a=%q:~10,1%%q:~3,1%%q:~1,1%%q:~3,1%
@echo %a:~1%%a%%a%

```

Used the line `SET Displays, sets, or removes Windows environment variables.` of the `help` output to set a variable to `SET` . Above is the "safe" version (178 bytes) that should work with localized versions as well. In the optimized version for **English** versions of cmd.exe **only** (otherwise the first line might run some unexpected commands, and/or not work at all), the first line changes to this, for a total of 169 bytes:
`@for /f %%a in ('help^|find "s e"') do @%%a s=%%a`  (this line ends with a trailing space!)
> 3 votes

# Answer
# BQN, 11 bytesSBCS

```
11⥊"rsr+"+2

```

`"rsr+"+2` add 2 to the code points of "rsr+" giving "tut-"

`11⥊` cyclically reshape to length 11

Run online!
> 2 votes

# Answer
# Python 2.7 and 3.xx, ~~45~~ 44 bytes

This was harder and easier than I though...

```
exec('prin\x74(("\x2d\x74\x75\x74"*3)[1:])')

```

I've tested it on Python 2.7.11+, 3.9.6 and 3.10.5.

Good 'ol ~~evil~~ ~~eval~~ exec to the rescue!

---

Thanks to @Dingus for pointing out a mistake, and @Bubbler for saving 1 byte.

---

---

# Alternative answers

Personally, I feel these are against the spirit of the challenge, and that's why they aren't replacing the "main" answer.

## Python 2.7 and 3.xx, 40 bytes

This is an alternative provided by @Bubbler.
It uses "TUT" instead of "tut", for the string, saving 1 byte.
I modified a little, to save 3 more bytes.

```
exec('prinT(("\x2dTUT"*3)[1:])'.lower())

```

This was edited to use `exec` to run in Python 2.7.

## Python 2.7 and 3.xx, 40 bytes

This alternative was written by @py3programmer.
It produces the correct output, and avoids the `[1:]` string indexing.

```
exec("prinT('TUT\x2d'*2+'TUT')".lower())

```
> 2 votes

# Answer
# PowerShell (Core or Windows), 46 bytes

No code points; taking advantage of the long cmdlet names for a change ...

```
$ofs='';"$((gal oh|% R*e)[3,2,1,2])"*3|% S*g 1

```

Try it online!

```
$ofs='';                                       # set the output field separator to an empty string
            gal oh                             # gal is an alias for Get-Alias; oh is an alias for Out-Host; returns an AliasInfo object
                  |% R*e                       # pipe the AliasInfo object for "oh" to % (an alias for ForEach-Object), and call its member ResolvedCommandName, which will return the string "Out-Host"
           (            )[3,2,1,2]             # take the characters at positions 3, 2, 1, 2 from "Out-Host" (-, t, u, t)
        "$(                       )"           # evaluate that in a subexpression $() and stuff it all into a single string "-tut"
                                    *3         # "multiply" with 3 to get "-tut-tut-tut"
                                      |% S*g 1 # pipe that to ForEach-Object again, and call its member "SubString" to get everything starting at position 1

```
> 2 votes

# Answer
# C (clang), 51 bytes

```
i;f(*b){for(i=0;i<4;b[i++]=i^3?762606932:7632244);}

```

Try it online!

# C (clang), ~~69~~ 63 bytes

```
f(){syscall(1,1,L"\x2d747554\x2d747574\x2d747574\x747574",15);}

```

Try it online!

-6 bytes thanks to ceilingcat!!
> 2 votes

# Answer
# Ruby, 70 bytes

```
p"#{[116,117,116,45,116,117,116,45,116,117,116].map{|c|c.chr}.join()}"

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 12 bytes

Four different alternatives:

```
…TUTl45ç«11∍
.•x`•45ç«11∍
'±È3£45ç«6∍û
"vwv/"ÇÍç6∍û

```

Try it online.

Without the it would have been just 3 bytes shorter:

```
"tut-"11∍

```

Try it online.

**Explanation:**

Part 1 alternatives:

```
…TUT       # Push string "TUT"
    l      # Convert it to lowercase
     45    # Push 45
       ç   # Convert it to a character with this codepoint: "-"
        «  # Append the two together: "tut-"

.•x`•      # Push compressed string "tut"
     45ç«  # Same as above

'±È       '# Push dictionary string "tutorial"
   3£      # Only keep its first 3 characters: "tut"
     45ç«  # Same as above

"vwv/"     # Push string "vwv/"
      Ç    # Convert it to a list of its codepoint-integers: [118,119,118,47]
       Í   # Decrease each by 2
        ç  # Convert it from codepoint-integers to a list of characters

```

Part 2 alternatives:

```
11∍        # Extend it to size 11: "tut-tut-tut"
           # (after which the result is output implicitly)

6∍         # Extend it to size 6: "tut-tu"
  û        # Palindromize it: "tut-tut-tut"
           # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `.•x`•` is `"tut"` and `'±È` is `"tutorial"`.
> 1 votes

---
Tags: code-golf, string, restricted-source
---


title: Ode-cay Olf-gay

text:
# Question
Title: Ode-cay Olf-gay
Write a program which accepts a sentence into stdin, and writes that sentence to stdout in pig latin.

Here are some test cases which your program should handle:

```
Input:
    Read your script
Output:
    ead-Ray our-yay ipt-scray

```

Hyphenation is mandatory. Note that multiple consonants at the start of the word must all be moved to the end. Capitalization of the output does not matter; `Ead-ray` or `ead-ray` are also valid translations of `Read`

```
Input:
    An utterance is allowed an opening vowel
Output:
    An-way utterance-way is-way allowed-way an-way opening-way owel-vay

```

Words starting with vowels have `-way` appended in their pig latin form (don't forget to handle capital opening vowels)

```
Input:
    sky
    -skyay

```

Words consisting entirely of consonants should have a hyphen prepended, and `ay` appended

Punctuation is undefined; I don't care if leading or trailing punctuation ends up inside the pig latin word.

This is code golf; the shortest program by character count wins. I've written a solution myself which handles all these cases which I shall post as a response.

# Answer
# Perl (53)

```
s/(.*?)([aeiou].*)/$1||=w;print"$2-$1ay "/iefor split

```
> 3 votes

# Answer
## Python, 89

```
import re
print re.sub('-a','-wa',re.sub('(?i)([^aeiou ]*)(\w*)',r'\2-\1ay',raw_input()))

```
> 4 votes

# Answer
## Perl, 41 excluding switches

A simple modification of Timwi's answer. Runs with `perl -p`. Does not meet the spec for 'sky', but the original doesn't either.

```
s/(\S*?)([aeiou]\S*)/"$2-".($1||w).ay/ige

```
> 4 votes

# Answer
## Perl (60)

Use `perl -n`. The -n switch is counted (as two characters).

```
s/(.*?)([aeiou].*)/print"$2-$1"."w"x!$1."ay "/iefor split

```
> 3 votes

# Answer
### Python - ~~122~~ 85 characters

```
import re
print re.sub("-a","-wa",re.sub("([^aeiou ]*)(\w*)",r"\2-\1ay",raw_input()))

```

122 -\> 85: Improved use of regexes; running regex on whole sentence rather than individual words, and doing all the processing with regexes rather than a conditional expression. This ended up making it pretty similar to grc's answer
> 2 votes

# Answer
**Cojure - 376 characters**

Obviously not winning this one, but figured I'd take a shot at it.

Minified:

```
(defn n [a b] (reduce #(and % %2) (map #(= (.indexOf a %) -1) (map string/lower-case (rest b)))))
(defn t [a] (let [vowels ["a" "e" "i" "o" "u"] x "ay"] (if (> (.indexOf vowels (string/lower-case (first a))) -1) (str a "-way") (if (n vowels a) (str a x) (str (reduce str (rest a)) "-" (first a) x)))))
(defn ay-ya [a] (reduce str (map #(str (t %) " ") (string/split a #" "))))

```

Actual:

```
(defn no-vowel [a b]
    (reduce #(and % %2) (map #(= (.indexOf a %) -1) (map string/lower-case (rest b)))))

(defn transform [text]
  (let [vowels ["a" "e" "i" "o" "u"]]
    (if (> (.indexOf vowels (string/lower-case (first text))) -1)
        (str text "-way")
        (if (no-vowel vowels text)
          (str text "ay")
          (str (reduce str (rest text)) "-" (first text) "ay")))))

(defn ay-ya [text]
    (reduce str
        (map #(str (transform %) " ")
             (clojure.string/split text #" "))))

```
> 2 votes

# Answer
# Perl 6,  ~~78~~  66 bytes

```
put get.words.map: {samecase S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||'w'}ay/, $_}
put get.words.map: {~S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||'w'}ay/}

```

( You would use the `samecase` one if you cared about capitalization )

```
$ perl6 -e 'put get.words.map: {~S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||"w"}ay/}'
Read your script
ead-Ray our-yay ipt-scray

$ perl6 -e 'put get.words.map: {~S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||"w"}ay/}'
An utterance is allowed an opening vowel
An-way utterance-way is-way allowed-way an-way opening-way owel-vay

$ perl6 -e 'put get.words.map: {~S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||"w"}ay/}'
sky
-skyay

```
> 2 votes

# Answer
## K, 95

```
" "/:{$[&/~x in v:v,_v:"AEIOU";"-",x,"ay";("-"/:|_[;x]0,*&t),$[*t:x in v;"way";"ay"]]}'" "\:0:0

```
> 1 votes

# Answer
## Clojure - 113 chars

```
(clojure.string/replace(read-line)#"([^aeiouAEIOU ]*)(\w*)"(fn[[a c r]](if(=""a)""(str r"-"(if(=""c)\w c)"ay"))))

```
> 1 votes

# Answer
**Ruby 1.9, 68**

```
puts ARGV.map{|w|w[/^([^aeiou]+)(.*)/i]?$2+"-"+$1+"ay":w+"-way"}*" "

```
> 1 votes

# Answer
# C, 134 bytes

```
char w[99],*p;c;main(l){for(;c^10;c=getchar())scanf("%s",w),p=strpbrk(w,"aeiouAEIOU"),l=p-w,printf("%s-%.*say ",p?p:"",l+!l,l?w:"w");}

```
> 0 votes

# Answer
# Lexurgy, 116 bytes

```
p:
([]+)$1 *=>$1 \-way/$ {a,e,i,o,u} _
({b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z}+)$1 ([]*)$2 => $2 \- $1 ay/$ _

```

+52 bytes if you want case-insensitive support.
> 0 votes

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


title: The Improved Caesar Pig Latin Cipher

text:
# Question
Title: The Improved Caesar Pig Latin Cipher
The problem with the Caesar cipher is the resulting words are often unpronounceable. The problem with Pig Latin is that it is easy to decode. Why not combine them?

**Input**

A word consisting of the 26 english letters.

**Output**

First, change every consonant in the word to the next consonant in the alphabet. So, b goes to c, d goes to f, and z goes to b. Then, change every vowel to the next vowel in the alphabet (u goes to a). Last, only if the first letter of the word is a consonant, move that letter to the end of the word and add "ay" to the end of the word.

Examples:

```
cat -> evday
dog -> uhfay
eel -> iim

```
* This is , so the shortest code wins.
* Case does not matter.
* Vowels that will be used are A, E, I, O, and U

# Answer
# Stax, 20 bytes

```
ù≥±╘├*Lâ■8O±âΓ║Θæ%º•

```

Run and debug it

**Explanation**

```
Vc:tVv:tBcVc#{sL"ay"+}ML             #Full program, unpacked, implicit input
Vc:t                                 #Push consonants and ring translate input
    Vv:t                             #Push vowels and ring translate input
        BCvc#                        #Push first letter and tail of word, find number
                                     #of occurrences to consonants
             {sL"ay"+}M              #If truthy (word starts with consonant)
                                     #swap stack, listify, add "ay"
                       L             #Listify stack (combines words that start with vowel)

```

I went through a few iterations and finally got it down to 20. My original solution was 53 bytes.
> 3 votes

# Answer
# Ruby, ~~96~~ 69 bytes

```
->s{/^[^aeiou]/=~(r=s.tr'zb-yadehinotu','b-zefijopuva')?$'+$&+'ay':r}

```

Try it online!

Fun fact of the day: tr() matches strings right-to-left. I always assumed it was left-to-right.
> 7 votes

# Answer
# , ~~86~~ 85 bytes

Simple way. `chartr` has the charming and useful property that it can specify letter *ranges*, which save a few bytes.

-1 bytes by stealing @GB's Ruby solution's translation strings - upvote it!

```
function(s)sub("^([^aeiou])(.*)","\\2\\1ay",chartr('zb-yadehinotu','b-zefijopuva',s))

```

Try it online!
> 6 votes

# Answer
# Java (JDK), 167 bytes

```
s->{String r="",a="aeiouabcdfghjklmnpqrstvwxyzb",c=s.split("")[0];s=a.indexOf(c)>5?s.substring(1)+c+"ux":s;for(var d:s.split(""))r+=a.charAt(a.indexOf(d)+1);return r;}

```

Try it online!

## Credits
> 5 votes

# Answer
# 05AB1E, 21 bytes

```
žMDÀ‡žNDÀ‡¬žNsåiÀ…ÿay

```

Try it online!

**Explanation**

```
žMDÀ‡                   # replace each vowel with the next vowel in the alphabet
     žNDÀ‡              # replace each consonant with the next consonant in the alphabet
          ¬žNsåi        # if the first letter is a consonant
                À…ÿay   # rotate the word left and add "ay"

```
> 4 votes

# Answer
# Node.js 10.9.0, ~~121~~ 116 bytes

Expects the input string in lower case.

```
s=>(v=n=>2130466>>n&1)((a=Buffer(s).map(n=>(g=i=>v(n=n%61?n+1:97)^i?g(i):n)(v(n))))[0],a+='')?a:a.slice(1)+a[0]+'ay'

```

Try it online!

### Identifying vowels

To identify vowels, the helper function \\$v\\$ uses the following bitmask:

```
2130466 = 000001000001000001000100010
               ^     ^     ^   ^   ^
          zyxwvutsrqponmlkjihgfedcba-

```

And does:

```
(2130466 >> n) & 1

```

We don't need to mask out the relevant bits of \\$n\\$, because it is done implicitly. Below is the relevant quote from the ECMAScript specification:

> Let *shiftCount* be the result of masking out all but the least significant 5 bits of *rnum*, that is, compute *rnum* & 0x1F.

### Commented

```
s =>                      // s = input string
  ( v = n =>              // v = helper function taking n = ASCII code in [97..122]
    2130466 >> n & 1      //     and returning 1 if the corresponding character is a vowel
  )                       //     or 0 otherwise (see the previous paragraph)
  (                       // this statement will ultimately invoke v on a[0]
    ( a = Buffer(s)       //   convert s to a Buffer, holding ASCII codes
      .map(n =>           //   for each ASCII code n in there:
        ( g = i =>        //     g = recursive function taking i = vowel flag
          v(              //       update n and invoke v on the new value:
            n = n % 61 ?  //         if n is less than 122 (meaning less than 'z'):
              n + 1       //           increment n
            :             //         else:
              97          //           wrap around by setting n to 97 (meaning 'a')
          ) ^ i ?         //       if v(n) is not equal to i:
            g(i)          //         do recursive calls until it is
          :               //       else:
            n             //         stop recursion and return the new n
        )(v(n))           //     initial call to g with i = v(n)
      )                   //   end of map()
    )[0],                 //   invoke v on a[0]
    a += ''               //   coerce the updated Buffer back to a string
  ) ?                     // if a[0] is a vowel:
    a                     //   return the string as-is
  :                       // else:
    a.slice(1) + a[0]     //   move the leading consonant to the end
    + 'ay'                //   and append the 'ay' suffix

```
> 4 votes

# Answer
# Python 2, ~~153~~ ~~121~~ ~~110~~ ~~99~~ 91 bytes

```
lambda s:[s[1:]+s[0]+"ux",s][s[0]in'aeiou'].translate(8*".ecdfighjoklmnpuqrstvawxyzb.....")

```

Try it online!

8 bytes shaved off due to a suggestion by Matthew Jensen
> 4 votes

# Answer
# T-SQL, 169 bytes

```
SELECT IIF(CHARINDEX(LEFT(a,1),'aeiou')=0,SUBSTRING(a,2,99)+LEFT(a,1)+'ay',a)FROM
(SELECT TRANSLATE(v,'aeioubcdfghjklmnpqrstvwxyz','eiouacdfghjklmnpqrstvwxyzb')a FROM t)s

```

Input is via a pre-existing table, per our IO standards.

Performs the characters substitution first, using the (new to SQL 2017) `TRANSLATE` function, then checks the first character.

Annoying long mostly due to SQL keyword length.
> 4 votes

# Answer
# Shell script, 70 bytes

```
tr a-z b-{|tr eiou{bfjpv fjpvbeioua|sed -E 's/^([^aeiou])(.*)/\2\1ay/'

```

Try it online!
> 3 votes

# Answer
# Haskell, 102 97 bytes

```
h(c:r)|elem c"aeiou"=c:r|True=r++c:"ay"
f s=h["ecdfighjoklmnpuqrstvawxyzb"!!(fromEnum y-97)|y<-s]

```

Try it online!
> 3 votes

# Answer
# Jelly, 24 bytes

```
,ṙ¥1y
ØẹçØḄçṙḢe©ØḄƊ®⁾ayx

```

Try it online!

Saved 1 byte thanks to Jonathan Allan (use the two-char syntax rather than quotes).
> 2 votes

# Answer
# Retina 0.8.2, 50 bytes

```
T`uo`aei\oub-df-hj-np-tv-zb
^([^aeiou])(.*)
$2$1ay

```

Try it online! Link includes test cases. Similar approach to the R answer. Explanation:

```
T`uo`aei\oub-df-hj-np-tv-zb

```

`o` refers to the other set, i.e. `aei\oub-df-hj-np-tv-zb`, which expands to `aeioubcdfghjlkmnpqrstvwxyzb`, so `uo` expands to `uaeioubcdfghjlkmnpqrstvwxyzb`. This results in the following transliteration:

```
uaeioubcdfghjlkmnpqrstvwxyzb
aeioubcdfghjlkmnpqrstvwxyzb

```

The second `u` and `b` are ignored as they can never be matched, so this provides the desired cipher. (Note that in Retina 1 you can of course use `v` instead of `aei\ou` for a 5 byte saving.)

```
^([^aeiou])(.*)
$2$1ay

```

If the first letter is not a vowel, rotate it to the end and suffix `ay`.
> 2 votes

# Answer
# \>\<\>, ~~94~~ 92 bytes

```
i:0(?v"a"%
2%?!v\~r:5g
a2r}<vr+ad*
ol?!;>4g
ecdfighjoklmnpuqrstvawxyzb
1   1   1     1     1

```

Try it online!

*Edit: Saved 2 bytes by taking input mod 97 rather than 32, so the dictionary could start at the beginning of the line. Previous version:*

```
i:0(?v84*%
2%?!v\~r:5g
37r}<vr*46*
ol?!;>4g
 ecdfighjoklmnpuqrstvawxyzb
 1   1   1     1     1

```
> 2 votes

# Answer
# Red, 149 bytes

```
func[s][c:"aeioua.bcdfghjklmnpqrstvwxyzb"t: copy""foreach p s[append t c/(1
+ index? find c p)]if 7 < index? find c t/1[move t tail t append t"ay"]t]

```

Try it online!

As (almost) always, the longest entry
> 1 votes

# Answer
# Perl 5, 56 bytes

```
y/a-z/ecdfighjok-npuq-tvaw-zb/;s/^([^aeiou])(.*)/$2$1ay/

```

Try it online!
> 1 votes

# Answer
# F# (Mono), 197 bytes

```
let f(s:string)=
 let a="aeiouabcdfghjklmnpqrstvwxyzb"
 new string(s|>Seq.map(fun c->a.[a.IndexOf(c)+1])|>Seq.toArray)|>(fun x->if a.IndexOf(x.[0])>5 then x.Substring(1)+(string x.[0])+"ay"else x)

```

Try it online!
> 1 votes

# Answer
# JavaScript (SpiderMonkey), 107 bytes

```
x=>x.replace(/./g,y=>(z='aeiouabcdfghjklmnpqrstvwxyzb')[z.search(y)+1]).replace(/^([^aeiou])(.+)/,'$2$1ay')

```

Try it online!

Expects input in lowercase.

Replaces each character of the string with a the one after it in the string `'aeiouabcdfghjklmnpqrstvwxyzb'`, and then piglatinifies anything with an initial consonant.
> 1 votes

# Answer
# PHP, 112 bytes

```
<?=strtr(($s=strstr(aeiou,($s=$argn)[0])?$s:substr($s,1).$s[0].ux),join(range(a,z)),ecdfighjoklmnpuqrstvawxyzb);

```

or

```
<?=strtr(($s=strstr(aeiou,($argn)[0])?$argn:substr($s,1).$s[0].ux),join(range(a,z)),ecdfighjoklmnpuqrstvawxyzb);

```

assume lower case input. Run as pipe with `-nR` or try them online.

---

You could as well use
`strtr($s,uzbcadfgehjklminpqrsotvwxy,range(a,z))` instead of
`strtr($s,range(a,z),ecdfighjoklmnpuqrstvawxyzb)`.
> 1 votes

# Answer
# Dyalog APL (SBCS), 57 bytes

```
{a←⎕A{(⍺~⍵)⍵}'AEIOU'⋄('AY',⍨1⌽⊢)⍣(∊/⊃¨⍵a)⊢(⊂⍵⍳⍨∊a)⌷∊1⌽¨a}

```

Try it online!

Takes input in uppercase only! (Because `⎕A` is uppercase alphabet)

* `⎕A{(⍺~⍵)⍵}'AEIOU'`: Vector of consonants and vowels
* `(⊂⍵⍳⍨∊a)⌷∊1⌽¨a`: Uses indices of each letter of the word in the normal alphabet (`⊂⍵⍳⍨∊a`) to index () into the cipher `∊1⌽¨a`.
* `('AY',⍨1⌽⊢)⍣(∊/⊃¨⍵a)`: Moves first letter to the end and appends 'AY', if the first letter is a consonant.

Thanks for the cool challenge!
> 1 votes

# Answer
# Lexurgy, 202 bytes

```
class C {b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z}
class V {a,e,i,o,u}
c:
{@C,@V}=>{{c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z,b},{e,i,o,u,a}}
p:
([]+)$1 *=>$1/$ @V _
(@C+)$1 ([]*)$2=>$2 $1 ay/$ _

```
> 0 votes

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


title: Sink that Bismark! (Errr, pig)

text:
# Question
Title: Sink that Bismark! (Errr, pig)
Pig-latin is a made-up language that is translated into by moving the first letter of a word to the end and adding `ay` to the end. For example: `hello` translates into pig-latin as `ellohay`. Therefore, translating pig-latin back into English is dropping the `ay` at the end and moving the last letter to the start (like `oodbyegay` to `goodbye`). When writing it out, some people will put a `-` at the end before moving the first letter for clarity, so it reads (for example) `ello-hay` instead of `ellohay` for `hello`. We will use this hyphenated version for this challenge.

# Objective

Undo a pig-latin string.

# Instructions

Write a program/function that takes one argument, a *single* word in the form of a string. If that word is in pig-latin, the program/function must output (i.e. `return` or print it) the non-pig-latin word. If it isn't pig-latin, output the word as-is.

Pig-latin for this challenge will be in the following format:

```
ello-hay

```

If the word ends in `-*ay`, it is pig-latin, where the `*` is a single wildcard character.

Non-letter characters should be treated as a normal letter. For multiple dashes, ignore all except the last.

# Examples

Using fictitious `unpig()` Python function for demo.

```
unpig("ello-hay")    #=> hello
unpig("hello-world") #=> hello-world
unpig("hello")       #=> hello
unpig("pple-aay")    #=> apple
unpig("apple")       #=> apple
unpig("ig-Stay")     #=> ig-Stay (+1 to ETHproductions for noticing.)
unpig("ello----hay") #=> hello---
unpig("la$s-gay")    #=> gla$s
unpig("ig-pay-yay")  #=> yig-pay

```

# Rules

1. Standard loopholes apply
2. This is , so shortest code wins.
3. Built-in functions (specifically for this purpose) are not permitted.
4. Use header `# Language, XX bytes`

# Leaderboard

```
var QUESTION_ID=127963,OVERRIDE_USER=46066;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 5 votes
## JavaScript (ES6), 34 bytes

```
s=>s.replace(/(.*)-(.)ay$/,'$2$1')

```

### Test cases

```
let unpig =

s=>s.replace(/(.*)-(.)ay$/,'$2$1')

console.log(unpig("ello-hay"))    // => hello
console.log(unpig("hello-world")) // => hello-world
console.log(unpig("hello"))       // => hello
console.log(unpig("pple-aay"))    // => apple
console.log(unpig("apple"))       // => apple
console.log(unpig("ig-Stay"))     // => ig-Stay
```

# Answer
> 3 votes
# PHP, 61 bytes

```
function f($v){echo preg_replace("#(.*)-(.)ay$#","$2$1",$v);}

```

Try it online!

# PHP, 46 bytes

without a function

```
<?=preg_replace("#(.*)-(.)ay$#","$2$1",$argn);

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~48~~ 46 bytes

*-2 bytes thanks to xnor.*

These are anonymous lambda functions that can be assigned to, say `unpig`.

```
lambda s:[s,s[-3]+s[:-4]][s[-4]+s[-2:]=="-ay"]

```

Try it online!

## Regex solution, 49 bytes

```
lambda s:re.sub('(.*)-(.)ay',r'\2\1',s)
import re

```

Try it online!

# Answer
> 2 votes
# Python 2.7, ~~68~~ ~~55~~ 52 bytes

```
def up(s):print(s,s[-3]+s[:-4])[s[-4]+s[-2:]=="-ay"]

```

Uses a ternary-like operator.

-13 bytes thanks to officialaimm and an update in rules.

-3 Changed ternary operator. See https://stackoverflow.com/a/470376/3210045.

# Answer
> 2 votes
# 05AB1E, 15 bytes

```
D'-¡θ¦„ayQi¨¨Á¨

```

Try it online!

`θ` is replaced by `®è` on TIO since it hasn't been pulled there yet.

# Answer
> 1 votes
# Lexurgy, 29 bytes

```
p:
([]+)$1 \- []$2 ay=>$2 $1

```

# Answer
> 0 votes
# Python 3, ~~59~~ 60 bytes

* 1 byte added thanks to @Erik the Outgolfer: $ to ensure `ig-payyay` outputs the same and not `yig-pa`

```
lambda a:a[-3]+a[:-4]if re.search("-.ay$",a)else a
import re

```

Try it online!

# Answer
> 0 votes
# Japt, ~~18~~ 17 bytes

Just the same RegEx replacement as everyone else, first posted by Arnauld.

```
r"(.*)-(.)ay$"ÏiZ

```

Try it

# Answer
> 0 votes
# Jelly, ~~22~~ 17 bytes

```
ṖṖṙ-Ṗµṣ”-ṪḊ⁼⁾ayµ¡

```

Try it online!

# Answer
> 0 votes
# Perl 6, 22 bytes

```
{S/(.+)\-(.)ay$/$1$0/}

```

Basic regular expression solution.

# Answer
> 0 votes
# Java (OpenJDK 8), 146 bytes

```
s->{Matcher m=Pattern.compile("(.*)-(.)ay").matcher(s);String g="";while(m.find())g=m.group(1);return (g!=""?s.charAt(s.lastIndexOf('-')+1)+g:s);}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, ~~15~~ 14 bytes

I know there already is a 15-bytes 05AB1E answer. ~~I haven't found anything shorter yet, but since I found two 15-byters with a different approach, I figured I'd post them as well~~ EDIT: Found a 14-byter. But I'll still mention the two 15-byters either way:

```
œ6è…-ayÅ¿i¨¨Á¨

```

Very slow for larger inputs.

Try it online or verify all test cases. (The test suite uses `S6.IJ` instead of `œ6è`, since it's A LOT faster, but basically does the same. Unfortunately, builtin `.I` doesn't work on strings - apparently.)

```
4(è«…ay-Å¿i¨¨Á¨

```

Try it online or verify all test cases.

```
`«ŠŠ«…ay-QiJÁëI

```

Try it online or verify all test cases.

**Explanation:**

```
œ               # Get all permutations of the (implicit) input-string
 6è             # Only leave the 7th one (0-based 6th)
   …-ayÅ¿i      # If this permutation ends with "-ay":
          ¨¨    #  Remove the last two characters from the (implicit) input-string ("ay")
            Á   #  Rotate it once towards the right
             ¨  #  Rotate the last character ("-")
                #  (after which it is output implicitly as result)
                # (implicit else)
                #  (implicitly output the implicit input unchanged)

4(è             # Get the 0-based -4'th character of the (implicit) input
   «            # Append it to the (implicit) input
    …ay-Å¿i     # If this string ends with "ay-"
           ¨¨Á¨ #  Same as above

`               # Push all characters of the (implicit) input separately to the stack
 «              # Merge the last two together
  ŠŠ            # Triple-swap the last three items twice (a,b,c to b,c,a)
    «           # Merge the top two together
     …ay-Qi     # If this is equal to "ay-":
           J    #  Join the other characters on the stack together
            Á   #  And rotate it once towards the right
          ë     # Else:
           I    #  Push the input
                # (after which the top of the stack is output implicitly as result)

```

# Answer
> 0 votes
# Pip, 18 bytes

```
a~`-(.)ay$`?$1.$`a

```

Try It Online!

### Explanation

```
a~`-(.)ay$`?$1.$`a
a                   First command-line argument
 ~                  Find first match
  `-(.)ay$`         of this regex (capture the letter in group 1)
           ?        If a match was found:
            $1        Contents of group 1
              .       Concatenated with
               $`     Portion of the string before the match
                    Else:
                 a    The string unchanged

```

---
Tags: code-golf
---


title: Broken Path Detection

text:
# Question
Title: Broken Path Detection
## Challenge

Given a plot with broken paths, return the plot with all paths connected in the minimum number of changes.

## Explanation

This problem deals with graphs on the Cartesian plane. Every node has 8 possible edges, extending vertically, horizontally, or diagonally. Each direction is represented by a number 0-7 as follows:

```
        0
     7     1
  6     X     2
     5     3
        4

```

In other terms:

```
0 = North
1 = Northeast
2 = East
3 = Southeast
4 = South
5 = Southwest
6 = West
7 = Northwest

```

A "broken path" occurs when one node has an edge that would reach another node, but the node it reaches toward does not have the corresponding path to reach it. For example, assume we have nodes A, B, C, and D laid out as:

```
AB
CD

```

If node A has the path 2 and all the other nodes have no paths, then there is a broken path between nodes A and B. This can be resolved in one of two ways:

* Removing path 2 from A
* Adding path 6 to B

In this case, it does not matter which way you choose to resolve the conflict, because either way results in 1 node being changed.

This first example can be illustrated as follows (`*` represents nodes):

```
Original:
 *- *

 *  *

First method:
 *  *

 *  *

Second method:
 *--*

 *  *

```

If node A has path 3, B has path 4, C has path 2, and D has no paths, the paths from A to D, B to D, and C to D are all broken. This can be resolved in one of two ways:

* Removing path 3 from A, 4 from B, and 2 from C
* Adding paths 6, 7, and 0 to D

In this case, adding to node D is the optimal choice, because it results in 1 node being changed rather than 3. It does not matter how many paths get changed when you change a node; the optimal method is determined by how many nodes get changed.

This example can be illustrated as:

```
Original:
 *  *
  \ |

 *- *

Suboptimal method:
 *  *

 *  *

Optimal method:
 *  *
  \ |
   \|
 *--*

```

## Input

A 2D matrix of bytes, where each bit represents whether that path is present in the node. 7 represents the most significant bit, and 0 the least significant; in other words, the bits are given in the order `76543210`.

For example, the first scenario given above would be:

```
0b00000010 0b00000000
0b00000000 0b00000000

```

The second scenario given above would be:

```
0b00000100 0b00001000
0b00000010 0b00000000

```

You may take in these values as strings in the base of your choice, or integral types with the width of your choice (e.g. if your language supports a `byte` or `char` type, you may still use `int` if you so choose), but include your choice in your answer.

## Output

You should either write a function that returns the corrected map or a program that prints it. Your output format should be the same as your input format.

## Test Cases

These are just one example of correct output; valid output with the same number of values changed is also accepted.

```
[[0x04, 0x00], [0x00, 0x00]] -> [[0x04, 0x40], [0x00, 0x00]]

[[0x08, 0x10], [0x04, 0x00]] -> [[0x08, 0x10], [0x04, 0xC1]]

[[0x04, 0x10, 0x00],            [[0x10, 0x10, 0x00],
 [0x01, 0x80, 0x10],         ->  [0x01, 0x09, 0x10],
 [0x00, 0x00, 0x81]]             [0x00, 0x00, 0x81]]

                          Or -> [[0x18, 0x10, 0x00],
                                 [0x01, 0x89, 0x10],
                                 [0x00, 0x00, 0x81]]

```

The first two test cases are illustrated above. The third test case can be illustrated as:

```
Original:
 *- *  *
    |
 | \
 *  *  *
       |
      \|
 *  *  *

Solution:
 *  *  *
 |  |
 |  |
 *  *  *
     \ |
      \|
 *  *  *

Another solution:
 *  *  *
 |\ |
 | \|
 *  *  *
     \ |
      \|
 *  *  *

```

This is , so the fewest bytes in each language wins.

# Answer
# Haskell, 655 bytes

```
u%w=u!!w
r=zip[-1,0,1,1,1,0,-1,-1][-1,-1,-1,0,1,1,1,0]
g _[]_= -1
g i(e:l)x|x==e=i|1>0=g(i+1)l x
l?x=g 0 l x
d _[]_ _=[]
d i(e:l)t v|i==t=v:l|1>0=e:d(i+1)l t v
c=d 0
f n|all(==0).concat.q$n=n|1>0=f$foldr(\p b->s b[k,m]p)n$k!m where
 h=length n-1
 e=mapM(\w->[0..w])[h,h]
 i!j=[[x,y]|[x,y]<-e,x>i-2&&x<i+2&&y>j-2&&y<j+2]
 q o=[[sum[1|[x,y]<-w!l,let
  u=(x-w,y-l)
  p=(w-x,l-y)in u/=p&&('1'==(o%w%l)%(r?u))/=('1'==(o%x%y)%(r?p))]|l<-[0..h]]|w<-[0..h]]
 v[x,y][a,b]|q n%x%y>q n%a%b=[x,y]|1>0=[a,b]
 [k,m]=foldr1 v e
 s w[x,y][a,b]|x==a&&y==b=w|'1'==w%x%y%(r?(a-x,b-y))=z '0'|'1'==w%a%b%(r?(x-a,y-b))=z '1'|1>0=w where z u=c w x$c(w%x)y$c(w%x%y)(r?(a-x,b-y))u

```

Man... 655 is a **lot**. I'm sure this isn't the best approach but since no one's answered this challenge yet I figured I would throw something at it.

Input is a list of lists of strings, viz. `[[String]]` or, equivalently, `[[[Char]]]`. The string format is `"76543210"`, where the string is a `'0'` or a `'1'` in any given position based on whether or not the node points in that corresponding direction. This should conform with the spec:

> 7 represents the most significant bit, and 0 the least significant; in other words, the bits are given in the order `76543210`.

But the examples below that seem to contradict it, instead doing something more like `?7654321`, so I'm not sure.

## Test suite:

```
main :: IO ()
main = print $ f
    [ ["00000100", "00010000", "00000000"]
    , ["00000001", "10000000", "00010000"]
    , ["00000000", "00000000", "10000001"]
    ]

```

(That's the last test case in the spec^)
> 2 votes

# Answer
## Python3, 497 bytes:

```
E=enumerate
L=lambda d,x,y:(x+(K:=d not in[6,2])*[1,-1][d%7<2],y+(d%2 or K==0)*[-1,1][d<4])
def f(b):
 q,Z=[([[(x,y),e]for x,j in E(b)for y,e in E(j)],[])],{}
 while q:
  B,T=q.pop(0)
  if[]==(o:=[(Y,b,c)for Y,(a,b)in E(B)if(c:=[(i,K[0])for i,(A,p)in E(B)if(K:=[(I,R)for I in p if L(I,*A)==a and(R:=[I+4,I-4][I+4>7])not in b])])]):Z[len({*T})]=B;continue
  for i,b,c in o:
   for I,(g,h)in c:Q=eval(str(B));W=eval(str(B));Q[i][1]+=[h];W[I][1].remove(g);q+=[(W,T+[I]),(Q,T+[i])]
 return Z[min(Z)]

```

Try it online!

This is a basic brute force solution. Below, however, is an optimized version, at the cost of 100 bytes:

---

## Python3, 597 bytes:

```
E=enumerate
L=lambda d,x,y:(x+(K:=d not in[6,2])*[1,-1][d%7<2],y+(d%2 or K==0)*[-1,1][d<4])
def f(b):
 q,Z,X=[([[(x,y),e]for x,j in E(b)for y,e in E(j)],[])],{},[]
 while q:
  B,T=q.pop(0)
  if[]==(o:=[(Y,b,c)for Y,(a,b)in E(B)if(c:=[(i,K[0])for i,(A,p)in E(B)if(K:=[(I,R)for I in p if L(I,*A)==a and(R:=[I+4,I-4][I+4>7])not in b])])]):Z[len({*T})]=B;continue
  if Z and len({*T})>=min(Z):continue
  for i,b,c in o:
   for I,(g,h)in c:
    Q=eval(str(B));W=eval(str(B));Q[i][1]+=[h];W[I][1].remove(g)
    if W not in X:q+=[(W,T+[I])];X+=[W]
    if Q not in X:q+=[(Q,T+[i])];X+[Q]
 return Z[min(Z)]

```

Try it online!
> 0 votes

---
Tags: code-golf, graph-theory
---


title: The von Koch conjecture

text:
# Question
Title: The von Koch conjecture
You may know the mathematician von Koch by his famous snowflake. However he has more interesting computer science problems up his sleeves. Indeed, let's take a look at this conjecture:

Given a tree with `n` nodes (thus `n-1` edges). Find a way to enumerate the nodes from `1` to `n` and, accordingly, the edges from `1` to `n-1` in such a way, that for each edge `k` the difference of its node numbers equals to `k`. The conjecture is that this is always possible.

Here's an example to make it perfectly clear :

**YOUR TASK**

Your code will take as input a tree, you can take the format you want but for the test cases I will provide the tree by their arcs and the list of their nodes.

For example this is the input for the tree in the picture :

```
[a,b,c,d,e,f,g]
d -> a
a -> b
a -> g
b -> c
b -> e
e -> f

```

Your code must return the tree with nodes and edges numbered. You can return a more graphical output but I will provide this kind of output for the test cases :

```
[a7,b3,c6,d1,e5,f4,g2]
d -> a 6
a -> b 4
a -> g 5
b -> c 3
b -> e 2
e -> f 1

```

**TEST CASES**

```
[a,b,c,d,e,f,g]             [a7,b3,c6,d1,e5,f4,g2]
d -> a                      d -> a 6
a -> b                      a -> b 4
a -> g             =>       a -> g 5
b -> c                      b -> c 3
b -> e                      b -> e 2
e -> f                      e -> f 1

[a,b,c,d]                   [a4,b1,c3,d2]
a -> b                      a -> b 3
b -> c            =>        b -> c 2
b -> d                      b -> d 1

[a,b,c,d,e]                [a2,b3,c1,d4,e5]
a -> b                      a -> b 1
b -> c                      b -> c 2
c -> d             =>       c -> d 3
c -> e                      c -> e 4

```

This is this the shortest answer in bytes win!

Note : This is *stronger* than the Ringel-Kotzig conjecture, which states every tree has a graceful labeling. Since in the Koch conjecture it is not possible to skip integers for the labeling contrary to the graceful labeling in the Ringel-Kotzig conjecture. Graceful labeling has been asked before here.

# Answer
# Jelly, 30 bytes

```
JŒ!³,$€
Çµy⁴VIAµ€Q⁼$€TðḢịø³JŒ!

```

Try it online! (Use `GṄ³çG` as footer to make output prettier. )

Inputs similar to example, e.g. `abcdef` and `[d,a],[a,b],[a,g],[b,c],[b,e],[e,f]`

Outputs the list e.g. `a,b,c,d,e,f` in order.

Note: My program produces different values than the test cases as there are several possibilities which are all valid.

**Explanation**

```
JŒ!³,$€                - helper function, generates all possible numberings, input is e.g. 'abcd'
J                      - range(len(input)). e.g. [1,2,3,4]
 Œ!                    - all permutations of the range.
   ³,$                 - pair the input with ...
      €                - each permutation. Sample element e.g. ['abcd',[3,1,2,4]]

Çµy⁴VIAµ€Q⁼$€TðḢịø³JŒ! - main dyadic link, input is e.g. 'abcd' and '[a,b],[b,c],[b,d]'
 µy                    - use a numbering as an element-wise mapping e.g. 'abcd'->[3,1,2,4]
   ⁴                   - apply this to the list of edges. e.g. '[3,1],[1,2],[1,4]'
    V                  - turn this into an internal list.
     IAµ€              - find absolute difference on each edge
         Q⁼            - Is this invariant under deduplication? Returns 1 if the numbering is valid; 0 otherwise.
Ç          $€          - apply this to all possible numberings
             Tð        - return the indices of all valid numberings
               Ḣ       - choose the first one and
                ị      - get the element corresponding to its index in
                 ø³JŒ! - all possible numberings

```

Save 1 byte by showing all possible solutions:

```
JŒ!³,$€
Çµy⁴VIAµ€Q⁼$€Tðịø³JŒ!

```

Try it online! (Use `GṄ³çG⁷³G` as a footer to make output prettier)

Use converter to copy-paste test case into an input list.
> 3 votes

# Answer
# Ruby, 108 bytes

lamba function, accepts an array of 2-element arrays containing the edges (where each edge is expressed as a pair of numbers corresponding to the relevant notes.)

```
->a{[*1..1+n=a.size].permutation.map{|i|k=a.map{|j|(i[j[0]-1]-i[j[1]-1]).abs}
(k&k).size==n&&(return[i,k])}}

```

**Ungolfed in test program**

```
f=->a{                                    #Accept an array of n tuples (where n is the number of EDGES in this case)
  [*1..1+n=a.size].permutation.map{|i|    #Generate a range 1..n+1 to label the nodes, convert to array, make an array of all permutations and iterate through it.
    k=a.map{|j|(i[j[0]-1]-i[j[1]-1]).abs} #Iterate through a, build an array k of differences between nodes per current permutation, as a trial edge labelling.
    (k&k).size==n&&(return[i,k])          #Intersect k with itself to remove duplicates. If all elements are unique the size will still equal n so
  }                                       #return a 2 element array [list of nodes, list of edges]
}

p f[[[4,1],[1,2],[1,7],[2,3],[2,5],[5,6]]]

p f[[[1,2],[2,3],[2,4]]]

p f[[[1,2],[2,3],[3,4],[2,5]]]

```

**Output**

output is a 2 element array, containing:

the new node numbering

the edge numbering.

For example the first edge of the first example `[4,1]` is between nodes 6 and 1 under the new node numbering and is therefore edge 6-1=5.

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

```

There are in fact multiple solutons for each test case. the `return` stops the function once the first one is found.
> 2 votes

# Answer
# Python3, 237 bytes:

```
def f(d,e,C=[]):
 if len(C)==len(d)-1:yield d
 for u,v in e:
  K={*range(1,len(d)+1)}-{*d.values()}
  for x in[K,[d[u]]][d[u]!=0]:
   for y in[K,[d[v]]][d[v]!=0]:
    if abs(x-y)==max(C+[0])+1:yield from f({**d,u:x,v:y},e,C+[abs(x-y)])

```

Try it online!
> 2 votes

---
Tags: code-golf, math, graph-theory
---


# Question
Title: Print ascending proper fractions using integers up to the given input
User inputs an integer. Print out proper fractions using all positive integers up to the user's input, in ascending order.

Rule 1: Eliminate equal fractions.

Rule 2: Fractions should be in their simplest form.

Rule 3: Use "/" as a fraction symbol and next line (\n or \r as convenient) as a separator between fractions.

Winning Criteria: The shortest code wins.

For example:

4:

```
1/4
1/3
1/2
2/3
3/4
1

```

6:

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

```

# Answer
# Husk, 10 bytes

```
¶OfεuΣ´Ṫ/ḣ

```

Try it online!

```
          ḣ # 1..input
       ´    # argdup: use this range twice
        Ṫ   # to construct a table
         /  # of one element divided by the other
            # (Husk will automatically simplify the fractions);
      Σ     # now flatten the table to a list
     u      # and keep only the unique elements,
   f        # filter to keep only those
    ε       # with value at most 1,
  O         # sort in ascending order,
 ¶          # and split by newlines

```

(or, also 10 bytes: `¶uOṁṠM`/ḣḣ` try it)
> 3 votes

# Answer
# JavaScript (ES6), 77 bytes

Based on the algorithm given in Wikipedia.

```
f=(d,a,b=(n=d,1),c=1)=>a^b?[a&&a+`/${b}
`]+f((k=(n+b)/d|0)*d-b,c,d,k*c-~~a):1

```

Try it online!

### Commented

```
f = (             // f is a recursive function taking:
  d,              //   the input n and the parameters (a, b, c, d)
  a,              //   which are initially set to:
  b = (n = d, 1), //   (undefined, 1, 1, n)
  c = 1           //
) =>              //
a ^ b ?           // if a is not equal to b:
  [ a &&          //   append either a + '/' + b + '\n' if a is defined
    a + `/${b}\n` //   or just an empty string if a is undefined (which
  ] +             //   happens only for the first iteration)
  f(              //   append the result of a recursive call:
    (k = (n + b)  //     set k = floor((n + b) / d)
         / d | 0) //
    * d - b,      //     update d to k * d - b
    c,            //     update a to c
    d,            //     update b to d
    k * c - ~~a   //     update c to k * c - a
                  //     (with a coerced to 0 if undefined)
  )               //   end of recursive call
:                 // else:
  1               //   stop the recursion and append the final '1'

```
> 3 votes

# Answer
# APL(Dyalog Unicode), 56 bytes SBCS

```
{↑↑'1',⍨(⊣,'/',⊢)⍥⍕/¨m[⍋÷/¨m←w/⍨≠÷/¨w←⊃⍵,.(¯1↓,¨)⍨,\⍵]}⍳

```

Try it on APLgolf!
> 2 votes

# Answer
# Goruby, 77 bytes

Very direct port of the code from Wikipedia

-4 bytes thanks to Raztime

```
->n{a,b,d=0,c=1,n
dw{k=(n+b)/d
a,b,c,d=c,d,k*c-a,k*d-b
sa b<2?a:a*1r/b
n>=c}}

```

Attempt This Online!

# Ruby, 85 bytes

```
->n{a,b,d=0,c=1,n
while n>=c
k=(n+b)/d
a,b,c,d=c,d,k*c-a,k*d-b
puts b<2?a:a*1r/b
end}

```

Attempt This Online!
> 2 votes

# Answer
# Factor \+ `math.matrices`,  ~~83 76~~  71 bytes

```
[ [1,b] 1 over n/v outer [ [ 1 min ] map ] gather natural-sort stack. ]

```

Attempt This Online!

#### How?

In Factor, division produces ratios that automatically reduce to simplified form, so that helps a lot.

* `[1,b] 1 over n/v outer` If \\$x\\$ is the input, \\$\Bigl\[1\ldots x\Bigr\]\otimes\Bigl\[\frac{1}{1}\ldots\frac{1}{x}\Bigr\]\\$ (where \\$\otimes\\$ is the tensor/outer product).
* `[ [ 1 min ] map ] gather` Get a list of the unique elements of the above matrix whose values are clamped to a maximum of 1.
* `natural-sort` Sort into ascending order.
* `stack.` Print each ratio to stdout with a newline.
> 2 votes

# Answer
# Pyth, 28 bytes

```
j{mj\//Ri.*dd<oc.*N^SQ2sUQ)1

```

Try it online!

##### Explanation

```
j{mj\//Ri.*dd<oc.*N^SQ2sUQ)1 | Full code
-----------------------------+------------------------------------------------------------------------------------------
                   ^SQ2      | Generate all pairs of integers [1..input]
              oc.*N          | Sort by division
             <         sUQ   | Keep only the first <input>th triangular number of pairs (the next pair is always [1, 1])
  m   /Ri.*dd                | Divide each pair by its GCD
  mj\/                       | Join each pair by '/'
 {                           | Remove duplicates
j                         )  | Join all by '\n'
                             | Print (implicit)
                           1 | Print 1

```
> 2 votes

# Answer
# Python, 99 bytes

```
def f(n):
 a,b,c,d=0,1,1,n
 while~n+c:k=(n+b)//d;a,b,c,d=c,d,k*c-a,k*d-b;print([1,f"{a}/{b}"][b>1])

```

Attempt This Online!

Another port of the Farey sequence generation algorithm, though this one's a bit cheaty since the code on the Wikipedia article is given in Python.
> 1 votes

# Answer
# Vyxal, 10 bytes

```
¨Vv/fU~ṅs⁋

```

Try it Online!

```
¨Vv/fU~ṅs⁋
¨Vv/        # Create a division table from [1, input]
    fU      # Flatten and uniquify
      ~ṅ    # Keep only elements <= 1
        s   # Sort
         ⁋  # Join on newlines

```
> 1 votes

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


title: Smooth vs. Chunky vs. Broken Squiggles

text:
# Question
Title: Smooth vs. Chunky vs. Broken Squiggles
Based on Chunky vs. Smooth Strings.

Squiggles `/\_/\/\__/\/\/\/\_/\_/\` are fun to make on a keyboard when you are really bored. But not all squiggles are created equal. Some squiggles are smooth, like `\___/`, and some are chunky, like `/\/\/\/\`. Others are just downright broken, like `////_\\\`

Inside every squiggle of `N` characters, there are `N-1` squiggle-junctions. Each squiggle-junction is classified into one of three types:

* Smooth (angle \> "90 degrees"):

`\_ __ _/`
* Chunky (angle = "90 degrees")

`/\ \/`
* Broken (anything that doesn't connect)

`// \\ /_ _\`

Let's define the *smoothness* to be the proportion of junctions that are smooth, with *chunkiness* and *brokenness* defined similarly. Each value ranges between `0` and `1`. The sum of a squiggle's smoothness, chunkiness, and brokenness is always equal to 1.

For example, the squiggle `/\/\\_//\_` has 3 smooth junctions, 4 chunky junctions, and 2 broken junctions. It is thus `0.3333` smooth, `0.4444` chunky, and `0.2222` broken.

**Empty strings and strings with only one character have undefined values, all input will be at least 2 characters long.**

## Challenge

Write a program that takes in a squiggle of arbitrary length and outputs any two of its smoothness, chunkiness, and brokenness values.

* You may write a program or function, with input via STDIN, command line, or as a string argument.
* You may assume the input is at least of **length \>= 2** and consists only of the characters `/\_` with an optional trailing newline.
* Print (or return if a function) the two floats to a precision of at least 4 decimals, rounded or truncated. If the true value is `2/3`, acceptable values include any value between `0.6666` and `0.6667`, even things like `0.666637104`. If the exact value is `1/3`, any answer containing `0.3333` is valid. You may leave off trailing zeros, or the leading zero if the value is less than one.
* Output any pair of the three values as you prefer, just be sure to state which two and in what order.

**The shortest code in bytes wins.**

## Examples

`/\/\\/\//\\` → Smoothness `0`, Chunkiness `0.7`, Brokenness `0.3`

`_/\\_/\\/__/\\\//_` → Smoothness `0.29411764705`, Chunkiness `0.29411764705`, Brokenness `0.41176470588`

`//\\__/_\/` → Smoothness `0.3333333`, Chunkiness `0.2222222`, Brokenness `0.4444444`

*Bonus question: Which do you prefer, smooth or chunky or broken squiggles?*

# Answer
# Pyth, 25 bytes

```
mcl@.:d2.:z2tlzc2"\__//\/

```

Test suite

Outputs smoothness, chunkiness. Basically, it takes the hard coded string and cuts it in half. Each half is decomposed into its 2 character substrings, and the same is done for the input. We take the intersection, resulting in the south and chunky pairs. Then, we take the the length, divide by the number of pairs, and print.
> 3 votes

# Answer
# Japt, 42 bytes

```
U=U¬ä@2+"\\/\\__/"bX+Y)f2};[T2]£U¬fX l /Ul

```

Outputs brokenness, chunkyness. Try it online!

### How it works

```
            // Implicit: U = input string
U=U¬ä@   }  // Set U to U split into chars, with each pair mapped by this function:
"..."bX+Y)  // Take the index in this string of the two chars concatenated.
            // This is 0-1 for chunky, 2-4 for smooth, and -1 for broken.
2+    f2    // Add two and floor to the nearest multiple of 2.
            // This is now 2 for chunky, 4 or 6 for smooth, and 0 for broken.
[T2]£       // Map each item X in [0,2] through this function:
U¬fX l      //  Count the occurances of X in U.
/Ul         //  Divide by U.length.
            // Implicit: output last expression

```

### Non-competing version, 36 bytes

```
U=Uä@2+"\\/\\__/"bZ)f2};[T2]£UèX /Ul

```

Works in basically the same way as the other, with a few minor changes:

* `ä` now works on strings. The chars are passed into the function in order `(X, Y, X+Y)`.
* `è` counts the number of occurrences of the argument in the string/array.
> 3 votes

# Answer
# Ruby, 71

Outputs smoothness, chunkiness.

Takes the minimal smooth and chunky strings and searches them for every two-character string in the initial string.

Thanks to Kevin Lau for EIGHT bytes!

```
->x{%w{\\__/ /\\/}.map{|t|(0..n=x.size-2).count{|i|t[x[i,2]]}/(n+1.0)}}

```
> 2 votes

# Answer
# Python 3, 149 bytes

This outputs smoothness and chunkyness.

```
def f(s):
 for i in"012":s=s.replace("\_/"[int(i)],i)
 a=len(s)-1;t=["bscbssbbc"[int(s[i:i+2],3)]for i in range(a)]
 for x in"sc":print(t.count(x)/a)

```

**Ungolfed:**

```
def f(s):
    for i in "012":
        s = s.replace("\_/"[int(i)], i)
    a = len(s) - 1
    t = []
    for i in range(a):
        t.append("bscbssbbc"[int(s[i:i+2],3)])
    for x in "sc":
        print(t.count(x) / a)

```
> 1 votes

# Answer
# Python 3.8 (pre-release), ~~82~~ 79 bytes

```
lambda x:[sum(a+b in s for a,b in zip(x,x[1:]))/~-len(x)for s in["\__/","/\/"]]

```

Try it online!

---

-3 from @xnor by not using index `i` into array

---

# Python, 90 bytes

```
f=lambda x,s=0,c=0,n=0:x[1:]and f(x[1:],s+(x[:2]in"\__/"),c+(x[:2]in"/\/"),n+1)or(s/n,c/n)

```

Attempt This Online!

Recursive solution -- longer, but I think it's more elegant.
> 1 votes

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


title: Code-Golf: Farey sequence (I)

text:
# Question
Title: Code-Golf: Farey sequence (I)
## Challenge

> In this task you would be given an integer N (less than 10^5), output the Farey sequence of order N.

The input N is given in a single line,the inputs are terminated by EOF.

**Input**

```
4
3
1
2

```

**Output**

```
F4 = {0/1, 1/4, 1/3, 1/2, 2/3, 3/4, 1/1}
F3 = {0/1, 1/3, 1/2, 2/3, 1/1}
F1 = {0/1, 1/1}
F2 = {0/1, 1/2, 1/1}

```

**Constraints**

* The number of inputs would not exceed 10^6 values
* You can use any language of your choice
* Shortest solution wins!

# Answer
> 4 votes
## J, 96

```
('F',],' = {0/1',', 1/1}',~('r';'/')rplc~', ',"1":"0@(3 :'}./:~~.,(%~}:\)i.1x+y')&".);._2(1!:1)3

```

( `/:~~.,(%~}:\)i.>:x:y` gives the list; the rest is I/O and formatting (with bad style))

E.g:

```
4
3
1
2
F4 = {0/1, 1/4, 1/3, 1/2, 2/3, 3/4, 1/1}
F3 = {0/1, 1/3, 1/2, 2/3, 1/1}
F1 = {0/1, 1/1}
F2 = {0/1, 1/2, 1/1}

```

### Edits

* **(114 → 106)** Clearer appending `,`
* **(106 → 105)** Cap `[:` to At `@`
* **(105 → 101)** Delete superfluous `":` conversion
* **(101 → 99)** Use infix `\` for the list
* **(99 → 96)**

# Answer
> 3 votes
# Python, 186 Chars

```
import sys
p=sys.stdout.write
while 1:
 a=0;b=c=x=1;d=y=N=input();p("F%d = {%d/%d, %d/%d"%(d,a,b,c,d))
 while y-1:x=(b+N)/d*c-a;y=(b+N)/d*d-b;p(", %d/%d"%(x,y));a=c;c=x;b=d;d=y
 p("}\n")

```

# Answer
> 3 votes
# Common Lisp, 156

```
(do((l()()))((not(set'n(read()()))))(dotimes(j n)(dotimes(i(1+ j))(push(/(1+ i
)(1+ j))l)))(format t"~&F~D = {0/1~{, ~A~}/1}"n(sort(delete-duplicates l)'<)))

```

(newlines not necessary)

Very brutal, but languages with native rationals are an invitation to that.

**Ungolfed with comments:**

```
                                        ; at each iteration:
(do ((l()()))                           ; - reset l to nil
    ((not (set 'n (read()()))))         ; - read a term (nil for eof)
                                        ;   assign it to n
                                        ;   stop looping if nil
  (dotimes (j n)                        ; for j in 0..n-1
    (dotimes (i (1+ j))                 ;   for i in 0..j
      (push (/ (1+ i) (1+ j)) l)))      ;     prepend i+1/j+1 to l
  (format t "~&F~D = {0/1~{, ~A~}/1}"   ; on a new line, including 0/1,
                                        ; forcing the format for 1
          n                             ; print sequence index, and
          (sort                         ; sorted sequence of
           (delete-duplicates l)        ;   unique fractions
           '<)))                        ; (in ascending order)

```

# Answer
> 2 votes
# Ruby, 110 108 102 97 94 92 91 89

```
#!ruby -lp
$_="F#$_ = {#{a=[];1.upto(eval$_){|d|a|=(0..d).map{|n|n.quo d}};a.sort*', '}}"

```

# Answer
> 2 votes
# J, 156 135 117 112

```
d=:3 :0
wd;'F';(":y);' = {';(}.,(', ';2|.'/';|.)"1(<@":)"0(2)x:/:~~.,(-.@>*%)"0/~i.x:>:y),<'}'
)
d@".;._2(1!:1)3

```

j602 or similar (`wd`). Input on stdin, output on stdout.

Still puzzling over how to golf the output code, which is 100 characters or so.

Edit: (156-\>135) Tacit-\>explicit for long monadic verb chains, less braindead list generation

Edit: (135-\>117) Found raze. Took me long enough. Switched string handling around.

Edit: (117-\>112) Slightly less braindead way to exclude fractions above 1. Unnecessary open.

# Answer
> 2 votes
## Golfscript (101)

```
~:c[,{){.}c(*}%.c/zip{+}*]zip{~{.@\%.}do;1=},{~<},{~\10c?*\/}${'/'*}%', '*'F'c`+' = {0/1, '+\', 1/1}'

```

# Answer
> 2 votes
# Haskell, 145 bytes

```
f(!)(%)n|p<-product[1..n]='F':n!" = {"++unwords[i%g!"/"++p%g![",}"!!(i%p)]|i<-[0..p],g<-[gcd i p],p<=n*g]
m@main=readLn>>=putStrLn.f shows div>>m

```

Try it online!

This reduces all of \\$\left\\{\frac{0}{n!}, \frac{1}{n!}, \dots, \frac{n!}{n!}\right\\}\\$ and selects the ones with denominator \\$\leq n\\$.

(The byte count went up a little again because I noticed the problem asks to handle multiple lines of input.)

The other Haskell answer is missing some imports and is missing `1/1` in the output. It also doesn't take multiple lines of input. When fixed, it comes out to 188 bytes:

```
import GHC.Real
import Data.List
f n="F"++show n++" = {"++(intercalate", ".("0/1":).map(\(i:%d)->show i++"/"++show d).sort.nub$[i%d|d<-[1..n],i<-[1..d]])++"}"
m@main=readLn>>=putStrLn.f>>m

```

# Answer
> 1 votes
# Haskell, 148

```
f n="F"++show n++" = {"++(intercalate", ".("0/1":).map(\(i:%d)->show i++"/"++show d).sort.nub$[i%d|d<-[1..n],i<-[1..d-1]])++"}"
main=interact$f.read
```

# Answer
> 1 votes
# Husk, 55 bytes

```
mλ:'F+s¹+" = "σ"1]""1/1}"σ"[0""{0/1"sOutfεmF/π2ŀ→)fImi¶

```

Try it online!

It was interesting messing with strings in Husk.

This gives the exact required output for the given test case.

There's a strange husk-ism in the `mi¶` function that gives intermediate 0's in the output. Hence, those are filtered out. Here's an explanation from Zgarb.

## Explanation

```
mλ:'F+s¹+" = "σ"1]""1/1}"σ"[0""{0/1"sOutfεmF/π2ŀ→)fImi¶
                                                      ¶ split input on newlines
                                                    mi  map to integers
                                                  fI    filter out zeroes
mλ                                               )      map each number through this function:
                                               ŀ→       range (0..n)
                                             π2         all possible pairs
                                          mF/           map each to it's fraction
                                        fε              keep elements ≤ 1
                                       t                remove first value (Any)
                                     Ou                 uniquify, sort ascending
                                    s                   convert to string
                         σ"[0""{0/1"                    change 0 → 0/1
              σ"1]""1/1}"                               change 1 → 1/1
        +" = "                                          add an equal sign
  :'F+s¹                                                prepend "F{N}"

```

# Answer
> 1 votes
# Jelly, 44 bytes

```
ƓµŻœċ2g/’$Ðḟ÷/Þj€”/j⁾, ,⁸Ø<,y“F> = {<}”Ṅ
Ç1¿

```

Try it online!

Could probably be improved if someone told me how to read and write multiline input properly in Jelly. I couldn't find any documentation on it, so I just have a while(true) loop that errors out when it reaches EOF.

# Answer
> 0 votes
# Python 3, 89 bytes

```
lambda n:[*zip(*sorted({j/i:(j,i)for i in range(n,0,-1)for j in range(i+1)}.items()))][1]

```

Try it online!

Basically generating all possible fractions and then using a dictionary comprehension to filter out the duplicates.

---

# Python 3, 142 bytes

```
while 1:n=input();print('F%s = {'%n+', '.join([*zip(*sorted({j/i:f'{j}/{i}'for i in range(int(n),0,-1)for j in range(i+1)}.items()))][1])+'}')

```

Try it online!

Abiding by all of the I/O requirements

# Answer
> 0 votes
# CJam, 73 bytes

```
'Fqi:T" = {"[[T1]Y,{_'\*',+\W%@_@_2$+2%Ta.+:/@f*\.-_1=T)<@W%\}g'\*\;]S*'}

```

Try it online!

Uses an algorithm to generate the terms in traditional order. A lot of maps and vector functions were used here. If anyone wants a write-up then I'll make one, unless I can figure out a better algorithm.

# Answer
> 0 votes
# Mathematica ~~13~~ 78 bytes

```
Column[Row@{"F",#," = ",FareySequence[ToExpression@#]}&/@StringSplit[#,"\n"]]&

```

---

**Example**

```
Column[Row@{#," = ",FareySequence[ToExpression@#]}&/@StringSplit[#,"\n"]]&["5\n4\n3"]

```

# Answer
> 0 votes
# 05AB1E, 40 bytes

```
|εÝ2.Æ2Å1ª.¡`/}€нΣ`/}'/ý„, ýy"Fÿ = {ÿ}",

```

Try it online.

**Explanation:**

```
|                     # Get all input-lines as a list
 ε                    # Map over each input-integer:
  Ý                   #  Pop and push a list in the range [0,n]
   2.Æ                #  Get all 2-element combinations of this list
      2Å1ª            #  Append pair [1,1]
  .¡                  #  Group the pairs by:
    `                 #   Pop and push both values separated to the stack
     /                #   Divide them
   }€                 #  After the group-by: map over each group
     н                #   Only leave the first pair of each group
      Σ  }            #  Then sort the pairs by:
       `/             #   Similar as above: dump and divide
  '/ý                '#  Then join each inner pair with "/"-delimiter
     „, ý             #  Join these strings with ", "-delimiter
         y            #  Push the current map-integer
          "Fÿ = {ÿ}"  #  Push this string, where the `ÿ` are automatically filled with
                      #  the integer and formatted list
                    , #  Pop and output it with trailing newline

```

# Answer
> 0 votes
# Japt `-R`, ~~18~~ 38 bytes

Stupid old challenges and their stupid & unnecessarily strict I/O requirements costing me 20 bytes!

```
N£"F{X} = \{{Xõ c_ô+'/+ZÃü!xO mÎqSi,}}

```

Try it

```
N£"F{X} = \{{Xõ c_ô+'/+ZÃü!xO mÎqSi,}}
N                                          :Array of all inputs
 £                                         :Map each X
  "F   = \{                          }     :  Build a string
    {X}                                    :  Interpolate X
           {                               :  Interpolate
            Xõ                             :    Range [1,X]
                c                          :    Flat map by
                 _                         :    Passing each Z through the following function
                  ô                        :      Range [0,Z]
                   +'/+Z                   :      Append "/" followed by Z to each
                        Ã                  :    End map
                         ü                 :    Group & sort by
                          !xO              :      Evaluating each as JavaScript
                              m            :    Map
                               Î           :      First element
                                q          :    Join with
                                 S         :      Space
                                  i,       :      Prepend comma
                                    }      :  End interpolation
                                           :Implicit output joined with new lines

```

---
Tags: code-golf, math
---