title: Don't repeat yourself

text:
# Question
Title: Don't repeat yourself
In this challenge you will be tasked with implementing a sequence of natural numbers such that:

* Each number appears a natural number of times
* No two numbers appear the same number of times
* No two numbers appear in the sequence next to each other more than once.

For some examples, the sequence

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

```

Is not valid because `1` appears an infinite number of times.

The sequence:

```
1,2,3,4,5,6,7,8,9,10,11,12,13,14,...

```

Is also not valid because every number appears exactly once, but different numbers must appear a distinct number of times.

The sequence:

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

```

meets the first two criteria but `2` occurs next to `3` two different times (`2,3,2`).

One sequence that meets all the criteria is:

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

```

You may use any option available in the default rules. You should assume natural numbers include 0. You may assume they don't, but it won't do you any help.

This is so the goal is to minimize the size of your source code as measured in bytes.

# Answer
> 10 votes
# JavaScript (V8), 37 bytes

```
for(i=0;;print(i**.5>>i%2))print(++i)

```

Try it online!

# JavaScript (V8), ~~41~~ 40 bytes

```
for(i=0;;i%2||print(i**.5>>1))print(++i)

```

Try it online!

I don't know how it works but it seems fine and \\$i\\$ appears \\$4i+3\\$ times except 0 which appears 1 time

# Answer
> 9 votes
# Vyxal, ~~8~~ ~~5~~ 3 bytes

```
₅[L

```

Try it Online!

Modified Kevin Cruijssen's 05AB1E answer. Equivalent python code: `lambda n: n if n%5 != 0 else len(str(n))`

# Answer
> 7 votes
# Brachylog (v2), 4 bytes

```
√ℕl|

```

Try it online!

A function submission, which takes the 1-based index of the position within the sequence as an argument, and returns the value of the sequence at that index, one of the allowed default I/O formats for . (The header in the TIO link calls the function with all indexes from 1 to 1000, printing the results, and therefore displays the first 1000 elements of the sequence.)

## Algorithm

This solution's algorithm is pretty similar to the other short entries: if the input is not a square number, it's returned unchanged; if it is a square number, the program returns the number of digits in its square root. As such, each natural number \\$n\\$ appears \\$9\times 10^n\\$ times, plus one time more if the number isn't square, meaning that there are no duplicate numbers-of-occurrences; and because the difference between any two positive square numbers is at least 3, there can't be any repeated pairs.

## Explanation

```
√ℕl|
√     {if} the square root of {the input}
 ℕ      is a natural number
  l   {then} {return} {the square root's} length {in digits}
   |  otherwise, {return the input unchanged}

```

(In explanations, I use the `{}` notation for things that are implied by rather than explicitly stated in the program, such as tacit variables and default behaviours of the language – I can't remember ever having needed to use it quite so much before!)

Contrary to what might be expected (given that  is normally a floating-point operation), `√ℕ` does correctly work on arbitrarily large integers without having to worry about floating-point overflow and without having to worry about non-integral floats being approximated to integers (there's a special case in the Brachylog interpreter).

# Answer
> 5 votes
# Retina 0.8.2, ~~59~~ 8 bytes

```
.*0$
$.&

```

Try it online! Link includes test cases. Outputs the nᵗʰ term of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2... where n appears ⌊9∙10ⁿ⁻²⌋ times if n is a multiple of 10 and an additional time if it is not. Explanation:

```
.*0$

```

Match any multiple of 10.

```
$.&

```

Replace it with its length.

It might even be possible to remove the `$` but then I'm not sure what behaviour the sequence would have.

# Answer
> 5 votes
# x86 32-bit machine code, 9 bytes

```
A8 03 75 04 0F BD C0 48 C3

```

Try it online!

Following the `regparm(1)` calling convention, this takes a 1-index in EAX and returns a number in EAX.

This produces the sequence 1, 2, 3, **1**, 5, 6, 7, **2**, 9, 10, 11, **2**, 13, 14, 15, **3**, 17, 18, 19, **3**, 21, 22, 23, **3**, 25, 26, 27, **3**, ..., with each *n* appearing 2*n*-1 times among the bolded terms, and if not divisible by 4, appearing one more time among the unbolded terms.

In assembly:

```
f:  test al, 3      # Check the low two bits of the number.
    jnz e           # If they're not both zero, jump to the end to return the number unchanged.
    bsr eax, eax    # Find the highest position of a 1 bit in the number...
    dec eax         # and decrease that by 1.
e:  ret             # Return.

```

# Answer
> 4 votes
# Python, ~~52~~ 46 bytes

```
i=2
while[*map(print,(i,i+1,int(i**.4)))]:i+=2

```

Attempt This Online!

* -6 thanks to loopy walt

# Answer
> 4 votes
# Vyxal, 14 bytes

```
ɾ:ẋfṖλ2lvsÞu;c

```

Try it Online!

Takes an integer as input. Takes a long time to calculate for larger integers. (Each element \\$x\\$ appears \\$x\\$ times.)

## Explanation

```
ɾ               # Make range from input [1,2,...,r]
 :ẋ             # Repeat each element x times [[1],[2,2],[3,3,3],...]
   f            # Flatten [1,2,2,3,3,3,...,r]
    Ṗ           # Get all permutations of input
     λ          # Opening a lambda function
      2l        # Get all adjacent pairs of items
        vs      # Sort each pair (so, e.g. (1,2) and (2,1) become the same)
          Þu    # Check if there are any duplicates
            ;c  # Take first item from list of permutations which satisfies the lambda above

```

# Answer
> 3 votes
# bc, 28 bytes

```
while(1){++x;++x;sqrt(x)-1}

```

Try it online! ~ Corrected per comments.

~~Try it online! Note, this calls `bc` via Zsh. TIO's `bc` interpreter seems to be having problems.~~

# Answer
> 3 votes
# JavaScript (V8), 30 bytes

```
for(n=.3;;)print(++n**(n%4)|0)

```

Try it online!

A messier but also shorter version of @Arnauld's answer. Was meant as a golf but they suggested I post it separately.

# Answer
> 2 votes
# Zsh, 39 bytes

```
while echo $[++i] $[++i] $[(i**.5-1)^0]

```

Try it online! ~~42 bytes~~

Similar to the @l4m2 solution. Thanks to @pxeger for -2 bytes. Corrected per comment from @m90.

# Answer
> 2 votes
# Charcoal, 8 bytes

```
⎇﹪Ｎ⁹θＩＬθ

```

Try it online! Link is to verbose version of code. Outputs the nᵗʰ term of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 1, 10, 11, 12, 13, 14, 15, 16, 17, 2, 19, 20, 21, 22, 23, 24, 25, 26, 2, 28, 29, 30... where n appears 10ⁿ⁻¹ times if n is a multiple of 9 and an additional time if it is not. Explanation:

```
  Ｎ         First input as a number
 ﹪          Modulo
   ⁹        Literal integer `9`
⎇           If not divisible then
    θ       First input as a string else
       θ    First input as a string
      Ｌ     Take the length
     Ｉ      Cast to string
            Implicitly print

```

# Answer
> 2 votes
# JavaScript (V8), 32 bytes

```
for(n=0;;)print(n++%3?n:n**.4|0)

```

Try it online!

### How?

This is similar (but not identical) to the sequence used by The Thonnu.

Two distinct sequences are interleaved. For any \\$n\ge0\\$, we use the sequence \\$s\_0(n)=n+1\\$ if \\$n\not\equiv 0 \pmod 3\\$ and the sequence \\$s\_1(n)=\lfloor (n+1)^{2/5}\rfloor\\$ if \\$n\equiv 0 \pmod 3\\$.

| \\$n\\$ | \\$s\_0(n)\\$ | \\$s\_1(n)\\$ |
| --- | --- | --- |
| 0 |  | 1 |
| 1 | 2 |  |
| 2 | 3 |  |
| 3 |  | 1 |
| 4 | 5 |  |
| 5 | 6 |  |
| 6 |  | 2 |
| 7 | 8 |  |
| 8 | 9 |  |
| 9 |  | 2 |
| 10 | 11 |  |
| 11 | 12 |  |
| 12 |  | 2 |
| 13 | 14 |  |
| 14 | 15 |  |
| 15 |  | 3 |
|  |  |  |

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

```
Input N
N-int(N/3
If not(fPart(N/3
int(.5√(Ans
Disp Ans

```

Outputs the nth term (1-indexed) of the sequence used in l4m2's JavaScript answer.

---

### 64 bytes

```
{3,1
While 1
Disp 1+2Ans(1),2+2Ans(1
For(I,1,dim(Ans
Disp Ans(I
End
Ans+1
If 1+2dim(Ans)=Ans(dim(Ans
augment(Ans,{dim(Ans
End

```

Outputs indefinitely. This is definitely not the simplest approach, but it uses an interesting sequence:

```
7, 8, 3, 1, 9, 10, 4, 2, 11, 12, 5, 3, 13, 14, 6, 4, 15, 16, 7, 5, 2, 17, 18, 8, 6, 3, 19, 20, 9, 7, 4...

```

When arranged like this, the pattern becomes apparent:

```
 7  8 |  3  1
 9 10 |  4  2
11 12 |  5  3
13 14 |  6  4
15 16 |  7  5  2
17 18 |  8  6  3
19 20 |  9  7  4
21 22 | 10  8  5
23 24 | 11  9  6
25 26 | 12 10  7  3
27 28 | 13 11  8  4
29 30 | 14 12  9  5
31 32 | 15 13 10  6
33 34 | 16 14 11  7
35 36 | 17 15 12  8
37 38 | 18 16 13  9  4
39 40 | 19 17 14 10  5
41 42 | 20 18 15 11  6
43 44 | 21 19 16 12  7
45 46 | 22 20 17 13  8
47 48 | 23 21 18 14  9
49 50 | 24 22 19 15 10
51 52 | 25 23 20 16 11  5
53 54 | 26 24 21 17 12  6
55 56 | 27 25 22 18 13  7
57 58 | 28 26 23 19 14  8
59 60 | 29 27 24 20 15  9
61 62 | 30 28 25 21 16 10
63 64 | 31 29 26 22 17 11
65 66 | 32 30 27 23 18 12...

```

For all natural numbers \\$n\\$, \\$n\\$ appears \\$n\\$ times if \\$n \< 3\\$, \\$n+1\\$ times if \\$2 \< n \< 7\\$, and otherwise \\$n+2\\$ times.

# Answer
> 1 votes
# Jelly, 5 bytes

A port of ais523's Brachylog answer \- do upvote that.

```
ẈÆ²¡Ṫ

```

A monadic Link that accepts \\$n\\$ and yields:

$$a(n) = \begin{cases} \lfloor n \log\_{10} \rfloor + 1 & \text{if $n$ is a perfect square} \\ n & \text{otherwise} \end{cases}$$

**Try it online!**

### How?

A byte saved over the naive `DL$Æ²¡`.

```
ẈÆ²¡Ṫ - Link: integer, n
   ¡  - repeat...
 Æ²   - ...times: is square? (using integer only arithmetic)
Ẉ     - ...action: length of each (implicit range [1..n], implicit cast to digits)
    Ṫ - tail (for the list this is the length of digits of n, otherwise it's just n)

```

# Answer
> 1 votes
# 05AB1E, ~~7~~ ~~6~~ 5 bytes

```
∞TÅ€g

```

Slightly modified port of *@Neil*'s Retina and Charcoal answers, so make sure to upvote him as well!

Outputs the sequence `1,2,3,4,5,6,7,8,9,10,2,12,13,14,15,16,17,18,19,20,2,22,...`. A.k.a.:

$$a(n) = \begin{cases} \text{length}(n) & \text{if $(n-1)$ is divisible by 10} \\ n & \text{otherwise} \end{cases}$$

Try it online.

**Explanation:**

```
∞      # Push the infinite positive sequence: [1,2,3,...]
 TÅ€   # Map every 10th item to:
       # (where the 0-based index is visible by 10)
    g  #  The length of the current integer
       # (after which the infinite sequence is output implicitly as result)

```

# Answer
> 0 votes
# 05AB1E, 9 bytes

```
∞Ðtï.ι¦.ι

```

Try it online!

Port of AndrovT's Vyxal answer.

#### Explanation

```
∞          # Infinite list of positive integers
 Ð         # Triplicate
  tï       # Square root and floor
    .ι     # Interleave
      ¦    # Remove first item
       .ι  # Interleave

```

# Answer
> 0 votes
# Scala, 97 bytes

Golfed version. Try it online!

```
object M extends App{Stream from 0 foreach(i=>{println(math.pow(i,.5).toInt>>i%2);println(i+1)})}

```

---
Tags: code-golf, sequence, integer, open-ended-function
---


title: Enumerate the rationals

text:
# Question
Title: Enumerate the rationals
The cardinality of the set \\$\mathbb Q\\$ of rational numbers is known to be exactly the same as that of the set \\$\mathbb Z\\$ of integers. This means that it is possible to construct a bijection between these sets—a mapping such that each integer corresponds to exactly one rational number, and vice versa.

Provide such a bijection from \\$\mathbb Z\\$ to \\$\mathbb Q\\$. You may choose to use as the domain any contiguous subset of the integers instead of the whole of \\$\mathbb Z\\$. For example, you could instead choose a domain of \\$\\{\cdots,5,6,7\\}\\$ (integers \\$\le 7\\$) or \\$\\{0,1,2,\cdots\\}\\$ (like a 0-indexed infinite list), but not \\$\\{1,2,3,5,8,\cdots\\}\\$.

# Answer
# Vyxal, 12 bytes

```
⌊d-‹Ė)1Ḟ:NY‹

```

Try it Online!

A completely different tactic, using an alternating form of the Calkin-Wilf sequence inspired by Jordan's answer. Append an `i` if outputting an infinite sequence is not allowed.

```
       Ḟ    # Generate a sequence...
      1     # Starting with 1
-----)      # Each value is the previous value n, put into the following...
⌊           # floor(n)
 d          # 2 * floor(n)
  -         # n - 2 * floor(n)
   ‹        # n - 2 * floor(n) - 1
    Ė       # 1 / (n - 2 * floor(n) - 1)
         Y  # Interleave with
       :N   # The sequence negated
          ‹ # Decrement every term to add a 0

```
> 6 votes

# Answer
# , <sup>~~21~~</sup> 16 bytes

```
**|1&(1%+-2*|)-~

```

Attempt This Online!

Uses the Calkin-Wilf generator. The domain is full \\$\mathbb{Z}\\$. `f(n) = CalkinWilf(n)` and `f(-n) = -f(n)` for `n>=0`. The input must be given as a bigint.

```
**|1&(1%+-2*|)-~    input: n, bigint
  |                 abs(n)
    &(       )-~    repeat ^ times, starting from bigint zero:
   1& 1%+-2*|       1/((1 + x) - 2 * frac(x))
**                  multiply sign(n) to ^

```
> 5 votes

# Answer
# Ruby, ~~67~~ 50 bytes

-17 bytes thanks to Bubbler

This is the Calkin-Wilf sequence but mapped to the negative rationals for negative inputs, plus \\$f(0) = 0\\$.

```
F=->n{n<1?0:(m=F[n-1]
n%2>0?1r/(1-2*m.ceil+m):-m)}

```

Attempt This Online!

## Ruby, 40 bytes

This is the Calkin-Wilf sequence for positive inputs/outputs only.

```
F=->n{n<2?1:1r/(2*(m=F[n-1]).floor+1-m)}

```

Attempt This Online!
> 3 votes

# Answer
# , ~~71~~ 66 bytes

```
f=\(x,n=abs(x))`if`(n,c(sum(m<-f(n-1))-2*m[2]%%m[1],x/n*m[1]),1:0)

```

Attempt This Online!

Outputs rational numbers represented as vectors of (*denominator*, *numerator*).

---

# , 67 bytes

```
\(x,y=rle(intToBits(2*abs(x)+1))$l)sign(x)*head(c(y[1]-1,y[-1]),-1)

```

Attempt This Online!

Outputs rational numbers represented as continued fractions.
Works by calculating element i of the Calkin–Wilf sequence using the run-length encoding of the binary representation of i.
> 3 votes

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

-2 bytes from Arnauld

```
f=lambda i,m=1,n=1:i>3and f(i//2,m+i%2*n,n+~i%2*m)or(-~i*2%3*m-m,n)

```

Try it online!

Maps \\$\\{1,2,\ldots,\\}\\$. Represents fractions as pairs of integers; \\$0\\$ represented as \\$(0,1)\\$.
> 2 votes

# Answer
# Vyxal, 19 bytes

```
›"ƛȧ‹*[½₍⌊⌈Uvx∑;÷ȧ"

```

Try it Online!

A mess. Uses the Stern-Brocot sequence and works in theory...

Given an integer, outputs a pair of integers.

```
›"                  # [n, n+1]
  ƛ            ;    # Map to...
      [             # If ....
   ȧ‹               # |a| - 1
     *              # * a
       ½            # Then take a/2
        ₍⌊⌈         # [floor(a/2), ceil(a/2)
           U        # Uniquify (if even, just n/2)
            vx      # Recurse on each
              ∑     # Sum
                ÷ȧ" # Take the absolute value of the second.

```
> 2 votes

# Answer
# PARI/GP, 44 bytes

```
f(n)=if(n<0,-f(-n),n,(1+f(n\2)^q=n%2*2-1)^q)

```

Attempt This Online!

Using the Calkin-Wilf sequence like other answers.

---

## PARI/GP, 47 bytes

```
n->t=0;[t=(1+t^q--)^q|q<-2*binary(n)];t*sign(n)

```

Attempt This Online!

Starting from \\$t=0\\$. For each binary digit of the input \\$n\\$, take \\$t=t+1\\$ if the digit is \\$1\\$, and \\$t=\frac{t}{t+1}\\$ if the digit is \\$0\\$. Finally multiply the result with \\$\operatorname{sign}(n)\\$.

---

## PARI/GP, 47 bytes

```
n->for(i=!t=0,abs(n),t=1/(1-t+t\1*2));t*sign(n)

```

Attempt This Online!
> 2 votes

# Answer
# Charcoal, 37 bytes

```
ＮθＦ²⊞υιＦ↔θ⊞υ⁻Σ…⮌υ²⊗﹪§υ±²↨υ⁰‹θ⁰⪫⮌…⮌υ²/

```

Try it online! Link is to verbose version of code. Explanation: Port of my JavaScript answer to Output the nth rational number according to the Stern-Brocot sequence.

```
Ｎθ

```

Input `n`.

```
Ｆ²⊞υι

```

Start with `0/1`.

```
Ｆ↔θ

```

Repeat `|n|` times.

```
⊞υ⁻Σ…⮌υ²⊗﹪§υ±²↨υ⁰

```

Calculate the next term of the sequence.

```
‹θ⁰

```

Output a `-` if the input was negative.

```
⪫⮌…⮌υ²/

```

Output the last two terms of the sequence, joined with `/`.

Alternative implementation, also 37 bytes:

```
Ｎθ≔¹η≔⁰ζＦ↔θ«≔⁻⁺ζη⊗﹪ζηε≔ηζ≔εη»‹θ⁰Ｉζ/Ｉη

```

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

```
Ｎθ

```

Input `n`.

```
≔¹η≔⁰ζ

```

Start with `0/1`.

```
Ｆ↔θ«

```

Repeat `|n|` times.

```
≔⁻⁺ζη⊗﹪ζηε

```

Calculate the next term of the sequence.

```
≔ηζ≔εη

```

Shuffle the terms into the desired variables.

```
»‹θ⁰

```

Output a `-` if the input was negative.

```
Ｉζ/Ｉη

```

Output the current two terms, separated by `/`.
> 1 votes

# Answer
# Retina 0.8.2, 61 bytes

```
\d+
$*#/1
+`#(?=1*/(1+))(\1*)(1*)/\3(1+)
$1/$2$4
^/
0/
1+
$.&

```

Try it online! Link includes test cases. Explanation: Another port of my JavaScript answer to Output the nth rational number according to the Stern-Brocot sequence.

```
\d+
$*#/1

```

Convert the absolute value of `n` to unary using `#`s, then append `/1` representing `0/1` in unary.

```
+`#(?=1*/(1+))(\1*)(1*)/\3(1+)

```

Match and consume one `#` each time, so that the replacement happens `n` times; look ahead and capture `b` as `$1` so that `a-a%b` and `a%b` can be calculated as `$2` and `$3`, and therefore also `b-a%b` as `$4`.

```
$1/$2$4

```

Replace `a` with `b` and `b` with `a-a%b+b-a%b` i.e. `a+b-a%b*2`.

```
^/
0/

```

Special case `0/`, since `0` in unary is the empty string.

```
1+
$.&

```

Convert to decimal.
> 1 votes

# Answer
# Python, 207 bytes.

\\$ \text{207 bytes, it can be golfed much more.} \\$

Golfed version. Try it online!

```
from fractions import Fraction as F
def g(n):
    if n < 1:
        return 0
    else:
        m = g(n-1)
        if n % 2 > 0:
            return F(1, (1 - 2*int(m) + m))
        else:
            return -m

```

Ungolfed version. Try it online!

```
from fractions import Fraction

def F(n):
    if n < 1:
        return 0
    else:
        m = F(n-1)
        if n % 2 > 0:
            return Fraction(1, (1 - 2*int(m) + m))
        else:
            return -m

for i in range(101):
    print(f"{i} => {F(i)}")

```
> 0 votes

---
Tags: code-golf, sequence, rational-numbers, open-ended-function
---


# Question
Title: Shortest way to convert the result of a test to a string output (e.g. true or false) in bash
I'm trying to shorten a bash solution to a Code Golf challenge, which requires an output of `true` or `false`. I've managed to condense the key piece of the code down to a substring check, to determine if the provided argument, `$1`, is a substring of a particular hard-coded fixed string, of the form:

```
[[ FIXEDSTRING = *$1* ]]&&echo true||echo false

# And a minor improvement to shave a character on the test:
[[ FIXEDSTRING =~ $1 ]]&&echo true||echo false

```

**My question is, is there some clever way to shorten this, either in general, or for the specific case of converting success to `true` and failure to `false`?**

In a language like Python, I'd use:

```
# Shortest solution without imports I know of
str(sys.argv[1]in"FIXEDSTRING").lower()  # Also feels a little long, kinda
                                         # curious if there is a better way

# Shorter when json is already imported for some other purpose, saves a character (more if
# json aliased or dumps denamespaced via from json import*):
json.dumps(sys.argv[1]in"FIXEDSTRING")

```

for the specific case of "success is `true`, failure is `false`", and one of:

```
# When string lengths close enough for stepped slicing to work, only 3 characters longer
# than the true/false specific solution
"ftarlusee"[sys.argv[1]in"FIXEDSTRING"::2]

# When string lengths aren't compatible for stepped slicing,
("false","true")[sys.argv[1]in"FIXEDSTRING"]

```

when I need to select between arbitrary strings, not just `true`/`false`.

But AFAICT:

1. `bash` has no concept of converting from success/failure to a specific string (without relying on `if`/`then`/`fi`,`case`/`esac` or `&&`/`||` and manually running `echo` with a literal string for each string option)
2. `bash` arrays can't be used "anonymously", and the array indexing and slicing syntax is so verbose you can't save any characters this way (e.g. `a=(true false);[[ FIXEDSTRING = *$1* ]];echo ${a[$?]}` is six characters longer than my current approach; useful if I needed to convert exit status to true/false in multiple places, but not for a one-off use)
3. Stepped slicing of a string isn't a thing.

# Answer
> 5 votes
Here's a slightly shorter method in pure Bash. It doesn't beat the `expr` based method, but it doesn't use any utils.

```
false
[[ FIXEDSTRING =~ $1 ]]&&true
echo $_

```

# Answer
> 5 votes
This one is the **same size** as the `expr` method while still being **pure Bash**. It takes advantage of `$_` and the fact that `true`/`false` are builtins that simply returns the status you would expect.

```
FIXEDSTRING
${_/*$1*}true||false
echo $_

```

##### Explanation:

* "FIXEDSTRING" gets stored into `$_` by attempting to execute it with no args.
* If $1 is a substring of "FIXEDSTRING", then it will be removed in the pattern replacement and allows Bash to execute the `true` builtin.
* Otherwise, the pattern replacement will result in no change to "FIXEDSTRING" if it's not a substring, thus executing `FIXEDSTRINGtrue`, which is not a valid command and fails through to executing `false`. Thus putting either "true" or "false" into `$_` based on the pattern replacement result.
* `$_` is then echoed out.

# Answer
> 3 votes
I found one way to improve on this using the `expr` command; not `bash` itself, but at least a GNU coreutil so it exists pretty universally (and more importantly, on the Code Golf test bed):

```
expr true \& FIXEDSTRING : .*$1 \| false

```

`FIXEDSTRING : .*$1` is a regex pattern match; it's implicitly anchored with a leading `^`, thus the need for the `.*` in front of `$1` (probably would need to be `.\*$1` if there was a possibility of a file with a name matching the pattern). `true \&` will evaluate to the string `true` if the pattern match succeeds, and `0` otherwise, which, when paired with `\| false`, will replace all cases where it evaluated to `0` with the string `false`. Shaves off seven characters from my original approach (and six characters relative to the slightly shorter version I updated the question with, using `=~` to avoid a pair of `*`s).

If anyone can come close to that with pure `bash`, or beat it using near-universally available tools like `expr`, let me know; I'll happily accept such an answer.

# Answer
> 2 votes
Here's an option that abuses the filesystem for 41 bytes:

```
echo true>FIXEDSTRING
dd<*$1*||echo false

```

Attempt This Online!

This requires that your fixed string is not empty, `.`, `..`, nor contains `/`.

# Answer
> 0 votes
Found a `sed`-based solution that beats `expr` significantly. Obviously not a `bash` built-in, but it's using solely portable `sed` features AFAICT so it should be near universally available:

```
sed "/$1/ctrue
cfalse"<<<FIXEDSTRING

```

`/$1/ctrue` selects "lines" (there's only one line) which match the regex from `$1`, and `ctrue` short-circuits for that line, emitting `true` and discarding the line. If it wasn't short-circuited, `cfalse` with no selector handles everything else by echoing `false` and discarding the line.

Shaves four characters off the `expr` solution: Ignoring length of the fixed string, which appears once in each, it's 25 characters, vs. 29 for `expr`. It also has similar flexibility (it's not just `true` or `false`, you can use *mostly* arbitrary string outputs).

---
Tags: tips, bash
---


# Question
Title: Can Bitshift Variations in C Minor be compressed down to less than 185 characters?
Bitshift Variations in C Minor by Robert Miles is a Code Golf music piece written in C (with some additional bash commands). It was originally presented in a 2016 Computerphile video Code Golf & the Bitshift Variations. You can listen to clean renderings of it here (by Lucia Ceionia).

The original 2016 source code presented in the description under the YouTube video was **245** characters long:

```
echo "g(i,x,t,o){return((3&x&(i*((3&i>>16?\"BY}6YB6%\":\"Qj}6jQ6%\")[t%8]+51)>>o))<<4);};main(i,n,s){for(i=0;;i++)putchar(g(i,1,n=i>>14,12)+g(i,s=i>>17,n^i>>13,10)+g(i,s/3,n+((i>>11)%3),10)+g(i,s/5,8+n-((i>>10)%3),9));}"|gcc -xc -&&./a.out|aplay

```

A tweet from 2017 (or some other Rob Miles tweet, not sure) stands **216** characters:

```
gcc -xc -oa -<<<'i;n;g(x,t,o){return(3&x&(i*((3&i>>16?"BY}6YB6%":"Qj}6jQ6%")[t%8]+51)>>o))<<4;}main(s){for(;;)putchar(g(1,n=++i>>14,12)+g(s=i>>17,n^i>>13,10)+g(s/3,n+(i>>11)%3,10)+g(s/5,8+n-(i>>10)%3,9));}';./a|aplay

```

Another version using only **185** characters (written by MayMeta from Manifold Markets):

```
gcc -xc -oa -<<<'i;n;g(m,t,o){return("GTj?TG?5"[7&t]+!(n&12|t&2)*9)*i>>o&m&24;}main(s){for(;;)putchar(g(8,n=++i>>14,8)+g(n,n^(s=i>>10)/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5));}';./a|aplay

```

Will someone be able to shrink it down below 185 characters, or the limit has been reached?

Extra Credit (Resolution criteria for a related betting market):

* The bash command compiles the C source code and runs + plays it using aplay (or similar)
* You ARE allowed to slightly change the played notes, but their relative frequencies should not differ more than 1.4% from the original, and the entire piece should not be shifted more than one semitone (6%) from the original.
* Compiles and works as intended on an average linux machine.
* Does not use the internet

A winning entry will be the shortest entry that is less than 185 characters, and follows the Extra Credit guidelines. Entries that do not follow the extra credit are appreciated, but will not be selected as the winner. Solutions that could be argued to be following the spirit extra credit guidelines in their attempt to get under 185 will be considered to be winners as well, as it's a bit subjective.

Related Links:

Deep analysis of Bitshift Variations in C Minor code

BitShift-Variations-unrolled

Bitshift Variations Humanized + Rust version

# Answer
## 183 bytes

This isn't a big improvement or super impressive or anything, but saves 2 bytes in the main loop with some rearranging.

```
gcc -xc -oa -<<<'i;n;g(m,t,o){return("GTj?TG?5"[7&t]+!(n&12|t&2)*9)*i>>o&m&24;}main(s){for(;;putchar(g(8,n=s>>4,8)+g(n,n^s/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5)))s=++i>>10;}';./a|aplay

```

The changes are more visible when they are put side by side:

```
for(;;)putchar(g(8,n=++i>>14,8)+g(n,n^(s=i>>10)/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5));
for(;;putchar(g(8,n=s>>4,8)+g(n,n^s/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5)))s=++i>>10;

```
> 10 votes

# Answer
# 182

"Compiles and works as intended on an average linux machine."...
In common distros, cc is symlinked to gcc. Thus the first byte can be shaved off.

```
cc -xc -oa -<<<'i;n;g(m,t,o){return("GTj?TG?5"[7&t]+!(n&12|t&2)*9)*i>>o&m&24;}main(s){for(;;putchar(g(8,n=s>>4,8)+g(n,n^s/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5)))s=++i>>10;}';./a|aplay

```
> 5 votes

---
Tags: code-golf, tips, music, c
---


# Question
Title: Re-name all identifiers to a single letter
Imagine a very simple language. It has just 2 syntax features: `()` indicates a block scope, and any word consisting only of 1 or more lower case ASCII letters, which indicates a identifier. There are no keywords.

In this language, the value of identifiers is not important except when they appear multiple times. Thus for golfing purposes it makes sense to give them names that are as short as possible. A variable is "declared" when it is first used.

The goal of this challenge is to take a program, either as a string or as a ragged list, and make the identifiers as short as possible. The first identifier (and all its references) should be re-named to `a`, the next `b` then so on. There will never be more than 26 identifiers.

Each set of `()` encloses a scope. Scopes can access variables created in the parent scope defined before but not those created in child or sibling scopes. Thus if we have the program `(bad (cab) (face))` the minimum size is `(a (b) (b))`. A variable belongs to the scope when it is first used. When that scope ends the variable is deleted.

## In summary:

1. If a variable name has appeared in the scope or enclosing scopes before, re-use the letter
2. Else create a new letter inside the current scope
3. At the end of a scope delete all variables created inside the scope.

## Test cases

```
{
    "(rudolf)":                   "(a)",
    "(mousetail mousetail)":      "(a a)",
    "(cart fish)":                "(a b)",
    "(no and no)":                "(a b a)",
    "(burger (and fries))":       "(a (b c))",
    "(burger (or burger))":       "(a (b a))",
    "(let (bob and) (bob let))":  "(a (b c) (b a))",
    "(let (a (fish (let))))":     "(a (b (c (a))))",
    "(kor (kor kor) (kor kor))":  "(a (a a) (a a))",
    "((kor) kor)":                "((a) a)",
    "(aa (ab ac ad) (ad ad) ad)": "(a (b c d) (b b) b)",
    "(aa not (ab ac ad) (ad ad))":"(a b (c d e) (c c))",
    "(((((do) re) mi) fa) so)":   "(((((a) a) a) a) a)",
    "(do (re (mi (fa (so)))))":   "(a (b (c (d (e)))))",
    "((mark sam) sam)":           "((a b) a)",
}

```

## IO

1. You can take input as either a string or ragged array.
2. You can give output either as a string or ragged array.
3. However, you must use the same format for input and output. Specifically, you need to produce output in such a way that it would also be a valid input. Applying the function or program more than once always has the same result as applying it once.

Neither scopes nor variable names may be empty. Applying your program to its result again should be a no-op.

# Answer
# tinylisp, 149 bytes

```
(load library
(d G(q((L N)(i(c()(h L))(i L(c(G(h L)N)(G(t L)N))L)(i(contains? N(h L))(c(last-index N(h L))(G(t L)N))(G L(insert-end(h L)N
(q((L)(G L(

```

The last line is an anonymous function that takes a nested list and returns a nested list. The returned list uses nonnegative integers instead of letters, which seems to be allowed by this comment.

Try it online! Or, verify all test cases.

### Ungolfed

```
(load library)

(def _rename
 (lambda (expr names)
  (if (type? (head expr) List)
   (if expr
    (cons
     (_rename (head expr) names)
     (_rename (tail expr) names))
    nil)
   (if (contains? names (head expr))
    (cons
     (last-index names (head expr))
     (_rename (tail expr) names))
    (_rename expr
     (insert-end (head expr) names))))))

(lambda (expr) (_rename expr nil))

```

---

Here's a **167-byte** version that uses letters instead of numbers:

```
(load library
(d G(q((L N)(i(c()(h L))(i L(c(G(h L)N)(G(t L)N))L)(i(contains? N(h L))(c(single-char(a(last-index N(h L))97))(G(t L)N))(G L(insert-end(h L)N
(q((L)(G L(

```

Try it online!
> 14 votes

# Answer
# Python, 79 bytes

```
f=lambda _,**s:[i==[*i]and f(i,**s)or s.setdefault(i,chr(97+len(s)))for i in _]

```

Attempt This Online!

Thanks to @loopy walt.

## Whython, 66 bytes

```
f=lambda _,**s:[s.setdefault(i,chr(97+len(s)))?f(i,**s)for i in _]

```

Attempt This Online!

Port of the above.

## Whython, 72 bytes

```
f=lambda a,s={}:s.setdefault(a,chr(97+len(S:={**s})))?[f(i,S)for i in a]

```

Attempt This Online!

My original solution
> 9 votes

# Answer
# Prolog (SWI), ~~81~~ 70 bytes

```
\X,[I]-->[H],{copy_term(X,Z),\(Z,H,I);nth1(I,X,H)},(\X;[]).
a--> \_,!.

```

Try it online!

Instead of using predicates, I use definite clause grammar (DCG) notation. DCG notation is syntactic sugar in Prolog that allows for more writing more concise code for sequence processing. The basic way my program operates is that it iterates through the input and output list using DCG notation to bind the first item of the remainder of the input list to `NextItem` and the first item of the remainder of the output list to `ProcessedItem`. Then the program handles each potential case for `NextItem` and binds `ProcessedItem` to the appropriate value. Finally, the program attempts to process the following items, or, if none are found, terminates.

I stumbled onto an 11 byte golf of my program when I realized my original code was broken. The issue was that when parsing a sublist, the inner scope would leak into the outer scope since `InScopeVars` was having new variables placed into it by `nth1/3`, instead of by the intended `append/3`. I found a way to exploit this behavior though with the `copy_term/2` predicate, which unifies the second argument with a copy of the first argument but with fresh variables (e.g. `copy_term(X,Z)` where `X=[aa|SomeVar]` unifies `Z` with `[aa|SomeNewVar]`). This allows us to create a copy of the scope to use when handling a sublist where its uninitialized tail can be used without the inner scope leaking, thereby allowing us to use `nth1/3` for both appending and finding the index.

## Ungolfed Code

```
rename_item(InScopeVars),
  [ProcessedItem]
  -->
    [NextItem],
    {
      % Case 1: NextItem is a sublist
      % This predicate sets InScopeVarsCopy to a copy of InScopeVars,
      % but replaces all Prolog variables in it with newly instantiated ones.
      % This means any unifications that occur in the following rename_item call
      % will not affect InScopeVars
      copy_term(InScopeVars, InScopeVarsCopy),
      % DCGs are syntactic sugar for predicates with an additional two arguments:
      % the input sequence and the output sequence.
      % This fails if NextItem is not a list, in which case we'll
      % do Case 2 instead.
      rename_item(InScopeVarsCopy, NextItem, ProcessedItem)
    ;
      % Case 2: NextItem is a variable
      % We unify ProcessedItem with the index of NextItem in the list InScopeVars.
      % Note that since InScopeVars initially uninitialized,
      % it gets unified with [NextItem|UninitializedVariable].
      % On later calls, if NextItem appears in InScopeVars then ProcessedItem is
      % unified with the index of NextItem.
      % Otherwise the head of the uninitialized tail of InScopeVars is set to
      % NextItem, and NextItem's new index in InScopeVars is unified with
      % ProcessedItem.
      nth1(ProcessedItem, InScopeVars, NextItem)
    },
    (
      % Attempt to rename the next remaining item in the list
      rename_item(InScopeVars)
    ;
      % If that fails then we are done!
      []
    ).

rename -->
  % Due to the way the nth1/3 predicate works, passing in an
  % uninitialized variable for the initial scope is in essence passing in an
  % infinite list of uninitialized variables.
  % As we encounter new (not Prolog) variables in the input program they will be
  % unified with the first uninitialized (Prolog) variable in the scope.
  rename_item(_),
  % Once we get the first solution, we use the cut to prevent backtracking
  !.

```

Before I realized that it was permitted to output numbers instead of letters I wrote the following program, which I've modified to use some of the golfs I later found:

## 92 bytes

```
\X,[I]-->[H],{copy_term(X,Z),\(Z,H,I);nth1(N,X,H),C is 96+N,name(I,[C])},(\X;[]).
a--> \_,!.

```

Try it online!
> 9 votes

# Answer
# Prolog (SWI), 101 bytes

This version uses 1-26 instead of a-z (alternative version for a-z below). Had to (re)learn about Prolog dictionaries for this one, I like them!

```
[H|T]+[I|U]+A/N:-(H@>[],H+I+A/N;I=A.get(H)),T+U+A/N;I is N+1,T+U+A.put(H,I)/I.
A+A+_.
A+B:-A+B+_{}/0.

```

Try it online!

(The `H@>[]` part is a bit hacky, it's a list check (`is_list(H)`) that works on TIO, but there's probably a way to get rid of it, as neither are necessary in my ungolfed solution. Please correct me!)

### Ungolfed, commented

```
f([H|T],[NewH|NewT],Dict,N):-
% Case 1) No dict update needed
  ( f(H,NewH,Dict,N); % First element is a list (matches f([H|T]... or f([]...)
    NewH=Dict.get(H)), % First element is an atom
  f(T,NewT,Dict,N);
% Case 2) If first part failed, need to update the dictionary
  NewH is N+1,
  NewDict = Dict.put(H,NewH),
  f(T,NewT,NewDict,NewH).
f([],[],_,_).

% Wrapper predicate for recursive predicate
A+B:-f(A,B,_{},0).
```

### a-z solution, 114 bytes

```
[H|T]+[I|U]+A/N:-(H@>[],H+I+A/N;I=A.get(H)),T+U+A/N;Z is N+1,name(I,[Z]),T+U+A.put(H,I)/Z.
A+A+_.
A+B:-A+B+_{}/96.

```

Try it online!
> 7 votes

# Answer
# C (clang), 208 bytes

```
a[26];b[26];c;d;e;f;g;h;i(*j){for(;f=*j;j++)if(f/47)c=c?:j;else{if(c){for(*j=g=d=0;a[d]*!g;wcscmp(a[d],c)?d++:g++);g||(a[d]=c,b[e=d]=h);putchar(d+97);}for(c=!putchar(f);f==41&b[e]==h;a[e--]=0);h+=f%17-47%f;}}

```

Try it online!

-1 byte thanks to Noodle9!

-2 bytes thanks to ceilingcat!

-1 byte thanks to c--!
> 6 votes

# Answer
# Ruby, ~~69 65~~ 60 bytes

```
f=->l,*r{l.map{|x|x*0==[]?f[x,*r]:""<<97+(r|=[x]).index(x)}}

```

Try it online!
> 4 votes

# Answer
# K (ngn/k), ~~65~~ 54 bytes

```
{$[x~*x;`s$`c$97+(s::?s,x)?x;[t:s;r:o'x;s::t;r]]};s:!0

```

Try it online!
> 4 votes

# Answer
# Rust, 277 bytes

```
enum N{A(String),B(Vec<N>)};fn f(a:&[N],b:&mut Vec<String>)->Vec<N>{a.iter().map(|j|match j{N::A(j)=>N::A(('a'..='z').map(|i|i.to_string()).nth(b.iter().position(|a|a==j).unwrap_or_else(||{b.push(j.clone());b.len()-1})).unwrap()),N::B(j)=>N::B(f(j,&mut b.clone()))}).collect()}

```

Playground Link
> 3 votes

# Answer
# JavaScript (Node.js), 109 bytes

```
s=>s.replace(/\w+|\S/g,m=>m>')'?v[m]=v[m]||Buffer([v[0]++]):(v=m<')'?S.push(v)&&{...v}:S.pop(),m),S=[v=[97]])

```

Attempt This Online!

## Ungolfed and Explained

```
str => str.replace(
  /\w+|\S/g,                          // replace each variable name or bracket
  m => m > ')' ?                      // if match is a variable
    v[m] = v[m] || Buffer([v[0]++]) : // lookup the new var name, otherwise assign new
    (
      v = m < ')' ?                   // otherwise, if match is opening bracket
        S.push(v) && {...v} :         // push current var dict to stack
        S.pop(),                      // otherwise pop var dict
      m                               // return matched bracket (no-op)
    ),
  S = [                               // initialise stack
    v = [                             // initialise var dict
      97                              // v[0] = char code of next var name
    ]
  ]
)

```
> 3 votes

# Answer
# Raku, 76 bytes

```
sub f($x,%h?){$x~~Str??(%h{$x}//=chr 97+%h)!!$x.map:{f $^a,$_}with %h.clone}

```

Try it online!
> 2 votes

# Answer
# Perl, ~~63~~ ~~60~~ 29 bytes

(+1 for `-p`)

```
s/\w+/$a{$&}||=chr$i+++97/ge

```

Run like:

```
$ perl -pe 's/\w+/$a{$&}||=chr$i+++97/ge' <<<"(rudolf)"

```

or even

```
$ perl -pe 's/\w+/$a{$&}||=chr$i+++97/ge' file

```

### Ungolfed and explained

This is a simple replacement using the powerful `/e` modifier, which instructs perl to **e**valuate the replacement as code. It finds each identifier and checks it against a hash. If the hash is empty, it populates the next available letter, starting with ASCII code 97 (`a`):

```
s/                     # substitute
   (\w+)               # match: 1+ word characters
 /
   $letter{$1} ||=     # use existing letter or else assign …
      chr($i++ + 97)   # … a char w/ value of $i + 97, then increment $i
 /gex;                 # match globally and eval the replacement as code
                       # (this explanation uses /x for comments & spacing)

```

Running through the examples on a file containing each test case on its own line:

```
$ while IFS= read line; do
    printf "%-30s  %s\n" "$line" \
      "$(perl -pe 's/\w+/$a{$&}||=chr$i+++97/eg' <<<"$line")"
  done < test-cases
(rudolf)                        (a)
(mousetail mousetail)           (a a)
(cart fish)                     (a b)
(no and no)                     (a b a)
(burger (and fries))            (a (b c))
(burger (or burger))            (a (b a))
(let (bob and) (bob let))       (a (b c) (b a))
(let (a (fish (let))))          (a (b (c (a))))
(kor (kor kor) (kor kor))       (a (a a) (a a))
((kor) kor)                     ((a) a)
(aa (ab ac ad) (ad ad) ad)      (a (b c d) (d d) d)
(aa not (ab ac ad) (ad ad))     (a b (c d e) (e e))
(((((do) re) mi) fa) so)        (((((a) b) c) d) e)
(do (re (mi (fa (so)))))        (a (b (c (d (e)))))
((mark sam) sam)                ((a b) b)

```

This prints the input in a 30-char column before printing the answer.
> 1 votes

---
Tags: code-golf, string, ragged-list
---


title: Print last inputted byte

text:
# Question
Title: Print last inputted byte
# Challenge

You have one string of input bytes, output *only* the last byte in it.

# Rules

Your submission may be a program or function outputting the last byte in the input which

* is either a string, *stdin* or command-line arguments, and
* is non-empty.

I was trying to solve this with brainfuck, however all languages are allowed to participate. This is .

# Examples

```
"?" -> "?"
"29845812674" -> "4"

```

# Answer
# x86-16 machine code, 2 bytes

As @CodyGray correctly points out, taking input as a string and output to a register removes the bulk of the standalone program version.

Input string is in `SI`, length in `CX` and output character is in `AL`:

```
F3 AC  REPZ LODSB      ; start at memory location pointer in SI, put next value in AL,
                       ; loop CX number of times. The last char will be in AL when done.

```

Or **4 bytes** as a "Pascal string" (length is prepended to beginning of string):

```
AC     LODSB           ; first byte is string length
91     XCHG AX, CX     ; move length to CX for loop
F3 AC  REPZ LODSB      ; start at memory location pointer in SI, put next value in AL,
                       ; loop CX number of times. The last char will be in AL when done.

```

Or **5 bytes** as a "C string" (zero/null terminated), input in `DI`:

```
F2 AE     REPNZ SCASB     ; scan for value in AL (0), end when found and advance DI
8A 45 FE  MOV AL, [DI-2]  ; DI is now two bytes ahead of last, put value of DI-2 into AL

```

# x86-16 machine code, IBM PC DOS, ~~12~~ ~~11~~ 10 bytes

Or as complete program as IBM PC DOS executable. Input is from command line, output is to console.

```
B3 80   MOV  BL, 80H            ; BX to DOS PSP at 80H
8A 07   MOV  AL, BYTE PTR[BX]   ; get command line tail length
D7      XLAT                    ; AL = [BX+AL]
B4 0E   MOV  AH, 0EH            ; PC BIOS write to screen function
CD 10   INT  10H                ; display
C3      RET                     ; exit to DOS

```

**Output:**
> 13 votes

# Answer
# Attache, 4 bytes

```
Last

```

Try it online! (If the input could be a list of characters, `&/S` could work.)

## Alternatives

**5 bytes:** ``@&-1`

**8 bytes:** `&/S@List`

**10 bytes:** ``@«_,-1»`

**10 bytes:** `Fold!Right`

**10 bytes:** ``@<~_,-1~>`

**10 bytes:** ``^^&:Right`

**10 bytes:** `{Right^^_}`

**11 bytes:** `Get«_,-1»`

**11 bytes:** `Get<~_,-1~>`

**12 bytes:** ``@«_,#_-1»`

**12 bytes:** ``@<~_,#_-1~>`

**13 bytes:** `Get«_,#_-1»`

**13 bytes:** `Get<~_,#_-1~>`
> 13 votes

# Answer
# Brainf\***, 7 bytes

```
,[>,]<.

```
> 8 votes

# Answer
# MATL, 2 bytes

```
0)

```

MATL uses 1-based modular indexing so this solution grabs the element in the `0`-th position of the input which is the same as the last since the `0` wraps around to the end.

Try it out at MATL Online

**Explanation**

```
    % Implicitly grab the input
0   % Push the literal 0 to the stack
)   % Use this zero to grab the character at the end of the string
    % Implicitly display the result

```
> 7 votes

# Answer
# INTERCAL, ~~270~~ ~~258~~ ~~247~~ 246 bytes

```
DO,1<-#1PLEASECOMEFROM(2)DOWRITEIN,1DO.1<-,1SUB#1DO.5<-#1$.1~#256DO.2<-.3DO(1)NEXTPLEASE.2<-!3~#15'$.3~#240PLEASE.2<-!2~#15'$.2~#240PLEASE.2<-!2~#15'$.2~#240DO(1010)NEXTDO,1SUB#1<-.3DOREADOUT,1(1)DO(1002)NEXTDO(1009)NEXTDO.3<-.3~#255(2)DOFORGET#1

```

Try it online!

*-8 thanks to 鳴神裁四点一号 removing `DOGIVEUP` to terminate by NEXT stack explosion, opening up another -4 changing a `PLEASE` to `DO`.*

*-11 removing some grouping from the bit-reversing expression from hell. It seems that binary operators generally act right-associative in C-INTERCAL, though having no precedence among themselves.*

*-1 trying something else for bit reversal--definitely expected more savings than that! A more principled approach might be able to do it in two steps unless there's some obvious invariant I'm missing, but I'm too tired to take a stab at that just yet.*

Writing this was... interesting. I was thinking I might want to use INTERCAL to INTERCALate, but I'm a bit less sure now.

Ungolfed and commented:

```
        DO ,1<-#1             PLEASE NOTE We want the input array to only have space for one element, so it will only take one at a time
        DO COME FROM (2)
        DO WRITE IN ,1        PLEASE NOTE If this is the first byte of the input, it'll write its value... but if not, it'll write the
                              previous value minus its value mod 256.
        DO .1<-,1SUB#1
        DO .5<-#1$!1~#256'    PLEASE NOTE .5 is 3 if the input is 256, 2 otherwise
        DO .2<-.3
        DO (1) NEXT

                              PLEASE NOTE If we're here, we've found the end of the input. Now, we need to print it back out... C-INTERCAL's
                              array I/O, in order to determine what it will actually print, subtracts the value it's going to print from the
                              previous one (still mod 256, and with the previous value defaulting to 0), and then reads the bits of the byte
                              backwards. So in order to go from the value we want to display to the value we need to feed into READ OUT, we
                              reverse the bits and then subtract from 256. Rather than select the bits out individually and mingle them all
                              in one expression, I mingle the back and front halves of the byte until it adds up to a reversal.

        DO .2 <- !3~#15' $ !3~#240'
        DO .2 <- !2~#15' $ !2~#240'
        DO .2 <- !2~#15' $ !2~#240'

        DO (1010) NEXT        PLEASE NOTE .1 already has 256 in it, which is very convenient for when you need to subtract .2 from 256.

        DO ,1SUB#1 <- .3      PLEASE NOTE If we just read .3 out, we'd get a Roman numeral instead of the correct output.
        DO READ OUT ,1

        DON'T GIVE UP         PLEASE NOTE Logical end of program. However, if we don't gracefully terminate here, nothing more is output,
                              and the FORGET can't keep up with the NEXTs.

    (1) DO (1002) NEXT        PLEASE NOTE that that line in syslib does 1001 next, which pops .5 entries off the next-stack and returns
                              control flow to the last one, such that if .5 is 2 flow will come back here, but if it's 3 then it'll go back
                              to the line that nexted to this one.

                              Here we add .1 and .2 into .3, then truncate it to a byte before looping back (while managing the next-stack
                              responsibly so the program doesn't disappear into the black lagoon for any input over 79 (?) bytes)

        DO (1009) NEXT
        DO .3<-.3~#255
    (2) DO FORGET #1

```
> 7 votes

# Answer
# Python 3, 14 bytes

```
lambda x:x[-1]

```

Try it online!
> 6 votes

# Answer
# PHP, 13 bytes

```
<?=$argn[-1];

```

Try it online!

Run with `php -nF` input is STDIN. Example:

```
$ echo 29845812674|php -nF lost.php

```
> 6 votes

# Answer
# Javascript, 14 bytes

```
a=>a.slice(-1)

```
> 5 votes

# Answer
# Java 11+

Input from STDIN, ~~71~~ 61 bytes

-10 bytes thanks to OlivierGrégoire

```
v->{var x=System.in;x.skip(x.available()-1);return x.read();}

```

Try it online!
Function Argument, 25 bytes

```
s->s.charAt(s.length()-1)

```
> 4 votes

# Answer
# Haskell, ~~9~~ 4 bytes

```
last

```

Try it online!
> 4 votes

# Answer
# TI-BASIC (TI-84), 10 bytes

```
sub(Ans,length(Ans),1

```

Gets the last character in the input string.
Input is in `Ans`.
Output is in `Ans` and is automatically printed out.
> 4 votes

# Answer
# Bash + coreutils, 8 bytes

```
tail -c1

```

Input is from stdin, output is to stdout.
> 4 votes

# Answer
# Turing Machine But Way Worse, 391 bytes

```
1 0 1 1 0 0 0
0 0 0 1 1 0 0
1 1 1 1 0 0 0
0 1 0 1 2 0 0
1 2 1 1 0 0 0
0 2 0 1 3 0 0
1 3 1 1 0 0 0
0 3 0 1 4 0 0
1 4 1 1 0 0 0
0 4 0 1 5 0 0
1 5 1 1 0 0 0
0 5 0 1 6 0 0
1 6 1 1 0 0 0
0 6 0 1 7 0 0
1 7 1 1 0 0 0
0 7 0 1 8 0 0
1 8 1 1 0 0 0
0 8 0 0 9 0 0
0 9 0 0 a 0 0
0 a 0 0 b 0 0
0 b 0 0 c 0 0
0 c 0 0 d 0 0
0 d 0 0 e 0 0
0 e 0 0 f 0 0
0 f 0 0 h 0 0
0 h 0 0 g 0 0
0 g 0 0 0 1 1
1 g 1 0 0 1 1

```

Try it online!

**EXPLANATION**

```
Detect eight zero bits (which will occur at the end of the input, since TMBWW uses an infinite tape of bits.)
1 1 1 1 0 0 0
0 1 0 1 2 0 0
1 2 1 1 0 0 0
0 2 0 1 3 0 0
1 3 1 1 0 0 0
0 3 0 1 4 0 0
1 4 1 1 0 0 0
0 4 0 1 5 0 0
1 5 1 1 0 0 0
0 5 0 1 6 0 0
1 6 1 1 0 0 0
0 6 0 1 7 0 0
1 7 1 1 0 0 0
0 7 0 1 8 0 0
1 8 1 1 0 0 0
0 8 0 0 9 0 0

-------------

When eight 0 bits are detected, move back to the final byte of the input and print it out while halting the program.
0 9 0 0 a 0 0
0 a 0 0 b 0 0
0 b 0 0 c 0 0
0 c 0 0 d 0 0
0 d 0 0 e 0 0
0 e 0 0 f 0 0
0 f 0 0 h 0 0
0 h 0 0 g 0 0
0 g 0 0 0 1 1
1 g 1 0 0 1 1

```
> 4 votes

# Answer
# Excel, 10 bytes

Pretty much equivalent to @remoel's VBA answer:

```
=RIGHT(A1)

```
> 4 votes

# Answer
# Seed, 11 bytes

```
5 370394306

```

Try it online!

The resulting Befunge-98 program `~2j@,` was stolen borrowed from *Jo King* here, so credit to them for that.
> 4 votes

# Answer
# Mornington Crescent, 389 Bytes

Even a task as simple as this presents an interesting optimisation challenge when riding the London Underground.

```
Take Northern Line to Bank
Take Circle Line to Bank
Take Central Line to Mile End
Take Central Line to Holborn
Take Piccadilly Line to Heathrow Terminals 1, 2, 3
Take Piccadilly Line to Acton Town
Take District Line to Acton Town
Take District Line to Parsons Green
Take District Line to Mile End
Take Central Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

```

Try it online!

Visiting Mile End station allows you to take a substring from the end of the input - but to chop just 1 character, you need to generate the integer 1 somehow. Rather than doing any arithmetic, the fastest method turns out to be to parse it from the station name "Heathrow Terminals 1, 2, 3".

To bypass that, an alternate strategy for this challenge would be to reverse the input, read the character code for the now first byte, and then turn that back into a char to output - but this approach takes 12 bytes longer. (Although there are fewer trips needed, so the tickets would be cheaper.)
> 4 votes

# Answer
# Arn, 2 bytes

```
:}

```

Pretty simple, the suffix `:}` gets the last element of an array (implicit casting)
> 4 votes

# Answer
# Befunge-93, 12 ~~15~~ bytes

```
:1+_p1-,@>~#

```

Try it online!

Thanks to @Jo King for golfing off 3 bytes.

Alternate 15 byte version that is less messy:

```
~:1+#v!_
  @,$<

```

Taking strings as input in Befunge isn't the easiest. If there were a single command to take in multiple characters, it would be as simple as reading the string, popping/printing the top character, and exiting.
> 3 votes

# Answer
# Jelly, 1 byte

Try it online!

Not the most difficult challenge in Jelly...

Note this accepts the input as a string; if the input could be interpreted otherwise (e.g. a number, a list), then it the argument will need to be quoted (e.g. "123456" or "\[123,197\]"). Alternatively this can be seen as a link that takes a byte array and returns the last member of that array, in accordance with PPCG standard rules.

Thanks to @MilkyWay90 and @ბიმო for pointing this out.
> 3 votes

# Answer
# \>\<\>, 2 bytes

Using command line args

```
o;

```

Try it online!

# \>\<\>, 11 bytes

Using stdin

```
\~o;
/?(0:i

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 1 byte

```
¤

```

Try it online!

`θ` or ``` would also work.
> 3 votes

# Answer
# Cubix, 6 bytes

```
pA/@po

```

Try it online!

```
  p
A / @ p
  o

```

Watch it run

* `A` Takes all the input
* `/` Redirect around the cube
* `pp` bring bottom of the stack to the top twice
* `o/@` output as character, redirect and halt
> 3 votes

# Answer
# Emotion, 5 bytes

```

```

Explanation

```
 Push a copy of the first stack value.
 Push the length of the first stack value interpreted as a string.
 Push literal 1
 Push the difference of the second and first stack values.
 Push the character of the second stack value at the index of the top stack value.

```

Try it online!
> 3 votes

# Answer
# Cascade, 9 bytes

```
?a|,
;.]^

```

Pretty happy with this, as it is only 3 bytes longer than my cat program

# Expanded

```
   ?
  ^;.
 | |a
 ] |
a ,|

```

This essentially just loops through pushing input characters into the `a` stack until EOF is reached. Then it outputs the item at the top of the `a` stack using `.a`.

Try it online!
> 3 votes

# Answer
## Rust, 25 16 10 bytes

```
|s|s.pop()

```

Try it on the Rust Playground!

An anonymous function that takes in a mutable String and outputs the char at the end of the string. Minus a lot of bytes, thanks to madlaina
> 3 votes

# Answer
# PowerShell, 11 bytes

```
"$args"[-1]

```

Try it online!
> 2 votes

# Answer
# SmileBASIC, 16 bytes

```
INPUT S$?POP(S$)

```
> 2 votes

# Answer
# Bash, 13 bytes

```
echo ${1: -1}

```

string is passed as argument.

Try it online !
> 2 votes

# Answer
# Python 3, ~~11~~ ~~18~~ 34 Bytes

```
import sys;print(sys.argv[-1][-1])

```

Usage via running the program as a python script on the command line. Input is provided as the last argument to the program.

Try it online!
> 2 votes

# Answer
# Turing Machine Code, ~~72~~ 42 bytes

Assumes an input with no empty cells (spaces). Thanks to ASCII-only for saving 30 bytes.

```
0 * * r 1
1 * * l 2
1 _ _ l halt
2 * _ r 0

```

Old version in 72 bytes:

```
0 * * r 0
0 _ * l 1
1 * * l 2
2 * _ l 2
2 _ _ r 3
3 _ _ r 3
3 * * * halt

```

Try it online.
> 2 votes

# Answer
# Twig, 37 bytes

This just uses a simple "extract 1 char from the end and print it" aproach.

```
{%macro a(a)%}{{a[-1:1]}}{%endmacro%}

```

It was really easy to do, and test, but was fun!

---

To use it, you have to put it on a `.twig` file and import it:

```
{% import 'a.twig' as a %}
{{ a.a("string") }} {# should display "g" #}

```

You can test it on https://twigfiddle.com/aa19wd (testcases included)
> 2 votes

# Answer
# APL+WIN, 4 bytes

```
¯1↑⎕

```

Prompt for input string and select last byte.
> 2 votes

# Answer
# VBA (Excel), ~~14~~ 12 bytes

using Immediate Window and Cell `A1` as input

Thanks @tsh

`?[RIGHT(A1)]` ~~or `?Right([A1],1)`~~
> 2 votes

# Answer
# IBM/Lotus Notes Formula, 11 bytes

```
@Right(i;1)

```

Computed field formula taking its input from editable field `i`
> 2 votes

# Answer
# C# 8.0, 8 bytes

*Requires .NET Core 3.0, which is in beta. This currently crashes the CLR due to a bug, but once the bug is fixed, this will run as expected and fulfill the challenge requirements.*

`s=>s[^1]`

# C# 8.0, Runs without crashing at time of writing, 22 bytes

`s=>s.ToCharArray()[^1]`

# C# 8.0, Full Program, 78 bytes

`using C=System.Console;class A{static void Main(){C.Write(C.ReadLine()[^1]);}}`
> 2 votes

# Answer
# LiveScript, 8 bytes

```
(.[*-1])

```

Explanation:

```
(.[*-1])
(.[*-1]) # "BIOP": operator section à la Haskell
 .[   ]  # Index into the implicit argument
   *-1   # In [], "*" refers to the length

```
> 2 votes

# Answer
# Forth (gforth), 17 bytes

```
: f 1- + 1 type ;

```

Try it online!

### Explanation

Adds `string-length - 1` to the string address and then prints a string of length 1 starting at that address.

### Code Explanation

```
: f        \ start a new word definition
  1-       \ subtract 1 from string length
  +        \ add result to string address
  1 type   \ print string of length 1 starting at the new address
;          \ end word definition

```
> 2 votes

# Answer
## F#, 14 8 bytes

```
Seq.last

```

-6 bytes thanks to aloisdg.

Strings are treated as sequences in F#, so you can use the `Seq.last` function to get the last character in it.
> 2 votes

# Answer
# Retina, ~~10~~ 9 bytes

```
(.|¶)*
$1

```

Try it online!
> 2 votes

# Answer
# C (gcc), 31 bytes

```
f(int*s){gets(s),printf("%s");}

```

Try it online!
> 2 votes

# Answer
## Caboose, 1514 bytes

Caboose hates me, because it *does*. *There isn't any convenient string-indexing instruction in Caboose!*

```
var a=input();print(a.endsWith(' ')and' 'or a.endsWith('!')and'!'or a.endsWith('"')and'"'or a.endsWith('#')and'#'or a.endsWith('$')and'$'or a.endsWith('%')and'%'or a.endsWith('&')and'&'or a.endsWith("'")and"'"or a.endsWith('(')and'('or a.endsWith(')')and')'or a.endsWith('*')and'*'or a.endsWith('+')and'+'or a.endsWith(',')and','or a.endsWith('-')and'-'or a.endsWith('.')and'.'or a.endsWith('/')and'/'or a.endsWith('0')and'0'or a.endsWith('1')and'1'or a.endsWith('2')and'2'or a.endsWith('3')and'3'or a.endsWith('4')and'4'or a.endsWith('5')and'5'or a.endsWith('6')and'6'or a.endsWith('7')and'7'or a.endsWith('8')and'8'or a.endsWith('9')and'9'or a.endsWith(':')and':'or a.endsWith(';')and';'or a.endsWith('<')and'<'or a.endsWith('=')and'='or a.endsWith('>')and'>'or a.endsWith('?')and'?'or a.endsWith('@')and'@'or a.endsWith('A')and'A'or a.endsWith('B')and'B'or a.endsWith('C')and'C'or a.endsWith('D')and'D'or a.endsWith('E')and'E'or a.endsWith('F')and'F'or a.endsWith('G')and'G'or a.endsWith('H')and'H'or a.endsWith('I')and'I'or a.endsWith('J')and'J'or a.endsWith('K')and'K'or a.endsWith('L')and'L'or a.endsWith('M')and'M'or a.endsWith('N')and'N'or a.endsWith('O')and'O'or a.endsWith('P')and'P'or a.endsWith('Q')and'Q'or a.endsWith('R')and'R'or a.endsWith('S')and'S'or a.endsWith('T')and'T'or a.endsWith('U')and'U'or a.endsWith('V')and'V'or a.endsWith('W')and'W'or a.endsWith('X')and'X'or a.endsWith('Y')and'Y'or a.endsWith('Z')and'Z'or a.endsWith('[')and'['or a.endsWith('\\')and'\\'or a.endsWith(']')and']'or'~');

```

If I add more constants, then Caboose will say that there are too many constants in the chunk. Fortunately it passes all test cases given. Basically it (tries to) check the last character against all characters in printable ASCII.

TIO
> 2 votes

# Answer
# Scratch 3.0, 7 blocks/68 bytes

*or, as scratchblocks syntax*

```
when gf clicked
ask()and wait
say(letter(length of(answer))of(answer

```

Try it on scratch

Did I mention this was done **100%** on mobile? Because it was *really* hard making this, but I think it was worth it.
> 2 votes

# Answer
# naz, 38 bytes

```
2a2x1v1x1f1r3x1v2e2x2v1f0x1x2f2v1o0x1f

```

Works for any input string terminated with the control character STX (U+0002).

**Explanation** (with `0x` commands removed)

```
2a2x1v             # Set variable 1 equal to 2
1x1f1r3x1v2e2x2v1f # Function 1
                   # Read a byte of input
                   # Jump to function 2 if it equals variable 1
                   # Otherwise, store it in variable 2,
                   # then jump back to the start of the function
1x2f2v1o           # Function 2
                   # Load variable 2 into the register and output it
1f                 # Call function 1

```
> 2 votes

# Answer
# Ruby `-pl`, 9 bytes

Similar to the Perl solution, but `chop` doesn't return the last character in Ruby. (It instead returns the rest of the string without the last character.)

```
$_=$_[-1]

```

Try it online!
> 2 votes

# Answer
# MAWP, 2 bytes

```
|;

```

Outputs top of stack.

Try it!
> 2 votes

# Answer
# Flurry, 14 bytes

```
([]{(){}{}}{})

```

### Run example

```
$ echo -n "?" | ./flurry -bnb -c "([]{(){}{}}{})"
?
$ echo -n "Hello world" | ./flurry -bnb -c "([]{(){}{}}{})"
d

```

`-bnb` flag means "print stack as chars, print nothing for return value, and take stdin as chars".

If the challenge were asking for "the last value from an integer array", I would use return value output and write 2 byte solution `{}` (pop the stack and return it). But since character I/O is required and the only way to output a char is via the stack, I had to manually empty the stack.

### How it works

```
(
 []     Stack height as Church numeral; Given 2 arguments `f` `x`,
          a Church numeral `n` acts as "apply `f` `n` times to `x`"
 {      Define f, with its argument pushed to the stack:
  ()      K; Given two arguments, ignore the second
  {}      Pop; the argument
  {}      Pop; pop an extra item from the stack (ignored by K)
 }      End definition of f: Return its argument unchanged,
          popping and discarding an item from the stack
 {}     Pop an item (last char)
        At this point, the stack is empty and the value is the last char
)     Push the result of the above

```
> 2 votes

# Answer
## Notepad, ~~9~~ 5 keystrokes

Assuming the cursor is at the end of the file.

```
[LeftArrow][Ctrl-Shift-LeftArrow][Delete]

```

I know it is not a language, but I'm posting just for fun.
> 2 votes

# Answer
# dotcomma, 48 bytes

```
[[[],],][.[[[,.][.[,]].,][[,].[,]].]][,[,].[,.]]

```

Try it online!

Because dotcomma is queue-based, you can't easily access the last character. My solution is to reverse the input and then output the first character of it.

**Code:**

```
                # reverse the input
[[[],],]        mark the end with 0 0
[.[             while there are characters in input
  [[,.]         put a character on the recursion stack
    [.[,]]      go to reverse section
  .,]           save the character in the reverse section
  [[,].[,]]     go to input section
.]]

[               # get first character and delete all others
  ,[,]          delete 0 and append the next character (last of input) to the end of the queue
  .[,.]         delete everything until we reach a 0
]
                implicitly output the queue

```

# dotcomma (experimental), 17 bytes

```
[,][[],][.[,.]].,

```

Try it online!

I marked this "experimental" because the language dotcomma is still very young and I don't know if this is intentional behaviour. If you pass input as a list of strings it reverses each string, so you only need to extract the first letter.

```
[,]      put first character on recursion stack
[[],]    put 0 (end of queue marker) on queue
[.[,.]]  delete everything from queue
.,       write back character

```
> 2 votes

# Answer
# vim, 6 bytes

```
VGJ$d^

```

## Annotated

```
VGJ     # join all lines
$       # move cursor to (before) last character
d^      # delete to beginning

```

Try it online!
> 2 votes

# Answer
# Julia, 4 bytes

```
last

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 16 bytes

```
#~StringTake~-1&

```

Try it online!
> 1 votes

# Answer
# C# (.NET Core), 81 bytes, command-line input

```
class M{static void Main(string[] a){System.Console.Write(a[0][a[0].Length-1]);}}

```

Try it online!

If you run this from an actual command line, you will need to wrap your string in quotes if it contains spaces.
> 1 votes

# Answer
# C# (.NET Core), 115 bytes, console input

```
using C=System.Console;class M{static void Main(string[] a){int c=0,d;while((d=C.Read())>-1)c=d;C.Write((char)c);}}

```

Try it online!

This feels kinda janky, but it does work. Interestingly, I can't save any bytes with a for loop as the code stands.
> 1 votes

# Answer
# Perl 6, 11 bytes

```
*.comb[*-1]

```

Try it online!

Anonymous Whatever lambda that takes a string, splits it into characters, and returns the last one.
> 1 votes

# Answer
## Batch, 24 bytes

```
@set s=%1
@echo %s:~-1%

```

Takes input as a command-line argument. Note that arguments can't include special characters or spaces, but you can fake arguments with spaces in this case by preceding it with a `"`, which results in a single argument that begins with `"`, however there is no easy solution for arguments that include special characters. Batch can't easily read "all of stdin". To read up to but not including the first newline itself would however be a byte shorter:

```
@set/ps=
@echo %s:~-1%

```

Edit: A version that handles arbitrary characters in a (quoted) argument for 92 bytes:

```
@set s="%~1"
@set "s=%s:~-2,1%
@if "%s%"=="" (echo ^")else for %%s in ("%s%")do @echo %%~s

```

Explanation: The first line makes a copy of the argument in a variable and ensures that it is quoted. The second argument then takes the second last character (because the quote is now the last character). However, if that was also a quote then this results in an empty variable, so we need to special-case that and output a (quoted) quote. Otherwise, we still need to quote the character in case it is a special character as echoing `"%s%"` will echo the quotes and echoing `%s%` will actually interpret special characters, so the variable needs to be quoted to allow it to be parsed but then immediately unquoted so it can be printed. This is achieved using the `for` command. 86 bytes to read up to but not including the first newline from stdin while supporting special characters:

```
@set/ps=
@set "s=%s:~-1%
@if "%s%"=="" (echo ^")else for %%s in ("%s%")do @echo %%~s

```
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 11 bytes

```
x=>x.Last()

```

Try it online!
> 1 votes

# Answer
# Scratch 3.0, scratchblocks3 syntax

## As a function, 61 bytes

```
define l
ask[]and wait
say(letter(length of(answer))of(answer

```

## As a full program, 68 bytes

```
when gf clicked
ask[]and wait
say(letter(length of(answer))of(answer

```

Try both online
> 1 votes

# Answer
# Befunge-98, 5 bytes

```
~2j@,

```

Try it online!

### Explanation:

```
~           Take input
 2j         Skip next two instructions
~           Repeat until EOF, where it reflects
   @,       Print the last character and exit

```
> 1 votes

# Answer
# Japt, 1 byte

```
Ì

```

Try it online!

-1 byte thanks to Quintec!
> 1 votes

# Answer
# Whitespace, 54 bytes

```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S N
S _Duplicate][S S S T   S T S N
_Push_10][T S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_PRINT][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_top][T N
S S _Print_as_character]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Since Whitespace can only take input as integer or character, we must add a trailing character to indicate we're done with the input-string after reading it character by character, for which I've used a newline.

**Try it online** (with raw spaces, tabs and new-lines only).

**Example run: `input = A2#`**

```
Command    Explanation                   Stack                Heap    STDIN STDOUT STDERR

NSSN       Create Label_LOOP             []
 SSSN      Push 0                        [0]
 SNS       Duplicate top (0)             [0,0]
 TNTS      Read STDIN as character       [0]                  {0:65}  A
 TTT       Retrieve at heap address (0)  [65]                 {0:65}
 SNS       Duplicate top (65)            [65,65]              {0:65}
 SSSTSTSN  Push 10                       [65,65,10]           {0:65}
 TSST      Subtract top two (65-10)      [65,55]              {0:65}
 NTSSN     If 0: Jump to Label_PRINT     [65]                 {0:65}
 NSNN      Jump to Label_LOOP            [65]                 {0:65}

 SSSN      Push 0                        [65,0]
 SNS       Duplicate top (0)             [65,0,0]
 TNTS      Read STDIN as character       [65,0]               {0:50}  2
 TTT       Retrieve at heap address (0)  [65,50]              {0:50}
 SNS       Duplicate top (50)            [65,50,50]           {0:50}
 SSSTSTSN  Push 10                       [65,50,50,10]        {0:50}
 TSST      Subtract top two (50-10)      [65,50,40]           {0:50}
 NTSSN     If 0: Jump to Label_PRINT     [65,50]              {0:50}
 NSNN      Jump to Label_LOOP            [65,50]              {0:50}

 SSSN      Push 0                        [65,50,0]
 SNS       Duplicate top (0)             [65,50,0,0]
 TNTS      Read STDIN as character       [65,50,0]            {0:35}  #
 TTT       Retrieve at heap address (0)  [65,50,35]           {0:35}
 SNS       Duplicate top (35)            [65,50,35,35]        {0:35}
 SSSTSTSN  Push 10                       [65,50,35,35,10]     {0:35}
 TSST      Subtract top two (35-10)      [65,50,35,25]        {0:35}
 NTSSN     If 0: Jump to Label_PRINT     [65,50,35]           {0:35}
 NSNN      Jump to Label_LOOP            [65,50,35]           {0:35}

 SSSN      Push 0                        [65,50,35,0]
 SNS       Duplicate top (0)             [65,50,35,0,0]
 TNTS      Read STDIN as character       [65,50,35,0]         {0:10}  \n
 TTT       Retrieve at heap address (0)  [65,50,35,10]        {0:10}
 SNS       Duplicate top (10)            [65,50,35,10,10]     {0:10}
 SSSTSTSN  Push 10                       [65,50,35,10,10,10]  {0:10}
 TSST      Subtract top two (10-10)      [65,50,35,10,0]      {0:10}
 NTSSN     If 0: Jump to Label_PRINT     [65,50,35,10]        {0:10}

NSSSN      Create Label_PRINT            [65,50,35,10]        {0:10}
 SNN       Discard top                   [65,50,35]           {0:10}
 TNSS      Print as character to STDOUT  [65,50]              {0:10}        #
                                                              {0:10}               error

```

Stops with the error: Exit not defined.
> 1 votes

# Answer
# Japt `-h`, 1 byte

```
U

```

Run it online
> 1 votes

# Answer
# Runic Enchantments, 5 bytes

```
i1Z%@

```

Try it online!

Note that input handling in Runic has implicit conversion and breaks on spaces. `\` denotes a literal space (works on newlines too) and numerical values are never strings.
> 1 votes

# Answer
# Binary-Encoded Golfical, 17 bytes

Hex-dump of binary encoded file:

```
00 60 02 1b 1a 08 01 14
16 14 24 1d 0a 01 14 18
14

```

Original image:

Magnified 45x with colors labeled:

The original image (the tiny one, not the magnified version) can be run using the interpreter normally. The binary encoded file (of which a hexdump is included above) can either be transpiled back to the image version with the Encoder program included in the github repo, or run directly using the interpreter by adding the `-x` flag.
> 1 votes

# Answer
# Chip `-z`, 41 bytes

```
S
>vvvvvv~t
ABCDEFG
|Zz||Zz
zbcZzfg
a  de

```

Try it online!

Assumes that either the byte string does not contain zero (`\0`), or that it designates the end of the string.

---

Alternate solution (45 bytes):

```
azABZbczCDZdezEFZfgzG
S-^^----^^----^^----^~t

```

Try it online!
> 1 votes

# Answer
# , 35 bytes

Takes the input, splits it in to a list, outputs the last element of the list.

```
tail(strsplit(scan(,''),'')[[1]],1)

```

Try it online!
> 1 votes

# Answer
# Japt `-h`, 1 byte

Can handle input as a string, integer or character/digit array.

```
s

```

Try it
> 1 votes

# Answer
# C, ~~36~~ ~~35~~ 34 bytes

```
x(char*v){printf(v+strlen(v)-1);}

```

Really simple stuff here. Nothing to ungolf either.

Saved one byte thanks to ceilingcat
Fixed the answer and saved another byte thanks to ASCII-only
> 1 votes

# Answer
# Haskell, 4 bytes

```
last

```

Functions are allowed, right?

Also with IO (18 bytes):

```
main=interact$last

```
> 1 votes

# Answer
# Pepe, 13 bytes

```
REEeREEEeReEe

```

Try it online! Disable "Separated by" check box below the input text box.

**Explanation:**

```
REEe  # Input as string (stack R)
REEEe # Goto last char (stack R)
ReEe  # Output char (stack R)

```
> 1 votes

# Answer
## Keg, 1 byte

This is the exact thing that Keg was built for.

```
,

```

Explanation

```
# Push implicit string input
,# Output the last pushed character
# There is no implicit output since something was outputted

```

TIO
> 1 votes

# Answer
# Triangular, 10 bytes

```
(#~p../)?<

```

Try it online!

Pretty straight-forward; reads characters until it gets a null read, then prints the top of the stack.

Ungolfed:

```
   (
  # ~
 p . .
/ ) ? <
--------------------------------------------
(            Set a point to jump back to
 ~.<         Read a character, change directions ("." is a no-op)
    ?)/      If ToS <= 0, skip next instruction and change directions; otherwise, jump back to "("
       p#    Pop the top value from the stack (the null input), then pop again and print that value

```
> 1 votes

# Answer
# Commodore 8-bit BASIC (CBM/PET, VIC-20, C64/TheC64Mini, C128, C16/+4) - byte count later

```
 0inputa$:iflen(a$)thenprintright$(a$,1)

```

### Simplified (without the sanity check):

```
 0inputa$:?right$(a$,1)

```

There is a small limitation in that Commodore 8-bit BASIC the maximum length of a string is 255 characters, so any entry above that will cause an error.
> 1 votes

# Answer
# Brain-Flak`-cr`, (6 bytes code + 3 bytes command line) = 9 bytes

```
({}<>)

```

Try it online!

Code:

The command line argument "-cr" means "use ASCII input and output" and "reverse the stack", so when you pop a value, the last byte of the input is popped, and when you push a value, it is pushed to the end.

```
 {}     pop a character
(    )  and push it
   <>   on the other stack
        implicitly output the current stack

```
> 1 votes

# Answer
# MarioLANG, 18 bytes

```
>,
"+
)[
!<(-
#==.

```

Try it online!

code:

```
>    go right
,    read input
+    increment it (because EOF = -1)
[    ignore the next command, if current cell = 0
<    go to the left
!    stop moving (Mario is now standing on the elevator (#),
     which rides up to the elevator end (")
)    go to the next memory cell
     Mario is now at the starting position (>) and runs another round
     until the end of input

else (if he ignored the "<" instruction)
(    go one memory cell back (to the last inputted byte)
-    decrement it, so it becomes the original value again
.    print it

```
> 1 votes

# Answer
# Clojure, ~~32 bytes~~ 24 bytes

```
(print(last(read-line)))

```

```
(print             ;; prints output
  (last            ;; get last character of input
    (read-line)))  ;; read input

```

Try it online!
> 1 votes

# Answer
# GolfScript, 3 bytes

The GolfScript `=` yields a decimal. That's pretty weird ... However, (luckily enough,) GolfScript supports slicing over a string, which allows me to slice the last item of the string.

```
-1>

```

Try it online!

# Explanation

```
-1  # The last item
  > # Choose everything in the string
    # after the last item, including the last item
    # this (obviously) yields the last item

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 2 bytes<sup>SBCS</sup>

```
⊢/

```

Try it online!

The code taken literally means to "reduce by right argument function". It works like the following (basically like `foldr1 (flip const)` in Haskell):

```
  ⊢/ 'abcd'
→ 'a' ⊢ 'b' ⊢ 'c' ⊢ 'd'
→ 'a' ⊢ 'b' ⊢ 'd'
→ 'a' ⊢ 'd'
→ 'd'

```

This is an idiom for taking last element from a vector (or taking last element from each row of a multi-dimensional array).
> 1 votes

# Answer
# GolfScript, 3 bytes

Though there was already a Golfscript 3 byte solution, I figured I'd throw in the more general-purpose one.

```
)\;

```

Where ( is the front-uncon function (Golfscript treats strings as char arrays), \ swaps the string and char positions, and ; deletes the string, leaving only the last char.
> 1 votes

# Answer
# Burlesque, 2 bytes

```
[~

```

Try it online!

If it needs to be pretty formatted `[~Q`

```
[~ # Last char

```
> 1 votes

# Answer
# Integral, 2 Bytes

```
Vn

```

Try it!

## Explanation

```
V  Reverse the input
 n Head

```
> 1 votes

# Answer
## Pip, 4 bytes

```
a@-1

```

`@RVa` also works, and is the same size.

Try it online!
> 1 votes

# Answer
# Marbelous, 13 bytes

```
@0
00
]]..
@0

```

Marbelous is a language based on marble machines

* `@n` (`n` from `0` to `Z`) is a portal which teleport the marble to another portal with the same value
* `00`-`FF` initiate a marble with this value
* `]]` passing marble take value of next input byte if there is one, else the marble is diverted to the right
* `..` is a noop
* marbles going out of the board to the bottom are implicitly outputed

interpretor
> 1 votes

# Answer
# Labyrinth, 8 bytes

```
,);.@
"(

```

Try it online!

```
,)("  Loop until EOF (-1): push a char input, increment, then decrement
;.@   On EOF, discard top, print the last char, and halt

```
> 1 votes

# Answer
# Pyth, 1 byte

```
e

```

Try it online!
> 1 votes

# Answer
# Regex, 2 bytes

```
.$

```

Matches character then end of string.
> 1 votes

# Answer
# APOL, 7 bytes

`g(i -1)`

About as simple as possible, just gets the last character of the input string.
> 1 votes

# Answer
# Fig, \\$1\log\_{256}(96)\approx\\$ 0.823 bytes

```
]

```

Try it online!

1-byters?? Seriously?? Why have that when you can have 0.823 bytes?? Literally "grab last char of (implicit) input."
> 1 votes

# Answer
# nroff, 57 bytes

```
.de F
.ds X \\$1
.length L \\*X
.substring X \\nL
\\*X
..

```

Attempt This Online!

## Usage

```
.F "41382239"
.F "e"
.F "what"
.F " a "
.F "b c"

```

## How it works

```
.de F             \" define macro F
.ds X \\$1        \" store 1st argument to string variable X
                  \" I had to do so because arguments are not in variable, but
                  \" can be obtained via requests only
.length L \\*X    \" store length of X to register L
                  \" no numerical express to do so
.substring X \\nL \" 1-indexed. replace X with L-th to last substring
\\*X              \" content of X
..                \" end of definition

```
> 1 votes

# Answer
# AArch64 machine code, 12 bytes

```
20 8c c0 28 e3 ff ff 35 c0 03 5f d6

```

Commented assembly

```
    .globl lastchar
    // Input: x1: null terminated UTF-32 string
    // Output: w0: last char in string
    // char32_t lastchar(int dummy, const char32_t *str);
lastchar:
.Lloop:
    // load two chars, advance by one char
    // w0 = *x1++; w3 = *x1;
    ldp     w0, w3, [x1], #4
    // loop if w3 was not zero (null terminator)
    cbnz    w3, .Lloop
    // return
    // result is in w0
    ret

```

This can be called from C using a dummy parameter to put the null terminated UTF-32 string in `x1`.

```
char32_t lastchar(int dummy /* x0 */, const char32_t *ptr /* x1 */);

```

I don't usually do AArch64 because it isn't very compact at 4 bytes per instruction and almost always longer than Thumb, but this particular solution is really elegant even if it is larger than the equivalent Thumb code by 2 bytes (it's solely because of the return instruction being 2 bytes) (Thumb does better with ptr+length though)
> 1 votes

# Answer
# ARM Thumb machine code, 6 bytes

```
01 39 40 5c 70 47

```

Commented assembly:

```
    .syntax unified
    .arch armv7-a
    .thumb
    .globl lastchar
    .thumb_func
    // C-callable function
    // Input:
    //  - r0: String of ASCII (not utf-32)
    //  - r1: Length of string
    // Output:
    //  - r0: Char
    // int lastchar(const char *ptr, uint32_t length);
lastchar:
    // It's literally ptr[length - 1]
    // Subtract 1 from the length since ARM can't do [reg, reg, offset]
    subs    r1, #1
    // load ptr[length]
    ldrb    r0, [r0, r1]
    // return in r0
    bx      lr

```

I mean it is literally `return ptr[length - 1]`, there isn't much to explain. The function is callable using the C convention, using **byte string + length** (not null-terminated UTF-32 like most of my solutions):

```
int lastchar(const char *ptr, uint32_t length);

```

---

# ARM Thumb machine code, 10 bytes

This is the "equivalent Thumb code" I mentioned on my aarch64 answer. It is much less elegant.

```
01 c9 0b 68 00 2b fb d1 70 47

```

Commented assembly:

```
    .syntax unified
    .arch armv7-a
    .thumb
    .globl lastchar
    .thumb_func
    // C-callable function
    // Input:
    //  - r1: Null terminated UTF-32LE string
    // Output:
    //  - r0: Char
    // char32_t lastchar(int dummy, const char32_t *str);
lastchar:
.Lloop:
    // load 1 char, advance pointer
    ldmia   r1!, {r0}
    // Load next char into temp
    ldr     r3, [r1]
    // compare and loop if r3 wasn't a null terminator
    cmp     r3, #0
    bne     .Lloop
    // return in r0
    bx      lr

```

This uses the same function signature, taking a null terminated UTF-32 string and a dummy parameter to put `str` in `r1`:

```
char32_t lastchar(int dummy /* r0 */, const char32_t *str /* r1 */);

```

In an ideal world, the direct equivalent could be done:

```
lastchar:
.Lloop:
    ldrd    r0, r3, [r1], #4
    cbnz    r3, .Lloop
    bx      lr

```

But unfortunately:

* `ldrd` will bus error if the pointer is not 8 byte aligned (even with unaligned access support), and advancing the pointer by 4 will end up unaligned.
* `ldmia` always advanced by `4 * NumRegisters`
* `cbnz` can only branch forwards
> 1 votes

# Answer
# Python 3, 16 bytes

This is a pretty basic answer, but I think that it is the lowest Python 3 can go...

```
x=lambda a:a[-1]

```

TIO
> 0 votes

# Answer
# T-SQL, 23 bytes

```
SELECT RIGHT(v,1)FROM i

```

Didn't see a SQL solution yet.

Input is via a pre-existing table \\$i\\$ with `varchar` field \\$v\\$, per our IO rules.
> 0 votes

# Answer
# Perl 5, 7 bytes

```
$_=chop

```

This must be executed using the `-pe` flags.

## Example

```
$ echo -n "abcd" | perl -pe '$_=chop'
d

```

## Explanation

The `-p` flag wraps code inside a block that appears as: `while (<>) { ... ; print }` whereas the '...' would include the code provided. The entire script would expand to:

```
while (<>) { $_ = chop ; print }

```

What I did here was set the context variable `$_` to the return value of chop, which returns the last character of a string. Shortly after, `print` with no statements on its own will display the previously assigned context variable.
> 0 votes

# Answer
# Zsh, 11 bytes

try it online!!

```
<<<${1: -1}

```

clone of the `bash` answer, 2 bytes shorter
> 0 votes

# Answer
# Pushy, 1 byte

```
'

```

Try it online!

Print the top of stack as a character!
> 0 votes

# Answer
# Scala, 6 bytes

```
_.last

```

Try it online!

Not much to say here - it's just a function that takes a string (or really any iterable) and outputs its last element.
> 0 votes

# Answer
# MathGolf, 2 bytes

```
┤Þ

```

Try it online.

Or alternatively:

Try it online.

**Explanation:**

```
┤   # Pop the left character of the (implicit) input-string loose to the stack
 Þ  # Only leave the top item of the stack, and discard everything else
    # (implicitly output the entire stack joined together)

b   # Push -1
 §  # Get the -1'th character of the (implicit) input-string
    # (0-based modulair similar as Python, so will index into the last character)
    # (implicitly output the entire stack joined together)

```
> 0 votes

# Answer
# Rockstar, 30 bytes

```
listen to S
cut S
say S at S-1

```

Try it here (Code will need to be pasted in)

Or 51 bytes if we need to be able to handle newlines in the input:

```
listen to S
while S
listen to S

cut S
say S at S-1

```
> 0 votes

# Answer
# 05AB1E, 1 byte

```
θ

```

Try it online!

```
   # (implicit) push STDIN to stack
θ  # push last character of top of stack
   # (implicit) output top of stack to STDOUT

```
> 0 votes

# Answer
# CSASM v2.2.1.1, 46 bytes

```
func main:
in ""
push ^1
push ^0
substr
print
ret
end

```

**Commented:**

```
func main:
    ; Get the input
    in ""
    ; Get a substring of the input from (length - 1) to (length - 0)
    push ^1
    push ^0
    substr
    ; Print it
    print
    ret
end

```
> 0 votes

# Answer
# Duocentehexaquinquagesimal, 3 bytes

```
t`F

```

Try it online!
> 0 votes

# Answer
# , 2 bytes

```
{:

```

`{:` is implicit verb for last element of any array (including strings)

Try it online!
> 0 votes

# Answer
# Factor, 11 bytes

```
[ 1 tail* ]

```

Try it online!
> 0 votes

# Answer
# M4, 36 bytes

```
define(f,`substr($1,decr(len($1)))')

```

Attempt This Online!
> 0 votes

# Answer
# Brainfuck, 11 bytes

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

```

Explained:

```
,> [ ,> ]   get input
  + -  +    sentinels
         <. output last non-NUL byte (NUL doesn't count, doesn't it?)

```
> 0 votes

# Answer
# MAWP, 2 bytes

```
|;

```

Try it!

Explanation:

```
|      take whole input onto stack as ASCII value
 ;     output top of stack

```
> 0 votes

# Answer
# Go, 38 bytes

```
func(s []byte)byte{return s[len(s)-1]}

```

Attempt This Online!
> 0 votes

# Answer
# Standard ML, 8 bytes

There are two common ways of string processing: char lists and strings. In both cases, the underlying char is an 8 bit value using "extended ASCII".

For char lists:

```
hd o rev

```

I'm not sure why `List.last` isn't top-level, but that works too.

For strings, convert to List and use `explode`:

```
hd o rev o explode

```
> 0 votes

# Answer
# Vyxal, 1 byte

```
t

```

Try it Online!
> 0 votes

# Answer
# JavaScript (Node.js), 10 bytes

Assumes every byte is a letter one of `0` through `9`. Is this justified?

```
s=>s%10+""

```

Attempt This Online!
> 0 votes

# Answer
# Thunno 2 `t`, 0 bytes

Attempt This Online!

That's right: no bytes. The `t` flag does all the work.

Or **1 byte** flagless:

```
t

```

Attempt This Online!

Built-in for last item.
> 0 votes

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