title: Enklactify these strings

text:
# Question
Title: Enklactify these strings
*Inspired by this comment chain...*

> I wanna `enklact` my way out of this challenge but I can't...
>
> @ETHproductions *to enklact* (v): to implement a lookup table using a subsection consisting of unique elements.

---

Enklacting is a very useful way to compress a lookup table. For example, let's say you had the following list of colors:

```
red
green
blue
yellow
purple
orange

```

If you want to be able to take a color as input and return it's index in this list, there's obviously the straightforward way:

```
["red", "green", "blue", "yellow", "purple", "orange"].index(input())

```

But there's a way we could do this in way less bytes:

```
"rgbypo".index(input()[0])

```

This works because the first (or 0'th) index of each string is unique. This example is obvious, but sometimes it's a little bit harder. What if we wanted to make a lookup table for this list?

```
Sweet Onion Chicken Teriyaki
Oven Roasted Chicken
Turkey Breast
Italian BMT
Tuna
Black Forest Ham
Meatball Marinara

```

In this case, we can't do this:

```
"SOTITBM".index(input()[0])

```

because there are two different inputs that start with a `'T'`, namely "Tuna" and "Turkey". We must look at a different index. If you look at the 4th index of each string, you'll notice that they are all unique. So we can do this...

```
"enklact".index(input()[3])

```

In this case, the *"enklaction string"* is "enklact".

That leads us to today's challenge...

Given a list of strings, return any valid enklaction string. Or in other words, given a list of strings, return any new string where each letter is unique, and the string is formed by joining the i'th letter of each string.

If there is no valid enklaction string, your submission must return an empty string or a consistent falsy value instead. As usual, either functions or full programs are allowed, and the input/output formats are permissive (within reason).

Each string will only contain printable ASCII, and this challenge is case sensitive.

This is , so try to write the shortest program possible in your language of choice!

## Test cases

```
Input:
Programming
Puzzles
Code
Golf

Output (any one of these):
"ozdl"
"gzef"

Input:
the quick
brown fox
jumped over
lazy dogs

Output:
"tbjl"
"hrua"
"eomz"
" wpy"
"qne "
"if o"
"kxvs"

Note that "u dd" and "coog" are not valid.

Input:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Output:
""

Input:
AbC
aBc
bbC

Output:
"Aab"

Input:
@#$%^_
Hello_World
How are you?

Output:
"#eo"
"$lw"
"%l "
"^oa"

Input:
a
ab
ac

Output:
""

```

# Answer
> 9 votes
# Python 2, ~~68~~ ~~67~~ 61 bytes

```
lambda a:`{0:j for j in zip(*a)if len(set(j))==len(j)}`[6::5]

```

Try it online!

*Improvements*

* From 68 bytes to 67 bytes by Jo King
* From 66 to 65 bytes by Lynn

---

**If output would not have to be a string:**

# Python 3, 49 bytes

```
lambda a:[j for j in zip(*a)if len({*j})==len(j)]

```

Try it online!

# Answer
> 8 votes
# Python3, 59 bytes

```
lambda l:{len({*d}):''.join(d)for d in zip(*l)}.get(len(l))

```

Returns a string with the enklact, None otherwise

# Answer
> 7 votes
# Retina, ~~43~~ 32 bytes

```
+/^(.).+^\1|^$/ms&m`^.

|""Lm`^.

```

Try it online! Edit: Saved 11 bytes thanks to @MartinEnder. Explanation:

```
+

```

Repeat while the input changes...

```
/^(.).+^\1|^$/ms&

```

...only if one line is empty or two lines begin with the same character...

```
m`^.

```

...delete the first character of every line. The repeat therefore stops if either a) all the lines begin with different characters, in which case the condition fails and the input does not get changed, or b) at least one line becomes empty, in which case all the characters eventually get deleted, at which point the input stops changing.

```
|""L`^.

```

Collect the first character of every line. (If there was no solution, the above loop will have deleted everything and there will be nothing to collect.)

# Answer
> 5 votes
# Haskell, 71 bytes

```
f x|elem""x=""|y<-head<$>x,and[filter(==a)y==[a]|a<-y]=y|1<2=f$tail<$>x

```

Try it online!

BMO saved 3 bytes with `any null x``elem""x`.

Ørjan Johansen saved a byte with `sum[1|b<-y,a==b]<2``filter(==a)[y]==[a]`.

## Explanation

```
f x|elem""x=""                      -- Once any of the strings is empty, return "".
   |y<-head<$>x                     -- Otherwise, let y be all the first letters...
   ,and[                 |a<-y]     -- If, for all a in y,
        filter(==a)y==[a]           -- a occurs just once in y:
                               =y   -- return y.
   |1<2=f$tail<$>x                  -- Else, chop off all the first letters and recurse.

```

If throwing an error (`Prelude.head: empty list`) when there's no solution is OK, `|elem""x=""` can be erased for **61 bytes**.

# Answer
> 4 votes
# Pyth, 6 bytes

```
>1{I#C

```

Test suite.

The output is a singleton list, as allowed by default; the list **\[ \]** (empty list, falsy) is returned in case the string cannot be *enklactified*.

### Explanation

```
>1{I#C – Full program.
     C – Transpose the input, cropping absences.
    #  – Filter by:
  {I   – Invariant under deduplication.
>1     – Slice to 1. list[:1] in Python.

```

---

**Pyth, 5 bytes**

This would've been valid if crashing would have counted as a falsy value.

```
h{I#C

```

Test suite.

# Answer
> 4 votes
# Ruby, 38 bytes

```
->x,*y{x.zip(*y).find{|z|z==z-[p]|[]}}

```

Try it online!

Thanks to G B for pointing out a bug.

# Answer
> 3 votes
# Jelly, 7 bytes

```
z0Q€fZḢ

```

Returns the integer **0** if the strings cannot be enklactified.

Try it online!

### How it works

```
z0Q€fZḢ  Main link. Argument: A (string array)

z0       Zip/transpose, filling shorter rows with 0.
  Q€     Unique each deduplicate resulting string.
     Z   Zip/transpose, without using a filler.
    f    Filter; keep only string that appear in the results to both sides.
      Ḣ  Head; extract the first string. Returns 0 if the array is empty.

```

# Answer
> 3 votes
# Haskell, ~~76~~ 74 bytes

```
f t=last$"":(id=<<foldr(zipWith(#))([[]]<$t)t)
x#[s]=[x:s|all(/=x)s]
x#e=e

```

Try it online! Returns the last valid lookup string or an empty string if no such string exists.

---

### ~~71~~ 69 bytes

If throwing a consistent exception as falsy value is allowed:

```
f t=head$id=<<foldr(zipWith(#))([[]]<$t)t
x#[s]=[x:s|all(/=x)s]
x#e=e

```

Try it online! Throws an `empty list` exception if no string is found, returns the first valid string otherwise.

*-2 bytes thanks to Ørjan Johansen*

# Answer
> 3 votes
# , ~~116~~ ~~107~~ 95 bytes

**R+pryr**

```
pryr::f(for(i in 1:min(nchar(v)))`if`(anyDuplicated(t<-substr(v,i,i)),0,{cat(t,sep="")
break}))

```

Try it online!

**base R**

```
function(v)for(i in 1:min(nchar(v)))`if`(anyDuplicated(t<-substr(v,i,i)),0,{cat(t,sep="")
v=0})

```

Try it online!

*These two variants saving 9 bytes thanks to Giuseppe.*

### Explanation:

This effectively truncates all stings in the vector `v` to the length of the shortest and iterates through subsequent indexes. Then checks whether there are any duplicates within chosen letters and if not, pastes them together and prints with `cat`. If all indexes return duplicated results, this prints empty string.
All wraped in an anonymous `pryr` function with `break` to halt the loop, or base R function zeroing the vector to break the loop.

# Answer
> 2 votes
# Perl 5 `-plF`, 56 bytes

Saved 5 bytes thanks to @Xcali!

```
map$;[$_].=$F[$_],0..@F}{($_)=grep$.==y///c*!/(.).*\1/,@

```

Try it online!

# Answer
> 2 votes
# Japt v2.0a0, 7 bytes

Takes input as an array of ~~character arrays~~ strings, returns ~~an array of characters~~ a string or `undefined`.

```
ÕæÈ¶¸¬â

```

Try it

# Answer
> 2 votes
# Stax, ~~9~~ 8 bytes

```
åτIⁿs↓µg

```

Run and debug it

Explanation (unpacked):

```
M{c0-u=}j Full program, implicit input
          e.g. ["Programming", "Puzzles", "Code", "Golf"]
M         Transpose
                ["PPCG", "ruoo", "ozdl", "gzef", "rl\0\0", "ae\0\0", "ms\0\0", "m\0\0\0", "i\0\0\0", "n\0\0\0", "g\0\0\0"]
 {     }j Find first matching element:
            e.g. "PPCG"
  c0-       Copy and remove zero bytes (padding)
                 "PPCG" "PPCG"
     u      Unique
                 "PPCG" "PCG"
      =     Check if equal:
                 1
          First matching here: "ozdl". If none is found, the stack is empty
          Implicit output if anything on stack

```

# Answer
> 2 votes
# , 127 bytes

```
function(S,s=sapply(S,substring,x<-1:max(nchar(S)+1),x))cat(rbind(s[!apply(s,1,anyDuplicated)&!rowSums(s==""),],"")[1,],sep="")

```

Try it online!

`sapply` typically returns a `matrix` when all the `length(FUN(X[[i]]))` are equal, except when `length(FUN(X[[i]]))==1`, in which case it returns a `vector`. In order to use the matrix operations, then, we have to `substring` one further than we need to guarantee a `matrix`, which is why `x` extends to `max(nchar(S)+1)`.

We then filter for rows that have no duplicates and no empty strings. Since we can only return a single string, we take the first one, except that when there are no rows that meet the criteria, we would throw an error, so we append an extra row of `""` to the end.

Then we print out the `enklact`ified string or the empty string.

# Answer
> 2 votes
# Perl 6, 27 bytes

```
{([Z] $_).first:{.Set==$_}}

```

Try it online!

After seeing that the ruby version has been upvoted, I have copied the approach and used character lists, instead of strings. I don't like it.

My older, and more correct submission is as below:

# Perl 6, 38 bytes

Split, zip, check uniqueness, join.

```
{[~] ([Z] @_>>.comb).first:{.Set==$_}}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 7 bytes

```
øʒDÙQ}н

```

Try it online!

**Explanation**

```
ø        # Zip the input array
 ʒ   }   # Filter by ...
  DÙQ    # ... an entry is equal to itself deduplicated
      н  # Take the first element

```

# Answer
> 1 votes
# Python 3, 75 bytes

```
def f(t):c=[s.pop(0)for s in t];return all(t)and(f(t),c)[len(t)==len({*c})]

```

Operates on character lists instead of strings. Returns False if no valid enklaction string exists.

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 54 bytes

```
#&@@Select[PadRight@#,#~FreeQ~0&&Union@#==Sort@#&]&

```

Try it online!

Takes a list of list of characters as input, returns a list of characters. Contains U+F3C7, corresponding to "Transpose" operator.

Returns `#1` and throws a bunch of ignorable errors when there is no suitable string.

### Explanation:

```
PadRight@#

```

Pad the input so that each "string" (list of characters) is the same length. This appends integer `0`s (not string `"0"`s). Then transpose.

```
Select[ ... ,#~FreeQ~0&&Union@#==Sort@#&]

```

Select the strings that have no integer `0`s in them and have all unique characters.

```
#&@@

```

Get the first one.

# Answer
> 1 votes
# Charcoal, ~~23~~ 21 bytes

-2 bytes thanks to @Neil!

```
§ΦＥ⌊ＥθＬι⭆θ§λι⬤ι⁼¹№ιλ⁰

```

Try it online!

# Answer
> 1 votes
# C (gcc), 161 bytes

