title: Slowly turn a string into another

text:
# Question
Title: Slowly turn a string into another
## The Challenge

Given two strings/an array of strings, output the first string slowly shrinking and expanding back into the second string.

You can assume the strings will always start with the same character.

## Example

```
Input:
"Test", "Testing"

Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing

```

First you output the first word:

```
Test

```

Then you keep removing one letter until the string is one character long:

```
Tes
Te
T

```

Then keep adding one letter of the second word until it's done:

```
Te
Tes
Test
Testi
Testin
Testing

```

(if both strings are one character long, then just output one of them once.)

## Test Cases

```
"Hello!", "Hi."
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.

"O", "O"

O

"z", "zz"

z
zz

".vimrc", ".minecraft"

.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft

"     ", "   "

SSSSS
SSSS
SSS
SS
S
SS
SSS

"0123456789", "02468"

0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0
02
024
0246
02468

```

*(note: on the space/fourth test case, replace the S with spaces)*

## Rules

* This is , so shortest answer in bytes wins! Tiebreaker is most upvoted post. Winner will be chosen on 09/10/2016.
* Standard loopholes are forbidden.

# Answer
# Pyth, 9 bytes

```
j+_._Et._

```

A program that takes the second string, and then the first string, as quoted strings on STDIN and prints the result.

Try it online

**How it works**

```
j+_._Et._  Program. Inputs: Q, E
   ._E     Yield prefixes of E as a list
  _        Reverse the above
       ._  Yield prefixes of Q as a list (implicit input fill)
      t    All but the first element of above
 +         Merge the two lists
j          Join on newlines
           Implicitly print

```
> 11 votes

# Answer
# , 14 bytes

```
òYp$xhòjòÄ$xhh

```

Try it online!

Explanation:

```
ò     ò     "Recursively:
 Yp         "  Yank the current line and paste it
   $        "  Move to the end of the current line
    x       "  Delete one character
     h      "  Move One character to the right.
            "  Because of the way loops work in V, this will throw an error if there
            "  Is only one character on the current line.

```

Now, the buffer looks like this:

```
0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0

```

We just need to do the same thing in reverse for the next line:

```
j           "Move down one line
 ò     ò    "Recursively (The second ò is implicit)
  Ä         "  Duplicate this line up
   $        "  Move to the end of the current line
    x       "  Delete one character
     hh     "  Move two characters to the right.
            "  Because of the way loops work in V, this will throw an error if there
            "  Is only two characters on the current line.

```

More interesting alternate solution:

```
òÄ$xhòç^/:m0
ddGp@qd

```
> 14 votes

# Answer
# Python, 93 bytes

```
f=lambda a,b,r='',i=2:a and f(a[:-1],b,r+a+'\n')or(len(b)>=i and f(a,b,r+b[:i]+'\n',i+1)or r)

```

Starts with the empty string `r`, adds `a` and a newline and removes the last character from `a` until `a` is empty then adds the required portions of `b` and a newline by keeping a counter, `i`, which starts at `2` until the length of `b` is exceeded, then returns `r`. Has a trailing newline.

All tests are on **ideone**
> 9 votes

# Answer
# Retina, ~~50~~ ~~41~~ 26 bytes

Thanks to Martin Ender for saving 15(!) bytes.

```
M&!r`.+
Om`^.¶[^·]+|.+
A1`

```

Takes input with the two strings separated by a newline:

```
Test
Testing

```

Try it online!

## Explanation

```
M&!r`.+

```

The first line generates the "steps" of both words:

```
Testing
Testin
Testi
Test
Tes
Te
T
Test
Tes
Te
T

```

`M` is for match mode, `&` considers overlapping matches, and `!` prints the matches instead of the number of them. The reason it's reversed is the `r`ight-to-left option: the engine starts looking for matches at the end of the string and continues toward the beginning.

```
Om`^.¶[^·]+|.+

```

This gets everything in the right order: it s`O`rts all matches of the subsequent regex: A character on its own line and every character (including newlines) after it, which matches the whole second half as one chunk, or otherwise a line of characters, which matches each individual line. These matches are then sorted by code point, so the T followed by the newline goes first, followed by the lines, ascending by length.

```
A1`

```

Now we just have that first character line on top so we use `A`ntigrep mode to discard the first match of the default regex `.+`.

## Old version

```
M&!r`.+
O`\G..+¶
s`(.*)¶.¶(.*)
$2¶$1
¶.$

```

Try this version online!

### Explanation

The first line is the same, so see the explanation for that above.

```
O`\G..+¶

```

This reverses the lines of the first half (second input word). It actually s`O`rts the lines, and the regex limits the matches: it must be a line of two or more characters (`..+`) followed by a newline () that begins where the last one left off (`\G`). In the above example, the single `T` in the middle doesn't match, so nothing after it can.

```
Te
Tes
Test
Testi
Testin
Testing
T
Test
Tes
Te
T

```

Now we have the right two components, but in the wrong order.

```
s`(.*)¶.¶(.*)
$2¶$1

```

`¶.¶` matches the lone T in the middle, which we don't need but separates the two parts. The two `(.*)` capture everything before and after, including newlines thanks to `s`ingle-line mode. The two captures are substituted in the right order with a newline in between.

Now we're done, unless the input strings are one character long, in which case the input hasn't changed. To get rid of the duplicate, we replace `¶.$` (when the last line of the string a single character) with nothing.
> 7 votes

# Answer
# 05AB1E, 9 bytes

```
.pRI.p¦«»

```

**Explanation**

```
.pR           # prefixes of first word
     I.p       # prefixes of second word
         ¦       # remove first prefix
          «     # concatenate
           »    # join with newlines

```

Try it online!
> 7 votes

# Answer
# Python 2, ~~88~~ 82 bytes

```
x,y=input(),input()
for i in x:print x;x=x[:-1]
s=y[0]
for i in y[1:]:s+=i;print s

```

Takes two inputs, each surrounded by quotes.

Thanks @JonathanAllan for saving some bytes and pointing out a bug.
> 4 votes

# Answer
# Perl, ~~34~~ 28 bytes

Includes `+2` for `-0n`

Run with the strings on separate lines on STDIN:

```
perl -M5.010 -0n slow.pl
Test
Testing
^D

```

`slow.pl`:

```
/(^..+|
\K.+?)(?{say$&})^/

```

Let regex backtracking do the work...
> 4 votes

# Answer
# C (gcc), ~~102~~ ~~97~~ ~~95~~ 93 bytes

```
n;f(char*a,char*b){for(n=strlen(a);n;puts(a))a[n--]=0;for(a=b+1;*a++;*a=n)n=*a,*a=0,puts(b);}

```

Try it online!

The first loop overwrites the string with 0 bytes starting from the end, and uses `puts()` to print the string. The second loop can't just overwrite from the beginning, it has to store the old value so it can put it back; the 0 byte is just walking towards the end.

Thanks to @homersimpson and @ceilingcat for each shaving off 2 bytes!
> 4 votes

# Answer
# Python 3, 104 bytes

Meh.

```
n='\n';lambda x,y:x+n+n.join(x[:-i]for i in range(1,len(x)-1))+n+n.join(y[:i]for i in range(1,len(y)+1))

```

Thanks to @DJMcMayhem for golfing 21 bytes off.

**Ideone it!**
> 3 votes

# Answer
# Javascript, 103 81 bytes

```
f=(x,y,n=1)=>x?`
`+x+f(x.slice(0,-1),y):n++<y.length?`
`+y.slice(0,n)+f(x,y,n):''

```

Example: `f("Test", "Testing")`

Output:

```
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing

```

Original answer

```
f=(x,y,n=1)=>x?(console.log(x),f(x.slice(0,-1),y)):n++<y.length?(console.log(y.slice(0,n)),f(x,y,n)):''

```
> 3 votes

# Answer
# Cheddar, 76 bytes

```
(a,b,q=s->(|>s.len).map((_,i)->s.head(i+1)))->(q(a).rev+q(b).slice(1)).vfuse

```

A bit longer than I'd liked. I'll add an explanation soon

Try it online!
> 3 votes

# Answer
# Brachylog, 32 bytes

```
:1aLtT,Lhbr:Tc~@nw
:2fb
~c[A:B]h

```

Try it online!

### Explanation

Brachylog has no prefix built-in, therefore we will get the prefixes by using `concatenate` (See predicate 2): a prefix of `S` is `P` if `P` concatenated to `Q` (whatever it is) results in `S`.

* Main predicate:

```
:1aL                  L is all prefixes of both elements of the input (see predicate 1)
   LtT,               T is the second element of L
       Lhbr           Remove the first prefix of the first list of L and reverse it
           :Tc        Concatenate with T
              ~@n     Join with newlines
                 w    Write to STDOUT

```
* Predicate 1:

```
:2f                   Find all prefixes of the input string (see predicate 2)
   b                  Remove the first one (empty string)

```
* Predicate 2:

```
~c[A:B]               Input is the result of concatenating A to B
       h              Output is A

```
> 3 votes

# Answer
## Pyke, 14 bytes

```
VDO)KKQlFh<)_X

