title: Diagonalize a vector

text:
# Question
Title: Diagonalize a vector
Diagonalize a vector into a matrix.

## Input

A vector, list, array, etc. of integers \\$\mathbf{v}\\$ of length \\$n\\$.

## Output

A \\$n \times n\\$ matrix, 2D array, etc. \\$A\\$ such that for each element \\$a\_i \in \mathbf{v}\\$,

$$ A = \left( \begin{array}{ccc} a\_1 & 0 & \cdots & 0 \\ 0 & a\_2 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & a\_n \end{array} \right) $$

where the diagonal of \\$A\\$ is each element in \\$\mathbf{v}\\$.

## Notes

* This is , so shortest program or function in bytes wins!
* Construct the Identity Matrix may be of use to you.
* If the length of \\$\mathbf{v}\\$ is 0, you may return an empty vector, or an empty matrix.
* If the length of \\$\mathbf{v}\\$ is 1, you must return a \\$1 \times 1\\$ matrix.

## Not Bonus

You can receive this Not Bonus if your program is generic across any type, using the type's zero-value (if it exists) in place of \\$0\\$.

## Test Cases

```
[] -> []
[0] -> [[0]]
[1] -> [[1]]
[1, 2, 3] -> [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
[1, 0, 2, 3] -> [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
[1, -9, 1, 3, 4, -4, -5, 6, 9, -10] -> [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -9, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 4, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -4, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, -5, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 6, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 9, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, -10]]

```

# Answer
> 11 votes
# K (ngn/k), 7 bytes

```
{x*=#x}

```

My first K post. I tried real hard to make a Bubbler train work here but failed.

Try it online!

# Answer
> 8 votes
# Haskell, 39 bytes

```
f[]=[];f(a:b)=(a:map(0*)b):map(0:)(f b)

```

Recursively generates the matrix by appending a value at the top left corner of a smaller matrix.

# Answer
> 6 votes
# MATL, 2 bytes

```
Xd

```