```
f(s,i)char**s;{char**t,a[255],*u=a;for(i=0;memset(a,0,255),u&&~i;i+=!!~i&&u)for(t=s;(u=u?*t++:0)&&~(i=u[i]?i:-1)&&!a[u[i]]++;);while(~i&&(u=*s++))putchar(u[i]);}

```

Try it online!

Each character position is tested for duplication and skipped if a duplicate is detected; this is continued until the shortest string ends. It's ASCII only, sadly: DBCS/UTF-8 strings break this function badly!

# Answer
> 1 votes
# Japt, 12 bytes

Returns `undefined` for non-enklactic strings.

```
y ·æ_¬n ä¦ e

```

Try it online!

## Explanation:

```
y ·æ_¬n ä¦ e
y             // Split the input at newlines and transpose
  ·           // Join on newlines
   æ_         // Return the first item that returns truthy when ran through:
     ¬n       //   Sort
        ä¦    //   Reduce with !=
           e  //   All items are truthy (unique)

```

# Answer
> 1 votes
# JavaScript (ES6), 66 bytes

Returns either a string or `undefined` if no solution exists.

```
f=(a,i=0)=>a.every(s=>(o[k+=c=s[i],c]^=1)&&c,o=k=[])?k:c&&f(a,i+1)

```

Try it online!

### Commented

```
f = (           // f = recursive function taking:
  a,            //   a[] = input array
  i = 0         //   i   = pointer
) =>            //
  a.every(s =>  // for each string s in a[]:
    (o[k +=     //   append to the key string k
      c = s[i], //   the character c at position i in s
      c] ^= 1   //   and toggle o[c] (undefined -> 1 -> 0)
    ) && c,     //   additionally, make sure that c is defined
    o = k = []  //   start with o = k = empty array
  ) ?           // every() is true if all characters were distinct and defined:
    k           //   in which case we return k
  :             // else:
    c &&        //   provided that every() didn't fail because of an undefined character,
    f(a, i + 1) //   try again at the next position

```

# Answer
> 1 votes
# Husk, 9 bytes

```
ḟS=UḞz:∞ø

```

Try it online!

### Explanation

```
fS=UḞz:∞ø
    Ḟz:∞ø  Transpose the input dropping characters of longer strings
    Ḟ        Fold right
     z:      Zip with prepend
       ∞ø    Infinite list of empty lists
ḟS=U       Find the first string without duplicates, returns an empty string if none
ḟ            Return first value satisfying predicate
  =          Equal
 S U         to itself with duplicates removed

```

# Answer
> 1 votes
# Retina, ~~81~~ 56 bytes

```
m`$
$.=*£¢
N$`.
$.%`
¶

~`(.*?¢)+
L`.{$#1}
A`(.).*\1|£|¢

```

Try it online!

*-25 bytes thanks to @Neil*

---

Transposing rectangular text in Retina is surprisingly difficult.

# Answer
> 1 votes
# C (gcc), ~~121~~ ~~113~~ 110 bytes

```
i;d;f(s)char**s;{char**_=s,x[255]={0},y[99]={0};for(d=i=0;*_;)d+=x[y[i++]=*(*_++)++]++;d=d?*x?0:f(s):puts(y);}

```

Try it online!

## Ungolfed

```
void enklactify(char *strings[]) {
    int quit = 0;
    while (!quit) {
        char **arg = strings;      // current row
        int exists[255] = {0};     // which characters exist in the column
        char output[99] = {0};     // will hold output string
        int index = 0;             // where to insert in output
        int duplicates = 0;        // have we found any duplicates?
        while (*arg != NULL) {
            char *word = *arg;     // current word
            char first = *word;    // first letter of current word
            if (exists[first])
                duplicates = 1;    // we found a duplicate
            exists[first] = 1;     // mark it as in our string
            output[index] = first; // add it to our output
            index++;
            (*arg)++;              // advances the current word to the next
                                   // character by reference (chops first char)
            arg++;                 // advance to next whole argument
        }

        if (!duplicates) {         // This is a valid solution
            puts(output);
            quit = 1;
        }

        if (exists[0]) {           // We hit the null terminator of one of the
                                   // input strings, so we failed
            quit = 1;
        }
    }
}

```

-3 thanks to ceilingcat

This abuses the ability to just add 1 to a string pointer in C to get the 'tail' of the string. The main byte savers are:

* `d+=x[y[i++]=*(*_)++]++` which appends the first character of the first string of `_` to `y`, advances the first string of `_` to remove its first character, adds the `x` entry at that character to `d`, and increments said `x` entry
* `q=d?*x:puts(y)` which prints `y` if `d` is non-zero while setting `q` to a non-zero value, or sets `q` to non-zero if the first element of `x` is non-zero (if we were at the end of one of the strings then said element would be non-zero)

Edit: Shaved bytes by switching from while loop to recursive tail call and removing brackets from for loop.

# Answer
> 1 votes
# Husk, 8 bytes

```
ḟȯ=L¹LUT

```

Try it online!

Different approach to the previous Husk answer. Gets the longest prefix with all-unique characters from each index position, and then selects the first that is the same length as the number of input strings.

```
ḟ           # first element that satisfies
 ȯ=L¹L      # length (of string) equals length of input (array), of
      U     # longest prefixes of all unique characters of
       T    # transpose of input

```

# Answer
> 0 votes
# Pyth, 13 bytes

```
e+kf{IT@.TQ.t

```

Try it here

```
e+kf{IT@.TQ.t
           .tQ   Transpose the (implicit) input with padding.
        .TQ      Transpose the input without padding.
       @         Take the strings in both.
   f{IT          Find the ones that have no duplicates.
e+k              Get the last, or an empty string.

```

# Answer
> 0 votes
# Red, 139 bytes

```
func[b][m: length? first b foreach a b[m: min m length? a]repeat n m[c: copy[]foreach a b[append c a/(n)]if c = unique c[return rejoin c]]]

```

Try it online!

## Explanation:

Takes the input as a block (list) of strings. Returns the *enklaction* string or `none` otherwise.

```
f: func[b][
    m: length? first b                   ; the minimal length of the first string
    foreach a b[m: min m length? a]      ; find the minimal length of all strings
    repeat n m[                          ; limit the search to the minimal length
        c: copy[]                        ; an empty block
        foreach a b[append c a/(n)]      ; for each string append the current char
        if c = unique c[return rejoin c] ; if all chars are unique, return the block
    ]
]

```

# Answer
> 0 votes
# APL+WIN, ~~35~~ 33 bytes

2 bytes saved thanks to Adám

Prompts for the lines of text as a character matrix:

```
⊃((↑⍴¨a)=+/¨((a⍳¨a)=⍳¨⍴¨a))/a←,⌿⎕

```

Try it online! Courtesy of Dyalog Classic

Explanation:

```
a←,⌿⎕ prompts for input and creates a nested vector of the input matrix columns

((a⍳¨a)=⍳¨⍴¨a) creates a binary vector for each nested element with a 1 for each unique element

((↑⍴¨a)=+/¨ sums each binary vector and compares to number of characters in each element

(...)/a←⊂[1]⎕ selects only those elements where number of uniques = column length

⊃ converts nested vector back to a matrix of each valid enklaction string

```

# Answer
> 0 votes
# Röda, ~~80~~ 77 bytes

```
f a{a|seq 0,#_|try{{|i|a|[_[i:i+1]]|orderedUniq|concat|[_]if[#_1=#a]}_|head}}

```

Try it online!

*-1 byte thanks to Cows quack*

Explanation:

```
f a{
  a|         /* Push the strings in a to the stream */
             /* For each string (_): */
  seq 0,#_|     /* Push a range from 0 to the length of _ to the stream */
  try{       /* Ignore errors during the following block */
    {|i|        /* For each i in the stream: */
      a|           /* Push strings in a to the stream */
      [_[i:i+1]]|  /* For each string, push the ith character to the stream */
      orderedUniq| /* Remove duplicate characters */
      concat|      /* Join the characters into a string */
      [_]if        /* Push the string to the stream if */
      [#_1=#a]     /* Its length is the length of a */
    }_|
    head        /* Take the first string in the stream and return it */
  }
}

```

The `try` keyword is used to dismiss errors that occur if `i` is larger than the length of the smallest string in `a`, or there is no answer and `head` causes an error.

# Answer
> 0 votes
# Java 10, 106 bytes

```
a->{for(int i=0;;i++){var r="";for(var s:a)r+=s[i];if(r.length()==r.chars().distinct().count())return r;}}

```

Will give an error instead of returning an empty String if no solution can be found. Input is a character-matrix.

Try it online.

**Explanation:**

```
a->{                  // Method with character-matrix parameter and String return-type
  for(int i=0;;i++){  //  Loop `i` upwards
    var r="";         //   Result-String, starting empty
    for(var s:a)      //   Loop over the character-arrays of the input
      r+=s[i];        //    And append every `i`'th character to `r`
    if(r.length()==r.chars().distinct().count())
                      //   If `r` only contains unique characters
      return r;}}     //    Return `r` as result

```

# Answer
> 0 votes
## Clojure, 59 bytes

```
#(for[s(apply map list %):when(=(count(set s))(count %))]s)

```

Returns a list of lists of characters.

# Answer
> 0 votes
# Scala, 97 bytes

```
l=>l.flatMap(h=>(0 to l.map(_.size).min-1).find(i=>l.map(_(i)).toSet.size==l.size)map(h))mkString

```

input is `List[String]` and returns an empty `String` if no solution found.

Try it online.

**Explanation:**

```
l                                    // List("Programming", "Puzzles", "Code", "Golf")
  .flatMap(                          //
    h =>                             // "Programming"
      (0 to l.map(_.size).min-1)     // Range(0, 3) range from 0 to size of smallest word ("Code".size - 1 = 3)
        .find(                       // returns an Option[Int]: if for a given index, all words have a different char, return Some(i)
          i =>                       // index in words, let's say i = 2
            l.map(_(i)).toSet.size   // Set('o', 'z', 'd', 'l').size = 4; checks the nbr of unique chars for the given index
              == l.size              // and compare it to the nbr of words (4)
        )                            //
        map(h)                      // Option(i).map(i => h(i)) which gives Some(2).map(h) = Some('o') and for another index: None.map(h) = None; this is why the begining is l.flatMap and not l.map.
  )mkString                         // joins the List[Char] into a String

```

# Answer
> 0 votes
# C# (.NET Core), 167 bytes (149 + 18 for `using System.Linq;`)

```
p=>{int l=p.Count(),m=p.Min(s=>s.Length);for(int i=-1;i++<m;){var d=p.Select(s=>s[i]).Distinct();if(d.Count()==l)return string.Join("",d);}return"";}

```

Try it online!

# Answer
> 0 votes
# Thunno 2 `ch`, 4 bytes

```
ṬæU:

```

Try it online!

Uses `[]` as the consistent falsy value. If we could output a list of all possible outputs, the `h` flag wouldn't be needed.

#### Explanation

```
ṬæU:  # Implicit input
Ṭ     # Transpose the input
 æ    # Filter this list by:
   :  #  Invariant under:
  U   #   Deduplicating?
      # Get the first item
      # (or [] if it's empty)
      # Implicit output

```

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


title: Iterate over strings II

text:
# Question
Title: Iterate over strings II
This is a successor to a previous challenge.

# Input

An integer \\$1 \leq n \leq 5\\$.

# Task

Your code should produce all strings that satisfy the following properties:

* Your string should contain exactly two each of the first \\$n\\$ letters of the alphabet.
* It should not contain the same letter twice in a row
* It must start with the letter `a`.
* If there is a letter at index `i` in the string, all the letters earlier in the alphabet must occur somewhere at the indices `1..i-1`. This means, for example, that the first `c` can't come before the first `b`.
* It must contain exactly \\$2n\\$ zeros.
* For each zero there must exist a pair of identical letters so that one of the pair is somewhere to its left and one of the pair is somewhere to its right in the string.
* It must not contain anything other than zeros and the lower case letters.

# Examples

```
n=1,`a00a` is the only valid output.

n=2,`a0ab000b`and `ab0000ab` are both valid outputs.  `a0bab000` and `a0a0b00b` are not valid.

n=3,`a0bc0b0a000c` and `a0b000ca0b0c`  are both valid outputs.  ` a0cb0b0a000c` and `a0b000ba0c0c` are not valid.

```

# Answer
> 4 votes
# Charcoal, 61 bytes

```
Ｎθ⊞υωＦ×⁴θ≔ΣＥυ⁺κ⁺Ｅ∧‹№κ0⊗θ⊙β⁼¹№κμ0Φ⪪…βθ¹∧⁻μΦ⮌κ¬π∧‹№κμ²⬤…βν№κξυυ

```

Attempt This Online! Link is to verbose version of code. Explanation: Based on my answer to Iterate over all non-equivalent strings.

```
Ｎθ

```

Input `n`.

```
⊞υω

```

Start with an empty string.

```
Ｆ×⁴θ

```

Loop `4n` times.

```
≔ΣＥυ⁺κ⁺Ｅ∧‹№κ0⊗θ⊙β⁼¹№κμ0Φ⪪…βθ¹∧⁻μΦ⮌κ¬π∧‹№κμ²⬤…βν№κξυ

```

For each string so far, create strings with zero and all of the first n lowercase letters appended to it, but exclude those that fail to satisfy the criteria.

```
υ

```

Output the final strings.

There are two criteria that are checked before a zero can be appended:

* There must be fewer than `2n` zeros already in the string.
* There must be a letter that appears exactly once in the string.

# Answer
> 4 votes
# JavaScript (V8), 139 bytes

*The criterion on 0's is borrowed from Neil's answer. ("There must be a letter that appears exactly once" before a zero.)*

Prints the strings.

```
f=(n,s='',m=1,q=0,p,g=i=>~i&&g(i-1,(b=1<<i*4,i?i!=p:q&1118480&&n)*2>q/b%16&&f(n,s+"0abcde"[i],m+(i==m&m<n),q+b,i)))=>s[4*n-1]?print(s):g(m)

```

Try it online!

Hacked version printing the number of solutions up to \\$n=4\\$

### How?

Because we have \\$n\le5\\$ and because a character may not appear more than \\$10\\$ times, we can store the character counts in a bitmask \\$q\\$ of \\$6\times4\\$ bits:

```
0000 0000 0000 0000 0000 0000
\__/ \__/ \__/ \__/ \__/ \__/
  e    d    c    b    a    0

```

The 4-bit width is actually only required for 0's. The possible values for letter nibbles are **0000**, **0001** and **0010**.

When inserting a zero, we need to test whether there's at least one letter that appears exactly once. This is achieved by doing a bitwise AND of \\$q\\$ with:

```
0001 0001 0001 0001 0001 0000 = 1118480

```

All in all, this is shorter and faster than my previous method that was using an array.

### Commented

```
f = (                   // f is a recursive function taking:
  n,                    //   n = input
  s = '',               //   s = output string
  m = 1,                //   m = upper character bound
  q = 0,                //   q = bitmask keeping track of char. counts
  p,                    //   p = previous character index
  g = i =>              //   g is a recursive function taking a counter i
  ~i && g(              //   unless i = -1, do a recursive call to g:
    i - 1,              //     decrement i
    (                   //     compute the max. count for this character:
      b = 1 << i * 4,   //       b = LSB of the character nibble
      i ?               //       if this is a letter:
        i != p          //         the max. count is 2 if i != p
      :                 //       else (this is a zero):
        q & 1118480     //         the max. count is 2n if it's preceded
        && n            //         by a letter appearing exactly once
    ) * 2 > q / b % 16  //     abort if this char. appeared too many times
    && f(               //     otherwise, do a recursive call to f:
      n,                //       pass n unchanged
      s + "0abcde"[i],  //       append the new character to s
      m +               //       increment m if ...
      (i == m & m < n), //       ... i = m and m < n
      q + b,            //       update the bitmask
      i                 //       set the previous character index to i
    )                   //     end of recursive call
  )                     //   end of recursive call
) =>                    //
s[4 * n - 1] ?          // if the target length is reached:
  print(s)              //   print s
:                       // else:
  g(m)                  //   call g to generate more characters

```

# Answer
> 2 votes
# 05AB1E, 40 bytes

```
A£©Î×ì2×œÙʒáÙ®Q}ʒÔág;Q}ʒS>ƶ©þε®s¡`áÃgĀ}P