```

Try it here!

And 17 bytes just because it's an awesome solution:

```
mVDO)Fto!I_O(RKsX

```

Try it here!
> 3 votes

# Answer
# Java, ~~188~~ 179 bytes

```
interface E{static void main(String[]a){int i=a[0].length();while(i>1)System.out.println(a[0].substring(0,i--));while(i<=a[1].length())System.out.println(a[1].substring(0,i++));}}

```

**Update**

* Removed s variable, saved 9 bytes

**Ungolfed**:

```
interface E {

    static void main(String[] a) {
        int i = a[0].length();
        while (i > 1) {
            System.out.println(a[0].substring(0, i--));
        }
        while (i <= a[1].length()) {
            System.out.println(a[1].substring(0, i++));
        }
    }
}

```

**Usage**:

```
$ java E 'test' 'testing'
test
tes
te
t
te
tes
test
testi
testin
testing

```
> 3 votes

# Answer
## Haskell, ~~54~~ ~~53~~ 47 bytes

```
t[]=[]
t x=x:t(init x)
(.reverse.t).(++).init.t

```

Usage example: `((.reverse.t).(++).init.t) "Hello" "Hi!"` -\> `["Hello","Hell","Hel","He","H","Hi","Hi!"]`.

Some pointfree magic. It's the same as `f x y = (init(t x))++reverse (t y)` where `t` makes a list of all initial substrings e.g. `t "HI!"` -\> `["H","HI","HI!"]`.
> 3 votes

# Answer
## GNU sed, ~~57~~ 45 + 2(rn flags) = 47 bytes

```
:;1{/../p};2G;2h;s/.(\n.*)?$//;/./t;g;s/.$//p

```

**Run:**

```
echo -e "Test\nTesting" | sed -rnf morphing_string.sed

```

The input should be the two strings separated by a newline. The code is run by sed for each line.

The loop `:` deletes one character from the end of the string iteratively. The output related to the first string is printed directly, except the first character: `1{/../p}`. The output for the second string is stored in hold space in reverse order (`2G;2h`) during deletion and printed at the end.
> 3 votes

# Answer
# Floroid, 69 bytes

```
a,b=L.J
c=1
NZ(a)!=1:z(a);a=a[:-1]
z(a)
NZ(a)!=Z(b):c+=1;a=b[:c];z(a)

```

It's a start. Takes the input from STDIN.

## Testcases

```
Input: Test Testing
Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing

Input: O O
Output: O

```
> 2 votes

# Answer
# REPL/Javascript, 109 Bytes

Uses false string to whittle down the original string

Abuses substring with larger numbers to grow the second one, stops when its about to print the same word as last time.

```
(a,b)=>{l=console.log;z='substring';for(c=a.length;d=a[z](0,c--);){l(d)}for(c=2;d!=(n=b[z](0,c++));){l(d=n)}}

```

Demo:

```
> ((a,b)=>{l=console.log;z='substring';for(c=a.length;d=a[z](0,c--);){l(d)}for(c=2;d!=(n=b[z](0,c++));){l(d=n)}})("asdf","abcd")
[Log] asdf
[Log] asd
[Log] as
[Log] a
[Log] ab
[Log] abc
[Log] abcd

```
> 2 votes

# Answer
# Racket 193 bytes

```
(define(f l)
(let*((s(list-ref l 0))
(x(string-length s)))
(for((n x))
(println(substring s 0(- x n))))
(set! s(list-ref l 1))
(for((n(range 1(string-length s))))
(println(substring s 0(add1 n))))))

```

Testing:

```
(f(list "Test" "Testing"))

"Test"
"Tes"
"Te"
"T"
"Te"
"Tes"
"Test"
"Testi"
"Testin"
"Testing"

(f(list "Hello!" "Hi."))

"Hello!"
"Hello"
"Hell"
"Hel"
"He"
"H"
"Hi"
"Hi."

```
> 2 votes

# Answer
## Brainfuck, 38 55 bytes

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

```

Edit: included newlines in output
> 2 votes

# Answer
# Dyalog APL, ~~20~~ 13 bytes

```
↑(⌽,\⍞),1↓,\⍞

```

matrify

`(⌽,\⍞)` reversed () cumulative concatenation (`,\`) of character input ()

`,` prepended to

`1↓` one element dropped from

`,\⍞` cumulative concatenation of character input

TryAPL online!
> 2 votes

# Answer
# Husk, 7 bytes

```
+↔ḣ²tḣ⁰

```

Try it online!
> 2 votes

# Answer
# Canvas, 8 bytes

```
［］↕ｋ；［］∔

```

Try it here!

Explanation:
```
[]↕k;[]+ | Full program (characters replaced for clean formatting)
---------+--------------------------------------------------------
[]       | Prefixes of first input
  ↕      | Reversed
   k     | Remove the last item
    ;    | Swap (places the second input on top)
     []  | Prefixes of second input
       + | Add vertically

```
> 2 votes

# Answer
# Thunno 2 `N`, 6 bytes

```
€ƒẸrsḥ

```

Try it online!

Takes inputs in reverse order.

#### Explanation

```
€ƒẸrsḥ  # Implicit input
€ƒ      # Prefixes of each
  Ẹr    # Dump and reverse
    sḥ  # Swap and concatenate
        # Implicit output

```
> 2 votes

# Answer
# Python, 88 bytes (function) (92 for lambda) (beginner)

As lambda-function (92 bytes):

```
f=lambda A,B:"\n".join([(A+" ")[:-i]for i in range(len(A))]+[B[:i+1]for i in range(len(B))])

```

As function:

```
def f(a,b,c=""):
 while a!=b[0]and a:print(a);a=a[:-1]
 while b:c+=b[0];b=b[1:];print(c)

```

In code: or 72 bytes (from 93 bytes) Shall 'a' be the word to decrease an 'b' be the word to raise up to, this should do:

```
for i in range(len(a)+(a[0]!=b[0])):print((a+"_")[:-i])
for k in range(len(b)):print(b[:k+1])

```

or with 72 chars

```
c=""
while a!=b[0]and a:print(a);a=a[:-1]
while b:c+=b[0];b=b[1:];print(c)

```

Apart from the lambda-version my solutions will work even with the strings starting differently (overread that part o.0 )
> 1 votes

# Answer
## JavaScript (ES6), 92 bytes

```
(s,t)=>s.replace(/./g,`
$\`$&`).split`
`.slice(2).reverse().join`
`+t.replace(/./g,`
$\`$&`)

```

The `replace` statements build up a triangle of strings, which is exactly what's required for the second half of the output, however the first half needs to be reversed and the duplicate single-character line removed. Note: outputs a leading newline if the first string is a single character. If this is undesirable then for an extra byte this version always outputs a trailing newline:

```
(s,t)=>s.replace(/./g,`
$\`$&\n`).split(/^/m).slice(1).reverse().join``+t.replace(/./g,`
$\`$&\n`)

```
> 1 votes

# Answer
# C, 142 bytes

```
#define _(x,y) while(y)printf("%.*s\n",d,x-c);
f(char*a,char*b){int c=1,d=strlen(a)+1;while(*++a==*++b)c++;_(a,--d>=c)d++;_(b,d++<strlen(b-c))}

```

Provide `f(char* str1, char* str2)`.
> 1 votes

# Answer
# TI-Basic, 56 bytes

```
Prompt Str1,Str2
Str1
While 1<length(Ans
Disp Ans
sub(Ans,1,length(Ans)-1
End
For(I,1,length(Str2
Disp sub(Str2,1,I
End

```

**Example usage**

```
Str1=?Test
Str2=?Testing
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing

Str1=?O
Str2=?O
O

Str1=?z
Str2=?zz
z
zz

```
> 1 votes

# Answer
# Java, ~~168~~ 136 bytes

```
(s,d)->{int i=s.length()+1;while(i-->1)System.out.println(s.substring(0,i));while(i++<d.length())System.out.println(d.substring(0,i));};

```

# Ungolfed test program

```
public static void main(String[] args) {

    BiConsumer<String, String> biconsumer = (s, d) -> {
        int i = s.length() + 1;
        while (i-- > 1) {
            System.out.println(s.substring(0, i));
        }
        while (i++ < d.length()) {
            System.out.println(d.substring(0, i));
        }
    };

    biconsumer.accept("Test", "Testing123");

}

```
> 1 votes

# Answer
# C, 100 bytes

```
n;f(char*c,char*s){n=strlen(c);while(n)printf("%.*s\n",n--,c);for(n=1;s[n++];)printf("%.*s\n",n,s);}

```

**Ungolfed test**

```
#include <stdio.h>
#include <string.h>
n;
f(char*c,char*s)
{
    n=strlen(c);
    while(n)
        printf("%.*s\n",n--,c);
    for(n=1;s[n++];)
        printf("%.*s\n",n,s);
}

int main(void)
{
    char * s1 = "Test";
    char * s2 = "Testing";
    f(s1, s2);
    return 0;
}

```
> 1 votes

# Answer
# PHP, ~~117~~ 109 bytes

```
for($i=strlen($a=$argv[1]);$i>1;)echo" ".substr($a,0,$i--);
for(;$j<strlen($b=$argv[2]);)echo" ".$c.=$b[$j++];

```
~~```
for($i=strlen($a=$argv[1]);$i>1;)echo substr($a,0,$i--)." ";
for(;$i<=strlen($b=$argv[2]);)echo substr($b,0,$i++)." ";

```~~

### PHP, 107 bytes (not working with strings containing `0`)

```
for($a=$argv[1];$a[$i];)echo substr($a.a,0,-++$i)." ";
for($b=$argv[2];$b[$j];)echo substr($b,0,++$j+1)." ";

```
> 1 votes

# Answer
# C#, 129 bytes

```
void f(string i, string j){for(int k=i.Length,l=0;i!=j;){Console.Write(i+'\n');i=k>1?i.Remove(--k):i+j[k+l++];}Console.Write(i);}

```

**Ungolfed**

```
void f(string i, string j)
{
   for (int k = i.Length, l = 0; i != j; )
   {
      Console.Write(i+'\n');
      i = k > 1 ? i.Remove(--k) : i + j[k + l++];
   }
   Console.Write(i);
}

```
> 1 votes

# Answer
# C++, 120 bytes

```
[](string s,string t){int n=s.length(),k=t.length(),l=n,j=0;s+=t;while(n?n:++j<k)cout<<s.substr(n?0:l,n?n--:1+j)<<endl;}

```

**Ungolfed test**

```
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
    string s1 = "Test";
    string s2 = "Testing";
    auto f = [](string s, string t)
    {
        int n = s.length(),
            k = t.length(),
            l = n,
            j = 0;
        s += t;
        while (n?n:++j<k)
            cout << s.substr( n?0:l, n?n--:1+j) << endl;
    };
    f(s1, s2);
    return 0;
}

```
> 1 votes

# Answer
# (Lambdabot) Haskell - 41 bytes

```
f=(.drop 2.inits).(++).reverse.tail.inits

```

More readable, but two bytes longer:

```
a!b=(reverse.tail$inits a)++drop 2(inits b)

```

Output:

```
f "Hello" "Hi!"
["Hello","Hell","Hel","He","H","Hi","Hi!"]

```
> 1 votes

# Answer
# J, 18 bytes

```
]\@],~[:}:[:|.]\@[

```

Ungolfed:

```
]\@] ,~ [: }: [: |. ]\@[

```

This is a 7-train:

```
]\@] ,~ ([: }: ([: |. ]\@[))

```

The innermost train `[: |. ]\@[` consists of a cap `[:` on the left, so we apply `|.` (reverse) to the result of `]\@[`, which is `]\` (prefixes) over `[` (left argument).

Here's what that looks like on the `testing, test` input:

```
   'testing' ([: |. ]\@]) 'test'
test
tes
te
t

```

This gives us the first portion, almost. The 5-train outside of that is `([: }: ([: |. ]\@[))`, which applies `}:` (betail, remove last element) to the above expression:

```
   'testing' ([: }: [: |. ]\@]) 'test'
test
tes
te

```

(This is because we can't have a duplicate midpoint.)

The outer part is finally:

```
]\@] ,~ ([: }: ([: |. ]\@[))

```

This is composed of `]\@]` (prefixes of left argument) and `,~` (append what's to the left with what's to the right), leaving us with the desired result:

```
   'testing' (]\@] ,~ ([: }: ([: |. ]\@[))) 'test'
testing
testin
testi
test
tes
te
t
te
tes
test