The code uses the builtin function `Xd` (which corresponds to MATLAB's `diag`). Try it online!

# Answer
> 5 votes
# Jelly, 5 bytes

```
J=þ`a

```

Try it online!

```
J=þ`     Identity matrix:
  þ      table
J        [1 .. length]
   `     with itself
 =       by equality.
    a    Vectorizing logical AND; replace ones with elements of the vector.

```

If output can be flat:

# Jelly, 3 bytes

```
jn`

```

Try it online!

```
j      Join the vector on
 n     the list of, for each element, if it doesn't equal
  `    itself.

```

If the empty vector didn't have to be handled, this could tie non-flat as `jn`sL`; it passes all current test cases as  owing to all inputs being nonzero (which is not guaranteed by the spec).

# Answer
> 5 votes
# Go, ~~135~~ 130 bytes

```
func(v[]int)(A[][]int){for i,_:=range v{r:=make([]int,len(v))
for j,_:=range v{e:=0
if i==j{e=v[i]}
r[j]=e}
A=append(A,r)}
return}

```

Attempt This Online!

# Go, ~~141~~ 136 bytes + Not Bonus

```
func f[T any](v[]T)(A[][]T){for i,_:=range v{r:=make([]T,len(v))
for j,_:=range v{var e T
if i==j{e=v[i]}
r[j]=e}
A=append(A,r)}
return}

```

Attempt This Online!

# Answer
> 5 votes
# Octave, 4 bytes

```
diag
```

Try it online!

# Python, 23 bytes

```
from numpy import*
diag

```

Attempt This Online!

# Answer
> 5 votes
# Haskell, 34 bytes

```
foldr(\a m->(a:(0<$m)):map(0:)m)[]

```

Try it online!

Uses the recursive method from Magma of expanding the matrix with a new value in the top left, but with `foldr` and `<$`.

# Answer
> 5 votes
# Nekomata, 6 bytes

```
x:ᵒ-¬*

```

Attempt This Online!

Multiplies the identity matrix like other answers.

```
x:ᵒ-¬*
x       [0 .. length - 1]
 :      Duplicate
  ᵒ     Outer product with
   -        Subtract
    ¬   Logical NOT
     *  Multiply

```

# Answer
> 4 votes
# Dyalog APL, 9 bytes

Thanks to @att for -4

```
⊢×⍤1⍋∘.=⍋
⊢          # v
 ×⍤1       # multiplied row-wise with
    ⍋∘.=⍋  # the identity matrix of size (#v)

```

Created with the help of Luminespire

## Dyalog APL, 16 bytes + Not Bonus

The only other applicable scalar type are characters, where APL uses the space as the empty character, so this code also does

```
,⍨∘≢⍴∊⍤(⊢↑¨⍨1+≢)
    ⍴             # Reshape
,⍨∘≢              # to (#v)*(#v) matrix
     ∊⍤           # the flattened list of lists built by
        ⊢ ¨       # taking each item of v
         ↑ ⍨      # and padding it with
            1+≢   # (#v) zeros

```

Created with the help of Luminespire

This works by noticing that, if the diagonalized matrix is read as a single list, row by row, each entry of `v` is spaced with as many zeros as the length of `v`.

# Answer
> 4 votes
# , 6 bytes

```
*[:=#\

```

Try it online!

# Answer
> 4 votes
# Thunno 2, 5 bytes

```
ėDȷ=×

```

Try it online!

Inspired by Unrelated String's Jelly answer.

#### Explanation

```
ėDȷ=×  # Implicit input
ė      # Length range
 D     # Duplicate
  ȷ    # Outer product over:
   =   #  Check for equality
    ×  # Multiply by the input
       # Implicit output

```

# Answer
> 4 votes
# Python, ~~56~~ 55 bytes

*-1 byte thanks to xnor*

```
def f(a,i=0):
 for b in a:l=a[i]=[0]*len(a);l[i]=b;i+=1

```

Attempt This Online!

Outputs by modifying arguments.

# Answer
> 4 votes
# Haskell, 67 bytes

```
f v=m.(m.).h where m g=map g[0..length v-1];h z i j|i==j=v!!i|1>0=z

```

Attempt This Online!

# Answer
> 4 votes
# TypeScript's Type System, 62 bytes

```
type F<V>={[I in keyof V]:{[J in keyof V]:J extends I?V[J]:0}}

```

Try it at the TypeScript Playground!

It's been a little while since I've golfed in TS types, so it's possible (though I think unlikely) that I missed a shorter way to do this. This one is pretty simple, but I'll leave an explanation anyway:

```
type F<V> =           // type F taking generic tuple type V
  { [I in keyof V]:   // for each I in V's indices:
    { [J in keyof V]: //   for each J in V's indices:
      J extends I     //     are J and I the same type?
        ? V[J]        //       if so, index into V with J
        : 0           //       otherwise, 0
    }                 //   end
  }                   // end

```

I tried putting `keyof V` into `type F<V,K=keyof V>` but that doesn't work since the compiler complains that `K` could be a type unrelated to an array key, and it doesn't save enough bytes for `//ts-ignore` to be worth it.

# Answer
> 3 votes
# PARI/GP, 11 bytes

```
matdiagonal

```

Builtins are always a sad answer, aren't they?

# Answer
> 3 votes
# Factor \+ `math.matrices`, 15 bytes

```
diagonal-matrix

```

Try it online!

# Answer
> 3 votes
# APL(Dyalog Unicode), 9 bytes SBCS

```
-∘⍳⍤≢↑⍤0⊢

```

Try it on APLgolf!

Left-pads each \\$v\_i\\$ to a vector of length \\$i\\$ and implicitly mixes.

Each row's fill elements match the type of the corresponding element of the vector.

# Answer
> 3 votes
# JavaScript (Node.js), 34 bytes

```
x=>x.map((v,i)=>x.map(_=>i--?0:v))

```

Try it online!

# Answer
> 3 votes
# Excel, 33 bytes

```
=IFERROR(MUNIT(ROWS(A1#))*A1#,"")

```

# Excel, 39 bytes + Not Bonus

```
=IFERROR(IF(MUNIT(ROWS(A1#)),A1#,0),"")

```

Input is *vertical* spilled range `A1#`.

Having to deal with the empty vector is inconvenient; otherwise these would be just 21 and 27 bytes respectively.

# Answer
> 3 votes
# Mathematica, 14 bytes

Try it online!

```
DiagonalMatrix

```

# Answer
> 3 votes
# Itr, 9 bytes

`#äLºµÍ·®£`

prints the elements of the matrix separated by spaces, with `,` separating the rows. Does not print the zero entries above the diagonal.

online interpreter

# Explanation

```
#          ; read array from standard input
 äLº       ; push the range from zero to array.length-1
    µÍ     ; replace each element in the range with a vector having a one at the given index
           ; this will give an identity matrix of size array.length represented as 2D array
      ·    ; point-wise multiplication
       ®   ; convert result to matrix
        £  ; print

```

---

# Itr, ~~10~~ 9 bytes

~~`#äLºµÍ·®+£`~~ (broken in current version)

`#LºµÍ·®+£`

Adds zero to the result to force the entries above the diagonal to be printed.

---

# Itr, 8 bytes

`#LºµÍ·®£`

the `ä` before the `L` is no longer necessary in newer versions

# Answer
> 2 votes
# , 20 bytes

```
\(x)diag(x,sum(x|1))

```

Attempt This Online!

The `diag` built-in almost works here, but fails for inputs of length 1, where it produces identity matrix of size of the input. Unless specified `nrow` argument.

---

Less boring - without `diag` built-in:

# , 54 bytes

```
\(x,`[`=matrix)c(x,rep(0*x,n<-sum(x|1)))[n+1,n,T][n,n]

```

Attempt This Online!

Idea: construct a vector such that every entry of the input \\$x\\$ of length \\$n\\$ is followed by \\$n\\$ zeros. A matrix with \\$x\\$ in the first row and followed by \\$n\\$ rows of zeros works too. Then, we can put this in a \\$n\times n\\$ `matrix` resulting in \\$x\\$ on the diagonal.

Ungolfed:

```
\(x){n=length(x)
m=matrix(c(x,rep(0,n^2)), nrow=n+1, ncol=n, byrow=TRUE)
matrix(m, nrow=n, ncol=n)}

```

---

# , 27 bytes

```
\(v,x=seq(a=v))v*!x%o%x-x^2

```

Attempt This Online!

Heavily inspired by @Kirill L.'s answer to the linked challenge.

# Answer
> 2 votes
# Python, 23 bytes

```
import numpy
numpy.diag

```

Attempt This Online!

# Answer
> 2 votes
# Vyxal, 25 bitsv2, 3.125 bytes

```
LÞ□*

```

Try it Online!

The `P` flag on the permalink is to make the test cases pass (for some strange reason, I never made it not check exact string representation.) Individual cases all produce the right output with vyxal list syntax without the flag.

## Explained

```
LÞ□*
L     # Push the length of the input
 Þ□   # Construct an NxN identity matrix
   *  # and pair-wise vectorise multiplication

```

Created with the help of Luminespire.

# Answer
> 2 votes
# Rust, ~~83~~ 81 bytes

Simple and dirty imperative solution.

-2 bytes by taking a slice instead of a vec

```
|v:&[i8]|{let l=v.len();let mut r=vec![vec![0;l];l];for i in 0..l{r[i][i]=v[i]}r}

```

Try it online!

# Rust, ~~126~~ 124 bytes + Not Bonus

The Copy bound is technically too strict and a Clone bound would be enough, but it would also be one byte longer *:shrug:*.

```
fn f<T:Default+Copy>(v:&[T])->Vec<Vec<T>>{let l=v.len();let mut r=vec![vec![T::default();l];l];for i in 0..l{r[i][i]=v[i]}r}

```

Try it online!

# Answer
> 2 votes
# \>\<\> (Fish), 53 bytes

```

```

Hover over any symbol to see what it does

Try it

# Answer
> 2 votes
# Pip `-P`, 6 bytes

```
g*EY#g

```

(The flag is only necessary to format the output in a readable way; any of `-P`, `-p`, `-S` will do.)

Attempt This Online!

### Explanation

```
g*EY#g
     g  ; List of command-line arguments
    #   ; Length
  EY    ; Identity matrix of that size
g*      ; Multiply each row by the corresponding element of g

```

# Answer
> 2 votes
# Uiua, ~~7~~ 6 bytes

```
×⊞=.⍏.

```

-1 thanks to Bubbler

Try it!

```
×⊞=.⍏.
     .  # duplicate
 ⊞=.⍏   # identity matrix
×       # multiply

```

# Answer
> 1 votes
# Python, 66 bytes

```
def f(a):n=range(len(a));return[[(i==j)*a[i]for i in n]for j in n]

```

Attempt This Online!

# Python, 66 bytes

```
def f(a):x=len(a);return[[0]*i+[a[i]]+[0]*(x+~i)for i in range(x)]

```

This solution was inspired by this answer.

Attempt This Online!

# Answer
> 1 votes
# Charcoal, 11 bytes + Not Bonus

```
⭆¹ＥθＥθ×⁼μξν

```

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

```
   θ        Input array
  Ｅ         Map over elements
     θ      Input array
    Ｅ       Map over elements
        μ   Row index
       ⁼    Equals
         ξ  Column index
      ×     Multiplied by
          ν Inner element
⭆¹          Pretty-print

```

Using `And` instead of `Times` would have made the code minusculely more efficient but this way the code produces empty strings on the non-diagonal entries when given a string array as input.

# Answer
> 1 votes
# Racket, 97 bytes; Not Bonus

```
(define(f v)(let([n(length v)])(for/list([i(range n)])(list-set(make-list n 0)i(list-ref v i)))))

```

Try it online!

---

## Explanation

After reading in the input as a list called `v`, we obtain the length of `v` and store it as `n`.

```
(define (f v)
  (let ([n (length v)])
    ...))

```

We then loop through the range \\$ 0 \le i \< n \\$ and for each iteration, we return a new list (a row of the matrix) of `n` length filled with zeros except at the index of `i` which is filled with the corresponding value from `v` at index `i`.

```
(define (f v)
  (let ([n (length v)])
    (for/list ([i (range n)])
      (list-set (make-list n 0)
                i
                (list-ref v i)))))

```

The `for/list` function returns the collected rows after each iteration.

## Not Bonus

While the rows start with zeros, any data in `v` will still be preserved. What this means is that we can pass list of strings to `f` and receive a matrix with both strings and zeros as the zero-value:

```
; Strings
(f '("h" "e" "y"))
;;> '(("h" 0 0) (0 "e" 0) (0 0 "y"))

; Symboles
(f '(a b c))
;;> '((a 0 0) (0 b 0) (0 0 c))

; Characters
(f '(#\d #\e #\f))
;;> '((#\d 0 0) (0 #\e 0) (0 0 #\f))

```

*Have a wonderful weekend!*

# Answer
> 1 votes
# KamilaLisp v0.3, 21 bytes

```
[* #0[(⌼ =)#0#0]∘⍳∘⍴]

```

The code generates a range vector from 0 to the size of the argument; then it computes the Cartesian product of the range vector and itself using equality as the functor, therefore computing the identity matrix. Each row of the identity matrix is then multiplied by the initial vector.

# Answer
> 1 votes
# Japt, 7 bytes

```
£çT hYX

```

Try it

```
£çT hYX     :Implicit input of array U
£           :Map each X at index Y
 ç          :  Fill U with
  T         :    0
    hYX     :  Replace the element at index Y with X

```

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
āDδQ*

```

Try it online or verify all test cases.

**Explanation:**

```
āDδQ   # Create an identify matrix the size of the input-length:
ā      #  Push a list in the range [1, (implicit) input-length]
 D     #  Duplicate it
  δ    #  Apply double-vectorized:
   Q   #   Check whether the values are equal
    *  # Multiply the values in each row with the values of the (implicit) input-list
       # (after which the matrix is output implicitly as result)

```

# Answer
> 1 votes
# Kotlin, 65 bytes

```
{a:IntArray->Array(a.size){i->IntArray(a.size).also{it[i]=a[i]}}}

```

Try it online!

# Answer
> 0 votes
# Pyth, 8 bytes

```
.eXmZQkb

```

Try it online!

### Explanation

```
.eXmZQkbQ    # implicitly add Q
             # implicitly assign Q = eval(input())
.e      Q    # enumerated map Q over lambda, b, k
   mZQ       # list of zeros the same length as Q
  X   kb     # replace position k with b

```

# Answer
> 0 votes
# PowerShell Core, 77 bytes

```
if($l=($a=$args).count){($k=1..$l)|%{$r++
$c=1
,($k|%{$a[$_-1]*!($c++-$r)})}}

```

Try it online!

# Answer
> 0 votes
# BQN, 6 bytes

```
⊢×⍋=⌜⍋

```

Try it at BQN online!

### Explanation

```
⊢×⍋=⌜⍋
      ⍋  Grade up; for our purposes, gives a list of unique integers of the same
          length as the argument
  ⍋      Grade up again
    =⌜   Create an equality table
         This gives an identity matrix the same size as the length of the argument
⊢×       Multiply each row by the corresponding element of the argument

```

# Answer
> 0 votes
# Scala 3, 70 bytes

```
x=>x.zipWithIndex.map((e:Int,i:Int)=>Seq.fill(x.size)(0).updated(i,e))

```

Attempt This Online!

# Answer
> -2 votes
# Python 3.8 (pre-release), 67 bytes

```
lambda a:[[x*(i==j) for i,x in enumerate(a)]for j in range(len(a))]

```

A 42-byte solution that only works if all elements are unique:

```
lambda a:[[x*(x==y) for x in a]for y in a]

```

Try it online!

---
Tags: code-golf, math, array, matrix, linear-algebra
---


# Question
Title: Split string on first occurrence of each character
Related.

Given a printable ASCII string, split it into a list of non-empty strings with a new sub-string beginning every time a character, which has not previously been seen in the same case, occurs.

### Examples

```
"mississippi" → ["m","i","ssissi","ppi"]

"P P & C G" → ["P"," P ","& ","C ","G"]

"AAA" → ["AAA"]

"Adam" → ["A","d","a","m"]

"" → []

```

---

**Anecdote**: The result will have between 0 and 95 elements. The 95th sub-string will necessarily continue until the end because at that point, all printable ASCII characters have begun a sub-string, so every additional character will have occurred before and thus cannot cause a new sub-string to begin.

# Answer
> 24 votes
# Jelly, 4 bytes

```
QƤĠị

```

Try it online!

## Explanation

```
QƤĠị  Input is a string, say s = "adam"
 Ƥ    For each prefix of s: ["a","ad","ada","adam"]
Q     remove duplicates: ["a","ad","ad","adm"]
  Ġ   Group indices by equal values: [[1],[2,3],[4]]
   ị  Index into s: ["a","da","m"]

```

The internal representation of the strings, which the TIO link displays, is slightly different.

# Answer
> 10 votes
## Retina, 9 bytes

```
q1,`.
¶$&

```

Try it online!

### Explanation

Match each character (`.`), discard repeated matches (`q`), discard the first match (`1,`), and insert a linefeed in front of each match `¶$&`.

# Answer
> 6 votes
# 05AB1E, 11 bytes

```
ÙSk¥sg¸«£õK

```

Try it online!

**Explanation**

```
Ù             # remove duplicates in input
 S            # split to a list of characters
  k           # get the (first) index of each character in the input
   ¥          # calculate delta's
    sg¸«      # append the length of the input
        £     # split the list into pieces of these sizes
         õK   # remove empty string (for the special case "" -> [])

```

# Answer
> 6 votes
# C,  ~~75~~   ~~65~~  63 bytes

*Thanks to @Digital Trauma for saving 10 bytes and thanks to both @gastropner and @l4m2 for saving a byte each!*

```
f(char*s){for(int l[128]={};*s;putchar(*s++))l[*s]++||puts(l);}

```

Prints a leading newline.

Try it online!

**Without a leading newline (71 bytes):**

```
f(char*s){int l[128]={};for(l[*s]=1;*s;putchar(*s++))l[*s]++||puts(l);}

```

Try it online!

# Answer
> 6 votes
# , 7 bytes

```
~:<;.1]

```

Try it online!

# Explanation

Nub sieve's chance to shine!

```
~: <;.1 ]
        ]  Input
~:         Nub sieve (1 if the character is the first instance in string)
    ;.1    Split input on 1s in nub sieve
   <       And box each

```

# Answer
> 6 votes
# APL (Dyalog Unicode), 8 bytesSBCS

```
(≢¨∪\)⊆⊢

```

Try it online!

# Answer
> 6 votes
# 05AB1E, 8 bytes

```
Ùvyy¶ì.;

```

Try it online!

---

Always will output 1 preceding newline, which is constant and not indicative of a split, the 10-byte alternative that does not output a preceding newline is `Ùvyy¶ì.;}¦`, you can try that here. According to Adam a preceding or trailing newline is acceptable.

---

```
Input      = mississippi                               | Stack
-----------#-------------------------------------------+----------------------------------
Ù          # Push unique letters of first input.       | ['misp']
 v         # Iterate through each unique letter.       | []
  yy       # Push 2 copies of the letter (or yD)       | ['m','m']
    ¶      # Push a newline char.                      | ['m','m','\n']
     ì     # Prepended to the letter.                  | ['m','\nm']
      .;   # Replace first instance with '\n + letter' | ['\nmississippi']

```

**After each iteration we get:**

```
['\nmississippi'] > ['\nm\nississippi'] > ['\nm\ni\nssissippi'] > ['\nm\ni\nssissi\nppi']

```

**Which is:**

```
m
i
ssissi
ppi

```

# Answer
> 5 votes
# Perl 6,  ~~58 52~~  40 bytes

```
{$/={};.comb.classify({$+=!$/{$_}++}).sort».value».join}

```

Try it

```
*.comb.classify({$+=!(%){$_}++}).sort».value».join

```

Try it

```
*.classify({$+=!(%){$_}++}).sort».value

```

Try it
(input is a list of characters, and output is a list of lists of characters)

## Expanded:

```
*                   # parameter for WhateverCode lambda

  .classify(        # classify that list
    {
        $           # anonymous scalar state variable (accumulator)

      +=            # increment it if:

        !           # Bool invert the following
          (
            %       # anonymous hash state variable
          ){ $_ }++ # look to see if the character was seen already
    }
  ).sort\           # sort the Pairs by key (makes the order correct)
  ».value           # get the value from each Pair

```

---

The output from `classify` is

```
{ # Hash
  1 => ['m'],
  2 => ['i'],
  3 => ['s','s','i','s','s','i'],
  4 => ['p','p','i'],
}

```

And `.sort` just turns it into:

```
[
  1 => ['m'],
  2 => ['i'],
  3 => ['s','s','i','s','s','i'],
  4 => ['p','p','i'],
]

```

`».value` removes the keys

```
[
  ['m'],
  ['i'],
  ['s','s','i','s','s','i'],
  ['p','p','i'],
]

```

# Answer
> 5 votes
# Haskell, 39 bytes

```
foldl(\s c->s++['\n'|all(/=c)s]++[c])""

```

Try it online!

Inserts a newline symbol before every character that appears for the first time, resulting in a newline-separated string, with a leading newline. Prepend `lines.` to produce a list.

---

**Haskell, 55 bytes**

```
(""%)
_%[]=[]
p%s|(a,b)<-span(`elem`s!!0:p)s=a:(a++p)%b

```

Try it online!

Repeatedly takes the prefix the first character plus the non-unique characters that follow it.

# Answer
> 4 votes
# APL (Dyalog), 9 bytes

Thanks, Erik the Outgolfer for saving 1 byte!

```
⊢⊂⍨⍳∘≢∊⍳⍨

```

Try it online!

# Explanation:

`⍳⍨`: For each character, get the index of its first occurrence. e.g `mississippi -> 1 2 3 3 2 3 3 2 9 9 2`

`⍳∘≢`: The range from 1 to the length of the input.

: Membership. e.g `1 2 3 4 5 6 7 8 9 10 11∊1 2 3 3 2 3 3 2 9 9 2 -> 1 1 1 0 0 0 0 0 1 0 0`

`⊢⊂⍨`: Partition the input string with new partitions starting at `1`s in the vector above

# Answer
> 4 votes
# Japt, 11 bytes

```
¬â r@=iRUbY

```

Test it online!

### Explanation

This was inspired by Magic Octopus Urn's 05AB1E solution.

```
¬â r@=iRUbY    Implicit: U = input string
¬â             Split U into chars, and keep only the first occurrence of each.
   r@          Reduce; for each char Y in this string...
        UbY      Find the first index of Y in U.
      iR         Insert a newline at this index in U.
     =           Set U to the result.
               As reduce returns the result of the last function call, this gives the
               value of U after the final replacement, which is implicitly printed.

```

# Answer
> 3 votes
# Python 2, ~~81~~ 74 bytes

```
def f(s):d=sorted(map(s.find,set(s)));print map(lambda a,b:s[a:b],d,d[1:])

```

Try it online!

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

*Saved 7 bytes: a leading newline was explicitly allowed (Thanks @Shaggy!)*

Takes input as an array of characters. Outputs a newline-separated string.

```
s=>s.map(c=>s[c]=s[c]?c:`
`+c).join``

```

### Test cases

```
let f =

s=>s.map(c=>s[c]=s[c]?c:`
`+c).join``

;[
  [..."mississippi"],
  [..."P P & C G"],
  [..."AAA"],
  [..."Adam"],
  [...""]
]
.forEach(s => console.log('{' + f(s) + '}\n'))
```

# Answer
> 3 votes
## brainfuck, 66 bytes

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

```

Formatted:

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

```

Try it online

The leading newline in the output (which is only printed if the input is non-empty) can be removed at the cost of 5 bytes by replacing the body `x` of the main (outermost) loop with `.>,[x]`.

# Answer
> 2 votes
# Jelly, 6 bytes

```
ŒQœṗ⁸Ḋ

```

Try it online!

# Answer
> 2 votes
# , ~~94~~ 87 bytes

```
function(s,n=nchar(s),g=substring)g(s,d<-which(!duplicated(g(s,1:n,1:n))),c(d[-1]-1,n))

```

Try it online!

Returns a (possibly empty) list of substrings.

*Thanks to Michael M for saving 7 bytes!*

# Answer
> 2 votes
# K4, 19 bytes

**Solution:**

```
$[#x;(*:'.=x)_;,]x:

```

**Examples:**

```
q)k)$[#x;(*:'.=x)_;,]x:"mississippi"
,"m"
,"i"
"ssissi"
"ppi"
q)k)$[#x;(*:'.=x)_;,]x:"P P & C G"
,"P"
" P "
"& "
"C "
,"G"
q)k)$[#x;(*:'.=x)_;,]x:"AAA"
"AAA"
q)k)$[#x;(*:'.=x)_;,]x:"Adam"
,"A"
,"d"
,"a"
,"m"
q)k)$[#x;(*:'.=x)_;,]x:""
,[""]

```

**Explanation:**

8 bytes is just to handle `""`...

```
$[#x;(*:'.=x)_;,]x: / the solution
                 x: / save input as variable x
$[  ;         ; ]   / $[condition;true;false]
  #x                / length of x ("" has length 0, i.e. false)
             _      / cut right at left indices
     (      )       / do together
          =x        / group x into key/value (char!indices)
         .          / return value (get indices)
      *:'           / first (*:) each
               ,    / enlist, "" => [""]

```

# Answer
> 2 votes
# JavaScript, ~~61~~ ~~54~~ 52 bytes

Takes input as an array of characters.

```
s=>s.map(x=>a[x]?a[y]+=x:a[x]=a[++y]=x,a=[],y=-1)&&a

```

---

## Try it

```
o.innerText=JSON.stringify((f=
s=>s.map(x=>a[x]?a[y]+=x:a[x]=a[++y]=x,a=[],y=-1)&&a
)([...i.value=""]));oninput=_=>o.innerText=JSON.stringify(f([...i.value]))
```

```
<input id=i><pre id=o></pre>
```

# Answer
> 2 votes
# \>\<\>, ~~22 17~~ 14 bytes

*-1 byte thanks to Emigna*

```
i:::a$1g?!o1po

```

Try it online!

Prints a leading and trailing newline.

It keeps track of which letters have already appeared by `p`utting a copy of the character at that corresponding spot on the second row, and printing a newline if the value fetched from that position was not 1. Ends in an error when it tries to print `-1`

# Answer
> 2 votes
# Perl, 30 bytes

Includes `+1` for `p`

Give input without trailing newline on STDIN. Output is also without trailing newline:

```
echo -n adam | perl -pE 's%.%$v{$&}+++!pos?$&:$/.$&%eg'; echo

```

If you don't care about leading and trailing newlines this `25` (`+3` for `-p` because the code contains `'`) also works:

```
#!/usr/bin/perl -p
s%%$/x!$v{$'&~v0}++%eg

```

# Answer
> 2 votes
# Stax, 8 bytes

```
ç↓‼►▐NVh

```

Run and debug online

The ascii representation of the same program is this.

```
c{[Ii=}(m

```

For each character, it splits when the index of the current character is the current position.

```
c            copy the input
 {    }(     split the string when the result of the enclosed block is truthy
  [          duplicate the input string under the top of the stack
   I         get the character index of the current character
    i=       is it equal to the iteration index?
        m    print each substring

```

# Answer
> 2 votes
# BQN, ~~11~~ 6 bytes

```
⌈`∘⊐⊸⊔

```

Try it at BQN online!

### Explanation

```
⌈`∘⊐⊸⊔
   ⊐    Classify: replace each letter with a number based on the order of
        their first occurrences
⌈`∘     Scan with maximum: replace each number with the largest number so far
    ⊸⊔  Group the original string into those buckets

```

A couple of worked examples:

```
"dodos"            "Mississippi"
⟨ 0 1 0 1 2 ⟩       ⟨ 0 1 2 2 1 2 2 1 3 3 1 ⟩
⟨ 0 1 1 1 2 ⟩       ⟨ 0 1 2 2 2 2 2 2 3 3 3 ⟩
⟨ "d" "odo" "s" ⟩   ⟨ "M" "i" "ssissi" "ppi" ⟩

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), ~~115~~ ~~91~~ 77 bytes

```
	N =INPUT
S	N LEN(1) . Y	:F(END)
	S =S Y
	N SPAN(S) . OUTPUT REM . N	:(S)
END

```

Try it online!

Prints the substrings separated by newlines.

Explanation:

line `S` (for `SPLIT`) doesn't actually split, but instead extracts the first character of `N` and saves it (`.`) to `Y`. On `F`ailure, it jumps to `END`. The match should only fail when `N` is the empty string. Thus, when the input is empty, it jumps directly to `END` and outputs nothing.

`S = S Y` concatenates `Y` onto `S`.

`SPAN(S)` greedily matches a run of characters in `S`, and sends it (`.`) to `OUTPUT`, setting (`.`) `N` to the `REM`aining characters of `N` (if there are any). Then it jumps back to `S`.

# Answer
> 1 votes
## Haskell, 62 bytes

```
r#c|any(elem c)r=init r++[last r++[c]]|1<2=r++[[c]]
foldl(#)[]

```

Try it online!

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

```
s=>s.map(c=>o[c]?t+=c:(t&&m.push(t),t=o[c]=c),t='',o=m=[])&&[...m,t]

```

Takes input as a list of characters.

**Test cases:**

```
let f=
s=>s.map(c=>o[c]?t+=c:(t&&m.push(t),t=o[c]=c),t='',o=m=[])&&[...m,t]

console.log(f([...'mississippi']));
console.log(f([...'P P & C G']));
console.log(f([...'AAA']));
console.log(f([...'Adam']));
console.log(f([...'']));
```

# Answer
> 1 votes
# Ruby, ~~65~~ ~~62~~ 58 bytes

```
->s,*a{s.size.times{|i|(i==s.index(c=s[i])?a:a[-1])<<c}
a}

```

Try it online!

A lambda accepting a string and returning an array of strings.

Approach: For each index, either append the character at that index in `s` to the result array, or to the last string in the result array. `String#index` returns the index of the first instance of the argument.

-2 bytes: Initialize `a` as a splat argument instead of on its own line. *Thanks, Value Ink!*

-1 byte: Use `c=s[i]`...`c` instead of `s[i]`...`s[i]`. *Thanks, Value Ink!*

-4 bytes: Use `.times` instead of `.map`

# Answer
> 1 votes
# Python 2, 47 bytes

```
lambda s:reduce(lambda r,c:r+'\n'[c in r:]+c,s)

```

Try it online!

Outputs a newline-separated string. Barely beats the program version:

**Python 2, 48 bytes**

```
r=''
for c in input():r+='\n'[c in r:]+c
print r

```

Try it online!

# Answer
> 1 votes
# PHP, 317 bytes

```
function SplitOnFirstUnique($s){
    $len = strlen($s);
    $output = [];
    $newstring = '';
    for ($i=0; $i < $len ; $i++) {
        $newstring = $newstring.$s[$i];
        if(!in_array($s[$i] , $output  )){
            $output[] = $newstring;
            $newstring = '';
        }
    }
    return $output;
}

```

Try it online!

# Answer
> 1 votes
# Red, 79 bytes

```
func[s][foreach c next unique/case append s"^@"[print copy/part s s: find s c]]

```

Try it online!

## Ungolfed:

```
f: func [s] [
    b: next unique/case append s "^@"  ; append `null` to the end of the string, than
                                       ; find the unique characters and
                                       ; store all except the first to b
    foreach c b [                      ; for each character in b
        print copy/part s s: find s c  ; print the part of the string to
                                       ; where the character is found and
                                       ; set the beginning of the string to that position
    ]
]

```

# Answer
> 1 votes
# Java 8, ~~193~~ ~~169~~ ~~155~~ 151 bytes

```
s->{for(int l=s.length(),i=0,j;i<l;i++)if(s.indexOf(s.charAt(i))==i){for(j=i;++j<l&&s.indexOf(s.charAt(j))!=j;);System.out.println(s.substring(i,j));}}

```

-14 bytes thanks to *@raznagul* (for something obvious I somehow missed myself..)
-3 bytes thanks to *@O.O.Balance* (again for something obvious I somehow missed myself.. :S)

**Explanation:**

Try it online.

```
s->{                    // Method with String parameter and no return-type
  for(int l=s.length(), //  The length of the input-String
          i=0,j;        //  Index integers
      i<l;i++)          //  Loop `i` from 0 to `l` (exclusive)
    if(s.indexOf(s.charAt(i))==i){
                        //   If the character at index `i` hasn't occurred yet:
      for(j=i;++j<l     //    Inner loop `j` from `i` to `l` (exclusive),
          &&s.indexOf(s.charAt(j))!=j;);
                        //     as long as the character at index `j` has already occurred
      System.out.println(//    Print:
        s.substring(i,j));}}
                        //     The substring of the input from index `i` to `j` (exclusive)

```

# Answer
> 1 votes
# PowerShell, 73 bytes

```
{$r=@();$h=@{};[char[]]$ARGS[0]|%{if(!($h[$_]++)){$r+=""};$r[-1]+=$_};$r}

```

## Usage

```
PS> & {$r=@();$h=@{};[char[]]$ARGS[0]|%{if(!($h[$_]++)){$r+=""};$r[-1]+=$_};$r} "mississipi" | ConvertTo-Json -Compress
["m","i","ssissi","pi"]

```

# Answer
> 1 votes
# Ruby, 40 bytes

```
->a{i=0
a.slice_when{a.index(_2)==i+=1}}

```

Attempt This Online!

# Answer
> 1 votes
# Perl 5 \+ `-pl`, 22 bytes

```
s@.@$/x!$h{$&}++.$&@ge
```

Try it online!

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

```
≠⊂⊢

```

Attempt This Online!

the Boolean mask indicating first occurrence of each character…

splits…

the argument

# Answer
> 0 votes
# Retina 0.8.2, ~~22~~ ~~20~~ 19 bytes

```
1>`(.)(?<!\1.+)
¶$&

```

Try it online! Edit: Saved ~~2~~ 3 bytes thanks to @MartinEnder.

# Answer
> 0 votes
# Javascript, 200 bytes

My first (I think?) attempt at code golf:

```
function split(s) {let x=[];let y=[];let z="";let w=1;for(l of s.split('')){if (x.includes(l)){z+=l;}else{w=!w;if (w) {y.push(z);z='';w=0;}z+=l;x.push(l);}}y.push(z);if (y.join('')==0) y=[];return y;}

```

# Answer
> 0 votes
# Mathematica, 84 bytes

```
a@{}={};a@b_:=a@b[[;;(c@b=Position[b,Tally[b][[-1,1]]][[1,1]])-1]]~Append~b[[c@b;;]]

```

Defines a function `a`. Takes a list of characters as input and returns a list of lists of characters as output. Uses a basic recursive structure.

# Answer
> 0 votes
# Perl 5 \+ `-p`, 37 bytes

```
for$a(32..126){$a=chr$a;s/\Q$a/\n$a/}

```

Run through printable ASCII and insert a newline before the first appearance

Try it online!

# Answer
> 0 votes
# Lua, 74 bytes

```
t={}print(((...):gsub(".",load"c=...a=(t[c]or'\\n')..c t[c]=''return a")))

```

Try it online!

Prints one additional leading newline.

# Answer
> 0 votes
# GNU sed, 37 bytes

(includes +1 for `-r` option)

```
s/./\n&/g
:a
s/((.).*)\n\2/\1\2/
ta

```

We start by prepending a newline to every character in the string; then in the loop, we remove those that precede a second or subsequent occurrence.

Note that newline can't occur in the input, as that's the separator between strings. And it's not classified as a *printable* character.

# Answer
> 0 votes
## C++, 176 bytes

```
#include<string>
#include<set>
std::string*s(std::string e){auto*r=new std::string[96];std::set<int>u;for(char p:e){if(u.find(p)==u.end())u.insert(p);r[u.size()]+=p;}return r;}

```

Returns an array of strings, valid strings member of the answer array are not of size 0.
Each call of the function allocate `sizeof(std::string)*96`, with the pointer returned, and must be `delete[]`d after usage. Code to test :

```
auto tests = {
    "mississippi","P P & C G", "AAA", "Adam",""
};

for (const auto& a : tests) {

    std::string* res = s(a);

    for (int i = 0; i < 96; ++i) {
        if (res[i].size() > 0)
            std::cout << '\"' << res[i] << "\", ";
    }

    delete[] res;
    std::cout << '\n';
}

```

# Answer
> 0 votes
# AWK, 63 bytes

```
func u(v){for(;j++<split(v,A,"");)S[s]=S[s+=m[A[j]]++?0:1]A[j]}

```

Try it online!

Calling function `u()` assigns strings to string array `S[]` which is of size `s`

TIO link has some functionality in the footer to clear assigned variables.

Might be able to save a byte or two by using `FS=""`, but this is a more general solution.

# Answer
> 0 votes
## JavaScript, ~~105~~ 87 bytes

Changes: replaced poop emojis for tabs (Thanks @Adám !), replaced parenthesis and aposthrophes for template literals

```
a=[];f=s=>s.split``.map(x=>!a.includes(x)&&a.push(x)?'  '+x:x).join``.split`    `.slice(1);

```

Takes a string, returns an array of strings. A big chunk is converting from String-\>\[char\]-\>String-\>\[string\]. whitout conversions, this becomes:

```
a=[];f=s=>s.map(x=>!a.includes(x)&&a.push(x)?'\n'+x:x).join``.slice(1);

```

takes char array, returns newline separated string (71 bytes).

Also, this is my first post on this stack exchange!

# Answer
> 0 votes
# PowerShell, 61 bytes

```
$args|% t*y|%{if(!($r-cmatch"^[$_]")){$r+=,''};$r[-1]+=$_}
$r

```

Try it online!

# Answer
> 0 votes
## Clojure, ~~111~~ 96 bytes

```
#(reverse(reduce(fn[[f & r :as R]i](if((set(apply str R))i)(cons(str f i)r)(cons(str i)R)))[]%))

```

As Jim Carrey would say: Beautiful! :D

# Answer
> 0 votes
# Gema, 20 characters

```
?=${$1;\n}@set{$1;}?

```

Sample run:

```
bash-4.4$ gema '?=${$1;\n}@set{$1;}?' <<< 'mississippi'

m
i
ssissi
ppi

```

Try it online!

# Answer
> 0 votes
# Java 8, 159 bytes

134 bytes of lambda + 25 bytes for HashSet import. Rip all linters and IDEs.

```
import java.util.HashSet;
...
s->{HashSet h=new HashSet();return s.chars().mapToObj(c->(char)c+"").reduce("",(x,y)->x+(!h.isEmpty()&h.add(y)?","+y:y)).split(",");};

```

Try it online!

# Answer
> 0 votes
# Uiua SBCS, 6 bytes

```
⊜□\+◰.

```

Try it!

```
⊜□\+◰.
     .  # duplicate
    ◰   # mark firsts
  \+    # cumulative sum
⊜□      # split

```

# Answer
> 0 votes
# Vyxal, 5 bytes

```
ÞUÞṗḢ

```

Try it Online!

```
  Þṗ  # Partition before
ÞU    # Uniquity mask
    Ḣ # Remove leading empty list

```

# Answer
> 0 votes
# Scala 3, 109 bytes

```
_.foldLeft(Seq.empty)((l,c)=>if(l.exists(_.contains(c)))l.dropRight(1):+l.last.appended(c)else l:+c.toString)

```

Attempt This Online!

---
Tags: code-golf, string, text-processing
---


# Question
Title: What is the fastest safe way down a mountain?
## Intro

Help! I'm stuck on a snow-covered mountain and I need to get down as fast as possible, preferably without dying. I have a map showing how high each part of the mountain is above the normal ground.

I am a novice skier, which means I like to stick to slopes that aren't too steep. I'm willing to go down just two moderately steep sections, however - but not back to back!

## Rules

Your program's job is to, given a *n* x *m* matrix of height values, navigate from the skier's current position (the top left corner) to the base (the bottom right corner). Height values will be given as integers between 0 and 25, with 25 being the highest possible point and 0 being the base of the mountain. It should be noted the mountain does not have to start at 25 units high, but will always finish at the 0 in the bottom right corner.

There are a few constraints:

* The skier can move up, down, left, or right on the map. No diagonals.
* The skier is usually only comfortable on slopes that bring him down 2 units or less.
* The only exception to the above rule is that the skier can go down a maximum of two sections that will bring him down 3 or 4 units.
* The skier can move upwards if necessary, but only one unit at a time. **The skier also cannot go upwards or flat then immediately thereafter go down a steep slope of 3 or 4 units, he must already be headed downwards before taking a steep slope. Also, his first move cannot be to go down a steep slope, and he cannot do two steep slopes back to back**.
* It is possible for the skier to visit a location twice (as seen in the fourth example - this is due to the fact that the skier cannot go down two steep slopes in a row)

## Input

As mentioned above, the map will be given by a matrix containing integer values from 0 to 25, with a 0 in the bottom left corner (there could be zeroes in other places on the map). These maps will always have at lease one best solution but could have several worse solutions. These matrices will always have spaces and line breaks as separators - double spaces will be used if the integer is just one character (see examples below)

## Output

Your program is to output a sequence of moves (the format of this sequence does not matter so long as it is coherent) that shows the best way down the mountain - meaning fewest moves on the map. These moves can be represented by any strings, numbers, or characters you like, so long as they are distinct and are described in your solution. A sample output might look like `RRDDRRRURRDDDDRR`, where `R` means right, `D` means down, `U` means up, and `L` means left.

## Test cases

Input 1:

```
10 13 13 13 13
8  9  11 13 25
0  7  11 12 23
6  5  2  2  0

```

Sample output 1:

```
DRDDRRR

```

Input 2:

```
16 12 12 10 8 6
14 12 6  8  0 4
10 20 4  2  1 2
8  20 10 8  4 0
9  8  9  25 2 0

```

Sample output 2:

`DDDDRRURRDR` or `DRURRRRDDDD`

Input 3:

```
20 19 15 11 0  9  15 6
18 20 13 12 11 9  18 12
16 25 9  7  6  2  1  1
12 20 10 4  4  4  3  2
13 12 13 0  0  0  0  0

```

Sample output 3:

```
RRDDRRDRRRD

```

Input 4:

```
20 18 10 11 12 0
19 11 1  4  5  0
18 16 3  3  3  3
19 8  7  17 19 3
18 20 11 12 13 3
17 17 16 16 14 2
20 21 11 14 11 0

```

Sample output 4:

```
DDDDDRRRRULLULRURRRDDDD

```

## Scoring:

This is . Shortest answer wins - get creative!

# Answer
> 11 votes
# JavaScript (ES6),  ~~223 ... 205~~  199 bytes

```
f=(m,x=o=0,y=0,n=2,V,s,p='',r=m[y]||0,v=r[x],h=V%32-v%32|0)=>63>>h+1&v<64&!p[o.length-1]?h<3||s*n--?1+r[x+!m[y+1]]?[...'LURD'].map((c,d)=>r[f(m,x+--d%2,y+~-d%2,n,r[x]+=32,6>>h&1,p+c),x]=v)&&o:o=p:0:0

```

Try it online!

## Commented

The 5 least significant bits of the cells are left unchanged. The upper bits are used to count the number of times a cell has been visited in a given path.

We need quite a lot of variables to fully describe the skier status at any given time, notably the possibility to do a big steep slope.

### Header

```
f = (                      // a recursive function taking:
  m,                       //   m[] = input matrix
  x =                      //   (x, y) = current position, starting at (0, 0)
  o = 0,                   //   o = output string, initialized to a numerical value
  y = 0,                   //
  n = 2,                   //   n = remaining number of big steep slopes
  V,                       //   V = value of the previous cell
  s,                       //   s = a flag that is set if a big steep slope is allowed
                           //       for this turn
  p = '',                  //   p = current path string
  r = m[y] || 0,           //   r[] = current row (using 0 as a fallback)
  v = r[x],                //   v = value of the current cell (or undefined)
  h = V % 32 - v % 32 | 0  //   h = height between the previous and the current cell
) =>                       //       (0 if V is undefined)
  (...)                    //

```

### Tests

```
63 >> h + 1 &              // if the height is greater than or equal to -1 and less
                           // than or equal to 4 and
v < 64 &                   // v is defined and less than 64 and
!p[o.length - 1] ?         // the current path is shorter than the best solution or
                           // we don't have a solution yet (in which case o.length - 1
                           // is NaN):
  h < 3 ||                 //   if the height is less than 3 or
  s * n-- ?                //   a big steep slope is allowed and we can still do one:
    1 + r[x + !m[y + 1]] ? //     if we haven't reached the bottom-right cell,
                           //     i.e. m[y + 1] is defined or 1 + r[x + 1] is not NaN:
      (...)                //       process the recursive calls
    :                      //     else:
      o = p                //       update the solution to this path
  :                        //   else:
    0                      //     do nothing
:                          // else:
  0                        //   do nothing

```

### Recursive calls

```
[...'LURD'].map((c, d) =>  // for each direction character c at index d:
  r[                       //   we will eventually restore r[x]
    f(                     //     recursive call:
      m,                   //       m[] is unchanged
      x + --d % 2,         //       add dx to x
      y + ~-d % 2,         //       add dy to y
      n,                   //       n is unchanged
      r[x] += 32,          //       add 32 to the current cell
      6 >> h & 1,          //       set s if h is either 1 or 2
      p + c                //       append c to the path
    ),                     //     end of recursive call
    x                      //     restore r[x] to ...
  ] = v                    //   ... v
) && o                     // end of map(); yield o

```

# Answer
> 3 votes
# , 185 bytes

Far from perfect, but it's something. Could theoretically save 17 bytes by omitting the check for revisiting places, but then the last example ran out of memory on my machine and I couldn't truthfully say all examples were verified. :-)

Takes in the map and outputs a list of offset coordinates `1 0,0 1,_1 0,0 _1` that I've mapped to `DRUL` in TIO for easier comparison.

```
}.@{.@(((](\:+/"2)@#~[*/@((4((1>=&3-_1|.2=])*>&0*3>[:+/\3=])@:|(+:<:i.4)I.0,2-/\({~ ::_"_ 0<"1))*3>[:+/[:="1/~<"1@])0 2+/\@|:])[:,/((,-)=i.2),~"1 2/])^:(0=<:@$@[-:+/@{.@])^:_&(1 1 2$0))

```

Try it online!

### How it works

```
(1 1 2$0)

```

We keep the routes as a list of offsets, starting with `0 0`.

```
(…)^:(0 = <:@$@[ -: +/@{.@])^:_

```

Do until the head of the list – which is nearest the bottom right – equals the dimensions of the map - 1.

```
[: ,/ ((,-)=i.2) ,~"1 2/ ]

```

Each route gets the 4 offsets added, so we have 4 times as many routes: `(0 0,1 0),(0 0,0 1),(0 0,_1 0),(0 0, 0 _1)`. Then we have to filter these routes based on several checks.

```
0 2 +/\@|: ]

```

List of offsets -\> List of absolute coordinates, transposed so each routes' first points are in one list, then each routes' second points are in one list, etc:

```
0 0,0 0, 0 0,0  0
1 0,0 1,_1 0,0 _1

```

This format seems more suitable for the checks, but maybe a `(…)"2` would have been enough. However, now each check can build up a matrix saying which coordinate is ok and which not and in the end we can easily reduce it.

```
3 > [: +/ [: ="1/~ <"1@]

```

No place should be visited 3 times. This check is just to keep the number of routes from exploding.

```
0, 2 -/\ ({~ ::_"_ 0<"1)

```

Gets the height values from the map at the absolute coordinates. If something is out of range, it will be replaced with infinity. Then we'll get the diff between neighboring heights and prepend 0 so the matrix will align with the previous one. Now we have (given the first map):

```
0  0 0 0
2 _3 _ _

```

With

```
4 …@| (+:<:i.4) I.

```

we sort the height diffs into 4 categories: 0 = not reachable, 1 = climb up, 2 = gentle slope, 3 = steep slope.

```
3 > [: +/\ 3=]

```

Less then 3 steep slopes.

```
>&0

```

Point must be reachable

```
1 > =&3 - _1 |. 2 = ]

```

3 is only allowed if 2 was in front of it.

```
] …@ #~ [ */

```

A route is only taken if all of its coordinates passed all tests.

```
(\:+/"2)

```

Sort the routes based on their last, absolute coordinate.

```
}.@{.

```

Finally the loop has ended and the first route contains the best route written in offsets, with only a `0 0` at the top that gets dropped.

# Answer
> 2 votes
# Python3, 425 bytes

```
E=enumerate
M=[('R',0,1),('L',0,-1),('U',-1,0),('D',1,0)]
def f(B):
 d={(x,y):v for x,r in E(B)for y,v in E(r)}
 q=[(0,0,{},'',2,0,0)]
 for x,y,D,m,l,s,u in q:
  if(x,y)==(len(B)-1,len(B[0])-1):return m
  for T,X,Y in M:
   if(N:=(x+X,y+Y))in d:
    a,b=d[(x,y)],d[N]
    L=a-b in[3,4]and l and not u and m and not s
    if N not in(U:=D.get((x,y),[]))and(0<=a-b<3 or L or b-a==1):q+=[(*N,{**D,(x,y):U+[N]},m+T,l-L,L,b-a==1)]

```

Try it online!

---
Tags: code-golf, combinatorics, path-finding
---