```

Brute-force, so very slow. Is able to output the result for \\$n=2\\$ in about 20 seconds on TIO.

Try it online.

**Explanation:**

Step 1: Create a string with the correct characters, to comply to the first and sixth rules ("*Your string should contain exactly two each of the first \\$n\\$ letters of the alphabet.*" and "*It must contain exactly \\$2n\\$ zeros.*"), and get all its unique permutations:

```
A               # Push the lowercase alphabet
 £              # Pop and leave the (implicit) input amount of leading characters
  ©             # Store it in variable `®` (without popping)
   Î            # Push 0 and the input-integer
    ×           # Pop both, and push a string with the input amount of 0s
     ì          # Prepend it to the string
      2×        # Double the entire string
œ               # Pop and push a list of all its permutations
 Ù              # Uniquify this list

```

Try just step 1 online.

Step 2: Verify the fifth rule ("*If there is a letter at index `i` in the string, all the letters earlier in the alphabet must occur somewhere at the indices `1..i-1`.*"):

```
ʒ    }          # Filter this list of strings by:
 á              #  Only keep its letters, removing the 0s
  Ù             #  Uniquify it
   ®Q           #  Check whether it's equal to string `®` of step 1

```

Try the first two steps online.

Step 3: Verify the second rule ("*It should not contain the same letter twice in a row*"):

```
ʒ     }         # Filter it again by:
 Ô              #  Connected uniquify its characters
  á             #  Then remove all 0s again by keeping letters
   g;           #  Pop and push its length, and halve it
     Q          #  Check if halve this length equals the (implicit) input-integer

```

Try the first three steps online.

Step 4: Verify the seventh rule ("*For each zero there must exist a pair of identical letters so that one of the pair is somewhere to its left and one of the pair is somewhere to its right in the string.*"), which implicitly also verifies the third and fourth rules at the same time ("*It must start with the letter `a`.*" and "*It must end with a letter*"), and output the result:

```
ʒ               # Filter it once more:
 S              #  Convert the string to a list of characters
  >             #  Increase all 0s to 1s (and keep the letters unchanged)
   ƶ            #  Multiply all values by their 1-based index
    ©           #  Store this list as new variable `®` (without popping)
     þ          #  Pop and keep just its digits, removing the letters
      ε         #  Map over this list of integers:
       ®        #   Push list `®`
        s       #   Swap so the current integer is at the top
         ¡      #   Split list `®` by the current integer, leaving a pair of lists
          `     #   Pop and push both lists to the stack
           á    #   Only keep the letters of the second string
            Ã   #   Only keep the letters from the first string that are also in the second
             gĀ #   Check if what remains is NOT empty
      }P        #  After the map: product to check if all are truthy
                # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Haskell, 215 bytes

```
import Data.List
f n|c<-"__">>take n['a'..]=[x|x<-permutations$c++(c>>"0"),x!!0=='a',all(\i->not$isInfixOf[i,i]x)c,all((\(f,z:s)->last$(any(>z)$intersect f s):[all(`elem`z:f)['a'..z]|z>'0']).(`splitAt`x))[0..4*n-1]]

```

Attempt This Online!

# Answer
> 2 votes
# Perl 5, 238 bytes

```
sub{$_=substr(10**$_[0].abcdefghij,1,2*pop)x2;my%r;1while s/^(.*)(.)(.*)(.)(??{$t="$1$4$3$2$'";my%a;$t=~m,(\D).*(0).*\1(??{$a{$-[2]}++;X}),;y|||c!=2*keys%a||$t=~m,(\D)(\1|.*(\D).*\3(??{$1lt$3})),||$r{$t}++;$s{$t}++||''})/$1$4$3$2/;keys%r}

```

Try it online!

Returns arrays of 1, 28, 1816, 180143 strings for n = 1,2,3,4. Spent more than half an hour for n=4.

# Answer
> 2 votes
# Retina, 114 bytes

```
.+
*
Y`\_`l
.+
<$&>$&$.&*2*0
/>./+Lrv$`(?(2)(\3.+))<(.+)?([a-z])|(\6.*)<(.+([a-z]).*)(0)\b
$%`$1$4$3$7<$2$5$%'
<>

```

Try it online! Explanation: Based on my answer to Iterate over all non-equivalent strings.

```
.+
*
Y`\_`l

```

Generate the first `n` lowercase letters.

```
.+
<$&>$&$.&*2*0

```

Make a duplicate set, wrap the first set in `<` and `>`, and also append `2n` `0`s to the second set.

```
Lrv$`(?(2)(\3.+))<(.+)?([a-z])|(\6.*)<(.+([a-z]).*)(0)\b
$%`$1$4$3$7<$2$5$%'

```

For each string, make new strings by either a) moving the first letter from the first set or b) moving a letter from the second set that was moved from the first set but not in the immediately previous iteration c) moving the last zero, if there is a letter still in the second set that was moved from the first set.

```
/>./+`

```

Repeat until the second set is empty for all strings.

```
<>

```

Remove the `<>` markers.

# Answer
> 1 votes
# Jelly, 35 bytes

```
Øaḣx2;Œ!ḟQṢƑɗƇɗJ$⁼ƝÐṂṣⱮf/ƇƑ¥ƇḤOnaƊQ

```

A monadic Link that accepts \\$n\\$ and yields a list of lists of characters.

**Try it online!** (Will time out for anything above two though!)

### How?

Constructs all strings fulfilling the conditions with natural numbers in the place of zeros by filtering all permutations of the letters and numbers that, when deduplicated have their letters in order, maps the numbers back to zeros, and then deduplicates.

```
Øaḣx2;Œ!ḟQṢƑɗƇɗJ$⁼ƝÐṂṣⱮf/ƇƑ¥ƇḤOnaƊQ - Link: n
Øa                                  - alphabet
  ḣ                                 - head to {n}
   x2                               - times two -> "aabb..."
                $                   - last two links as a monad f(Letters):
               J                    -   indices -> [1..2n]
              ɗ                     -   last three links as a dyad - f(Letters, Indices)
     ;                              -   {Letters} concatenate {Indices} -> e.g. ['a','a','b','b',1,2,3,4]
      Œ!                            -   all permutations
             Ƈ                      -   keep those {Permuations} for which:
            ɗ                       -     last three links as a dyad - f(Permutation, indices)
        ḟ                           -       {Permutation} filter-discard {indices}
         Q                          -       deduplicate
           Ƒ                        -       is invariant under:
          Ṣ                         -         sort
                   ÐṂ               - keep those {Alphabet-Increaing-Permutations} minimal under:
                  Ɲ                 -   for neighbouring pairs:
                 ⁼                  -     equal?
                            Ƈ       - keep those {Alphabet-Increasing-Adjacency-Different-Permutations} for which:
                           ¥ Ḥ      -   last two links as a dyad - f(Permutation, 2n):
                      Ɱ             -     map across {i in [1..2n]} with:
                     ṣ              -       split {Permutation} at occurrence of {i}
                          Ƒ         -     is that list of Splits invariant under?:
                         Ƈ          -       filter keep {Splits} for which:
                        /           -         reduce {Split=[L,R]} by:
                       f            -           {L} filter keep {R}
                                 Ɗ  - last three links as a monad - f(Valid-Permutations):
                              O     -   cast {ValidPermutations} to ordinals (a no-op for integers) -> Ords
                               n    -   {Ords} not equal {ValidPermutations} (vectorises) -> Mask
                                a   -   {Mask} logical AND {ValidPermutations} (vectorises)
                                  Q - deduplicate

```