```

## Test cases

```
   k =: ]\@] ,~ ([: }: ([: |. ]\@[))
   'o' k 'o'
o
   k~ 'o'
o
   'test' k 'test'
test
tes
te
t
te
tes
test
   k~ 'test'
test
tes
te
t
te
tes
test
   '. . .' k '...'
. . .
. .
. .
.
.
..
...
   'z' k 'zz'
z
zz

```
> 1 votes

# Answer
# C, 111 bytes

```
f(char*a, char*b){int l=strlen(a),k=1;while(*a){printf("%s\n",a);a[--l]=0;}while(b[k]) printf("%.*s\n",++k,b);}

```

**Ungolfed test**

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

f(char*a, char*b) {
  int l=strlen(a), k=1;
  while(*a) {
    printf("%s\n",a);
    a[--l]=0;
  }
  while(b[k])
    printf("%.*s\n",++k,b);
}

int main() {
  char a[10] = {0};
  char b[10] = {0};

  for (int i=0; i<5; ++i) {
    a[i] = 'a' + i;
    b[i] = 'a' + i*2;
  }

  f(&(a[0]), &(b[0]));
}

```
> 1 votes

# Answer
# brainfuck, 162 bytes

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

```

Try it here

Input takes the two strings separated by a linefeed.

First program with brianfuck and first code golf so I'm sure there is plenty of optimization to be done. Had fun doing it though.

Ungolfed

```
,[>,] Read all input
++++++++++ Flag for 10
[                   Subtract 10 from each cell to flag space for blank
    [-<]
    >
        [->]
        <
]
++++++++++ Flag for 10
[                   Add 10 back to each cell with value in it
    <[+<]<[+<]
    >[+>]>[+>]<---
]
<[<]<[<]>               goto first cell in first string string

[                           Print first word subtracting one each time
    [.>]                    Print first string
    ++++++++++.----------   Print new line
    <[-]                    Kill last letter of first string
    <                       Back one
    [                       Move each first string character up one
          [->+<]
          <
    ]>>
]
>[<+>-]>                    Move to first letter of scond string back one goto second letter
[
    [<+>-]                  Move next letter back
    <[<]>                   Move to start of string
    [.>]                    Print string
    ++++++++++.----------   Print new line
    >
]

```
> 1 votes

# Answer
# Python 2, 76 bytes

```
lambda s,t:'\n'.join(g(s)[:-1]+g(t)[::-1])
g=lambda s:s and[s]+g(s[:-1])or[]

```

Try it online!
> 1 votes

# Answer
# Vyxal `j`, 45 bits<sup>v2</sup>, 5.625 bytes

```
¦Ṙ?¦ḢJ

```

Try it Online!

## Explained

```
¦Ṙ?¦ḢJ
¦Ṙ      # [prefixes of the first string] reversed
  ?¦Ḣ   # [prefixes of the second string] with the first prefix removed
     J  # Merged into a single list
# Joined on newlines by the j flag

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Alice, 29 bytes

```
/OM!w@On;?$!?/
KMd!h.$t..wKh\

```

Try it online!

```
/MM!w.Ot;.$K?h!w?.n$@h!dOK    Full program untangled
/MM                           Puts the two arguments as strings on the stack
   !                          Pops the second string and save it on the tape
    w    .$K                  While the string still have characters
     .O                       Print the string
       t;                     Remove the last character from the string
                              First string done, now second one
                              As the first letter is the same:
            ?                 Get the string from the tape
             h!               Keep the first character on the stack, save the rest on the tape
               w?.n$@    K    While there are still characters to read on the tape
                     h!       Get the first character, put the rest on the tape
                       dO     Join the stack into a new string and print it

```
> 1 votes

# Answer
# Raku (Perl 6) (rakudo), 56 bytes

```
{join "\n",reverse([\~] $^a.comb),([\~] $^b.comb)[1..*]}

```

Attempt This Online!
> 1 votes

# Answer
## PowerShell v2+, 99 bytes

```
param($a,$b)if($a-eq$b){$a;exit}$a.length..1|%{-join$a[0..--$_]};1..($b.length-1)|%{-join$b[0..$_]}

```

Straightforward. Loops downward through the first string `$a`, then loops upward through the second string `$b`. Has some additional logic at the start where if the strings are equal, so that it only outputs once then `exit`s. The loop indices are off from each other to account for fenceposting.
> 0 votes

# Answer
I guess I can beat a few with Groovy here...

# Groovy (96 Bytes)

```
def x(a,b,c){(a..b).each{println c.substring(0,it)}};{y,z->x(y.length(),1,y);x(1,z.length(),z);}

```

Try it: https://groovyconsole.appspot.com/script/5190971159478272

Explanation:

* X is a closure to print the substring from 0 to x from (a to b) for all integers from a to b.
* The second closure passes the first word from it's length to 1 then does the second word in reverse order.
> 0 votes

# Answer
# JavaScript (ES6), 75 bytes

```
f=(x,y,n=1)=>x||n++<y.length?(x||y.slice(0,n))+`
`+f(x.slice(0,-1),y,n):''

```

**Explanation**

```
f=(x,y,n=1)=>               //Take 2 inputs, initialize n to 1.
  x||n++<y.length?          //Increment n only if x doesn't have a value (short circuit).
  (x||y.slice(0,n))+`       //If x has a value, return it; otherwise, return y sliced.
  `+f(x.slice(0,-1),y,n):'' //Recurse, removing last char of x. No problem if x is empty.

```

**Snippet**

```
f=(x,y,n=1)=>x||n++<y.length?(x||y.slice(0,n))+`
`+f(x.slice(0,-1),y,n):''

console.log(f('Test','Testing'));
console.log(f('O','O'));
console.log(f('z','zz'));
console.log(f("0123456789", "02468"));
```
> 0 votes

# Answer
# Ruby, 63 bytes

```
->a,b{f=->s{(1..s.size).map{|l|s[0,l]}};puts f[a].reverse+f[b]}

```

It's an anonymous function taking two strings:

```
$ irb
2.3.0 :001 > ->a,b{f=->s{(1..s.size).map{|l|s[0,l]}};puts f[a].reverse+f[b]}["hey","you"]
hey
he
h
y
yo
you

```
> 0 votes

# Answer
# Gura, 115 bytes

```
t(a,b)={c=a.len()-1;for(i in 0..c){print(a[0..(c-i)]);println();}for(i in 1..b.len()-1){print(b[0..i]);println();}}

```

Just discovered this language on Github, it's pretty good !
> 0 votes

# Answer
# JavaScript (Node.js), 94 92 bytes

```
(x,y)=>[x,y].map(z=>[...z].map(e=>z.substr(0,Math.abs(i--)||--i)).join`
`,i=x.length).join``

```

Try it online!
> 0 votes

# Answer
# Powershell, 88 bytes

```
param($a,$b)@()+($a.Length..1|%{-join$a[0..--$_]})+(2..$b.Length|%{-join$b[0..--$_]})|gu

```

Ungolfed test script:

```
$f = {

param($a,$b)
@()+
($a.Length..1|%{-join$a[0..--$_]})+
(1..$b.Length|%{-join$b[0..--$_]})|
gu

}

@(
    ,('O', 'O', 'O')
    ,('Test', 'Testing', 'Test Tes Te T Te Tes Test Testi Testin Testing')
    ,('Hello!', 'Hi.', 'Hello! Hello Hell Hel He H Hi Hi.')
    ,('z', 'zz', 'z zz')
    ,('.vimrc', '.minecraft', '.vimrc .vimr .vim .vi .v . .m .mi .min .mine .minec .minecr .minecra .minecraf .minecraft')
) | % {
    $a, $b, $e = $_
    $r = &$f $a $b
    "$r"-eq"$e"
    $r
    ''
}

```

Test script output:

```
True
O

True
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing

True
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.

True
z
zz

True
.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft

```

Expalantion:

The sum of arrays puts by pipes to `gu` (alias for Get-Unique). The `gu` eliminates double strings.
> 0 votes

# Answer
# Forth (gforth), 65 bytes

```
: f dup 1 do 2dup cr type 1- loop 2drop 1 do dup cr i type loop ;

```

Try it online!

Takes arguments in order on the stack (will look like reverse order in code)

### Explanation

Loops from 1 to string1-length outputting the increasingly smaller string each time. Then loops from 1 to string2-length + 1, outputting the increasingly larger string each time

### Code Explanation

```
: f                    \ begin word definition
  dup 1 do             \ duplicate the string length, then loop from 1 to string-length
    2dup               \ duplicate string address and length
    cr type            \ output a newline, then print the word to the given length
    1-                 \ subtract 1 from string length
  loop                 \ end the loop
  2drop                \ drop address and string length of first string
  1 do                 \ loop from 1 to string2-length
    dup                \ duplicate string address
    cr i type          \ output a new line then print the first i characters of the string
  loop                 \ end the loop
;                      \ end the string definition

```
> 0 votes

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


# Question
Title: Randomly select a character, plinko-style
Let's see how good your language of choice is at selective randomness.

Given 4 characters, `A`, `B`, `C`, and `D`, or a string of 4 characters `ABCD` **as input**, output one of the characters with the following probabilities:

* `A` should have a 1/8 (12.5%) chance to be chosen
* `B` should have a 3/8 (37.5%) chance to be chosen
* `C` should have a 2/8 (25%) chance to be chosen
* `D` should have a 2/8 (25%) chance to be chosen

This is in-line with the following Plinko machine layout:

```
   ^
  ^ ^
 ^ ^ ^
A B \ /
     ^
    C D

```

Your answer must make a genuine attempt at respecting the probabilities described. A proper explanation of how probabilities are computed in your answer (and why they respect the specs, disregarding pseudo-randomness and big numbers problems) is sufficient.

## Scoring

This is so fewest bytes **in each language** wins!

# Answer
# Lean Mean Bean Machine, ~~55~~ ~~43~~ 42 bytes

*-13 bytes thanks to Alex Varga*

```
  O
  i
  ^
 ^ ^
\ ^ ^
 i / U
 ii
 ^
i U
U

```

Hope you guys don't mind me answering my own question after only 2 hours, but I highly doubt anybody else was planning on posting an answer in LMBM.

This literally just reflects the Plinko layout shown in the OP, flipped horizontally to cut down on unnecessary whitespace.
> 14 votes

# Answer
# Jelly, 6 bytes

```
Ḋṁ7;ḢX

```

A monadic link taking a list of four characters and returning one with the probability distribution described.

**Try it online!**

### How?

```
Ḋṁ7;ḢX - Link: list of characters, s  e.g. ABCD
Ḋ      - dequeue s                         BCD
 ṁ7    - mould like 7 (implicit range)     BCDBCDB
    Ḣ  - head s                            A
   ;   - concatenate                       BCDBCDBA
     X - random choice                     Note that the above has 1*A, 3*B, 2*C, and 2*D

```
> 9 votes

# Answer
# Cubix, ~~39~~ ~~24~~ ~~22~~ ~~21~~ 19 bytes

```
.<.^iD>D|@oioi.\i;U

```

**View in the online interpreter!**

This maps out to the following cube net:

```
    . <
    . ^
i D > D | @ o i
o i . \ i ; U .
    . .
    . .

```

# Random Distribution Implementation Explanation

Cubix is a language in which an instruction pointer travels around the faces of a cube, executing the commands it encounters. The only form of randomness is the command `D`, which sends the IP in a random direction: an equal chance of `1/4` each way.

However, we can use this to generate the correct weighted probabilites: by using `D` twice. The first `D` has a `1/4` of heading to a second `D`. This second `D`, however, has two directions blocked off with arrows (`> D <`) which send the instruction pointer back to the `D` to choose another direction. This means there are only two possible directions from there, each with a `1/8` overall chance of happening. This can be used to generate the correct character, as shown in the diagram below:

(Note that, in the actual code, the arrow on the right is replaced with a mirror, `|`)

# Code Explanation

```
        . <
        . ^
IP> i D > D | @ o i
    o i . \ i ; U .
        . .
        . .

```

The instruction pointer starts on the right, at the character `i`, facing right. It executes this `i`, taking the first character as input, and then moves onto the `D`, beginning the random process shown above.

* **Char A:** In the case that the first `D` sends us east, and the second south, we need to print character A. This is already on stack from the first `i`. The following is executed:

+ `\` \- Reflect the IP so it heads east
    + `i;` \- Take an input, then pop it again (no-op)
    + `U` \- Perform a U-turn, turning the IP left twice
    + `o` \- Output the TOS, character A
    + `@` \- Terminate the program
* **Char B:** If either the first or second `D` head north, we need to generate character B, which will be the next input. Both paths execute the following commands:

+ `^` \- Head north
    + `<` \- Head west, wrapping round to...
    + `i` \- Take another input, character B
    + `o` \- Output the TOS, character B
    + `;` \- Pop the TOS
    + `@` \- Terminate the program
* **Char C:** If the first `D` sends us west, the following is executed:

+ `i` \- Take another input, character B
    + `i` \- Take another input, character C
    + `o` \- Output TOS, character C
    + `@` \- Terminate the program
* **Char D:** If the first `D` sends us south, the following is executed:

+ `i` \- Take another input, character B
    + `..` \- Two no-ops
    + `i` \- Take another input, character C
    + `|` \- This mirror reflects east-west, but the IP is heading north, so we pass through it.
    + `^` \- This joins up with the path taken for character B. However, because we have taken two inputs already, the fourth character (character D) will end up being printed.
> 9 votes

# Answer
# Python, 50 bytes

```
lambda x:choice(x[:2]+x[1:]*2)
from random import*

```

An unnamed function taking and returning strings (or lists of characters).

**Try it online!**

### How?

`random.choice` chooses a random element from a list, so the function forms a string with the correct distribution, that is, given `"ABCD"`, `"ABCD"[:2] = "AB"` plus `"ABCD"[1:]*2 = "BCD"*2 = "BCDBCD"` which is `"ABBCDBCD"`.
> 8 votes

# Answer
# , 31 bytes

```
sample(scan(,''),1,,c(1,3,2,2))

```

Reads the characters from `stdin` separated by spaces. `sample` draws random samples from its first input in quantity of the second input (so `1`), (optional replacement argument), with weights given by the last argument.

Try it online!

Try it `n` times!

For the latter code, I sample `n` times (set `n` in the header) with replacement set to `T`rue (it's false by default), tabulate the results, and divide by `n` to see the relative probabilities of the inputs.
> 6 votes

# Answer
# PHP, 28 bytes

```
<?=$argn[5551>>2*rand(0,7)];

```

Run as pipe with `-nR`.

`01112233` in base-4 is `5551` in decimal ...
> 6 votes

# Answer
# APL, 14 bytes

```
(?8)⊃1 3 2 2\⊢

```

Input as a string.

**How?**

`1 3 2 2\⊢` \- repeat each letter x times (`'ABCD'``'ABBBCCDD'`)

\- take the element at index ..

`(?8)` \- random 1-8
> 5 votes

# Answer
# Java 8, ~~53~~ 44 bytes

```
s->s[-~Math.abs((int)(Math.random()*8)-6)/2]

```

This is a `Function<char[], Character>`.

Try it online! (this test program runs the above function 1,000,000 times and outputs the experimental probabilities of choosing `A`, `B`, `C`, and `D`).

The general idea here is to find some way to map `0-7` to `0-3`, such that `0` appears `1/8` times, `1` appears `3/8` times, `2` appears `2/8` times, and `3` appears `2/8` times. `round(abs(k - 6) / 2.0))` works for this, where `k` is a random integer in the range `[0,8)`. This results in the following mapping:

```
k -> k - 6 -> abs(k-6) -> abs(k-6)/2 -> round(abs(k-6)/2)

0 -> -6 -> 6 -> 3   -> 3
1 -> -5 -> 5 -> 2.5 -> 3
2 -> -4 -> 4 -> 2   -> 2
3 -> -3 -> 3 -> 1.5 -> 2
4 -> -2 -> 2 -> 1   -> 1
5 -> -1 -> 1 -> 0.5 -> 1
6 -> 0  -> 0 -> 0   -> 0
7 -> 1  -> 1 -> 0.5 -> 1

```

Which, as you can see, results in the indices `0 111 22 33`, which produces the desired probabilities of `1/8`, `3/8`, `2/8` and `2/8`.

But wait! How in the world does `-~Math.abs(k-6)/2` achieve the same result (again, where `k` is a random integer in the range `[0,8]`)? It's pretty simple actually... `(x+1)/2` (integer division) is the same thing as `round(x/2)`, and `x + 1` is the same thing as `-~x`. Although `x+1` and `-~x` are the same length, in the above function it is better to use `-~x` since it `-~` takes precedence and thus does not require parenthesis.
> 5 votes

# Answer
# Pyth, ~~8~~ 7 bytes

```
O+@Q1t+

```

Uses the exact same algorithm as in my Python answer.

Try it here!

# Pyth, ~~10~~ 8 bytes

```
O+<Q2*2t

```

Uses the exact same algorithm as is Jonathan Allan's Python answer.

Try it here!

---

### Explanation

* `O` \- Takes a random element of the String made by appending (with `+`):

+ `<Q2` \- The first two characters of the String.
    + `*2t` Double the full String (`*2`) except for the first character (`t`).

Applying this algorithm for `ABCD`:

* `<Q2` takes `AB`.
* `*2t` takes `BCD` and doubles it: `BCDBCD`.
* `+` joins the two Strings: `ABBCDBCD`.
* `O` takes a random character.

---

-2 thanks to Leaky Nun (second solution)

-1 thanks to mnemonic (first solution)
> 4 votes

# Answer
# Charcoal, 11 bytes

```
‽⟦εεζζηηηθ⟧