# Answer
> 1 votes
# JavaScript (V8), 148 bytes

```
n=>(g=(i,j,t,s=[])=>s.map(_=>g(i,j,t+_,s.filter(r=>r!=_)),s+s&&j&&g(i,j-1,t+0,s),i<n?g(i+1,j,t+(c='abcde'[i]),[...s,c]):j||s+s||print(t)))(0,2*n,'')

```

Try it online!

As comparison to the 139 one

---
Tags: code-golf
---


# Question
Title: Pythagorean triples given the hypotenuse
## Definition (from Wikipedia)

**A Pythagorean triple consists of three positive integers a, b, and c, such that a² + b² = c².**

The typical example of a Pythagorean triple is (3,4,5): 3² + 4² = 9 + 16 = 25 which is 5²

## Task:

Given an integer number `c`, write a program or function that returns the list of pythagorean triples where `c` is the hypotenuse.

The triples do not need to be primitive.

For example: if c=10, the answer will be `[[6,8,10]]`

## Input:

An integer number, the hypotenuse of the possible triples

## Output:

A list of triples, eventually empty. Order is not important, but the list must be duplicate-free (\[3,4,5\] and \[4,3,5\] are the same triple, only one must be listed)

Test cases:

```
5    -> [[3,4,5]]
7    -> []          # Empty
13   -> [[5,12,13]]
25   -> [[7,24,25],[15,20,25]]
65   -> [[16,63,65],[25,60,65],[33,56,65],[39,52,65]]
1105 -> [[47,1104,1105],[105,1100,1105],[169,1092,1105],[264,1073,1105],[272,1071,1105],[425,1020,1105],[468,1001,1105],[520,975,1105],[561,952,1105],[576,943,1105],[663,884,1105],[700,855,1105],[744,817,1105]]

```

This is , shortest entry for each language wins.

# Answer
# Vyxal, ~~11~~ 10 bytes

```
ɾ2ḋvp'²ḣ∑=

```

Try it Online!

*-1 byte thanks to @lyxal*

Thanks for the offer @lyxal, but nah, I don't need flags.

```
ɾ2ḋvp'²ḣ∑=    Full program, input: n, the hypotenuse
ɾ             1..n
 2ḋ           All pairs (2-combinations) without replacement
   vp         Prepend n to each pair
     '        Filter those which satisfy...
      ²         Square each number
       ḣ∑=      Does the sum of last two equal the first?

```

---

# Vyxal, 15 bytes

```
ɾ:Ẋ's=*²∑⁰²=;vJ

```

Try it Online!

Kinda port of my own Jelly answer, using filter instead of "truthy n-D indices".

```
ɾ:Ẋ's=*²∑⁰²=;vJ   Full program, input: n, the hypotenuse
ɾ:Ẋ               All pairs between 1..n and 1..n
   '        ;     Filter the pairs where...
    s=*             it is sorted and
       ²∑⁰²=        the sum of square is equal to n squared
             vJ   Append n to each pair

```
> 7 votes

# Answer
# Wolfram Language (Mathematica), ~~41~~ ~~40~~ 39 bytes

```
Solve[a^2+b^2==c#>c==#>b>a>0,Integers]&

```

-1 byte from ovs

-1 byte from att

`Integers` restricts it to integers; `>0` restricts it to positive integers; and `b>a` removes the duplicates. `c#` is c^2; `c==#` adds the input to each solution set (as required by the OP).

Alternately (also 39 bytes):

```
Solve[Norm@{a,b}==c==#>b>a>0,Integers]&

```

Here's a more verbose version that's similar to the first approach:

```
Solve[{a^2+b^2==#^2,c==#,b>a>0},Integers]&

```

Try it online!
> 6 votes

# Answer
# Excel, ~~100~~ ~~93~~ 90 bytes

```
=LET(a,SEQUENCE(A1),b,TRANSPOSE(a),CONCAT(IF((a<b)*(a^2+b^2)-A1^2,"",a&","&b&","&A1&"
")))

```

Input is in A1. Triples are delimited by a comma and each triple is separated by a new line with a trailing new line. The `LET()` and `SEQUENCE()` functions are only available in certain versions of Excel.

`LET()` allows us to define variables and reference them later. This goes a long way towards saving bytes. The final parameter doesn't define a variable and instead is the output result.

`a,SEQUENCE(c)` creates a 1D array of numbers from 1 to the input.

`b,TRANSPOSE(a)` creates the same array as `a` except transposed. This lets us work with a matrix of `a`x`b` so we can evaluate all possible combinations of integers less than or equal to the input.

```
CONCAT(IF((a>b)*(a^2+b^2)-A1^2,"",a&","&b&","&A1&"
"))

```

This is where all the calculation and concatenation happens so I'll break it into pieces.
`(a>b)*(a^2+b^2)-A1^2` does the math bit to check if it's a triple and, thanks to `(a>b)`, ignores half the results so we don't have duplicates. You cannot have a Pythagorean triple where `a=b` so this is an OK filter. We can use `(~)-A1^2` instead of `(~)<>A1^2` since Excel will interpret 0 as False and any non-zero number as True.
`a&","&b&","&A1&"\n"` (where `\n` is a literal line break in the original formula) creates a text string in the format `a,b,A1` with a trailing new line. These are the results that show up at the end.
`CONCAT(IF(~,"",~))` combines all the results into one big string. Those results are either triples with a trailing new line or blank text. This is what creates the final output.
> 6 votes

# Answer
# Haskell, 46 bytes

```
f c=[[a,b,c]|a<-[1..c],b<-[a..c],a*a+b*b==c*c]

```

Try it online!

* List comprehension made of all combinations *a\<-\[1..c\],b\<-\[a..c\]* with our Pythagorean condition as guard.
We add `c` to the pair yelded.
> 5 votes

# Answer
# , ~~71~~ 65 bytes

```
y=x=scan();while(y<-y-1)(z=(x^2-y^2)^.5)%%1||z>y&&print(c(x,y,z))

```

Try it online!

---

Or  **\>4.1** using recursive function: **64 bytes**
(thanks to pajonk for pointing-this out!)

```
t=\(x,y=1,z=(x^2-y^2)^.5)if(z>y){z%%1||print(c(x,y,z));t(x,y+1)}

```

Try it online!
> 4 votes

# Answer
# Ruby, ~~67 65~~  53 bytes

```
->c{c.times{|a|a.times{|b|p [b,a,c]if a*a+b*b==c*c}}}

```

Try it online!

* Thanks to @Dingus suggestion to print directly instead of yielding to a return array.
* Switched to a double *#times* structure surprisingly better than *#combination*.

```
r=[]             - return array
[*1..c].combination(2) - combinations of 1..input , since a,b are coprime we don't need a==b
{|a,b|r<<[a,b,c] - we add to r the pair yelded with input attached to it
if a*a+b*b==c*c} -  if it's a valid triangle
;r}              - finally we return r

```
> 4 votes

# Answer
# , ~~53~~ 50 bytes

```
rbind(x<-scan(),p<-combn(x,2))[,colSums(p^2)==x^2]

```

Try it online!

Thanks to Dominic van Essen and pajonk in the comments for some golf ideas; and thanks to Dominic van Essen and thothal for -3 bytes together.

Returns a (possibly empty) matrix with triples as columns.

Equivalent to (among others) ovs' Gaia answer.

```
x=scan()			# read input
pairs=combn(1:x,2)		# pairwise combinations of 1..x, as columns of a matrix
triple <- colSums(pairs^2)==x^2	# is it a triple?
rbind(pairs,x)[,triple]		# add a row of x's and filter the columns by the triple condition

```
> 4 votes

# Answer
# Python 3.8 (pre-release), ~~68~~ ~~67~~ 65 bytes

```
lambda c:[(a,b,c)for a in range(1,c)if(b:=(c*c-a*a)**.5)==b//1>a]

```

Try it online!

-1 by observing that `a` and `b` are never equal in a Pythagorean triple. -2 thanks to G B, by squaring by self-multiplying.
> 3 votes

# Answer
# Jelly, ~~10~~ 9 bytes

```
ŒcÆḊ=¥Ƈ;€

```

Try it online!

Backport of my improved Vyxal answer to use pairs without replacement. -1 byte because I just realized there's a 2-byte norm built-in that saves a square. Passes all small test cases and moderately large ones (like 850) but 1105 times out, and might not work for larger inputs due to floating-point errors.

### How it works

```
ŒcÆḊ=¥Ƈ;€   Monadic link; Input = n, the hypotenuse
Œc          Pairs of 1..n without replacement
  ÆḊ=¥Ƈ     Filter those whose norm (sqrt of self-dot-product) equals n
       ;€   Append n to each pair

```

---

# Jelly, 11 bytes

```
R²+²)=²ŒṪ;€

```

Try it online!

### How it works

```
R²+²)=²ŒṪ;€   Monadic link; Input = n, the hypotenuse
    )         For each number i of 1..n,
R²+²            collect the values of j^2+i^2 for j in 1..i
     =²ŒṪ     Coordinates (i,j) where j^2+i^2 = n^2
              (only gives the coordinates where i>j)
         ;€   Append n to each pair

```
> 3 votes

# Answer
# APL (Dyalog Classic), 38 bytes

```
{,∘⍵¨k[⍸(⍵*2)=+/¨2*⍨k←∪,{⍵[⍋⍵]}¨⍳⍵ ⍵]}

```

Try it online!

-10 thanks to @ovs!!!!

dfn, takes the hypotenuse on right
> 3 votes

# Answer
# JavaScript (V8), 55 bytes

Prints the triples.

```
n=>{for(q=n;p=--q;)for(;--p;)p*p+q*q-n*n||print(p,q,n)}

```

Try it online!
> 3 votes

# Answer
# Brachylog, ~~20~~ ~~18~~ 16 bytes

```
^₂~+Ċ√ᵐℕ₁ᵐ≤₁,?ẉ⊥

```

Outputs one triple per line. Try it online!

### Explanation

```
^₂~+Ċ√ᵐℕ₁ᵐ≤₁,?ẉ⊥
^₂                 The input number squared
  ~+               is the sum of
    Ċ              a list of two elements
     √ᵐ            Get the square root of each element
       ℕ₁ᵐ         Each of those must be a natural number greater than or equal to 1
          ≤₁       and they must be sorted in ascending order
            ,?     Append the original input to that list
              ẉ    and output it with a trailing newline
               ⊥  Fail unconditionally, forcing Brachylog to backtrack and find
                   the next output

```
> 3 votes

# Answer
# Alchemist, 179 bytes

```
_->In_n+f
f+n->f+b+c+m
f+0n->j
j+a->j+d+x
j+m+0a->k+d
k+d->k+a+x
k+0d->i
0q+b+x->e
0q+0b+e+m->q
q+e+x->q+b
q+0e->
i+0x+0e->j+Out_a+Out_" "+Out_b+Out_" "+Out_c+Out_"\n"
i+0x+e->j+e

```

Try it online!

`a`, `d`, `i`, `j`, and `k` define a source of `x`, while `b`, `e`, and `q` define a sink for `x`. `m` is equal to \\$b - a\\$ where relevant, and the program halts when it reaches zero to avoid duplicating triples.

### Initialization

```
_->In_n+f
f+n->f+b+c+m
f+0n->j

```

Simply sets `b`, `c`, and `m` to the input, puts the sink in state `j`, and puts the source in state `0q`.

### Source

```
j+a->j+d+x
j+m+0a->k+d
k+d->k+a+x
k+0d->i

```

When the source is in state `j`, this adds \\$2a+1\\$ `x` atoms while incrementing \\$a\\$ (using up an `m`), then returns to state `i`. Whenever the source is in state `i`, it has provided a total of \\$a^2\\$ `x` atoms.

### Sink

```
0q+b+x->e
0q+0b+e+m->q
q+e+x->q+b
q+0e->

```

Similar to the source, but without a special `i` state. The source starts in state `0q`, and in each cycle, it uses up \\$2b-1\\$ `x` atoms, decrements \\$b\\$, and uses up an `m`. While there is no special state to denote whether the number of atoms taken is equal to \\$c^2 - b^2\\$, the condition `e=0` will work.

### Output

The source waits for there to be no more `x` atoms before starting another cycle; without this check, it could pass every triple without detecting them. This is the purpose of the `i` state.

```
i+0x+0e->j+Out_a+Out_" "+Out_b+Out_" "+Out_c+Out_"\n"
i+0x+e->j+e

```

When there are no more `x` atoms in the `i` state, we check whether we are actually at a triple. If we are, output the triple. Either way, move the source to the `j` state without changing anything else.
> 3 votes

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

```
{+x,+(x=%+/*/2#,+:)#+&~|\=x}

```

Try it online!

It uses the indices of ones in an upper triangular matrix for creating all possible (a,b) pairs, then filters them based on the pythagorean condition. Prepends the hipotenuse for each pair found.
> 3 votes

# Answer
# APL (Dyalog Classic), 35 bytes

```
{⍵,⍨¨{⍵↑⍨2÷⍨≢⍵}⍸(⍵*2)=+/¨2*⍨∘.,⍨⍳⍵}

```

Calculates every combination of a^2 + b^2 and stores the values which add up to c^2

Try it Online!
> 3 votes

# Answer
# Vyxal, ~~18~~ 17 bytes

```
²Ṅ'Ḣ₃;'∆²A;:[√⌊vJ

```

Try it Online!

It times out for inputs greater than 7, but the algorithm works. I can't wait to be outgolfed by anyone with greater mathematical knowledge lol ;p

*-1 thanks to @EmanresuA and their tip from here*

## Explained

```
²Ṅ'Ḣ₃;'∆²A;:[√⌊vJ
²Ṅ                   # from all the integer partitions of the input squared,
  'Ḣ₃;               # only keep those where the length is 2. And from those,
      '∆²A;          # only keep those where all numbers are perfect squares.
           :[        # If that isn't empty,
             √⌊vJ    # get the square root of each item, and append the hypotenuse to each sublist.

```
> 2 votes

# Answer
# JavaScript (V8), 57 bytes

```
n=>(g=i=>(j=(n*n-++i*i)**.5)>i&&g(i,j%1||print(i,j,n)))``

```

Try it online!

A quite straightforward approach.
> 2 votes

# Answer
# C (clang), ~~99~~ \\$\cdots\\$ ~~75~~ 74 bytes

```
a;b;f(c){for(b=c;a=--b;)for(;--a;)c*c-b*b-a*a||printf("%d,%d,%d ",a,b,c);}

```

Try it online!

*Saved a byte thanks to ceilingcat!!!*

Inputs integer \\$c\\$ and outputs all unique Pythagorean triples with hypotenuse \\$c\\$. The side lengths are separated by commas and the Pythagorean triples separated by spaces.
> 2 votes

# Answer
# APL+WIN, 42 Bytes

Prompts for hypotenuse:

```
(((c*2)=+/¨n*2)/n←(,m∘.<m)/,m∘.,m←⍳c),¨c←⎕

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# Java, 91 bytes

```
c->{for(int i=c,j;--i>0;)for(j=i;--j>0;)if(i*i+j*j==c*c)System.out.println(j+" "+i+" "+c);}

```

Try it online!
> 2 votes

# Answer
# Gaia, 12 bytes

```
s¦e⁻+
┅r+¦↑⁈

```

Try it online!

```
s¦e⁻+    -- helper function; check whether 3 numbers form a pythagorean triple
s¦       -- square each number            -> [a^2 b^2 c^2]
  e      -- dump all values on the stack  -> a^2 b^2 c^2
   ⁻+    -- subtract and add              -> a^2+(b^2-c^2)

┅        -- range from 1 to input
 r       -- all pairs of values from this list
  +¦     -- append the input to each pair
    ↑⁈   -- Reject; Only keep elements where the above function returns 0