```

Try it online! Link is to verbose version of code, although you hardly need it;  picks a random element, `⟦⟧` creates a list, and the variables are those that get the appropriate input letters (in reverse order because I felt like it).
> 4 votes

# Answer
# Jelly, 8 bytes

```
122b4⁸xX

```

Try it online!

Remove the `X` to see `"ABBBCCDD"`. The `X` chooses a random element.
> 3 votes

# Answer
# C# (.NET Core), 76 55 bytes

```
s=>(s+s[1]+s[1]+s[2]+s[3])[new System.Random().Next(8)]

```

Try it online!

My first answer written directly on TIO using my mobile phone. Level up!

Explanation: if the original string is "ABCD", the function creates the string "ABCDBBCD" and takes a random element from it.
> 3 votes

# Answer
# Javascript 35 bytes

Takes a string `ABCD` as input, outputs `A` 1/8th of the time, `B` 3/8ths of the time, `C` 1/4th of the time, and `D` 1/4th of the time.

```
x=>x[5551>>2*~~(Math.random()*8)&3]

```

## Explanation

```
x=>x[                     // return character at index
    5551                  // 5551 is 0001010110101111 in binary
                          // each pair of digits is a binary number 0-3
                          // represented x times
                          // where x/8 is the probability of selecting
                          // the character at the index
    >>                    // bitshift right by
    2 *                   // two times
    ~~(                   // double-bitwise negate (convert to int, then
                          // bitwise negate twice to get the floor for
                          // positive numbers)
        Math.random() * 8 // select a random number from [0, 8)
    )                     // total bitshift is a multiple of 2 from [0, 14]
    &3                    // bitwise and with 3 (111 in binary)
                          // to select a number from [0, 3]
]

```
> 3 votes

# Answer
# \>\<\>, ~~25~~ ~~22~~ 19 bytes

```
i_ixio;o
ox</;
;\$o

```

Try it online!, or watch it at the fish playground!

A brief overview of \>\<\>: it's a 2D language with a fish that swims through the code, executing instructions as it goes. If it reaches the edge of the code, it wraps to the other side. The fish starts in the top left corner, moving right. Randomness is tricky in \>\<\>: the only random instruction is `x`, which sets the fish's direction randomly out of up, down, left and right (with equal probability).

At the start of the program, the fish reads in two characters of input with `i_i` (each `i` reads a character from STDIN to the stack, and `_` is a horizontal mirror, which the fish ignores now). It then reaches an `x`.

If the `x` sends the fish rightwards, it reads in one more character (the third), prints it with `o` and halts with `;`. The left direction is similar: the fish reads two more characters (so we're up to the fourth), wraps around to the right, prints the fourth character and halts. If the fish swims up, it wraps and prints the second character, before being reflected right by `/` and halting. If it swims down, it gets reflected left by the `/` and hits another `x`.

This time, two directions just send the fish back to the `x` (right with an arrow, `<`, and up with a mirror, `_`). The fish therefore has 1/2 chance of escaping this `x` in each of the other two directions. Leftwards prints the top character on the stack, which is the second one, but downwards first swaps the two elements on the stack with `$`, so this direction prints the first character.

In summary, the third and fourth characters are printed with probability 1/4 each; the first character has probability 1/2 x 1/4 = 1/8; and the second character has probability 1/4 + 1/2 x 1/4 = 3/8.
> 3 votes

# Answer
# 05AB1E, 5 bytes

```
¦Ćì.R

```

Try it online!

### Explanation

```
¦Ćì.R   Argument s                      "ABCD"
¦       Push s[1:]                      "BCD"
 Ć      Enclose: Pop a, Push a + a[0]   "BCDB"
  ì     Pop a, Concatenate a and s      "ABCDBCDB"
   .R   Random pick

```
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
ìD1è0ǝ.R

```

Try it online!

```
         # Implicit input                            | [A,B,C,D]
ì        # Prepend the input to itself               | [A,B,C,D,A,B,C,D]
 D1è     # Get the second character                  | [A,B,C,D,A,B,C,D], B
    0ǝ   # Replace the first character with this one | [B,B,C,D,A,B,C,D]
      .R # Pick a random character from this array   | D

```
> 2 votes

# Answer
# MATL, ~~12~~ 10 bytes

```
l3HHvY"1Zr

```

Try it online! Or run it 1000 times (slightly modified code) and check the number of times each char appears.

### Explanation

```
l3HH   % Push 1, 3, 2, 2
v      % Concatenate all stack contents into a column vector: [1; 3; 2; 2]
Y"     % Implicit input. Run-length decode (repeat chars specified number of times)
1Zr    % Pick an entry with uniform probability. Implicit display

```

Changes in modified code: `1000:"Gl3HH4$vY"1Zr]vSY'`

* `1000:"...]` is a loop to repeat `1000` times.
* `G` makes sure the input is pushed at he beginning of each iteration.
* Results are accumulated on the stack across iterations. So `v` needs to be replaced by `4$v` to concatenate only the top `4` numbers.
* At the end of the loop, `v` concatenates the `1000` results into a vector, `S` sorts it, and `Y'` run-length encodes it. This gives the four letters and the number of times they have appeared.
> 2 votes

# Answer
# C (gcc), ~~50~~ 49 bytes

```
i[8]={1,1,1,2,2,3,3};f(char*m){m=m[i[rand()%8]];}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 6 bytes

```
«À¨Ć.R

```

Try it online!

**Explanation**

Works for both lists and strings.

```
«       # concatenate input with itself
 À      # rotate left
  ¨     # remove the last character/element
   Ć    # enclose, append the head
    .R  # pick a character/element at random

```
> 2 votes

# Answer
# Ruby, 34 33 29 27 bytes

Saved 2 bytes thanks to @Value Inc

Input as four characters

```
a=$**2
a[0]=a[1]
p a.sample

```

construct an array `[B,B,C,D,A,B,C,D]` and sample it.

try it online!

try it `n` times! (I converted it to a function to repeat it more easily, but the algorithm is the same)
> 2 votes

# Answer
# Javascript, ~~31~~ 30 bytes / 23 bytes

Seeing asgallant's earlier Javascript answer got me to thinking about JS. As he said:

> Takes a string `ABCD` as input, outputs `A` 1/8th of the time, `B` 3/8ths of the time, `C` 1/4th of the time, and `D` 1/4th of the time.

Mine is:

```
x=>(x+x)[Math.random()*8&7||1]

```

**Explanation:**

```
x=>(x+x)[                 // return character at index of doubled string ('ABCDABCD')
         Math.random()*8  // select a random number from [0, 8]
         &7               // bitwise-and to force to integer (0 to 7)
         ||1              // use it except if 0, then use 1 instead
        ]

```

From `Math.random()*8&7` it breaks down as follows:

```
A from 4      = 12.5% (1/8)
B from 0,1,5  = 37.5% (3/8)
C from 2,6    = 25%   (1/4)
D from 3,7    = 25%   (1/4)

```

## Version 2, 23 bytes

But then thanks to Arnauld, who posted after me, when he said:

> If a time-dependent formula is allowed, we can just do:

which, if it is indeed allowed, led me to:

```
x=>(x+x)[new Date%8||1]

```

in which `new Date%8` uses the same break-down table as above.

And `%8` could also be `&7`; take your pick. Thanks again, Arnauld.
> 2 votes

# Answer
# Pyth, 7 bytes

```
@z|O8 1

```

Test suite

`O8` generates a random number from 0 to 7. `| ... 1` applies a logical or with 1, converting the 0 to a 1 and leaving everything else the same. The number at this stage is 1 2/8th of the time, and 2, 3, 4, 5, 6, 7 or 8 1/8 of the time.

`@z` indexes into the input string at that position. The indexing is performed modulo the length of the string, so 4 indexes at position 0, 5 at position 1, and so on.

The probabilities are:

* Position 0: Random number 4. 1/8 of the time.
* Position 1: Random number 0, 1 or 5. 3/8 of the time.
* Position 2: Random number 2 or 6. 2/8 of the time.
* Position 3: Random number 3 or 7. 2/8 of the time.
> 2 votes

# Answer
# ngn/apl, 10 bytes

```
⎕a[⌈/?2 4]
```

`?2 4` chooses randomly a pair of numbers - the first among 0 1 and the second among 0 1 2 3

`⌈/` is "max reduce" - find the larger number

`⎕a` is the uppercase alphabet

`[ ]` indexing

---

note the chart for max(a,b) when a∊{0,1} and b∊{0,1,2,3}:

```
    ┏━━━┯━━━┯━━━┯━━━┓
    ┃b=0│b=1│b=2│b=3┃
┏━━━╋━━━┿━━━┿━━━┿━━━┫
┃a=0┃ 0 │ 1 │ 2 │ 3 ┃
┠───╂───┼───┼───┼───┨
┃a=1┃ 1 │ 1 │ 2 │ 3 ┃
┗━━━┻━━━┷━━━┷━━━┷━━━┛

```

if a and b are chosen randomly and independently, we can substitute 0123=ABCD to get the desired probability distribution
> 2 votes

# Answer
# Python 3, ~~64 55~~ 51 bytes

*-9 bytes thanks to @ovs*

```
lambda s:choice((s*2)[1:]+s[1])
from random import*

```

Try it online!

---

## Explanation

`random.choice()` gets a random character of the String, while `(s*2)[1:]+s[1]` creates `BCDABCDB` for an input of `ABCD`, which has 1/8 `A`s, 2/8 `C`s, 2/8 `D`s and 3/8 `B`s.
> 1 votes

# Answer
# Mathematica, 25 bytes

```
RandomChoice@{##,##2,#2}&

```

**input**

> \["A", "B", "C", "D"\]

*-23 bytes from @MarkS!*
> 1 votes

# Answer
# QBIC, 27 bytes

```
?_s;+;+B+B+;+C+;+D,_r1,8|,1

```

## Explanation

```
?           PRINT
 _s         A substring of
   ;+       A plus
   ;+B+B+   3 instances of B plus
   ;+C+     2 instances of C plus
   ;+D      2 instances of D plus
   ,_r1,8|  from position x randomly chosen between 1 and 8
   ,1       running for 1 character

```
> 1 votes

# Answer
# \>\<\>, 56 bytes

```
v
!

"
D
C
B
A ;
" o
! @
! ^<
x!^xv!
@  v<
@  o
o  ;
;
o

```

Try it online!
> 1 votes

# Answer
# Chip, 60 bytes

```
)//Z
)/\Z
)\/^.
)\x/Z
)\\\+t
|???`~S
|z*
`{'AabBCcdDEefFGghH

```

Try it online!

The three `?`'s each produce a random bit. On the first cycle, these bits are run through the switches above (`/`'s and `\`'s) to determine which value we are going to output from this table:

```
000 a
01_ b
0_1 b
10_ c
11_ d

```

(where `_` can be either `0` or `1`). We then walk along the input as necessary, printing and terminating when the correct value is reached.

The big alphabetic blob at the end is copied wholesale from the cat program, this solution simply suppresses output and terminates to get the intended effect.
> 1 votes

# Answer
# Java (OpenJDK 8), ~~40~~ 38 bytes

```
s->s[5551>>2*(int)(Math.random()*8)&3]

```

Try it online!

`5551` in base 10 is `01112233` in base 4. So let's randomly pick one of those base-4 digits using bit shift and selection, then pick the n-th character from the originating `char[]`.
> 1 votes

# Answer
# Ruby, 32 bytes

Pretty straightforward..?

```
->s{s[[0,1,1,1,2,2,3,3].sample]}

```

Try it online!
> 1 votes

# Answer
# Applesoft, ~~29~~ oops, 32 bytes

A little "retrocomputing" example. Bear with me, I'm brand new at this. I gather that what is designated **as** the "input" need not be byte-counted itself. As stated in the OP, the input would be given as "ABCD". (I didn't initially realize that I needed to specify input being obtained, which added 4 bytes, while I golfed the rest down a byte.)

```
INPUTI$:X=RND(1)*4:PRINTMID$(I$,(X<.5)+X+1,1)

```

The terms INPUT, RND, PRINT and MID$ are each encoded internally as single-byte tokens.

First, X is assigned a random value in the range 0 \< X \< 4. This is used to choose one of the characters from I$, according to (X \< .5) + X + 1. Character-position value is taken as truncated evaluation of the expression. X \< .5 adds 1 if X was less than .5, otherwise add 0. Results from X break down as follows:

```
A from .5 ≤ X < 1           = 12.5%
B from X < .5 or 1 ≤ X < 2  = 37.5%
C from 2 ≤ X < 3            = 25%
D from 3 ≤ X < 4            = 25%

```
> 1 votes

# Answer
# Common Lisp, 198 bytes

```
(setf *random-state*(make-random-state t))(defun f(L)(setf n(random 8))(cond((< n 1)(char L 0))((and(>= n 1)(< n 4))(char L 1))((and(>= n 4)(< n 6))(char L 2))((>= n 6)(char L 3))))(princ(f "ABCD"))

```

Try it online!

Readable:

```
(setf *random-state* (make-random-state t))
(defun f(L)
    (setf n (random 8))
    (cond
            ((< n 1)
                (char L 0))
            ((and (>= n 1)(< n 4))
                (char L 1))
            ((and (>= n 4)(< n 6))
                (char L 2))
            ((>= n 6)
                (char L 3))
    )
)
(princ (f "abcd"))

```
> 1 votes

# Answer
# braingasm, 17 bytes

```
4[,>]<4r<#z[2r>].

```

Works like this:

```
4[,>]<             Input 4 bytes from stdin and stay in cell 3 (0-indexed).
        <          Move left ...
      4r           ... randomly between 0 (inclusive) and 4 (exclusive) times.
         #z[   ]   If we're at cell 0,
              >      move right ...
            2r       ... with 50% probability.
                .  Print the byte value of the cell.

```

Given the input `ABCD`, each character has 1/4 = 2/8 chance of being printed because of `4r`, but if we selected `A`, we have 1/2 chance of printing `B` instead, giving `A` (1/4)/2 = 1/8 chance and `B` 1/4 + 1/8 = 3/8 chance.
> 1 votes

# Answer
# J, 16 bytes

```
(1?8:){1 3 2 2&#

```

## how?

* `1 3 2 2&#` \- copy the input elementwise, ie, 1 copy of A, 3 copies of B, etc, yielding the list `ABBBCCDD`
* `1?8:` \- choose 1 element at random from the list `0 1 2 3 4 5 6 7`
* `{` \- "From", ie, choose from `ABBBCCDD` the random index generated by `1?8:`

Try it online!
> 1 votes

# Answer
# C, 106 bytes

```
int f(){int r=(int)random()%8;if(!r--)return 'A';if(--r-->0)if(r<2)return 'C';else return 'B';return 'D';}

```
> 0 votes

# Answer
# q/kdb+, ~~15~~ 13 bytes

**Solution:**

```
1?a[0],7#1_a:

```

**Example:**

```
q)1?a[0],7#1_a:"ABCD"
,"B"

```

**Explanation:**

This is pretty much a `q` version of the `jelly` solution. Create the list `"ABCDBCDB"` and then pick one item from it at random

**Bonus:**

Another `q` solution in 15 bytes, same style as the `APL` one:

```
1?(,/)1 3 2 2#'

```

A `k` version of this solution is 13 bytes:

```
1?,/1 3 2 2#'

```
> 0 votes

# Answer
# CJam, 11 bytes

```
XZYY]q.*smR

```

Try it Online

```
XZYY]    e# add [1,3,2,2] to stack
q        e# add input string to stack
.*       e# element-wise multiply the two arrays. char * int in CJam = repeat character x times
s        e# flatten result to string
mR       e# pick random char from string

```
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
•20åÝ•.Rè

```

Try it online!

```
•20åÝ•   # Push 33221110.
     .R  # Randomly selected index.
       è # Character at that index.

```
> 0 votes

# Answer
# Octave, ~~30~~ 28 bytes

```
@(S)S([1:4 2 2:4])(randi(8))

```

Try it online!

Previous answer:

```
@(S)S('ABBBCCDD'(randi(8))-64)

```

Try it online!

Input is taken as a string of 4 characters.

Explanation:

Instead of `[1 2 2 2 3 3 4 4 ]` we can write `'ABBBCCDD'-64` and randomly select one of indexes and use the index to extract the desired character from the string.
> 0 votes

# Answer
## JavaScript (ES6), 25 bytes / 30 bytes

In both following versions, we're looking for two positive integers ***m*** and ***n*** such that ***n MOD (m + i) MOD 4*** gives us results in **\[*0...3*\]** at the expected frequencies for ***i*** in **\[*0...7*\]**.

---

### Version 1, 25 bytes

If a time-dependent formula is allowed, we can just do:

```
s=>s[11%(new Date%8+2)%4]

```

This one is using ***n = 11*** (smallest possible value of ***n***) and ***m = 2***.

```
i | 2 + i | 11 % (2 + i) | 11 % (2 + i) % 4
--+-------+--------------+-----------------
0 |     2 |            1 |                1
1 |     3 |            2 |                2
2 |     4 |            3 |                3
3 |     5 |            1 |                1
4 |     6 |            5 |                1
5 |     7 |            4 |                0
6 |     8 |            3 |                3
7 |     9 |            2 |                2

```

### Demo

```
let f =

s=>s[11%(new Date%8+2)%4]

for(stat = {A:0, B:0, C:0, D:0}, i = 0; i < 80000; i++) {
  stat[f("ABCD")]++;
}
console.log(stat);
```

---

### Version 2, 30 bytes

With the native JavaScript PRNG -- which generates a floating-point number in **\[*0...1*)** -- we'd rather do:

```
s=>s[21%(Math.random()*8|8)%4]

```

Here, we use ***n = 21*** and ***m = 8*** because it allows us to do the addition and isolate the integer part at the same time with `Math.random()*8|8`.

```
i | 8 + i | 21 % (8 + i) | 21 % (8 + i) % 4
--+-------+--------------+-----------------
0 |     8 |            5 |                1
1 |     9 |            3 |                3
2 |    10 |            1 |                1
3 |    11 |           10 |                2
4 |    12 |            9 |                1
5 |    13 |            8 |                0
6 |    14 |            7 |                3
7 |    15 |            6 |                2

```

### Demo

```
let f =

s=>s[21%(Math.random()*8|8)%4]

for(stat = {A:0, B:0, C:0, D:0}, i = 0; i < 80000; i++) {
  stat[f("ABCD")]++;
}
console.log(stat);
```
> 0 votes

# Answer
# PowerShell, 64 bytes

```
$args|%{($_-replace '(^.)(.)',"`$1`$2`$2`$2$'")[(Get-Random)%8]}

```

Try it online!

It replaces the string `abcd` with `abbbcdcd` using `regex` witchcraft and then randomizes which of the eight characters it chooses. The regex is expensive; it requires a backtick per grouping, so there may be a better method using recursive lookups.

Here's a quick explanation of the regex:

For input `abcd` the full match is `ab`, grouping `$1` is 'a', grouping `$2` is 'b', and `$'` (note quote, not backtick) returns everything after the full match. Then, the pattern `$1$2$2$2$'` is substituted for the full match: `abcd` goes to `$1$2$2$2$'` \+ `cd` = `abbbcdcd`
> 0 votes

# Answer
# TI-Basic, 25 bytes

```
sub(Ans,randInt(1,8),1
If int(2rand(Ans="A
"B

```
> 0 votes

# Answer
# Bash, 52 bytes

```
f(){ c=$1$2$2$2$3$3$4$4;echo ${c:$(($RANDOM%8)):1};}

```

Usage exemple:

```
$ f a b c d
b
$ f a b c d
d
$ f a b c d
b
$ f a b c d
a

```
> 0 votes

# Answer
# Perl 5, 26 bytes

```
say((A..D,B..D,B)[rand 8])

```

Try it online!
> 0 votes

# Answer
# SmileBASIC, 31 bytes

```
LINPUT S$N=RND(8)?S$[N+!N*2>>1]

```

Pick a number from 0 to 7, add 2 if it's 0, then divide by 2.
> 0 votes

# Answer
# Thunno 2, 7 bytes

```
«¦/d×Jɼ

```

Try it online!

#### Explanation

```
«¦/d×Jɼ  # Implicit input
«¦/      # Push 1322
   d     # Cast to digits
    ×    # Multiply elementwise
     J   # Join into a string
      ɼ  # Choose a random character
         # Implicit output

```
> 0 votes

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


# Question
Title: Numbers that can be negated by reading backwards
Balanced ternary is a modified version of ternary (base 3), using the three digits `1`,`0` and `-1` (written as `T`) to represent numbers.

The balanced ternary representation of `-n` can be obtained by replacing `1` with `T` and `T` with `1` in the balanced ternary representation of `n`.

Examples:

```
1     // decimal: 1
T     // decimal: -1
1T    // decimal: 3-1 = 2
T1    // decimal: -3+1 = -2
1TTT0 // decimal: 3^4-3^3-3^2-3^1+0= 42

```

Your task is to write a function or program that outputs all positive integers `n` for which reversing the balanced ternary representation gives the balanced ternary representation of `-n` (OEIS 233571).

Example:

`1100T0100TT` (decimal `78080`) reversed is `TT0010T0011` (decimal `-78080`)

The first few numbers in the sequence:

```
1 -> 2  // balanced ternary: 1T
2 -> 8  // balanced ternary: 10T
3 -> 20 // balanced ternary: 1T1T
4 -> 26 // balanced ternary: 100T
5 -> 32 // balanced ternary: 11TT
6 -> 56 // balanced ternary: 1T01T
...
100 -> 14600 //  balanced ternary: 1T1T001T1T
...
9999 -> 132258878 // balanced ternary: 1001T00TT11001T00T

```

# Rules

* The standard sequence I/O rules apply
* It is allowed to output numbers in balanced ternary:
(as a string using three distinguishable characters, or as a list of digits)
* Your code should be able to handle at least the first 10000 elements of this sequence
* This is so the shortest solution (in each language) measured in bytes wins

# Answer
> 5 votes
# Python, 86 bytes

```
f=lambda x:x and[-~x%3]+f(-~x//3)or[]
i=1
while i:
 if f(i:=i+1)==f(-i)[::-1]:print(i)

```

Attempt This Online!

# Answer
> 5 votes
# JavaScript (V8), 59 bytes

Prints the sequence infinitely.

```
for(k=1;v=++k;t+k||print(k))for(t=0;v;v=v/3|0)t=++v%3-1+t*3

```

Try it online!

### How?

We convert \\$k\ge2\\$ to balanced ternary. Each produced digit is immediately used to convert the reversed balanced ternary representation of \\$k\\$ back to a decimal value \\$t\\$. If we end up with \\$k=-t\\$, we print \\$k\\$.

### Commented

```
for(                // outer loop:
  k = 1;            //   start with k = 1
  v = ++k;          //   increment k and set v = k
                    //   (this is > 0, so we loop forever)
  t + k || print(k) //   after each iteration: print k if t + k = 0
)                   //
  for(              //   inner loop:
    t = 0;          //     start with t = 0
    v;              //     stop when v = 0
    v = v / 3 | 0   //     after each iteration: update v to ⌊v/3⌋
  )                 //
    t =             //     update t:
      ++v % 3 - 1 + //       increment v and compute the next balanced
                    //       ternary digit (v mod 3) - 1
      t * 3         //       add t * 3

```

---

# C (gcc), 74 bytes

```
v;t;main(k){for(;v=++k;t+k||printf("%d ",k))for(t=0;v;v/=3)t=++v%3-1+t*3;}

```

Try it online!

# Answer
> 4 votes
# Pyth, 21 bytes

```
L?b+y/hb3%b3Y.fq_yZy_

```

Try it online!

Outputs the first `n` terms of the sequence.

### Explanation

```
L?b+y/hb3%b3Y.fq_yZy_ZQ    # implicitly add ZQ
                           # implicitly assign Q = eval(input())
L                          # define y(b)
 ?b                        #   conditional, if b:
    y/hb3                  #     y((b+1) / 3)
   +     %b3               #     append b % 3
            Y              #   else: []
             .f       Q    # return the first Q inputs where lambda Z is true
                _yZ        #   y(Z) reversed
               q           #   equals
                   y_Z     #   y(-Z)

```

# Answer
> 4 votes
# Charcoal, 27 bytes

```
Ｎθ1Φ⍘θT01κＦ⊖⊟⮌↨θ³0⮌Φ⍘θ10TκT

```

Try it online! Link is to verbose version of code. Outputs the `n`th term of the sequence. Explanation:

```
Ｎθ

```

Input `n`.

```
1

```

Start by printing a `1`.

```
Φ⍘θT01κ

```

Print `n` in base 3, decrementing all of the digits (so `0` becomes `T`), but skipping the first digit.

```
Ｆ⊖⊟⮌↨θ³0

```

Print a `0` if `n`'s first digit in base 3 is `2`.

```
⮌Φ⍘θ10Tκ

```

Print `n` in base 3, again decrementing after skipping the first digit, but then negating and reversing the result.

```
T

```

Print a `T`.

# Answer
> 2 votes
# Raku (Perl 6) (rakudo), ~~69~~ 66 bytes

```
.&(my&g={1 x?$_&&g(-+^$_ div 3)~$_%3})==g(-$_).flip&&.say for 1..*

```

Attempt This Online!

# Answer
> 2 votes
# 05AB1E, 25 bytes

```
∞ʒD(‚ε[©_#®>D3%s3/ï})}`RQ

```

Inspired by *@mousetail*'s Python answer and *@CursorCoercer*'s Pyth answer.

Outputs the infinite sequence.

Try it online.

Unfortunately 05AB1E rounds towards 0 for integer-division of negative values, unlike Python which always floors. Otherwise `[©_#®>D3%s3/ï}` could have been `[©_#®>3‰R`}` for -3 bytes by using divmod builtin .
See that it gives the expected result for positive integers, but not for negative ones.

**Explanation:**

```
∞              # Push an infinite positive list: [1,2,3,...]
 ʒ             # Filter it by:
    ‚          #  Pair the current value
   (           #  with a negative
  D            #  copy of that value
  ε            #  Map over this [n,-n] pair:
   [           #   Start an infinite loop:
    ©          #    Store the current value in variable `®` (without popping)
     _         #    Pop and if it's 0:
      #        #     Stop the infinite loop
    ®          #    If not, push `®` again
     >         #    Increase it by 1
      D        #    Duplicate it
       3%      #    Modulo-3
         s     #    Swap so the value+1 is at the top again
          3/   #    Divide by 3
            ï  #    Floor (by casting to an integer)
   })          #   After the infinite loop: wrap all values on the stack into a list
  }`           #  After the map: pop and push both lists to the stack
    R          #  Reverse the second list
     Q         #  Then check if the two lists are the same
               # (after which the filtered infinite list is output implicitly as result)

```

# Answer
> 2 votes
# ForWhile, 119 bytes

```
{1:2$4$[2@4;+'[1-:@48+#)1-:@[48#.]2@[1+:@48'-#).10#.4::@1+'$2@[:@2=[0~;$1+::@1+'$]:)2@4+=[3::@~'$@![2:@1+'$]2@3+1'$]1)}

```

Input: integer `n` on the stack

Prints the first `n` numbers of the sequence in balanced ternary with `/` as symbol for `-1`

Online Interpreter

Explanation:

Memory:

* cell 2 -\> length of first half of number
* cell 3 -\> marker if total length is odd
* cells 4ff -\> digits of first half of number (from center outwards)

```
{  \ procedure
  1:2$4$  \ store 1 in cells 2 (length) and 4 (start of value)
  [                                  \ loop-without pushing the loop-counter
    2@4;+'[1-:@48+#)                 \ write the first digits of the number
    1-:@[48#.]                       \ write 0 if number has odd length
    2@[1+:@48'-#).10#.4              \ write digits reversed and mirrored
    ::@1+'$2@[:@2=[0~;$1+::@1+'$]:)  \ increment number
    2@4+=[                           \ check for overflow
      3::@~'$                        \ flip cell 3
      @![2:@1+'$]                    \ increase length if new length is even
      2@3+1'$                        \ set top trit (ternary digit) to 1
    ]
  1)                                 \ go back to start of loop
}

```

# Answer
> 2 votes
# Nekomata, 14 bytes

```
Ňᵐ{3r~←}1c:↔_=

```

Attempt This Online!

Outputs the numbers in balanced ternary (as lists of digits).

---

# Nekomata, 16 bytes

```
Ňᵐ{3r~←}1c:↔_=3b

```

Attempt This Online!

Outputs the numbers in the usual form.

```
Ňᵐ{3r~←}1c:↔_=3b
Ň                   Choose a natural number n
 ᵐ{    }            Map the following function to the range [0, n)
   3r~                  Choose a random number from [0, 3)
      ←                 Decrement
                        (These two steps generate any tuple of [-1, 0, 1])
        1c          Prepends 1
                        (This ensures that it is the balanced ternary representation of a positive number)
          :         Duplicate
           ↔        Reverse
            _       Negate
             =      Check equality
              3b    Convert from base 3

```

# Answer
> 1 votes
# Perl 5, 134 bytes

```
while(++$n){for$c("",0){$_="T"x$n;s/T/1/;do{($b=reverse)=~y/1T/T1/;print"$_$c$b$/"}while(/(?=[T0]1*$)/g&&substr($_,pos)=~y/T01/01T/)}}

```

Like some other answers, it uses string manipulations only, no math, to produce the reflected pattern of the sequence elements.

* `while (++$n)` : Loop over increasing length of the prefix, endlessly.
    + `for $c ("",0)` : Do all the following twice, once with an empty string for the "center" and once with digit "0" for the "center".
        - `$_ = "T" x $n; s/T/1/;` : Form the smallest positive value of length `$n`, by creating a string of "T" characters then changing its first character to "1".
        - `do`...
            * `($b = reverse) =~ y/1T/T1/;` : Form the suffix by reversing the prefix then negating its digits.
            * `print "$_$c$b$/"` : Print the full output: prefix, center, suffix, and newline.
        - `while (/(?=[T0]1*$)/g && substr($_, pos) =~ y/T01/01T/)` : Increment the prefix as a ternary string. Find the position of the last digit which is not a "1". The loop ends if the string is nothing but "1" digits. Otherwise, change the digit found from "T" to "0" or from "0" to "1", and change all the following "1" digits (if any) to "T" digits.

Try it online!

# Answer
> 1 votes
# Jelly, 15 bytes

Port of Neil's Charcoal answer \- go show your love.

```
b3’µḢR¬;ṚN⁸;Ø+j

```

A monadic Link that accepts a positive integer, \\$n\\$, and yields the \\$n^{\text{th}}\\$ reverse-negate-invariant number in balanced ternary as a list of integers from \\$\\{-1,0,1\\}\\$.

**Try it online!** Or see the test-suite (first 100 converted to integers).

### How?

```
b3’µḢR¬;ṚN⁸;Ø+j - Link: positive integer, n            e.g. 21
b3              - convert {n} to base three                 [2,1,0]
  ’             - decrement {each digit}                D = [1,0,-1]
   µ            - start a new monadic chain - f(D=that)
    Ḣ           - pop the head off {D} and yield it         1  (and D -> [0,-1])
     R          - range {that} (1 -> [1] else [])           [1]
      ¬         - logical NOT {that} ([] -> []; [1] -> [0]) [0]
        Ṛ       - reverse {modified D}                      [-1,0]
       ;        - concatenate                               [0,-1,0]
         N      - negate {that}                             [0,1,0]
          ⁸     - chain's left argument -> modified D       [0,-1]
           ;    - concatenate                               [0,-1,0,1,0]
            Ø+  - signs literal -> [1,-1]                   [1,-1]
              j - join                                      [1,0,-1,0,1,0,-1]

```

---
Tags: code-golf, math, sequence, base-conversion, palindrome
---


# Question
Title: Start a program so that /proc/self/cmdline contains a binary representation of the input number
I am sorry for the very long description. But i think some information of how `/proc/self/cmdline` works and how it can be used to get a integer input was necessary. You may skip the sections you don't need.

While part of this task is related to C and Linux, it can be done in any almost language that can start other programs / OS where programs can be started with arguments.

##### Background

For golfed C programs (and possible others) that takes a number as input, it can be shorter to just use a `argv` string and interpret the bytes of it as a integer and don't bother with parsing a ASCII string (decimal) representation of the number. In C this can be done by `main(a,v)int **v{a=*v[1]...`. This is shorter than parsing a ASCII string like this `main(a,v)int **v{a=atoi(v[1])...`. The problem is that it isn't that trivial to create an argument list so that `a=*v[1]` contains a desired value.

So the idea came to make a new code golf task to create a program that creates such a layout.

##### Memory layout

The following applies to Linux but the task should also work on a different OS with a similar way to start a program as the `exec*()`-family on Linux (it doesn't matter if a new process is started or if the current one is replaced).

I also don't care if the hack of `int a=*v[1]` works on your platform or not.

The arguments and the `/proc/$PID/cmdline` have the following layout:

```
  V--- argv[0] points here        V--- argv[1] points here
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| . | / | a | . | o | u | t |\0 | A | R | G | 1 |\0 | A | R | G | 2 |\0 | ...
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
  ^------Program name---------^   ^---Argument 1--^   ^---Argument 2--^
Interpret this 4 bytes as integer:^-----------^

```

> The command-line arguments appear in this file as a set of strings separated by null bytes ('\0'), with a further null byte after the last string.

##### Task

Write a program that takes a number as input and call a program in a way that `/prog/$PID/cmdline` of that program contains the binary representation of that number (or would contain it if it would run on Linux, what matters are is which arguments you give to the called program).

This means, you have to call a program with possible multiple arguments. This arguments have to contain the the binary byte representation of that desired number. For every 0-byte inside this number, you have to generate a new argument, but for every non-0-byte you have to continue using the same argument.

You may or may not use this memory layout for the integer 0x12003400 (assuming little endian):

```
  V--- pointer 1 points here
       V--- pointer 2 points here
                 V--- pointer 3 points here
+----+----+----+----+----+
|0x00|0x34|0x00|0x12|0x00| <- last 0x00 ends the string of pointer 3
+----+----+----+----+----+

```

Or this

```
  V--- pointer 1 points here
              V--- pointer 2 points here
                             V--- pointer 3 points here
+----+     +----+----+     +----+----+
|0x00| ... |0x34|0x00| ... |0x12|0x00|
+----+     +----+----+     +----+----+

```

Or any other layout with similar effect.

And may or may not call the program like this `execl("./program_name",pointer1,pointer2,pointer3,NULL);`

##### Rules

* **Write a full running program** that calls a other programs with some of the arguments created like mentioned before.
* While i observed this layout on Linux, the task should also work on other OSs with the following rules:
    + You can call a other program with multiple arguments where each argument is `'\0'`-terminated and doesn't contain any `'\0'` byte inside the argument.
    + It uses 8 bit per byte.
* **The number is given as a written ASCII string or a user input in a base you choose**. If needed a prefix (like `0x`) can be required.
* You must set the arguments before or while calling. It isn't allowed to pause the called program and somehow overwrite `argv` in it.
* You can use signed integers, unsigned integers or floating point numbers. They have to use at least 4 bytes and need to have a fixed size.
* For integer, at least 2^32-1 different values have to be supported, for floats at least 2^31 different values have to be supported.
* The name of the called program can be hardcoded or a different parameter (it doesn't matter from where you get it). But it has to be a valid program name (not `.`, `/`, `..` ...) and it is different from the current program name.
* The number can be placed at any `argv`-number, including 0 as long as it doesn't change the name of the called program. But it has to be always at the same one.
* There can be any amount of arguments after the number is represented, as long as it is still possible to call a program.
* You can choose the endianness.
* The number format has no padding bits.

##### Examples

A non-golfed example in C:

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

int main( int argc, char **argv )
{
    if(argc<2)
        { exit(1); }
    int n = atoi( argv[1] ); //the number we should give to the called program
    unsigned char buffer[512]; //contains the binary representation of the number + 0-bytes
    memset( buffer, 0, sizeof buffer ); //Set all to 0 so the last argument ends automatically
    memcpy( buffer, &n, sizeof n ); //add the binary representation to the buffer
    unsigned char *args[4]; //pointers to the start of the "strings" containing the number
    args[0] = buffer; //first argument always starts at the beginning
    size_t position = 0; //position in the buffer
    for( size_t i = 0; i<3; i++ ) //loop for all relevant arguments
    {
        //As long as the current byte is not 0, it is still part of the previous argument
        while( buffer[position]!='\0' )
            { position++; }
        position++; //The ending 0 is still part of the previous argument
        args[i+1] = &buffer[position];
    }

    execl( "./a.out", "./a.out", args[0], args[1], args[2], args[3], NULL );
    perror( "execv" );
    return 0;
  }

```

Example program to be called (not part of the task):

That works when the layout it the same, little endian

```
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>

int main( int argc, uint32_t **argv )
{
    uint32_t a = *argv[1];
    printf( "%"PRIu32"\n", a );
}

```

That should work independent of how `argv` is positioned in memory.

```
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>

int main( int argc, char **argv )
{
    uint32_t result = 0; //should contain the number passed as binary representation to argv
    unsigned index = 1;  //Which argv the current byte is from. Start with argv[1]
    unsigned positionInString = 0; //Current byte inside the current argv[n]
    //32 bit number with 4 bytes
    for(unsigned byte = 0; byte<4; byte++ )
    {
        if( index>=argc )
        {
            fprintf( stderr, "argv is not big enough\n" );
            return 1;
        }
        //Get a single byte
        uint8_t currentValue = argv[index][positionInString] ;
        //move it to the correct place. Little endian
        result |= ( (uint32_t) currentValue ) << (8*byte);
        positionInString++;
        if( !currentValue ) //use next argument when current argument ends
        {
            index++;
            positionInString=0;
        }
    }

    printf( "result %"PRIu32"\n", result );
}

```

# Answer
# Python, 64 bytes

*-2 bytes thanks to corvus\_192*

```
import os
os.execl(*"aa",*int(input()).to_bytes(4).split(b'\0'))

```

Uses big endian and assumes binary is named "a".
> 2 votes

---
Tags: code-golf, number, binary, c
---


title: Range of ASCII values

text:
# Question
Title: Range of ASCII values
### Your task

Given a string, output the range of ASCII values.

### Example

Let's say we have the string `Hello`.

We get the ASCII values:

* `H` = 72
* `e` = 101
* `l` = 108
* `l` = 108
* `o` = 111

Now, we get the range (`max - min`):

* 111 - 72 = 39

Our answer is 39.

### Test cases

```
Input           Output
Hello, World!   82
aaaaa           0
Code Golf       79
Stack Exchange  88
ASCII           18

```

### Scoring

For scoring, we will get the range of ASCII/Unicode values of your program source code, and add that to the length of your code in bytes.

For example, with the program `abc`, the score would be:

* 3 (the length of the program) + 2 (the ASCII range of the program) = 5

You can use this TIO link to get your score.

### Clarifications

* There will be no non-ASCII characters in the input (but your program source code may contain non-ASCII characters)
* There will be no newline characters in the input (but your program source code may include newlines)
* **Lowest score wins**

# Answer
> 8 votes
# MATL, score 37 (length 7, range 30)

```
X>GX<ZP

```

Try it online! Or verify all test cases and source code.

```
X>    % Implicit input. Maximum
G     % Push input again
X<    % Minimum
ZP    % Distance (of code points). Implicit display

```

# Answer
> 8 votes
# C (clang), 79 bytes + 28 = ~~145 138 129 112 111~~ 107

*-7 score thanks to @Digital Trauma
~~-9~~ -10 score thanks to @jdt*

```
A,B;D(*C)??<*C<A?A=*C:*C>B?B=*C:0;*++C?D(C):0;??>C(*C)??<A=B=*C;D(C);*C=B-A;??>

```

Try it online!

## Explanation

`??<` and `??>` are trigraphs for `{` and `}` respectively

```
A,B;      // A will track the minimum, B will track the maximum
D(*C){    // D() will traverse C updating the values of A and B
  *C<A?   // if current character < A
    A=*C  //   update A with it's value
  :*C>B?  // else if current character > B
    B=*C  //   update B with it's value
  :0;     // else, do nothing
  *++C?   // if we're not at the end of the string
    D(C)  //   call D recursively with the next character
  :0;     // else, do nothing
}         // end D()
C(*C){    // C() takes the string, which is also where we'll store the output
  A=B=*C; // initialize A and B with the first character in C
  D(C);   // call D
  *C=B-A; // store the range (max - min) in the out argument
}         // end C()

```

# Answer
> 6 votes
# Bash \+ GNU utilities, 52 bytes + 92 range = 144

```
od -An -w1 -td1 -v|sort -n|sed -n '1p;$p'|dc -e??r-p

```

Try it online!

# Answer
> 4 votes
# Pip, 13 bytes + 39 = 52

```
a:A^aMXaADMNa

```

Try It Online!

### Explanation

A straight code-golf solution to the challenge might look like this:

```
A*:a;Ma-Na
   a        First command-line argument
A*          Get ASCII value of each character
  :         and assign that list of integers back to a
    ;       Statement separator
        Na  Minimum of a
      a-    Subtract that from each element in a
     M      and take the maximum of the resulting list

```

This gets a score of 65. The `a` for getting the command-line argument and `A` for taking ASCII values are both necessary, so to improve the score we'll need to look at the characters with ASCII values less than `A`.

The smallest character is `*`, which we can get rid of by splitting the string into a list of characters with `^` and passing that list to `A` directly:

```
A*:a
 ->
a:A^a

```

The next-smallest character is `-`, which we can get rid of by using the absolute difference operator `AD` instead. Then we have to rearrange a bit more to avoid needing a space; we'll use the old `MX` and `MN` operators for max and min instead of the newer `M` and `N`.

```
Ma-Na
 ->
MXaADMNa

```

(We could also keep using `M`, but since it also requires a semicolon to parse correctly, the score is the same if we replace it with `MX` which doesn't need the semicolon.)

# Answer
> 4 votes
# Alumin, ~~36~~ 19 bytes + ~~22~~ 20 = ~~58~~ 39

```
idiqdhhhwrvsruripkc

```

Try it online!

Both the right language for the job~~, and horribly inefficient at it!~~ Turns out, I'm just an inefficient thinker!

## Explanation

```
idiqdhhhwrvsruripkc
                       explanation           | stack
id                     take input, duplicate | MAX MIN
  iq           ip      while input > 0       | MAX MIN in
    d                    duplicate           | MAX MIN in in
     hhhw                grab top 3          | MAX [ MIN in in ]
         r               reverse stack       | MAX [ in in MIN ]
          v              get lesser of two   | MAX [ in MIN' ]
           s             ungrab              | MAX in MIN'
            r            reverse stack       | MIN' in MAX
             u           get greater of two  | MIN' MAX'
              r          reverse stack       | MAX' MIN'
                         (this gives us a better score than using `y` to swap 2)
                      loop finishes          | MAX MIN -1
                 k    discard eof            | MAX MIN
                  c   subtract               | MAX-MIN

```

## Explanation (Old)

```
hqidrlhcwrspkrklhhgwfufsykrlhcwfvfsc
h                                     push 1 (to start loop)
 q         p                          input loop
  id                                  take input, duplicate
    r                                 reverse stack
     lhc                              stack length - 1
        wrs                           reverse that many elements off the stack
                                      this has the effect of pushing two copies of the input
            krk                       pop trailing EOF twice
               lhhg                   stack length / 2
                   w                  grab that many elements into a new stack
                    fuf               fold over maximum
                       sykr           place on bottom stack, remove initial 1
                           lhc        stack length - 1
                              w       grab that many elements as before
                               fvf    fold over minimum
                                  sc  push and subtract

```

# Answer
> 3 votes
# Octave, score 56 (length 6, range 50)

```
@range

```

Try it online!

# Answer
> 3 votes
# Nibbles, ~~9~~ 12 bytes + ~~56~~ ~~49~~ 38 = 50

```
;*;-;o;/;\;`<@@o;/_$;`$$

```

This corresponds to the Nibbles program with nibbles:

```
6 a 6 9 6 e 6 a 6 b 6 e 4 d 4 e 6 a 5 3 6 d 7 3

```

Which, paired-up into bytes, gives

```
6a 69 6e 6a 6b 6e 4d 4e 6a 53 6d 73

```

which can be read-out as a string (with the same ASCII values)

```
jinjknMNjSms

```

with ASCII range 115 (`73`) - 77 (`4d`) = 38.

---

**How?** We start from a straightforward code-golf solution to the question: `-o/\;`<$$o/` (5.5 bytes, 11 nibbles):

```
-o/\;`<$@o/
-                   # subtract
 o                  #   character value of
  /                 #   fold over
   \                #     reverse of
    ;               #     (save)
     `<             #     sorted
       @            #     input
        $           #   returning left element each time
                    #   (so the fold returns the first element)
                    # from
         o          #   character value of
          /         #   fold over
                    #   (implicit) saved sorted input
                    #   (implicit) returning left element each time

```

The nibbles are slightly re-arranged in the final program, since the 2-nibble 'sort' function ( ``<`) wraps around its argument (here `$`). Thus, the paired-up nibbles from this are:

```
-o /\ ;` @< $o /    # program code (in final order)
9e ab 6e 4d 3e a    # nibbles

```

We can reduce the range of bytes by inserting 'save' operators (`;`, nibble `6`) to shift high-valued nibbles into the least-significant-nibble position of each byte.
This doesn't affect the output, but we need to override the final implicit variable to account for the saved (but ignored) values. Hence:

```
;- ;o ;/ ;\ ;` @< $o ;/ ;$   # program code (in final order), with final variable changed to ;$
69 6e 6a 6b 6e 4d 3e 6a 63   # nibbles

```

Modifying both folds (so returning right element `@` instead of left element `$`) avoids the lowest byte `3e`, but unfortunately outputs a negated value.
So we multiply (and save: `;*`) the negated value by its own sign (also saved: `;`$`): this corrects the output, introducing a new highest byte of `73`, but the overall score is still reduced.

# Answer
> 3 votes
# Excel, score = ~~103~~ 94 (length 46, range 48)

-9 score thanks to Engineer Toast

```
=LET(A,CODE(RIGHT(A1,ROW(A:A))),MAX(A)-MIN(A))

```

# Answer
> 3 votes
# Terse, 7 bytes + 6769 = 6776

```
找没最手样找到

```

Try it here

Could be worse.

```
找　　　　　　　　Char codes
　没　　　　　　　Maximum, after
　　最手　　　　　　Squaring and then square root (identity)
　　　　样　　　　Subtract
　　　　　找到　　Minimum

```

# Answer
> 3 votes
# Julia, 22 bytes + 80 = 102

```
+s=-(-(extrema(s)...))

```

Attempt This Online!

# Answer
> 3 votes
# Java 8, score: 134 (54 bytes)

```
s->s.chars().max().orElse(0)-s.chars().min().orElse(0)

```

**Try it online** (also contains code to extract the lambda function from the code-block and calculate its score: `(max_codepoint - min_codepoint) + length`).

Not too much too improve unfortunately.

* We could change the `x` to `\u0078`, but unfortunately the next highest codepoint then becomes `u` which isn't too much lower than `x`, so the +5 in byte-count is higher than the -3 in codepoint, giving a +2 in score instead of decrease: Try it online.
* Using a regular for-loop requires both `{}` and a space, so the difference of the max-min codepoints would widen on both ends. And in addition it's longer anyway: Try it online.

**Explanation:**

```
s->            // Method with String parameter and integer return-type
  s.chars()    //  Convert the String to an IntStream of codepoint integers
   .max()      //  Get the maximum of these codepoints
   .orElse(0)  //  Convert the OptionalInt to an int
               //  (`.orElse(0)` is 1 byte shorter than `.getAsInt()`)
  -            //  And subtract
   s.chars().min().orElse(0)
               //  The same to get the minimum codepoint

```

# Answer
> 3 votes
# K (ngn/k), ~~12 bytes + 86 = 98~~ 13 bytes + 56 = 69

h/t @isaacg

```
+/1_-':@/1<:\

```

Try it online!

# Answer
> 3 votes
# MATL, 3 bytes + 32 = 35

```
Sds

```

### Explanation

```
Sds
S     % Sort implicit input
 d    % Difference between adjacent elements
  s   % Sum the values

```

Try it online!

# Answer
> 2 votes
# Jelly, 5 bytes \+ 149 = 154

I think this is about as good as it's going to get in Jelly due to the distance between `O` (unavoidable as it's the only way to get the ordinals of the input string) and the large ordinals of Unicode characters representing the bytes for mapping and getting maximums and minimums, index into a list etc.

```
OÞOIS

```

A monadic Link that accepts a list of characters and yields the range size as an integer.

**Try it online!**

### How?

```
OÞOIS - Link: list of characters        (ordinal)
 Þ    - sort by:                        (222)
O     -   ordinal value                 (79)
  O   - ordinal values                  (79)
   I  - forward differences             (73)
    S - sum                             (83)
                                        ----
                                         222
                                       -  73
                                        ====
                                         149

```

# Answer
> 2 votes
# Charcoal -v, 35 bytes, score 61

```
castminusordceilceil[q]ordminmin[q]

```

Try it online! Abusing Charcoal's verbose parser again. In order for it to recognise `q` as a variable name I can't follow it with a letter, so the next nearest suitable characters are the list delimiters. I've also used `ceil` instead of `max` to avoid using an `x`; this costs 2 bytes but overall saves 1 from my score. Normally the program would be written like this:

```
Print(Cast(Minus(Ordinal(Maximum(q)), Ordinal(Minimum(q)))));

```

The best I could do in succinct Charcoal was a score of 10135:

```
⭆ψ⁻℅⌈θ℅⌊θ

```

Try it online! Link is to verbose version of code. Explanation: The limiting factors here are the Greek letter `θ` needed for the two occurrences of the input variable (the only other input method uses  which has a ridiculously high Unicode code point of 65531) and the  used to stringify the result (again,  would have had far too high a code point).

```
 ψ          Predefined string null character
⭆           Map over characters and join
     θ      Input string
    ⌈       Maximium
   ℅        Ordinal
  ⁻         Minus
        θ   Input string
       ⌊    Minimum
      ℅     Ordinal
            Implicitly print

```

If using bytes from Charcoal's code page was allowed, its score would "only" be 210:

```
ＳαＩ⁻℅⌈α℅⌊α

```

Try it online! Link is to verbose version of code. Explanation: The limiting factors here are that  (`Minimum`) is byte index 25 while `α` (variable `a`) is byte index 225, although I did reduce my score by 14 by taking the input into `α` rather than the default input of `θ` (variable `q`, byte index 241).

```
Ｓ           Input as a string
 α          Store in variable `a`
      α     Input string
     ⌈      Maximum
    ℅       Ordinal
   ⁻        Subtract
         α  Input string
        ⌊   Minimum
       ℅    Ordinal
  Ｉ         Cast to string
            Implicitly print

```

# Answer
> 2 votes
# Vyxal, 6 bytes + 67 = score 73

```
C:G$g-

```

Try it Online!

# Answer
> 2 votes
# Husk, 11 bytes + 63 = 74

```
ASz>o;FYOmc

```

Try it online!

```
ASz>o;FYOmc
         m   # map over input
          c  #   getting character values
        O    # and sort into ascending order;
  z          # now, zip together
   >         # getting differences
 S           #   the sorted list itself
             # and
    o;       #   the single-element list of
      F      #   fold over the sorted list
       Y     #   getting pairwise maxima
A            # finally, get the average
             # of the resulting single-element list.

```

# Answer
> 2 votes
# JavaScript (Node.js), 42 bytes + 80 = 122

```
s=>Math.max(...b=Buffer(s))-Math.min(...b)

```

Try it online!

# Answer
> 2 votes
# , score 70 (16 bytes, range 54)

```
[:+/2-/\a.I.]\:]

```

Try it online!

* `]` `\:` `]`: Pass the input (using the identity function `]`) on both sides of `\:` to sort it in descending order.
* `a.` `I.`: For each character of the sorted input, find its index in the "alphabet"; at least on TIO's setup, this contains all of ISO-8859-1 in order, which includes ASCII. Thus, this produces the ASCII values of the characters, while keeping the highest used character lower than the straightforward method of `3` `u:` would.
(`I.` would also take the following index if a character is not found, but that never happens; it was chosen over `i.` to reduce the highest used character.)
* `2-/\`: For each length-2 subarray (from the `2` and `\`), subtract the second value from the first (`-` `/`).
* `[:` `+/`: Take the sum (`+` `/`) of the values, using `[:` to do so monadically.

# Answer
> 2 votes
# Ly, 8 bytes + 70 = 78

```
ia0I-s>l

```

Try it online!

I found a shorter program, but the character range of the code was big enough that it had a higher total score.

```
ia        - read STDIN onto stack as codepoints, sort the stack
  0I      - copy the bottom of the stack to the top
    -     - subtract to get the range
     s>l  - save result, switch to clean stack, load result

```

# Answer
> 2 votes
# Raku, 25 bytes

ASCII range: 88 Length: 25 Total score: 113

```
[-] @_.ords.minmax[*-1,0]

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 98 score (18 bytes)

ASCII range: 80
Length: 18
Total score: 98

```
s=>s.Max()-s.Min()

```

Try it online!

* -27 score thanks to Kevin Cruijssen for the tip to use C# Interactive

---

# C# (Visual C# Compiler), 125 score (36 bytes)

ASCII range: 89
Length: 36
Total score: 125

```
s=>s.Max()-s.Min()

```

If we're going traditional through the compiler then we have to include an extra 18 bytes for `using System.Linq;`

Try it online!

# Answer
> 2 votes
# Pyth, 8 bytes + 34 = 42

```
+F.+CDCM

```

Try it online!

* `CM`: Map to ASCII value
* `CD`: Sort (equivalent to `S`)
* `.+`: Deltas (Differences between consecutive elements, all nonegative because of sort)
* `+F`: Sum (equivalent to `s`)

Using `.+` is golfier than `h` and `e`, and also stays within the established ASCII value range.

# Answer
> 2 votes
# Burlesque, 12 bytes + 52 = 64

```
)**J>]\/<].-

```

Try it online!

```
)**  # Map to char code
J    # Duplicate
>]   # Maximum
\/   # Swap
<]   # Minimum
.-   # Difference

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 31 bytes + 85 = 116

```
ToCharacterCode@s//Max@#-Min@#&

```

Try it online!

# Answer
> 2 votes
# Thunno 2 `GB`, 2 + 24 = 26

```
G_

```

Try it online!

Port of lyxal's Vyxal answer.

#### Explanation

```
G_  # Implicit input
    # Convert to codepoints
G   # Maximum codepoint
 _  # Subtract each input codepoint
    # Find the maximum
    # Implicit output

```

# Answer
> 1 votes
# Sequences, score = 73 + 4.12 = 77.12

(Sequences uses the 96 printable ASCII characters as its codepage, so the byte count of this program is \\$5\log\_{256}(96) \approx 4.12\\$)

```
`vMm-

```

### Explanation

```
`vMm-  # Implicit input as a string
`v     # Get the ASCII values of the input string in a list
  M    # Get the maximum value of that list
   m   # Get the minimum value of that list
    -  # And subtract to find the range
       # (implicit output)

```

# Answer
> 1 votes
# Python, 39 + 80 = 119

```
print(ord(max(s:=input()))-ord(min(s)))

```

Attempt This Online!

# Answer
> 1 votes
# Ruby, 26 bytes + 80 = 106

-2 bytes thanks to Steffan

```
->s{y=s.bytes;y.max-y.min}

```

Attempt This Online!

# Answer
> 1 votes
# Haskell, 27 bytes + 84 = score 111

```
_?s=(maximum$s)-(minimum$s)

```

Attempt This Online!

# Answer
> 1 votes
# J-uby, 21 bytes + 87 = 108

```
:bytes|:-%[:max,:min]

```

Attempt This Online!

# Answer
> 1 votes
# , 19 bytes

```
(-/)7h$(max;min)@\:

```

# k4, 17 bytes

```
(-/)7h$(|/;&/)@\:

```

# Answer
> 1 votes
# , score = 15 + 79 = 94

```
[:(>./-<./)3&u:

```

Attempt This Online!

```
[:(>./-<./)3&u:
[:               NB. enforce f (g y)
           3&u:  NB. convert string to list of char codes
  (       )      NB. monadic fork
       <./       NB. min
   >./           NB. max
      -          NB. subtract

```

# Answer
> 1 votes
# , 29 bytes + 77 = 106

```
\(a)diff(range(utf8ToInt(a)))

```

Attempt This Online!

Seems that most golfy approach has also the lowest score, since we need to use `utf8ToInt()` and it has the range of 77 by itself.

# Answer
> 1 votes
# 05AB1E, score: ~~158~~ 124 (4 bytes)

```
Ç{¥O

```

Try it online or verify all test cases or verify its score.

**Explanation:**

```
Ç     # Get a list of codepoint integers of the (implicit) input-string
 {    # Sort them
  ¥   # Get the forward differences/deltas
   O  # Sum those together
      # (after which the result is output implicitly)

```

# Answer
> 1 votes
# MathGolf, score: ~~200~~ 191 (~~4~~ 6 bytes†)

*†: MathGolf uses Code page 437*.

```
$_╙\╓-

```

Increased the byte-count to slightly improve the score, but this is pretty hopeless.. The `ord` builtin `$` is too far apart from most of the other useful builtins like `min`()/`max`()/`sum`(`Σ`)..

Input as a list of characters.

Try it online.

**Explanation:**

```
$       # Get the codepoint integers of each character in the (implicit) input-list
 _      # Duplicate it
  ╙     # Pop and push its maximum
   \    # Swap
    ╓   # Pop and push its minimum
     -  # Subtract this minimum from the maximum
        # (after which the entire stack is output implicitly)

```

# Answer
> 1 votes
# \>\<\>, Score: 50 bytes + 74 = 124

```
0ff*i:0(ee+*98++0.:@:@$:@)?$?>@$:@$:@(?$?>$30.@-n;

```

Try it online!

**Explanation**

Initialize **max = 0** and **min = 225**.
Then go through the input and update these values as needed.
At the end, print **max - min**.

**Range Max: n = 110**
We need **n** to print a number, so there isn't much we can do about this.

**Range Min: $ = 36**
**$** swaps the top 2 values of the stack. Replacing it could save **6** on the range, but since we are using it in 6 places it seems unlikely that could we could save on the score by the reducing the range.

**Code**

We've replaced **`~` = 126** with `?`  and **`r` = 114** with `@$` which saves **16** on the range at the cost of **3** bytes.

We've replaced the line feed **= 10** with jumps **`.` = 46** which saves **26** on the range at the cost of **6** bytes.

# Answer
> 1 votes
# Perl 5 `-plF''` 33 bytes + 84 = 117

```
@_=map ord,sort@F;$_=$_[-1]-$_[0]

```

Try it online!

# Answer
> 1 votes
# Factor, 70 range + 21 bytes = 91 score

```
math.statistics:range

```

Requires modernish Factor for fully-qualified word syntax, hence nothing online will suffice.

# Answer
> 1 votes
# PHP, 39 bytes + 84 -\> 123

```
fn($s)=>max($a=unpack('C*',$s))-min($a)

```

Try it online!

EDIT: OK this time I admit functional approach is way better :P

OLD VERSION:

# PHP, -F 67 bytes + 78 -\> 145

```
for($n=INF;$c=ord($argn[$i++]);$c<$m?:$m=$c)$c>$n?:$n=$c;echo$m-$n;

```

Try it online!

I wanted to give it a shot without arrays / min / max, in my traditional horrific-full of dollars-for loop Style and try to optimize for ASCII range rather. Stupid `$argn` cannot be in full caps. funny that it gives the same score like this (caps and no space nor brackets was the original plan):

# PHP, -F 88 bytes + 57 -\> 145

```
FOR($N=INF;$C=ORD($GLOBALS[STRTOLOWER(ARGN)][$I++]);$C<$M?:$M=$C)$C>$N?:$N=$C;ECHO$M-$N;

```

Try it online!

# Answer
> 1 votes
# APL, 11 chars + 9069-codepoint range = 9080.

## (In Dyalog one-byte encoding, range is 186 for a total of 197.)

```
(⌈/-⌊/)⎕UCS

```

Try it online!

# Answer
> 1 votes
# Python 3, 32 bytes + 88 = 120

```
lambda x:ord(max(x))-ord(min(x))

```

Try it online!

# Answer
> 1 votes
# GolfScript, 8 bytes, score 64

```
$(\)@-\;

```

Try it online!

# Explanation

```
char     : usage                                : stack
$        : ($)ort the (implicit) input          : <sorted input>
 (       : take the first element out           : <sorted input> <first item>
  \      : swap the top two values of the stack : <first item> <sorted input>
   )     : last item                            : <first item> <sorted input> <last item>
    @    : rotate the stack                     : <sorted input> <last item> <first item>
     -   : subtract, giving us the range        : <sorted input> <range>
      \  : swap the top two values on the stack : <range> <sorted input>
       ; : discard the top of the stack         : <range>
(after which the stack is implicitly output)

```

# Answer
> 1 votes
# Java 8, 106 ~~108~~ bytes + 80 range = score 186 ~~188~~

`-2 bytes thanks to @ceilingcat`

```
s->(s.chars().reduce(0,(a,b)->a>0?b>a>>16?b*65792-a%256*255:b<a%256?a/65536*65792-b*255:a:b*65537)>>8)%256

```

Try it online!

There is a better Java solution already posted, but maybe my answer could interest some people.
I'm not sure how to properly explain it, but by trying to keep only 1 inline Java stream, my goal was to carry 3 numbers \< 256 inside only 1 integer ("a", the accumulator of the stream reduction) using this structure:
`[_____max_value_____] [difference_between_max_and_min] [____min_value____]`
`<- 65 536 and over -> <- from 256 to 65 535 -> <- from 0 to 255 ->`

# Answer
> 1 votes
# Lua, ~~66~~ 57 bytes + ~~89~~ 86 = score ~~155~~ 143

```
s=...print(math.max(s:byte(1,#s))-math.min(s:byte(1,#s)))

```

Try it online!

Program which takes command line argument for the strings.

# Answer
> 1 votes
# Stax, 2 bytes + 57 = 59 score

```
:s

```

Run and debug it

Apparently there's a builtin...

# Answer
> 1 votes
# KamilaLisp v0.2, 88 + 35 = 123

```
[- $(foldl1 max) $(foldl1 min)]@ucs

```

# Answer
> 1 votes
# Go, 95 bytes + 93 = 188

```
func(s string)int{m:=rune(s[0]);n:=m;for _,r:=range s{if m<r{m=r};if n>r{n=r}};return int(m-n)}

```

Attempt This Online!

# Answer
> 1 votes
# Python 3, 39 bytes + 80 range = 119

```
print(ord(max(a:=input()))-ord(min(a)))

```

Try it online!

A full program is one point better here because it avoids the minimum character " " (32) for "(" (40).

# Answer
> 1 votes
# Arturo, 31 bytes + 33 = ~~106 94~~ 64

```
function[x][do[x|min]x|max|sub]

```

Try it!

# Answer
> 1 votes
# PowerShell, 58 bytes + 93 = 151

```
$args|%{$a=($_|% t*y)|%{[byte][char]$_}|sort;$a[-1]-$a[0]}

```

Try it online!

# Answer
> 1 votes
# Raku (Perl 6) (rakudo), 16 bytes + 78 = 94

```
+*.ords.minmax-1

```

Attempt This Online!

# Answer
> 1 votes
# Nekomata, 6 bytes + 66 = 72

```
eo:h-l

```

Attempt This Online!

```
eo:h-l
e       Convert to codepoints
 o      Sort
  :     Duplicate
   h    Head
    -   Subtract
     l  Last

```

# Answer
> 1 votes
# Vyxal 2.4.1 `K`, 4 bytes + 26 range = Score 30

```
G?-G

```

Try it Online!

If I knew what I was doing in 2021, this could have been 3 bytes with the `G` flag, but I never did figure out how to make the `K` flag play nice with other flags.

## Explained

```
G?-G
G     # Greatest character in the input
 ?-   # With each character code subtract from it
   G  # Greatest of those

```

Created with the help of Luminespire.

---
Tags: string, code-challenge
---