```
> 2 votes

# Answer
# TI-Basic, 34 bytes

```
Prompt C
For(A,1,C/√(2
√(C²-A²
If not(fPart(Ans
Disp {A,Ans,C
End

```
> 2 votes

# Answer
# Kotlin, 83 bytes

`fun x(c:Int){for(i in 1..c)for(j in 1..i)if(i*i+j*j==c*c)print("[${j} ${i} ${c}]")}`

Try it online!
> 2 votes

# Answer
# Raku, 45 bytes

```
{grep *²+*²==*²,flat .&combinations(2)X$_}

```

Try it online!

* `$_` is the hypotenese length, the argument to the function.
* `.&combinations(2)` is a list of all two-element combinations of the list of integers from zero to one less than the hypoteneuse. These are the possible triangle leg lengths. (The unusual syntax `.&` means to call the global function named `combinations`, passing `$_` as the first parameter. It saves a few bytes here.)
* `X $_` pastes the hypoteneuse onto the end of each combination using the cross-product operator `X`.
* `flat` flattens the list.
* `*² + *² == *²` is an anonymous function that returns true if the sum of the squares of its first two arguments is equal to the square of the third argument.
* `grep` consumes three elements at a time from the flattened list of side lengths (since its test function takes three arguments) and returns the triples that describe a right triangle.
> 2 votes

# Answer
# Swift, 87 bytes

```
let p={n in(1...n).reduce(into:[]){for j in $1...n{if $1*$1+j*j==n*n{$0+=[[$1,j,n]]}}}}

```

Using the `reduce` instead of the outer `for` loop to save the bytes needed to declare the result variable, and to return it.

Try it online!
> 2 votes

# Answer
# Excel, 86 bytes

```
=LET(a,SEQUENCE(A1/2^0.5),b,(A1^2-a^2)^0.5,CONCAT(IF(MOD(b,1),"",a&","&b&","&A1&"
")))

```

Link to Spreadsheet

a equals the sequence of numbers up to the hypotenuse / \\$\sqrt2\\$.

b equals the list of numbers that makes a Pythagorean triple with the corresponding number in a.

If mod(b,1) = 0 then return the triple otherwise return blank.
> 2 votes

# Answer
# Julia, 48 bytes

```
~c=[[a,b,c] for b=1:c for a=1:b if a^2+b^2==c^2]

```

Attempt This Online!

Another variation turns out to be a byte longer:

```
~c=[[a,b,c] for b=1:c,a=1:c if a<b&&a^2+b^2==c^2]

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 47 bytes

```
Cases[Range@#~Subsets~{2},x_/;x.x==#^2:>{x,#}]&

```

Try it online!
> 1 votes

# Answer
# Vyxal, 22 bytes

```
ɾ:vɾZƛ÷v";f2ẇ'²∑⁰²=;vJ

```

Try it Online!

What a horrible mess. I'm sure there's so many shorter ways of doing this...
> 1 votes

# Answer
# 05AB1E, 14 bytes

```
L2.ÆʒnOInQ}εIª

```

Try it online!

Second solution, just replace some boilerplate with sleek `2.Æ` (pairs without replacement), also this one is both the shortest and fastest among three

# 05AB1E, 14 bytes (Thanks to @ovs)

```
Lã€{ÙʒnOtQ}εIª

```

Try it online!

# 05AB1E, 14 bytes

```
nÅœ2ùʒÅ²P}tεIª

```

Try it online!

This is slower, but 2 bytes shorter.

```
n       # square
Åœ      # integer partitions
2ù      # keep length 2s
ʒ       # filter by
Å²      # perfect square?
P       # product
}       # end filter
t       # root
ε       # foreach
I       # input
ª       # tuck

```

# 05AB1E, 16 bytes

```
LDâ€{ÙʒnOInQ}εIª

```

Try it online!

The most obvious approach

```
L       # 1..n
D       # dup
â       # cartesian product
€       # vectorize
{       # sort
Ù       # nub
ʒ       # filter by
n       # square each
O       # sum
I       # input
n       # squared
Q       # equals?
}       # end filter
ε       # foreach
I       # input
ª       # append

```
> 1 votes

# Answer
# Retina 0.8.2, 83 bytes

```
^
$'$*_
_
$'$*_
(?<=^((_(?(2)\2_))+))(?=\1)(?=(_(?(3)\3_))+(\d+)$)
¶$#2,$#3,$4¶
A`_

```

Try it online! Link includes faster test cases. Explanation:

```
^
$'$*_

```

Prefix `c` `_`s to `c`.

```
_
$'$*_

```

Replace each `c` with `c` `_`s, thus creating .

```
(?<=^((_(?(2)\2_))+))

```

Match at any position which is a positive square number...

```
(?=\1)

```

... that is no more than half of ...

```
(?=(_(?(3)\3_))+(\d+)$)

```

... where the difference with  is also square, and match `c` while we're there, ...

```
¶$#2,$#3,$4¶

```

... and insert the discovered triple.

```
A`_

```

Delete everything else.

66 bytes in Retina 1:

```
.+
*
_
$=
L$v`(?<=^((_(?(2)\2_))+))(?=\1)(_(?(3)\3_))+$
$#2,$#3,$+

```

Try it online! No test suite due to the program's use of history. Explanation:

```
.+
*
_
$=

```

Convert the input to unary and square it.

```
L$v`(?<=^((_(?(2)\2_))+))(?=\1)(_(?(3)\3_))+$

```

Match all square suffixes which are greater than their square prefixes, ...

```
$#2,$#3,$+

```

... and output the resulting triple.
> 1 votes

# Answer
# Charcoal, 24 bytes

```
ＮθＦθＦι¿⁼×θθ⁺×ιι×κκＩ⟦⟦κιθ

```

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

```
Ｎθ

```

Input `c`.

```
Ｆθ

```

Loop `b` from `0` to `c`.

```
Ｆι

```

Loop `a` from `0` to `b`.

```
¿⁼×θθ⁺×ιι×κκ

```

If this is a triple, ...

```
Ｉ⟦⟦κιθ

```

... output `a`, `b` and `c` on separate lines, double-spacing each triple.
> 1 votes

# Answer
# APL(Dyalog Unicode), 28 bytes

```
(,/(+/=2×⊃)¨⍤×⍨⊆⊢)⊢,¨∘⍸⍳∘.<⍳

```

Try it on APLgolf!

---

# APL (Dyalog Extended), ~~39~~ 35 bytes

Longer with the Extended variant, but this one runs in linear time.

```
{⍵,¨1↑2 ¯1⍴(⌽,¨⊢)⍸0=1|√⍵-⍥(×⍨)⍳⍵-1}

```

Try it online!
> 1 votes

# Answer
## Batch, 131 bytes

```
@for /l %%b in (1,1,%1)do @for /l %%a in (1,1,%%b)do @call:c %%a %%b %1
@exit/b
:c
@set/ah=%1*%1+%2*%2-%3*%3
@if %h%==0 echo %*

```

Takes input as a command-line parameter and outputs each triple of space-separated values on its own line. Explanation:

```
@for /l %%b in (1,1,%1)do

```

Try all values of `b` between `1` and `c`.

```
@for /l %%a in (1,1,%%b)do

```

Try all values of `a` between `1` and `b`.

```
@call:c %%a %%b %1

```

Pass the values to a subroutine so that they can be calculated in separate statements.

```
@exit/b

```

Exit the script.

```
:c

```

Start the subroutine.

```
@set/ah=%1*%1+%2*%2-%3*%3

```

Calculate the difference between the sums of squares and the square of the input.

```
@if %h%==0 echo %*

```

If it's zero then output the triple.
> 1 votes

# Answer
# Python 3, 67 bytes

```
lambda n:[(j,i,n)for i in range(n)for j in range(i)if i*i+j*j==n*n]

```

Try it online!
> 1 votes

# Answer
# Thunno 2, 10 bytes

```
2Ṛȷaæ²DS½Ƈ

```

Try it online!

#### Explanation

```
2Ṛȷaæ²DS½Ƈ  # Implicit input
2Ṛ          # Combinations with length 2
  ȷa        # Append input to each pair
    æ       # Filter this list by:
     ²      #  Square each value
      D     #  Duplicate
       S½   #  Half of the sum
         Ƈ  #  Is in the list?
            # Implicit output

```
> 1 votes

---
Tags: code-golf
---


# Question
Title: Get the indices of an array after sorting
Your challenge today is to write a program or function which takes a list `l` and gives the positions in `l` at which each successive element of `l` sorted appears.

In other words, output the index of the smallest value, followed by the index of the second smallest value, etc.

You can assume that the input array will contain only positive integers, and will contain at least one element.

Test cases:

```
Input                  | Output (1-indexed)
[7, 4, 5]              | [2, 3, 1]
[1, 2, 3]              | [1, 2, 3]
[2, 6, 1, 9, 1, 2, 3]  | [3, 5, 1, 6, 7, 2, 4]
[4]                    | [1]

```

When two or more elements with the same value appear, their indices should appear next to each other from smallest to largest.

This is , fewest bytes wins!

# Answer
> 10 votes
# Jelly, 1 byte

Try it online!

# Answer
> 11 votes
# Dyalog APL, 1 byte

Dyalog APL has a built in operator function (thank you Zacharý for clearing this up) to do this.

## Example

```
⍋11 2 4 15
    2 3 1 4
{⍵[⍋⍵]}11 4 2 15
    2 4 11 15

```

Here I'm indexing into the list by the sorted indices to return the list in ascending order.

# Answer
> 10 votes
# Haskell, ~~43~~ 42 bytes

`1`-indexed:

```
import Data.List
map snd.sort.(`zip`[1..])

```

Try it online!

`-1` byte thanks to @ØrjanJohansen!

# Answer
> 9 votes
# Python 2, 56 bytes

This solution is 0-indexed. This abuses the fact that `sorted()` creates a copy of the original list.

```
l=input()
for k in sorted(l):a=l.index(k);print a;l[a]=0

```

Try it online!

# Answer
> 9 votes
# Javascript (ES6), 39 bytes

-2 bytes thanks to @powelles

This only works in browsers where `Array.prototype.sort` is stable.

```
a=>[...a.keys()].sort((b,c)=>a[b]-a[c])

```

1-indexed version (47 bytes):

```
a=>a.map((_,i)=>i+1).sort((b,c)=>a[b-1]-a[c-1])

```

**Example code snippet:**

```
f=
a=>[...a.keys()].sort((b,c)=>a[b]-a[c])
console.log("7,4,5 => "+f([7,4,5]))
console.log("1,2,3 => "+f([1,2,3]))
console.log("2,6,1,9,1,2,3 => "+f([2,6,1,9,1,2,3]))
console.log("4 -> "+f([4]))
```

# Answer
> 7 votes
# Python 2, 48 bytes

```
lambda x:sorted(range(len(x)),key=x.__getitem__)

```

Try it online!

# Answer
> 5 votes
# Perl 6,  ~~27~~  21 bytes

```
*.pairs.sort(*.value)».key

```

Test it

```
->\x{sort {x[$_]},^x}

```

Test it

Inspired by a Python answer

## Expanded:

```
->    # pointy block lambda
  \x  # declare sigilless parameter
{
  sort
    { x[$_] },  # sort by the value in ｢x｣ at the given position
    ^x          # Range up-to the number of elements in ｢x｣
}

```

# Answer
> 5 votes
# Bash + coreutils, 20

```
nl|sort -nk2|cut -f1

```

Try it online.

# Answer
> 4 votes
# , 5 bytes

There is a builtin function for this.

```
order

```

# Answer
> 4 votes
# Swift 4, 82 bytes

```
func f(l:[Int]){var l=l;for k in l.sorted(){let a=l.index(of:k)!;print(a);l[a]=0}}

```

Test Suite.

## Explanation

In Swift, `l.sorted()` creates a sorted copy of the original Array. We loop through the sorted elements in the list and after printing each item's index in the original Array with `let a=l.index(of:k)!;print(a)`, and then, in order to keep the correct indexes in the Array, we assign `l[a]` to `0`, because it does not affect our normal output.

---

Take note that this is 0-indexed, since it is a port of my Python solution. If you want it to be 1-indexed, replace `print(a)` with `print(a+1)` or Try it online!.

# Answer
> 4 votes
# Octave, 17 bytes

```
@(i)[~,y]=sort(i)

```

Try it online!

Octave is like MATLAB but with inline assignment, making things possible that gives the folks at Mathworks HQ headaches. It doesn't matter what you call `y`, but you can't do without that dummy variable, as far as I know.

# Answer
> 4 votes
# , 2 bytes

```
/:

```

Try it online!

Zero-based indexing.

# Answer
> 4 votes
# Ruby, 40 bytes

```
->a{a.zip([*1..a.size]).sort.map &:last}

```

Try it online!

# Answer
> 4 votes
# Julia, 8 bytes

```
sortperm

```

Attempt This Online!

# Answer
> 3 votes
# MATL, 2 bytes

```
&S

```

Try it online!

Input and output are implicit.

# Answer
> 3 votes
# MY, 3 bytes

MY also has a builtin for this!

```
⎕⍋↵

```

Try it online!

### How?

Evaluated input, grade up, then output with a newline.

Indexed however you set the index, with /`0x48`. (Can even be some weird integer like `-1` or `2`, the default is `1`).

# Answer
> 3 votes
# Java 8, 128 + 19 = 147 bytes

Based on Mr. Xcoder's solution. 0-based. Lambda takes input as an `Integer[]` and returns `Integer[]`. Byte count includes lambda expression and required import.

```
import java.util.*;

```

```
l->{Integer o[]=l.clone(),s[]=l.clone(),i=0;for(Arrays.sort(s);i<l.length;)l[o[i]=Arrays.asList(l).indexOf(s[i++])]=0;return o;}

```

Try It Online

## Ungolfed lambda

```
l -> {
    Integer
        o[] = l.clone(),
        s[] = l.clone(),
        i = 0
    ;
    for (Arrays.sort(s); i < l.length; )
        l[o[i] = Arrays.asList(l).indexOf(s[i++])] = 0;
    return o;
}

```

## Notes

I use `Integer[]` instead of `int[]` to allow use of `Arrays.asList`, which has no primitive versions. `Integer` is preferred to `Long` because values are used as array indices and would require casting.

This ended up being shorter than my best procedural-style `List` solution because of the cost of class and method names.

This also beat a solution I tried that streamed the inputs, mapped to *(value, index)* pairs, sorted on values, and mapped to indices, mostly because of the baggage needed to collect the stream.

## Acknowledgments

* -5 bytes thanks to *Nevay*

# Answer
> 3 votes
# Factor, 8 bytes

```
arg-sort

```

Try it online!

0-indexed

# Answer
> 2 votes
# Common Lisp, 82 bytes

```
(lambda(l)(loop as i in(sort(copy-seq l)'<)do(setf(elt l(print(position i l)))0)))

```

Try it online!

# Answer
> 2 votes
# MATLAB / Octave, 29 bytes

```
[~,y]=sort(input(''));disp(y)

```

Try it online!

# Answer
> 2 votes
## Clojure, 39 bytes

```
#(map key(sort-by val(zipmap(range)%)))

```

# Answer
> 2 votes
# CJam, 12 bytes

```
{ee{1=}$0f=}

```

Try it online!

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

0-indexed. Works for lists containing up to 65,536 elements.

```
a=>[...a=a.map((n,i)=>n<<16|i)].sort((a,b)=>a-b).map(n=>a.indexOf(n))

```

### Test cases

```
let f =

a=>[...a=a.map((n,i)=>n<<16|i)].sort((a,b)=>a-b).map(n=>a.indexOf(n))

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

# Answer
> 2 votes
# Python 3 with Numpy, ~~38~~ 26 bytes

*12 bytes saved thanks to Jo King (no need to give the function a name)*

```
import numpy
numpy.argsort

```

Output is 0-based.

Try it online!

# Answer
> 2 votes
# Python 3, 52 bytes

0-indexed. Based on Bruce Forte's Haskell answer here and G B's Ruby answer here.

```
lambda l:list(zip(*sorted(zip(l,range(len(l))))))[1]

```

Try it online!

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

This is a direct port of my Haskell answer, also `1`-indexed:

```
m→O`z,N

```

Try it online!

### Ungolfed/Explained

```
Code        Description               Example
         -- implicit input            [2,6,1]
      N  -- natural numbers           [1,2,3,..]
   `z,   -- zip, but keep input left  [(2,1),(6,2),(1,3)]
  O      -- sort                      [(1,3),(2,1),(6,2)]
m→       -- keep only indices         [3,1,2]

```

# Answer
> 2 votes
# Java (OpenJDK 8), 72 bytes

```
l->l.stream().sorted().map(i->{int j=l.indexOf(i);l.set(j,0);return j;})

```

Try it online!

Takes a `List<Integer>`, returns a `Stream<Integer>` containing the results.

We get a Stream based off the initial list, sort it, then map each number to it's index in the list. In order to accommodate duplicate elements, we set the original element in the list to `0`.

# Answer
> 2 votes
# SmileBASIC, 67 bytes

```
DEF I(A)DIM B[0]FOR I=1TO LEN(A)PUSH B,I
NEXT
SORT A,B
RETURN B
END

```

Very simple, all it does is generate a list of numbers from 1 to (length of array) and sort this by the same order as the input.

# Answer
> 2 votes
# Vyxal, 1 byte

Try It Online!

0-indexed

# Answer
> 2 votes
# Thunno 2, 1 byte

```
ƙ

```

Try it online!

Same as the other golflangs - built-in for "grade up".

# Answer
> 2 votes
# Desmos, 27 bytes

Yields a 1-indexed result.

```
f(l)=sort([1...l.length],l)

```

Try it on Desmos!

# Answer
> 1 votes
# 05AB1E, 4 bytes

```
ā<Σè

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 16 bytes

```
a->vecsort(a,,1)

```

Try it online!

# Answer
> 1 votes
# PHP, 54 bytes

```
<?php function i($a){asort($a);return array_keys($a);}

```

Try it online!

This is zero-indexed. Simply sorts the array and returns the keys.

# Answer
> 1 votes
# Tcl, 21 bytes

(0-indexed)

```
puts [lsort -indi $L]

```

Try it online!

# Answer
> 1 votes
# Ruby, 34 bytes

```
->a{(0...a.size).sort_by{|i|a[i]}}

```

0-indexed, 1-indexing requires one more net byte:

```
->a{(1..a.size).sort_by{|i|a[i-1]}}

```

Also, a slightly golfed version of G B's answer is 37 bytes:

```
->a{a.each_with_index.sort.map &:pop}

```

# Answer
> 1 votes
# Kotlin,  ~~44~~  34 bytes

not today, crossed out 44

```
{l->(1..l.size).sortedBy{l[it-1]}}

```

Try it online!

1-indexed because that's what the examples give. A 0-indexed version looks like this for 30 bytes:

```
{l->l.indices.sortedBy{l[it]}}

```

# Answer
> 1 votes
# Japt, ~~6~~ 5 bytes

0-indexed

```
ð ñ@v

```

Try it

---

### Alternative, 6 bytes

```
í ñÎmÌ

```

Try it

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


title: Be as fair as possible

text:
# Question
Title: Be as fair as possible
## Introduction

In this challenge you should split an integer into two pieces. Since nobody likes getting the smaller piece of cake, your goal is to be as fair as possible. For example if you wanted to split the integer `7129` into two pieces, there are 3 possible ways of doing so.

`7,129`, `71,29` and `712,9` are all possibilities, but `71,29` is the fairest way of splitting it into two pieces because it minimizes the difference between the two:

```
7 129 -> |7-129| = 122
71 29 -> |71-29| = 42
712 9 -> |712-9| = 703

```

## Challenge

Given an integer determine the best possible way of partitioning it as described above and **report the resulting difference.**

## Rules

* Splitting only makes sense for integers of length at least two, the input will always be ≥ 10
* Input can be either an integer, list of digits or a string
* You don't have to handle invalid input

## Testcases

You only need to report the resulting difference, the partitioning is only here for illustration:

```
10 -> 1,0 -> 1
11 -> 1,1 -> 0
12 -> 1,2 -> 1
13 -> 1,3 -> 2
101 -> 1,01 -> 0
128 -> 12,8 -> 4
313 -> 3,13 -> 10
1003 -> 1,003 -> 2
7129 -> 71,29 -> 42
81128 -> 81,128 -> 47
999999 -> 999,999 -> 0
9999999 -> 999,9999 or 9999,999 -> 9000

```

# Answer
> 12 votes
# Brachylog, ~~12~~ 11 bytes

My first Brachylog answer

Take input as a string

```
{~cĊịᵐ-ȧ}ᶠ⌋

```

Try it online!

### Explanation:

will **f**ind all possible outputs for the predicate in `{…}` and store them in a list. `~c` says that the output is a list that, when **c**oncatenated, is equal to the input. Next `Ċ` asserts that the the output of `~c` has length 2.

`ịᵐ` converts both elements of the output into integers (this gets rid of leading `0`s),  takes the absolute difference of the two elements.

Once we have our list of all possible outputs, we get the minimum element with

# Answer
> 10 votes
# 05AB1E, 9 bytes

### Code:

```
ā¤âε£ÆÄ}W

```

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

### Explanation

```
ā            # Get the array [1, 2, .., len(input)]
 ¤â          # Cartesian product with the last element, (e.g. for input 12345:
               [[1, 5], [2, 5], [3, 5], [4, 5], [5, 5]])
   ε   }     # For each element:
    £        #   Get the substrings (12345 [3, 5] £ --> [123, 45])
     Æ       #   Reduce by subtraction
      Ä      #   Get the absolute value
        W    # Take the minimum of all results

```

# Answer
> 10 votes
# Haskell, 48 bytes

```
f n=minimum[abs$n`div`10^k-n`mod`10^k|k<-[1..n]]

```

`[1..n]` makes this too slow for the larger test cases.

Try it online!

# Answer
> 9 votes
# Python 2, 64 bytes

```
lambda n:min(abs(int(n[i:])-int(n[:i]))for i in range(1,len(n)))

```

Try it online!

# Answer
> 7 votes
# Perl 6, 40 bytes

```
{min map {abs [-] @$_},m:ex/^(.+)(.+)$/}

```

Test it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  min
    map
      {
        abs
          [-]    # reduce with &infix:«-»
            @$_  # the input of this inner block as a Positional
      },

      # split ｢$_｣ into 2 in every possible way
      m
      :exhaustive
      /^ (.+) (.+) $/
}

```

# Answer
> 7 votes
# Prolog (SWI), ~~195~~ ~~189~~ ~~154~~ ~~117~~ 112 bytes

*35 bytes saved thanks to Eminga*

```
A*H:-findall(X,(between(0,A,I),r(A,I,X)),L),sort(L,[H|_]),!.
r(A,B,C):-Z is 10**B,divmod(A,Z,X,Y),C is abs(X-Y).

```

Try it online!

This is my first try at prolog golfing so it may be a bit horrendous. Here is how it works.

At the highest level we have `*`. `*` takes `A` and `H`, and determines if `H` is the smallest way to split `A`.

```
    A*H:-
      findall(X,(between(0,A,I),call(r,A,I,X)),L),
      sort(L,[H|_]),
      !.

```

The first line here uses a technique from this SO post, to essentially perform a map of the predicate `r(A)` over the integers from `0` to `A`. Since `r` confirms the values of each partitions this will give us the values of all possible partitions, plus a whole load of extra junk. All these partitions will be stored in `L` in no particular order. Once that is done we sort the list to find the smallest element. We then use a cut to prevent backtracing.

Next we have the definition of `r`. First `r` calculates the two results of the split naming them `X` and `Y`.

```
r(A,B,C):-
  Z is 10**B,
  divmod(A,Z,X,Y),
  C is abs(X-Y).

```

Then we assert that `C` is the difference of them and is positive.

```
  C is abs(X-Y).

```

# Answer
> 6 votes
# C, 94 bytes

```
c,r,d,a;f(n){for(c=1,r=0,d=n<11?1:n;n;r+=n%10*c,c*=10,n/=10)a=abs(r-n),d=r&&a<d?a:d;return d;}

```

Try it online!

# Answer
> 6 votes
# Python 2, 51 bytes

```
f=lambda n,k=1:min(abs(n/k-n%k),k/n*n or f(n,10*k))

```

Try it online!

# Answer
> 5 votes
# Haskell, ~~68~~ 65 bytes

```
f x=minimum[abs$read(take i x)-read(drop i x)|i<-[1..length x-1]]

```

Try it online!

## Explanation

```
minimum              -- Minimum of ...
 [abs$               -- The absolute value of ...
  read(take i x)     -- The first i characters of x
  -                  -- Minus ...
   read(drop i x)    -- The last i characters of x
 |i<-[1..length x-1] -- From i=1 to i=length x - 1
 ]

```

# Answer
> 5 votes
# Jelly, ~~9~~ 8 bytes

```
ḌÐƤḊạḌƤṂ

```

Try it online!

-1 byte thanks to Dennis. Input is a list of digits.

**Explanation**

```
ḌÐƤḊạḌƤṂ
ḌÐƤ          Convert to integer from decimal for all Ƥostfixes. [1,2,3]->[123,23,3]
   Ḋ         Remove the first element ->[23,3]
     ḌƤ      Convert to integer from decimal for all Ƥrefixes [1,2,3]->[1,12,123]
    ạ        Absolute difference. [23,3]ạ[1,12,123]->[22,9,123]
       Ṃ     Minimum

```

# Answer
> 4 votes
# Charcoal, 14 bytes

```
Ｉ⌊Ｅθ↔⁻Ｉ…θκＩ✂θκ

```

Try it online! Link is to verbose version of code. Conveniently I get to use the 2-arg variant of `Slice`. Explanation:

```
   θ            Input string
  Ｅ             Map over characters
        θ   θ   Input string
         κ   κ  Current map index
       …        Mold to length (i.e. head)
           ✂    Slice (i.e. tail)
      Ｉ   Ｉ     Cast to integer
     ⁻          Subtract
    ↔           Absolute value
 ⌊              Minimum
Ｉ               Cast to string
                Implicitly print

```

# Answer
> 3 votes
# APL (Dyalog), 27 bytes

```
{⌊/|-/⍎¨↑⊂∘⍵¨↓1,∘.=⍨⍳¯1+≢⍵}

```

Try it online!

**How?**

`¯1+≢⍵` \- length of `n` minus 1

`∘.=⍨⍳` \- identity matrix

```
      1,∘.=⍨⍳3
1 1 0 0
1 0 1 0
1 0 0 1

```

`1,` \- prepend `1` for each row

\- split by rows

`⊂∘⍵¨` \- for each, partition the string by it

```
      1 0 1 0 ⊂ '7129'
┌──┬──┐
│71│29│
└──┴──┘

```

\- flatten

`-/` \- reduce each pair with subtraction

`|` \- take absolute values

`⌊/` \- minimum

---

# APL (Dyalog), 35 bytes

```
{⌊/|-/⍎¨(⊂∘⍵⍤1)1,∘.=⍨⍳¯1+≢⍵}

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 64 bytes

Takes input as a string.

```
f=([c,...s],l=0)=>c?Math.min(Math.abs((l+=c)-s.join``),f(s,l)):l

```

### Test cases

```
f=([c,...s],l=0)=>c?Math.min(Math.abs((l+=c)-s.join``),f(s,l)):l

console.log(f("10"     )) // -> 1
console.log(f("11"     )) // -> 0
console.log(f("12"     )) // -> 1
console.log(f("13"     )) // -> 2
console.log(f("101"    )) // -> 0
console.log(f("128"    )) // -> 4
console.log(f("313"    )) // -> 10
console.log(f("1003"   )) // -> 2
console.log(f("7129"   )) // -> 42
console.log(f("81128"  )) // -> 47
console.log(f("999999" )) // -> 0
console.log(f("9999999")) // -> 9000
```

### Commented

```
f = ([c, ...s],           // c = current character, s = array of remaining characters
                l = 0) => // l = left part of the integer, initialized to 0 (see footnote)
  c ?                     // if c is defined:
    Math.min(             //   return the minimum of:
      Math.abs(           //     1) the absolute value of:
        (l += c) -        //       the updated left part
        s.join``          //       minus the right part
      ),                  //     end of Math.abs()
      f(s, l)             //     2) the result of a recursive call
    )                     //   end of Math.min()
  :                       // else:
    l                     //   stop the recursion by returning l (now equal to the input)

```

---

# Non-recursive (ES7), 65 bytes

Takes input as a string.

```
s=>Math.min(...[...s].map(c=>((l+=c)-s.slice(++i))**2,i=l=0))**.5

```

### Test cases

```
let f =

s=>Math.min(...[...s].map(c=>((l+=c)-s.slice(++i))**2,i=l=0))**.5

console.log(f("10"     )) // -> 1
console.log(f("11"     )) // -> 0
console.log(f("12"     )) // -> 1
console.log(f("13"     )) // -> 2
console.log(f("101"    )) // -> 0
console.log(f("128"    )) // -> 4
console.log(f("313"    )) // -> 10
console.log(f("1003"   )) // -> 2
console.log(f("7129"   )) // -> 42
console.log(f("81128"  )) // -> 47
console.log(f("999999" )) // -> 0
console.log(f("9999999")) // -> 9000
```

### Commented

```
s =>                            // given s
  Math.min(...                  // get the minimum value in the result of this map():
    [...s].map(c =>             //   for each character c in s:
      ((l += c)                 //     append c to l (the left part)
                - s.slice(++i)) //     and subtract the right part from it
      ** 2,                     //     square the result
      i =                       //     start with i = 0 (split position)
      l = 0                     //     and l = 0 (left part, see footnote)
    )                           //   end of map()
  )                             // end of Math.min()
  ** .5                         // return the square root of the smallest square

```

---

**Note**: In both versions, `l` is coerced to a string on the first iteration. Normally, we should be careful about leading zeros in a numeric literal: `0123 - 10 === 73` because `0123` is parsed as an octal value (this is now deprecated, but still valid in non-strict mode). But `'0123' - '10' === 113`, the leading zero being this time ignored. So, it's sound to do so.

From the specification of the abstract operation `ToNumber` applied to a string:

> A StringNumericLiteral that is decimal may have any number of leading 0 digits

# Answer
> 3 votes
# Jelly, 10 bytes

```
ŒṖṖLÐṂḌIAṂ

```

Try it online!

-3 bytes thanks to dylnan

## How it works

```
ŒṖṖLÐṂḌạ/€Ṃ - Main link. Argument: n (integer)    e.g    7129
ŒṖ          - Partitions of n's digits;                  [[7, 1, 2, 9], [7, 1, [2, 9]], [7, [1, 2], 9], [7, [1, 2, 9]], [[7, 1], 2, 9], [[7, 1], [2, 9]], [[7, 1, 2], 9], [7, 1, 2, 9]]
  Ṗ         - Remove the final element                   [[7, 1, 2, 9], [7, 1, [2, 9]], [7, [1, 2], 9], [7, [1, 2, 9]], [[7, 1], 2, 9], [[7, 1], [2, 9]], [[7, 1, 2], 9]]
    ÐṂ      - Keep the lists with the minimum...         [[7, [1, 2, 9]], [[7, 1], [2, 9]], [[7, 1, 2], 9]]
   L        -   length
      Ḍ     - From digits                                [[7, 129], [71, 29], [712, 9]]
        /   - Reduce...
         €  - ...each...
       ạ    - ...by absolute difference                  [122, 42, 703]
          Ṃ - Take the minimum                           42

```

# Answer
> 3 votes
# Funky, ~~159~~ ~~134~~ 99 bytes

```
s=>{S={}fori=1i<#s i++{S[#S]=(((v=s::sublist)(0,i)::reduce@..-v(i)::reduce@..)^2)^.5};math.min...S}

```

Actually fitting the spec is shorter it seems.

Try it online!

# Answer
> 3 votes
## Retina, 36 bytes

```
\B
,$'¶$`
\d+
$*
(1*),\1

Om`^.*
\G1

```

Try it online!

### Explanation

```
\B
,$'¶$`

```

This generates all possible partitions on separate lines, as well as a trailing line with the original input.

```
\d+
$*

```

Convert each number in each partition to unary.

```
(1*),\1

```

Remove a maximal and equal amount of `1`s from both parts of each partition (i.e. remove the minimum, and subtract it from the maximum, which gives the absolute difference).

```
Om`^.*

```

Sort the lines.

```
\G1

```

Count the `1`s on the first line, which gives the minimal absolute difference.

# Answer
> 3 votes
# , 32, 27 23 bytes

-5 bytes thanks to FrownyFrog! -4 bytes if input is a string.

```
[:<./}:@(".\)|@-1}.".\.

```

Try it online!

Original: Takes a number as input

```
(".\(}:@[([:<./|@-)}.@])".\.)@":

```

## How it works:

```
                             @": - convert the number to list of chars and
(".\                    ".\.)    - form all prefixes/suffixes and convert them to numbers
    (}:@[          }.@])         - drop the last prefix / first suffix
         (     |@-)              - find the absolute differences
          [:<./                  - find the minimum

```

Try it online!

# Answer
> 2 votes
# Python 2, 58 bytes

```
lambda n:min(abs(n%10**i-n/10**i)for i in range(len(`n`)))

```

Try it online!

# Answer
> 1 votes
# Pyth, 15 bytes

```
hSmaFvMdfqlT2./

```

Try it online!

# Answer
> 1 votes
# MATL, 15 bytes

```
"GX@:&)UwU-|vX<

```

Input is a string representing the integer.

Try it online! Or verify all test cases.

### Explanation

```
"         % Implicit input. Do the following as many times as input length
  G       %   Push input
  X@      %   Push iteration index (1-based), k
  :       %   Range: gives [1 2 ... k]
  &)      %   Two-ouput reference indexing: gives a substring with the first
          %   k characters in the input and then a substring with the rest
  U       %   Convert to number
  wU      %   Swap, convert to number
  -|      %   Absolute difference
  v       %   Vertically concatenate stack. This concatenates the obtained
          %   absolute difference with the minimum so far; does nothing in
          %   the first iteration
  X<      %   Minimum of array
          % Implicit end. Implicit display

```

# Answer
> 1 votes
# Clean, ~~106~~ 83 bytes

```
import StdEnv
@n#f=toInt o(%)n
=hd(sort[abs(f(0,i)-f(i+1,size n))\\i<-[0..size n]])

```

Defines the function `@`, taking a string.

Mostly self-evident, the only tricky bit is `f=toInt o(%)n`: This takes the `toInt` class of functions, and composes it (`o`) with the curried slice operator class (`%`) already supplied with the first argument (`n`). Since there is only one type (`String`, equivalent to `{#Char}`) which has overloads for both `%` and `toInt` the line actually compiles, whereas normally it's hard to compose functions when golfing due to the lack of contextual information given to the compiler.

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 66 bytes

```
Min@Abs[#-#2&@@FromDigits/@#&/@ReplaceList[#,{a__,b__}:>{a}|{b}]]&

```

Takes a list of digits.

Try it online!

# Answer
> 1 votes
# Jelly, 12 bytes

```
JṬ€œṗ€⁸Ḍạ/€Ṃ

```

A monadic link taking a list of digits and returning the integer.

**Try it online!**

### How?

```
JṬ€œṗ€⁸Ḍạ/€Ṃ - Link: list of digits     e.g. [7,1,2,9]
J            - range of length               [1,2,3,4]
 Ṭ€          - untruth €ach                  [[1],[0,1],[0,0,1],[0,0,0,1]]
      ⁸      - chain's left argument         [7,1,2,9]
   œṗ€       - partition at truthy for €ach  [[[],[7,1,2,9]],[7,[1,2,9]],[[7,1],[2,9]],[[7,1,2],9]]
       Ḍ     - undecimal (vectorises)        [[0,7129],[7,129],[71,29],[712,9]]
         /€  - reduce €ach by:
        ạ    - absolute difference           [7129,122,42,703]
           Ṃ - minimum                       42

```

# Answer
> 1 votes
# Pyth, 10 bytes

```
hSaMv<./Ql

```

Test suite

Takes input as a string.

This uses one of Pyth's more recent features, which is that applying a function to a list defaults to mapping the function over the list, if no other behavior is defined. This means that `v` applied to a list of list of strings evaluates all of the strings.

```
hSaMv<./Ql
hSaMv<./QlQ    Implicit variable
      ./Q      Form all partitions of the input string.
               Split it in all possible ways, maintaining the order.
               Partitions are ordered from shortest to longest.
     <   lQ    Take the prefix as long as the input string.
               This keeps just the splits into one and two pieces.
    v          Evaluate. All strings are converted to numbers.
  aM           Map the absolute difference function.
hS             Minimum

```

Note that the list of splits allows the split into 1 piece, but the value of this will always be larger than the minimum, so it is safely ignored.

# Answer
> 1 votes
# Tcl, 116 bytes

```
foreach d [split [set b [set R $argv]] {}] {append L $d
regexp .(.+) $R - R
set b [expr min($b,abs($L-$R))]}
puts $b

```

Try it online!

**Explanation**

```
b ← R ← input number
for each digit (d) in the input number:
  L += d
  strip first digit off of R using a regular expression
  b ← min( b, distance between L and R )
print b

```

It works by using a regex trick allowing a degenerate final case that will always compute to greater than the minimum difference. For “12345” the values are:

```
1 2345 → 2344
12 345 → 333
123 45 → 78
1234 5 → 1229
12345 5 → 12340 (degenerate case)

```

# Answer
> 1 votes
# Perl 5, ~~51~~ 41 + 1 (`-p`) = 42 bytes

```
$\=$_;$\=$\>($"=abs$'-$`)?$":$\while//g}{

```

Try it online!

*inspired by @Nahuel-Fouilleul's comment*

# Answer
> 1 votes
# Java 8, ~~88~~ ~~82~~ 79 bytes

```
n->{int r=-1,t,p=1;for(;n>=p;p*=10)r=r<0|(t=Math.abs(n/p-n%p))<r?t:r;return r;}

```

Port of *@Dennis*' Python 2 answer.
-66 bytes thanks to *@NahuelFouilleul*.
-3 bytes thanks to *@ceilingcat*.

Try it online.

# Answer
> 1 votes
# Ruby, 44 bytes

```
->a{((w=1)..a).map{((a%w*=10)-a/w).abs}.min}

```

Try it online!

# Answer
> 1 votes
# APL+WIN, 31 bytes

```
⌊/|(⍎¨m↓¨⊂n)-⍎¨(m←⍳¯1+⍴n)↑¨⊂n←⎕

```

Prompts for screen input of integer as a string.

Explanation:

```
m←⍳¯1+⍴n Create a list of numbers from 1 to length of string - 1

↑¨⊂n←⎕ Using m create a nested vector taking successively characters from the front of the string defined by m

⍎¨ Convert from character to integer

(⍎¨m↓¨⊂n) Using m create a nested vector dropping successively characters from the front of the string defined by m

⌊/| take the minimum absolute value after subtracting the two vectors of integers

```

# Answer
> 1 votes
# C# (.NET Core), 112 107 + 18 = 125 bytes

```
n=>Enumerable.Range(1,n.Length-1).Min(i=>System.Math.Abs(int.Parse(n.Remove(i))-int.Parse(n.Substring(i))))

```

Try it online!

The count includes the 18 bytes in `using System.Linq;`. Takes input as a `string`.

* 5 bytes saved by Caius Jard!

# Answer
> 1 votes
# **PHP, 121 bytes**

*-2 bytes for removing the closing tag*

```
 <?php $x=fgets(STDIN);for($i=1;$i<strlen($x);$i++){$z[$i-1]=abs(substr($x,0,strlen($x)-$i)-substr($x,-$i));}echo min($z);

```

Try it online!

I'm a bit late on this challenge because last night another family member was on the desktop computer and it's a little difficult to post an answer on mobile!

# Answer
> 1 votes
# Common Lisp, 131 bytes

My first time participating in code golf and I decided to use Lisp, since I like it.

Here is my solution:

```
(defun f (s) (loop for i from 1 below (length s) minimizing (abs (- (parse-integer (subseq s 0 i)) (parse-integer (subseq s i))))))

```

Input needs to be a string, not integer or list.

# Answer
> 1 votes
# Python 3, 104 bytes

My second ever PPCG answer.

```
o=input();d=[]
for i in range(len(o)-1):
 f=int(o[:i+1]);s=int(o[i+1:]);d.append(abs(f-s))
print(min(d))

```

Try it online!

# Answer
> 0 votes
# Stax, 13 bytes

```
ä╠╗╡♫ñ=╣n╤-±å

```

Run and debug it

Rare occurrence where the box drawing characters connect with each other.

# Answer
> 0 votes
# Thunno 2 `M`, 7 bytes

```
żṫıÇɱỵṛ

```

Try it online!

#### Explanation

```
żṫıÇɱỵṛ  # Implicit input
żṫ       # Push [1..length)
  ı      # Map over this list:
   Ç     #  Apply parallelly:
    ɱ    #   First n characters from input
     ỵ   #   Remove first n characters from input
      ṛ  #  Absolute difference
         # Implicit output of minimum

```

# Answer
> 0 votes
# Desmos, ~~66~~ 51 bytes

*-15 bytes thanks to Aiden Chow!*

```
a=10^{[1...logn]}
f(n)=abs(floor(n/a)-mod(n,a)).min

```

Try it on Desmos!

---
Tags: code-golf, math, sequence, arithmetic
---


# Question
Title: Shorten this recursive even fibonacci implementation
I have the following Haskell code to generate the the values of the Fibonacci sequence which are even as an infinite list:

```
z=zipWith(+)
g=z((*2)<$>0:0:g)$z(0:g)$(*2)<$>scanl(+)1g

```

This works by starting with 0,2 and then defining every following term to be the sum of:

* twice all prior terms
* the previous term
* twice the term before that
* 2

I'd like to make it shorter, however I want to preserve a few properties of it.

0. It must produce the same list.
1. The solution mustn't calculate intermediate terms of the Fibonacci sequence. The above code calculates each term purely in terms of previous terms of the sequence, and improved versions should as well.
2. The solution can't use any helper functions, other than point-free aliases like `z`.

I really feel like this can be done with only 1 zip, however I can't get anything to work.

How can I shorten this.

# Answer
> 4 votes
# Haskell, 27 bytes

```
g=2:zipWith((+).(*4))g(0:g)

```

Try it online!

Uses the recursive relationship \\$g\_n = 4 g\_{n-1} + g\_{n-2}\\$.

---
Tags: code-golf, tips, fibonacci, haskell
---