title: Fill a bowl with alphabet soup

text:
# Question
Title: Fill a bowl with alphabet soup
*We seem to never get tired of alphabet-related challenges...*

---

# The recipe

Given

* a string of letters `S`, and
* two positive integers `M`, `N`,

produce an alphabet soup with the letters of `S` occupying **random positions** in a **rectangular bowl** of size `M`×`N`, **framed** by a non-alphabetic, non-space character to represent the rim of the bowl.

Positions not used by letters should be displayed as spaces. See the **examples below**.

# Aditional rules

* The size `M`×`N` refers to the **interior** of the bowl. The size including the rim is `M+2`×`N+2`.
* Each character from `S` should appear *once* in the bowl, in a **different position**; that is, one character cannot overwrite another.
* `S` **may contain duplicates**. For instance, if `S` is the string `'abcc'`, the soup must contain one `a`, one `b`, and two `c` (all in different positions).
* The inputs will satisfy the **restrictions** `M >= 1`, `N >= 1`, `1 <= length(S) <= M*N`.
* The rim of the bowl can be **any non-alphabetic, non-space character**, consistent across program runs and input values.
* Letter positions in the bowl are random, so the result may differ every time the program is run with the same inputs.
* Given the input, every possible set of letter positions should have a **non-zero probability**. Since this cannot be checked from a few realizations of the program, please explain how your code fulfills this.
* Leading or trailing **whitespace** around the rim is allowed.
* `S` will contain are **only uppercase** letters. If wou wish, you can choose to take **only lowercase** letters.
* Input and output are flexible as usual. For example, the output can be a string with newlines, a 2D character array, or a list of lines.
* Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
* The shortest code in bytes wins.

# Examples

Inputs are shown as `S, [M N]`, where `M` is number of rows and `N` is number of columns. The character `#` is used for the rim.

```
'O', [1 1]:

###
#O#
###

'HEY', [1 3]:

#####
#YHE#
#####

'HELLO', [4 11]:

#############
#  O        #
#         H #
#    LE     #
#   L       #
#############

'ADVNJSGHETILMVXERTYIOJKCVNCSF', [8 12]:

##############
#K  V  L   S #
# A   V  X H #
#T    M C    #
# I       O N#
#  YC        #
# G  I   R SE#
#   J      F #
#JT  D  V EN #
##############

'OOOOOOOOOOXXXXX', [13 31]:

#################################
#    X                          #
#                O              #
#                               #
#                  X            #
#                        O      #
#             X           O     #
#      O                        #
#         X                     #
#                        O      #
#       X                       #
#                    O          #
#  O      O      O              #
#                             O #
#################################

'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ', [11 41]

###########################################
#                                       JU#
#     Q         C M    G     R T U Y  H   #
#  KI          E   H    M   YO            #
#      V BW        I    JC                #
#     SV           D     P   B          U #
#           A     F    RF   J  KP E       #
#            E   N      TH        Z       #
#    N  BM  O     Q   I        AS N  WX   #
#   S     O  K       G L       P       Q  #
#Z     L T         R   L       A      F DD#
#      V   Y           WX   C       G XZ  #
###########################################

```

# Answer
# 05AB1E, ~~20~~ ~~18~~ ~~16~~ ~~15~~ 14 bytes

```
*j.rS²ô2Føε8.ø

```

Takes three inputs in the order: height, width, string. Output as a 2D list of characters.
Uses `8` as border, but could be any digit.

-1 byte thanks to *@Grimy*.

Try it online or verify all test cases. (TIO contains `}}J»` in the footer to pretty-print the result; feel free to remove it to see the actual output 2D list of characters instead.)

**Explanation:**

```
*               # Multiply the (implicit) width and height inputs
 j              # Pad the (implicit) input-string with up to that amount of leading spaces,
                # so the total string-length is equal to that value
  .r            # Shuffle the characters in the string
    S           # Convert the string to a list of characters
                # (edge-case for the zip below with strings of size 1 with 1x1 dimensions)
     ²          # Push the width input again
      ô         # Split the list of characters into parts of that size
       2F       # Loop 2 times:
         ø      #  Zip/transpose the 2D list; swapping rows/columns
          ε     #  Inner map over each line:
           8.ø  #   And surround this line-list with a leading/trailing "8"
                # (after the loop, the result is output implicitly)

```
> 13 votes

# Answer
# APL (Dyalog Unicode), 25 bytesSBCS

```
'#',∘⌽∘⍉⍣4{⍵⍴⊃¨↓∘⍺¨?⍨×/⍵}

```

Try it online!

-22 thanks to @ngn, -7 thanks to @ngn and @Adám

Explanation:

```
'#',∘⌽∘⍉⍣4{⍵⍴⊃¨↓∘⍺¨?⍨×/⍵}
          {            ⍵} ⍝ Function that generates the content
                          ⍝  argument: ⍵ (width and height), ⍺ (string)
                     ×/   ⍝ get the product
                   ?⍨     ⍝ For each randomized elements
               ↓∘⍺¨       ⍝ take the character in ⍺
           ⍵⍴⊃¨           ⍝ turn it back into a matrix of shape ⍵
    ∘ ∘ ⍣4                ⍝ Then, 4 times, do these 3 things:
'#',                      ⍝ - prepend a # to the axis
     ⌽                    ⍝ - reverse the columns
       ⍉                  ⍝ - swap columns and lines

```

# ~~APL (Dyalog Extended), 21 bytesSBCS~~

**The rim's angles are different characters**

```
{⌂disp⊂⍵⍴⊃¨↓∘⍺¨?⍨×/⍵}

```

Try it online!

Using the dfn to display the box.
> 7 votes

# Answer
# Python 3, 110 bytes

```
lambda s,m,n,r=['#']:[r+(n*r+[i for i,j in{*zip(s+m*n*' ',range(m*n))}]+n*r)[k*n:-~k*n]+r for k in range(m+2)]

```

Try it online!

Randomizes by using a `set` comprehension and returns a 2D character array.
> 6 votes

# Answer
# , ~~30~~ 29 bytes

-1 byte thanks to Jonah

```
'#'|.@|:@,^:4[$*/@[(?~@[{{.)]

```

Try it online!
> 5 votes

# Answer
# Bash + coreutils, ~~139~~ 125 characters

```
r=`printf %$3s@@|tr \  @`
echo $r
printf %$[$2*$3]s $1|fold -1|shuf|tr -d \\n|fold -$3|paste -d@ <(:) - <(:)|head -$2
echo $r

```

Sample run:

```
bash-5.0$ bash soup.sh HELLO 4 11
@@@@@@@@@@@@@
@  H        @
@      OE   @
@    L      @
@          L@
@@@@@@@@@@@@@

```

Try it online!

### Bash + coreutils + boxes, 97 characters

```
printf %$[$2*$3]s $1|fold -1|shuf|tr -d \\n|fold -$3|boxes -dsimple -s$[$3+2]x$[$2+2] -pa0 -itext

```

Sample run:

```
bash-5.0$ set -- HELLO 4 11

bash-5.0$ printf %$[$2*$3]s $1|fold -1|shuf|tr -d \\n|fold -$3|boxes -dsimple -s$[$3+2]x$[$2+2] -pa0 -itext
*************
* O   L  E  *
*      H    *
*           *
*     L     *
*************

```

Try it online! (Partially, as `boxes` is not installed on TIO.)
> 5 votes

# Answer
# PowerShell, ~~163~~ ~~111~~ 93 bytes

```
param($w,$h,$s)'#'*$w+-join($s|% *ht($w*$h)|% t*y|sort{Random})+'#'*$w-replace".{$w}",'#$0#
'

```

Try it online!

Takes input as `$w`idth, `$h`eight, `$s`tring.

Constructs a string of `#` of the appropriate `$w`idth, string-joins that with some computation, and then that same `#` string again. The computation starts with taking the input `$s`tring, and doing a .padRig`ht` up to the `$w`idth by `$h`eight length (i.e., make a string long enough to completely take up the rectangular space. We then convert that string `t`oCharArra`y`, and `sort` it `Random`ly. That gives us the mixed-up middle portion. Finally, we `-replace` it into chunks of equal `$w`idth, and surround those chunks with `#`s.

*-52 thanks to inspiration from AZTECCO*
*-18 bytes thanks to mazzy*
> 5 votes

# Answer
# JavaScript (ES7), 125 bytes

Returns a string. Uses `0` as the frame character.

```
(s,h,w)=>(a=[...s.padEnd(w++*h++)].sort(_=>Math.random()-.5),g=x=>y+~h?(x%w&&y%h&&a.pop())+[`
`[x-w]]+g(x<w?x+1:!++y):a)(y=0)

```

Try it online!

### Commented

```
(s, h, w) => (               // s = string; h = height; w = width
  a =                        // build an array a[] consisting of:
    [...s.padEnd(w++ * h++)] //   all original characters in s padded with spaces for a
    .sort(_ =>               //   total length of w * h, in a random order
      Math.random() - .5     //   (this is not guaranteed to be uniform, but it is not
    ),                       //   required to be)
  g = x =>                   // g is a recursive function taking x:
    y + ~h ?                 //   if we haven't reached the end of the grid:
      ( x % w &&             //     if we're not located on a vertical border
        y % h &&             //     nor on a horizontal border,
        a.pop()              //     extract the last character from a[]
      ) +                    //     (otherwise, append '0')
      [`\n`[x - w]] +        //     if we've reached the end of the row, append a linefeed
      g(                     //     append the result of a recursive call:
        x < w ? x + 1 : !++y //       using either (x+1, y) or (0, y+1)
      )                      //     end of recursive call
    :                        //   else (end of grid):
      a                      //     a[] is now empty and can be used as an empty string
)(y = 0)                     // initial call to g with x = y = 0

```
> 4 votes

# Answer
# PHP 7.4, ~~107~~ ~~99~~ 94 characters

```
fn($s,$r,$c)=>_.chunk_split(($b=str_pad(_,$c,_)).str_shuffle(str_pad($s,$r*$c)),$c,"_
_").$b._

```

Thanks to:

* Ismael Miguel for reminding me about PHP 7.4's arrow functions (-10 characters)
* Night2 for efficiently reversing the concatenations and the `join()` (-8 characters)
* Night2 for showing how to use `chunk_split()`'s `$end` parameter (-5 characters)

Try it online!

### PHP 7.3, ~~117~~ ~~112~~ 108 characters

```
function s($s,$r,$c){echo _.chunk_split(($b=str_pad(_,$c,_)).str_shuffle(str_pad($s,$r*$c)),$c,"_
_").$b._;}

```

Thanks to:

* Night2 for efficiently reversing the concatenations and the `join()` (-5 characters)
* Night2 for showing how to use `chunk_split()`'s `$end` parameter (-4 characters)

Sample run:

```
php > function s($s,$r,$c){echo _.chunk_split(($b=str_pad(_,$c,_)).str_shuffle(str_pad($s,$r*$c)),$c,"_
php " _").$b._;}
php > s('HELLO', 4, 11);
_____________
_  L        _
_        L  _
_E          _
_    OH     _
_____________

```

Try it online!
> 4 votes

# Answer
# APL (Dyalog Extended), 23 bytesSBCS

Anonymous tacit infix function. Takes `[M,N]` as left argument and `S` as right argument.

```
'#',∘⌽∘⍉⍣4⊣⍴×/⍛(?⍨⍤⊣⊇↑)

```

Try it online!

`×/⍛(``)` apply the following function between the arguments, replacing the left argument with its product:

take `M`×`N` characters from `S`, padding with spaces on the right

reorder that to the following order:

`?⍨⍤` the shuffled indices 1 through…
the left argument (`M`×`N`)

**r**eshape that to the following shape:

the left argument (i.e. `M` rows and `N` columns)

`'#'``⍣4` apply the following function four times, each time with the hash character as left argument:
`∘⍉` transpose the right argument
`∘⌽` mirror the right argument
`,` concatenate a column of hashes to the left side of that
> 4 votes

# Answer
# Red, ~~120~~ ~~116~~ ~~114~~ 112 bytes

-2 bytes thanks to @Kevin Cruijssen!

```
func[s m n][random pad s m * n insert/dup t: copy"00"0 n
print t loop m[print rejoin[0 take/part s n 0]]print t]

```

Try it online!
> 3 votes

# Answer
# MATL, ~~22~~ 19 bytes

```
tZ"ibpyn&Z@(TT35&Ya

```

Try it online!

Thanks @LuisMendo for saving 3 bytes, so now it has the same bytecount as @flawr's answer, but sufficiently different to post anyway. High-level agorithm overview:

```
 Z"                  % Create n x m matrix of spaces
           (         % Index into this matrix:
   i                 %  The alphabet vermicelli (explicit input)
        &Z@          %  at a random locations (randperm), which are
      yn             %   length(S) numbers, ranging
t   bp               %   from 1 to n*m
            TT35&Ya  % And finally add a border

```
> 3 votes

# Answer
# Perl 6, ~~74~~ 67 bytes

*-5 bytes thanks to Jo King*

```
{0 X~0 x$^n,|comb($n,[~] $^s.comb[pick *,^$^m*$n]X//' '),0 x$n X~0}

```

Try it online!

### Explanation

```
{                                                                 }
                                         ^$^m*$n  # Range 0 .. M*N-1
                                  pick *,  # Shuffle
                         $^s.comb  # Split S into chars
                                 [              ]  # Pick shuffled elements
                                                 X//' '  # undef to space
                     [~]  # Join
             # Split into n-character strings
             comb($n,                                  )
            |  # Flatten
     # Add top and bottom of bowl
     0 x$^n,                                            ,0 x$n
 # Add left and right of bowl
 0 X~                                                          X~0

```
> 3 votes

# Answer
# k4, ~~32~~ 28 bytes

```
{4{|+x,'"#"}/y#a?(a:-*/y)$x}

```

edit: -4 thanks to Galen Ivanov!

called like

```
f["hey";3 3]

```

---

explanation:

```
                 (a:-*/y)    / neg product of y and assign to a
                         $x  / left pad x so we have char vector the length of the inner area
               a?            / take `a` random drawings. if a is negative, draw with no duplicates/replacements
             y#              / reshape to y's dimensions
 4{        }/                / do {} 4 times
   |+x,'"#"                  / append "#" along right-side of x then transpose (+) and reverse (|)

```
> 3 votes

# Answer
# Ruby, 121 bytes

Creates the bowl, queries the indices of all spaces within the bowl, samples a number of spaces equal to the size of the string, and fills them in. `sample` does not return a sorted list, so there is no need to shuffle. Searching indices up to `9*m*n` (which almost certainly goes out of range) will still get all spaces and is 1 byte shorter than `r.size`.

```
->s,m,n{r=[t=?@*(n+2),*["@#{' '*n}@"]*m,t]*$/;i=-1;(0..9*m*n).select{|j|r[j]==' '}.sample(s.size).map{|j|r[j]=s[i+=1]};r}

```

Try it online!
> 3 votes

# Answer
# Perl 5 `-lF`, ~~99~~ 97 bytes

*-2 bytes courtesy of @NahuelFouilleul*

```
%k=map{$_=>$F[$_]||$"}0..($m=<>)*($n=<>)-1;say+($p='#'x($n+1)),map"#
#"x!($i++%$n).$_,values%k,$p

```

Try it online!
> 3 votes

# Answer
# T-SQL 2017, 232 bytes

Testing this online is an older version of sql-server costing another character. I posted the shorter version.

**Golfed:**

```
DECLARE @ varchar(max)=''SELECT top 999 @+=substring(@i,number+1,1)FROM spt_values
WHERE type='P'and number<@a*@b
ORDER BY newid()WHILE-@b<1SELECT @=stuff(@+' ',@b*@a+1,0,'#
#'),@b-=1PRINT stuff(replicate('#',2+2*@a),2+@a,0,trim(@))

```

**Try it online**

**Ungolfed:**

```
DECLARE @ varchar(max)=''

SELECT top 999 @+=substring(@i,number+1,1)
FROM spt_values
WHERE type='P'and number<@a*@b
ORDER BY newid()

WHILE-@b<1
SELECT @=stuff(@+' ',@b*@a+1,0,'#
#'),@b-=1
PRINT stuff(replicate('#',2+2*@a),2+@a,0,trim(@))

```
> 3 votes

# Answer
# Java (JDK), ~~180~~ 178 bytes

Not a single extra import:

```
(y,m,n)->{for(m*=n;y.length()<m;y+=" ");var s="";for(;m-->0;y=s)for(var c:y.split(s=""))s=Math.random()<.5?s+c:c+s;s="#".repeat(n);return(s+y+s).replaceAll(".{"+n+"}","\n#$0#");}

```

Try it online!

It was quite the struggle to get this golfed down. In particular, the imports involved with Collections.shuffle()/Arrays methods were too much to accept, so I had to create my own String shuffling algorithm (probably neither efficient nor uniformly distributed). Massive thanks to Steven for proving any set of positions can be generated from the algorithm.

Formatted (with explanation):

```
(y, m, n) ->                                                   // y = yummies in the soup,
{                                                              // m = height, n = width
    for (m *= n; y.length() < m; y += " ")                     // set m to m*n and
        ;                                                      // add spaces to y to fill up
    var s = "";                                                // the rest of the soup
    for (; m-- > 0; y = s)                                     // for m*n iterations, scramble y
        for (var c : y.split(s = ""))                          // with random appends
            s = Math.random() < .5 ? s + c : c + s;
    s = "#".repeat(n);                                         // create the top/bottom of the rim
    return (s + y + s).replaceAll(".{" + n + "}", "\n#$0#"); // add all sides of the rim
};

```
> 3 votes

# Answer
# Charcoal, 27 bytes

```
ＮθＮη↖Ｂ⁺²θ⁺²η#ＦＳ«Ｗ℅ＫＫＪ‽θ‽ηＰι

```

Try it online! Link is to verbose version of code. Takes input in the order width, height, string. Explanation:

```
ＮθＮη

```

Input the width and height.

```
↖Ｂ⁺²θ⁺²η#

```

Frame the bowl.

```
ＦＳ«

```

Loop over the characters in the string.

```
Ｗ℅ＫＫＪ‽θ‽η

```

Jump to a random position in the bowl until an empty spot is found.

```
Ｐι

```

Print the current character without moving the cursor.
> 2 votes

# Answer
# Japt `-R`, ~~21~~ 18 bytes

```
úV*W ö¬òW ²Ô²û2W+2

```

Try it

```
úV*W ö¬òW ²Ô²û2W+2     :Implicit input of string U=S and integers V=M & W=N
úV*W                   :Right pad U with spaces to length V*W
     ö¬                :Random permutation
       òW              :Split to array of strings of length W
          ²            :Push 2
           Ô           :Reverse
            ²          :Push 2
             û2W+2     :Centre pad each element with "2" to length W+2
                       :Implicit output, joined with newlines

```
> 2 votes

# Answer
# MATL, ~~29 27~~ 19 bytes

```
pZ@iy~hw)1GeTT35&Ya

```

Try it online!

Thanks @LuisMendo for -8 bytes!

Explanation: `p` computes the number of soup-pixels. Then `Z@` produces a random permutation of size of number of soup pixels. We will use this as indices to `iy~h` which is the input string with enough spaces added. `w)` swaps the two and indexes one with the other. We then reshape `1Ge` the shape into the desired rectangle and `#`-pad it using `TT35&Ya`.
> 2 votes

# Answer
# Icon, ~~136~~ ~~133~~ ~~131~~ 118 bytes

```
procedure f(s,n,m)
s||:=repl(" ",m*n-*s)
!s:=:?s&\z
write(t:=repl(0,m+2))
write(0,s[1+(0to n)*m+:m],0)&\z
write(t)
end

```

Try it online!
> 2 votes

# Answer
# C (clang), ~~169~~ ~~...~~ 156 bytes

```
i,b;f(n,m,s)char*s;{char o[b=i=-~++n*(m+=3)],*a=o;for(srand(&a);--i;)*a++=i%m?-~i%m<3|i<m|i>m*n?35:32:10;for(*a=0;*s;*a=*a-32?*a:*s++)a=o+rand()%b;puts(o);}

```

Try it online!

Saved 7 @ceilingcat suggestion to use -~variable and auto storage for string o plus many improvements.

Saved 4 again from @ceilingcat

Degolf :

```
char*a,// pointer for set operations
*o=malloc(b=i=(m+=3)*(n+=2));  => o[b=i=(m+=3)*-~++n]
// before allocating for the whole bowl as a char array
// increments m by 3 (2 for rims and 1 for '\n') and n by one but allocates for 2(rims)
// and assigns bowl size to i and b.
srand(time(0));// seeds rand function
for(// loop to make empty bowl
a=o;// using pointer as iterator
 --i ;)//  i decremented as a counter

 *a=// sets every char to..
 i%m?// if(not) over right side of bowl (m+3)
   -~i%m<3|i<m|i>m*n-m?35// if on rim '#'//-~i == (i+1)
   :32 // else ' '
  :10;// i%m==0

for(*a=0;// before loop terminates bowl with \0
 *s;// for every letters(exit on '\n')
 *a=*a-32?*a:*s++)
 // puts letter if bowl at a is a space and
 // go to next letter

 a=o+rand()%b;
 // sets a to o offsetted by random

puts(o);// prints bowl

```
> 2 votes

# Answer
# Jelly, 16 bytes

```
P⁶ẋaẊs⁸ṪṾ€«”~ZƊ⁺

```

A dyadic Link accepting a list of integers, `[M, N]`, on the left and a list of characters, `S`, on the right which yields a list of lists of characters, the lines. Uses the tilde character, `~`, as the border.

**Try it online!**

All possible outputs have a non-zero chance of being yielded since we shuffle () a list of the characters of `S` along with the appropriate number of spaces.

The code `Ṿ€«”~ZƊ⁺` saves the byte which I imagine would be required to join with newlines that full programs using an integer such as zero would need to employ (e.g. `P⁶ẋaẊs⁸Ṫ;€0ZUƊ4¡Y` or `P⁶ẋaẊs⁸Ṫj@€Ø0Z$⁺Y`). Maybe there's a way to save more...?
> 1 votes

# Answer
# C# (.NET Core), 274 bytes

\[Without LINQ\]

Embarrassing number of bytes, but, this is what I got.

```
(x,y,z)=>{var f=new string('#',x+2)+'\n';char[] b=new string(' ',y*x).ToCharArray();Random r=new Random();while(z.Length>0){var d=r.Next(0,y*x);if(b[d]==' '){b[d]=z[0];z=z.Substring(1);}}z=f;for(var j=1;j<y*x+1;)z+=(j%x==1?"#":"")+b[j-1]+(j++%(x)==0?"#\n":"");return(z+=f);}

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~105~~ 78 bytes

Takes an array of characters and two integers; returns a string.

```
->s,h,w{((e=?#*w)+(s+[" "]*(h*w-s.size)).shuffle*""+e).gsub /.{#{w}}/,'#\&#
'}

```

Attempt This Online!
> 1 votes

---
Tags: code-golf, string, ascii-art, random, alphabet
---


title: ssTTsSTtRrriinInnnnNNNIiinngg

text:
# Question
Title: ssTTsSTtRrriinInnnnNNNIiinngg
## Challenge

For each character of the string except for the last one, do the following:

* Output the current character.
* Followed by randomly outputting from the following list a random number of times between 1 - 5 (inclusive):

+ The current character
    + The next character of the string
    + The switchcase version of the character that you are currently on
    + The switchcase version of the next character of the string.

## Test Cases

`String` --\> `SSSTSStrTrIiinIIngn`

`, . , . , . Hello world!` --\> `,,, .. , ,, .... , , .. .. . HHH HHEeelLlLllooO wwOworOOrrrRllDd!!D`

`Programming Puzzles and Code Golf` --\> `PrPPrRrOooooogggRgGraAraaaMMMmmmimMIiininGGgG PPPPuZzZZzZzzZzllLLEEeEsEsssS a aANnNddD C COCoooOOdeDe E GGGoOllFFf`

## Notes

* You only need to apply the switchcase version of a character if the character is part of the alphabet (A-Z and a-z).
* Your random function does not need to be uniform but it still needs to have a chance of returning any element in the list given.
* You are allowed to use any standard I/O format.
* You may assume that the length of the input is greater than or equal to two.
* You may assume that the input only consists of ASCII characters.
* The title is not a test case (it is unintentional if it is a valid test case).
* Switchcase means to turn the char to lowercase if it is uppercase and to turn it to uppercase if it is lowercase.

# Answer
# Gaia, 25 bytes

```
ṇ\+†ṅ\⟨)₌¤:~+4ṛ⟨ṛ₌¤⟩ₓ\⟩¦$

```

Try it online!

*Thanks to Kevin Cruijssen for pointing out 2 bugs!*

```
ṇ\				| delete the last character from the input
  +†				| push the input again and concatenate together, so for instance
				| 'abc' 'bc' becomes ['ab' 'bc' 'c']
    ṅ\				| delete the last element
       ⟨       		⟩¦	| for each of the elements, do:
	)₌			| take the first character and push again
	  ¤			| swap
	   :			| dup
	    ~			| swap case
	     +			| concatenate strings
	      4ṛ		| select a random integer from [1..5]
	        ⟨    ⟩ₓ		| and repeat that many times
		 ṛ₌¤		| select a random character from the string
		      \ 	| clean up stack
			   $	| convert to string
```

Note that `4ṛ` is because  is implemented for an integer `z` as python's `random.randint(1,z+1)`, which returns an integer `N` such that `1<=N<=z+1`.
> 6 votes

# Answer
# APL (dzaima/APL), 23 bytes

Anonymous tacit prefix function.

```
∊2(⊣,{?4⍴⍨?5}⊇,,-⍤,)/

```

Try it online!

`2(``)/` apply the following infix tacit function between each character pair:

`-` the switchcase
of
`,` the concatenation of the pair

`,,` prepend the concatenation of the pair to that

`{``}⊇` pick the following elements from that:

`?5` random number in range 1…5

`4⍴⍨` that many fours

`?` random indices for those

**ϵ**nlist (flatten)
> 4 votes

# Answer
# Bash, 121 bytes

*-20 bytes thanks to Nahuel*

*-9 bytes thanks to roblogic*

```
for((i=0;i<${#1};i++)){
s=${1:i:1}
m=${1:i:2}
m=${m,,}${m^^}
for((t=0;t++<RANDOM%6;)){
s+=${m:RANDOM%4:1}
}
printf "$s"
}

```

Try it online!

## Original answer

# Bash, 150 bytes

Have done very little golf bashing and trying to improve my bash, so any comments welcome.

```
for((i=0;i<${#1}-1;i++));do
c=${1:$i:1}
n=${1:$((i+1)):1}
a=($n ${c,} ${c^} ${n,} ${n^})
shuf -e ${a[@]} -n "$(shuf -i 1-5 -n 1)"|xargs printf %s
done

```

Try it online!

Code is straightforward loop through chars setting current `c` and next `n` character, then creating an array of the 4 possibilities, repeating one of them so there's exactly 5. Next we shuffle that array, and then choose n elements from it, where n itself is random between 1 and 5.
> 3 votes

# Answer
# Perl 6, 60 bytes

```
{S:g{.)>(.)}=$/~[~] roll ^5 .roll+1,$/.lc,$/.uc,$0.lc,$0.uc}

```

Try it online!

The lowercase/uppercase part is kinda annoying.
> 3 votes

# Answer
# Jelly, 12 bytes

```
;Œsṗ5X¤XṭṖµƝ

```

Try it online!
> 3 votes

# Answer
# Python 2, 107 bytes

```
f=lambda s:s and s[0]+''.join(sample((s[:2]+s[:2].swapcase())*5,randint(1,5)))+f(s[1:])
from random import*

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~18~~ 17 bytes

```
ü)vyн5LΩFyD.š«Ω]J

```

Inspired by *@Giuseppe*'s Gaia answer.
-1 byte thanks to *@Shaggy*.

Try it online 10 times or verify all test cases 10 times.

**Explanation:**

```
ü)             # Create all pairs of the (implicit) input
               #  i.e. "Hello" → [["H","e"],["e","l"],["l","l"],["l","o"]]
  v            # Loop over each these pairs `y`:
   yн          #  Push the first character of pair `y`
   5LΩ         #  Get a random integer in the range [1,5]
      F        #  Inner loop that many times:
       y       #   Push pair `y`
        D.š«   #   Duplicate it, swap the cases of the letters, and merge it with `y`
            Ω  #   Then pop and push a random character from this list of four
  ]J           # After both loops: join the entire stack together to a single string
               # (which is output implicitly as result)

```
> 2 votes

# Answer
# Charcoal, 27 bytes

```
ＦＬθ«Ｆ∧ι⊕‽⁵‽⭆✂θ⊖ι⊕ι¹⁺↥λ↧λ§θι

```

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

```
ＦＬθ«

```

Loop over all of the indices of the input string.

```
Ｆ∧ι⊕‽⁵

```

Except for the first index, loop over a random number from 1 to 5 inclusive...

```
‽⭆✂θ⊖ι⊕ι¹⁺↥λ↧λ

```

... extract the previous and next characters from the string, take the upper and lower case versions, and pick a random character of the four.

```
§θι

```

Print the character at the current index.
> 1 votes

# Answer
# Jelly, 14 bytes

```
;;;Œs$Xɗ¥5X¤¡Ɲ

```

Try it online!

### Explanation

```
             Ɲ | For each overlapping pair of letters
;              | Join the first letter to...
         5X¤¡  | Between 1 and 5 repetitions of...
      Xɗ¥      | A randomly selected character from...
 ;;Œs$         | A list of the two letters and the swapped case versions of both

```
> 1 votes

# Answer
# perl 5 (`-p`), 77 bytes

```
s/(.)(?=(.))/$x=$1;'$x.=substr"\U$1$2\L$1$2",4*rand,1;'x(1+5*rand)/gee;s/.$//

```

TIO
> 1 votes

# Answer
# Japt `-P`, 14 bytes

```
äÈ+Zu pv ö5ö Ä

```

Try it

```
äÈ+Zu pv ö5ö Ä     :Implicit input of string
ä                  :Take each consectutive pair of characters
 È                 :Pass them through the following function as Z
  +                :  Append to the first character of the pair
   Zu              :    Uppercase Z
      p            :    Append
       v           :      Lowercase
         ö         :    Get X random characters, where X is
          5ö       :      Random number in the range [0,5)
             Ä     :      Plus 1
                   :Implicitly join and output

```
> 1 votes

# Answer
# Python 3, 167 bytes

```
from random import*;c=choice
def f(s):
 i=0;r=""
 for i in range(len(s)-1):
  r+=s[i]
  for j in range(randrange(5)):r+=c([str.upper,str.lower])(c(s[i:i+2]))
 return r

```

Try it online!
> 1 votes

# Answer
# C(GCC) ~~175~~ ~~162~~ 150 bytes

-12 bytes from LambdaBeta

-12 bytes from ceilingcat

```
f(s,S,i,r,a)char*s,*S,*i;{srand(time(0));for(i=S;s[1];++s)for(r=rand(*i++=*s)%5+1;r--;*i++=rand()&1&&a>96&a<123|a>64&a<91?a^32:a)a=s[~rand()&1];*i=0;}

```

Try it online!
> 1 votes

# Answer
# PowerShell, ~~154~~ ~~105~~ ~~103~~ ~~95~~ 87 bytes

<sup>-67 bytes thanks to mazzy who can't be stopped</sup>

```
-join(($x=$args)|%{$_;$x[$i,++$i]*5|%{"$_"|% *wer;"$_"|% *per}|random -c(1..5|random)})

```

Try it online!

~~Not a fantastic method but it works.~~ Now it's pretty good. Takes input via splatting
> 1 votes

# Answer
# Japt `-P`, ~~43~~ 16 bytes

```
äÈ+(Zv +Zu)ö5ö Ä

```

Shortened by a lot now!

Try it
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~236~~ ~~213~~ 209 bytes

```
a=>{int i=0,j;var m=new Random();var s="";var c = a.Select(x=>Char.IsLetter(x)?(char)(x^32):x).ToArray();for(;i<a.Length-1;i++)for(j=m.Next(1,5);j-->0;)s+=new[]{a[i],c[i],a[i+1],c[i+1]}[m.Next(0,3)];return s;}

```

Try it online!
> 0 votes

# Answer
# Scala 2.12.8, 214 bytes

Golfed version:

```
val r=scala.util.Random;println(readLine.toList.sliding(2).flatMap{case a :: b :: Nil=>(a +: (0 to r.nextInt(5)).map{_=>((c: Char)=>if(r.nextBoolean)c.toUpper else c.toLower)(if(r.nextBoolean)a else b)})}.mkString)

```

Golfed with newlines and indents:

```
val r=scala.util.Random
println(readLine.toList.sliding(2).flatMap{
  case a :: b :: Nil=>
    (a +: (0 to r.nextInt(5)).map{_=>
      ((c: Char)=>if(r.nextBoolean)c.toUpper else c.toLower)(if(r.nextBoolean)a else b)
    })
}.mkString)

```

Ungolfed:

```
import scala.io.StdIn
import scala.util.Random

def gobble(input: String): String = {
  input.toList.sliding(2).flatMap {
    case thisChar :: nextChar :: Nil =>
      val numberOfAdditions = Random.nextInt(5)
      (thisChar +: (0 to numberOfAdditions).map { _ =>
        val char = if(Random.nextBoolean) thisChar else nextChar
        val cc = if(Random.nextBoolean) char.toUpper else char.ToLower
        cc
      })
  }.mkString
}

println(gobble(StdIn.readLine()))

```
> 0 votes

# Answer
# Perl 5 `-n`, 61 bytes

```
s/.(?=(.))/print$&,map{(map{lc,uc}$&,$1)[rand 4]}0..rand 5/ge

```

Try it online!
> 0 votes

# Answer
# T-SQL query, 286 bytes

```
DECLARE @ char(999)='String'

SELECT @=stuff(@,n+2,0,s)FROM(SELECT
top 999*,substring(lower(c)+upper(c),abs(v%4)+1,1)s
FROM(SELECT*,number n,substring(@,number+1,2)c,cast(newid()as varbinary)v
FROM(values(1),(2),(3),(4),(5))F(h),spt_values)D
WHERE'P'=type and n<len(@)-1and h>v%3+2ORDER
BY-n)E
PRINT LEFT(@,len(@)-1)

```

**Try it online** unfortunately the online version always show the same result for the same varchar, unlike MS SQL Server Management Studio
> 0 votes

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

```
n=>{var k=new Random();int i=0;foreach(var j in n.Skip(1).Zip(n,(a,b)=>a+b))for(Write(j[1]),i=0;i++<k.Next(5);)Write(k.Next()%2<1?j.ToUpper():j.ToLower());}

```

Try it online!
> 0 votes

# Answer
# C (gcc), ~~110~~ 109 bytes

```
i,p;g(char*_){for(i=rand(putchar(*_))%1024;p=_[i%2],putchar(i&2&&p>64&~-p%32<26?p^32:p),i/=4;);_[2]&&g(_+1);}

```

Try it online!

-1 thanks to ceilingcat

```
i,p;g(char*_){
    for(i=rand(putchar(*_)) //print current char
         %1024;             // and get 10 random bits
        p=_[i%2],           //1st bit => current/next char
        putchar(i&2&&       //2nd bit => toggle case
            p>64&~-p%32<26  // if char-to-print is alphabetic
            ?p^32:p),
        i/=4;);             //discard two bits
    _[2]&&g(_+1);           //if next isn't last char, repeat with next char
}

```

---

The number of characters printed (per input character) is not uniformly random:

```
1  if      i<   4 (  4/1024 = 1/256)
2  if   4<=i<  16 ( 12/1024 = 3/256)
3  if  16<=i<  64 ( 48/1024 = 3/ 64)
4  if  64<=i< 256 (192/1024 = 3/ 16)
5  if 256<=i<1024 (768/1024 = 3/  4)

```
> 0 votes

# Answer
# Zsh, ~~113~~ 107 bytes

With a lot of help from `man zshexpn` and `man zshparam`. Try it Online!

* ***-6*** *by me, tweaking*

```
for ((;i<#1;i++)){m=${1:$i:2};m=$m:l$m:u
for ((;t<RANDOM%5;t++))x+=${m[RANDOM%4]}
echo ${1[i]}$x\\c;t=;x=;}

```
> 0 votes

# Answer
# Ruby, 74 bytes

```
gsub(/.(?=(.))/){([$&,$1,$&.swapcase,$1.swapcase]*5).sample(rand 1..5)*""}

```

Attempt This Online!
> 0 votes

# Answer
# Stax, 17 bytes

```
êß~Φ~a[├x◙w↓┬┬►{⌂

```

Run and debug it at staxlang.xyz!

### Unpacked (20 bytes) and explanation:

```
2BFch]pc:~+5R|':$|'p
2B                      all size-2 subarrays
  F                     for each:
   ch]p                   print its first element
       c                  copy it on the stack
        :~                case-swap the copy
          +               concatenate
           5R|'           random integer 1-5, inclusive
               :$         Cartesian power
                 |'       random choice
                   p      print

```
> 0 votes

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


title: Construct a diverse array

text:
# Question
Title: Construct a diverse array
Given an integer \\$ n \ge 1 \\$, your task is to output an array \\$ a \\$ consisting of \\$ n^2 + 1 \\$ integers, such that all possible pairs of integers \\$ (x, y) \\$ satisfying \\$ 1 \le x, y \le n \\$ exist as a contiguous subarray in \\$ a \\$, exactly once.

For example, if \\$ n = 2 \\$, a valid output would be \\$ (1, 1, 2, 2, 1) \\$. We can check all possible pairs to verify that this is indeed correct:

$$ \begin{align} (1, 1) \to (\color{red}{1, 1}, 2, 2, 1) \\ (1, 2) \to (1, \color{red}{1, 2}, 2, 1) \\ (2, 1) \to (1, 1, 2, \color{red}{2, 1}) \\ (2, 2) \to (1, 1, \color{red}{2, 2}, 1) \\ \end{align} $$

### Notes

* It can be shown that a construction exists for all \\$ n \\$.
* \\$ a \\$ may be outputted in any reasonable form (e.g. a delimiter-separated string).
* It is recommended, but not required, to prove that your construction works for all \\$ n \\$.
* This problem is closely related to asking for the de Bruijn sequence of order \\$ n \\$.
* This is , so the shortest code in bytes wins.

# Answer
# Husk, 7 bytes

```
:1ṁSJṫṫ

```

Try it online!

This is OEIS A349526 reversed.

```
:1ṁSJṫṫ
      ṫ      Let i range from the input down to 1
             For each i
     ṫ         Range from i down to 1
   SJ          Insert an i between every two elements
  ṁ          Concatenate
:1           Prepend 1 to the result

```
> 13 votes

# Answer
# Vyxal, ~~16~~ 15 bytes

```
₌ɾ²›↔'2l?:Ẋ⊍¬;h

```

Try it Online!

So remember the last time I solved an array challenge with a brute force algorithm and it timed out for anything larger that a 2x2 matrix? Well I've made an improvement! This algorithm times out for anything larger than `n=3`.

## Explained

```
₌ɾ²›↔'2l?:Ẋ⊍¬;h
₌ɾ²›↔            # From the range [1, input], choose all combinations with repetition of length (input**2) + 1
     '       ;h  # And get the first combination where:
      2l         #   A list of all windows of length 2
        ?:Ẋ⊍¬    #   set xor'd with the cartesian product of the range [1, input] with itself is empty

```
> 7 votes

# Answer
# Husk, 14 bytes

```
§+oṘ2ḣoṁSJoḣ←ṫ

```

Try it online!

### How?

First, observe that this challenge is equivalent to the following:

* Create a complete digraph consisting of \\$n\\$ nodes, labeled \\$1\\$ through \\$n\\$
* Add a loop edge from each node to itself
* Construct a traversal of the graph which follows each (directed) edge exactly once

This solution generates a sequence like this (example for input `5`):

```
1,1,2,2,3,3,4,4,5,5,1,5,2,5,3,5,4,1,4,2,4,3,1,3,2,1

```

which can be divided into sections:

```
1,1,2,2,3,3,4,4,5,5  1,5,2,5,3,5,4  1,4,2,4,3  1,3,2  1

```
* In the first section, we go from node \\$1\\$ to node \\$n\\$ in order, taking the loop edge at each node as we reach it.
* In the second section, we take the edge from node \\$n\\$ to each node other than \\$n-1\\$ and immediately return to node \\$n\\$. Finally, we go to node \\$n-1\\$.
* In the next section, we do the same for node \\$n-1\\$, visiting each node except for \\$n-2\\$.
* We continue this pattern all the way back to node \\$1\\$.

This approach visits every directed edge exactly once: the edges \\$i \to i\\$ and \\$i \to i+1\\$ in the first section, and in \\$i\\$'s return section the edges \\$i \to j\\$ and \\$j \to i\\$ for all \\$j \< i-1\\$, as well as \\$i \to i-1\\$.

### Explanation

We construct the first section and the remaining sections separately and then concatenate them.

First section:

```
oṘ2ḣ
   ḣ  Range from 1 to argument, inclusive
o     Compose with
 Ṙ2   Repeat each element of a list twice

```

(Credit to Razetime for the `Ṙ2` code.)

Remaining sections:

```
oṁSJoḣ←ṫ
       ṫ  Range from argument down to 1, inclusive
o         Compose with
 ṁ        Map this function and concatenate the resulting lists:
      ←     Decrement
    o       Compose with
     ḣ      Range from 1 to argument, inclusive
   J        Insert a value between all elements
  S         using the argument as that value

```

Putting it all together:

```
§+oṘ2ḣoṁSJoḣ←ṫ
§               Apply each of these functions to the argument:
  oṘ2ḣ            First section function
      oṁSJoḣ←ṫ    Remaining sections function
                and combine the results using this function:
 +                Concatenate lists

```
> 7 votes

# Answer
# Jelly, 6 bytes

```
Rj)F;1

```

A monadic Link that accepts a positive integer and yields a list of positive integers.

**Try it online!**

### How?

Much like alephalpha's Husk answer...

```
Rj)F;1 - Link: integer, N
  )    - for each (n in [1..N]):
R      -   range (n)
 j     -   join with (n)
   F   - flatten
    ;1 - concatenate a one

```
> 7 votes

# Answer
# Python3, 173 bytes:

```
lambda n:next(F({(x,y)for x in R(1,n+1)for y in R(1,n+1)}))
def F(k,c=[]):
 if not k:yield c
 for i in k:
  if[]==c or c[-1]==i[0]:yield from F(k-{i},c+[*i][c!=[]:])
R=range

```

Try it online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 32 bytes

-3 bytes thanks to @hakr14.

```
#~DeBruijnSequence~2~Append~0+1&

```

Try it online!

Using the built-in `DeBruijnSequence`.

---

# Wolfram Language (Mathematica), 43 bytes

```
##~Join~{1}&@@Range@i~Riffle~i~Table~{i,#}&

```

Try it online!

This is OEIS A349526.
> 4 votes

# Answer
# Nibbles, 7.5 bytes (15 nibbles)

```
+.:,$1>>+.,$:@

```

A Nibbles port of the generator for A349526, thanks to alephalpha's Husk answer (upvote that!).

```
   ,$           # range 1..input
  :  1          # append 1
 .              # map each i over this:
         .,$    #   map over 1..i
            :@  #     prepend i
        +       #   flatten
      >>        #   and remove first element
+               # and flatten the list-of-lists

```
> 4 votes

# Answer
# , 50 bytes

```
f=function(x)if(x)c(1,rbind(x,x:1)[-x],f(x-1)[-1])

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 47 bytes

Returns a comma-separated string.

This generates the same results as alephalpha's answer, with a recursive algorithm.

```
f=n=>n?1+[,(g=k=>k>1?[k,n,g(k-1)]:f(n-1))(n)]:1

```

Try it online!

### How?

By using `[1,` instead of `1+[,` (like that), we can see that it actually builds the following structure (here for \\$n=3\\$):

```
+------ first call to f
|   +-- first call to g
|   |
v   v
[1, [3, 3, [2, 3, [1, [2, 2, [1, 1]]]]]]
                  ^
                  |
                  +-- second call to f

```

The purpose of `1+[,` is to force the result to be coerced to a string *and* implicitly flattened.
> 3 votes

# Answer
# Haskell, ~~49~~ 39 bytes

```
f n=n:do x<-[1..n];init$(:[x])=<<[x..n]

```

Try it online!

* saved 10 Bytes thanks to @xnor
> 3 votes

# Answer
# Rust, ~~84~~ 74 bytes

-10 bytes thanks to alepalpha

```
use itertools::*;|n|chain((1..=n).flat_map(|m|(1..=m).intersperse(m)),[1])

```

Plauground

Takes a `usize` and returns an iterator of usizes.
> 3 votes

# Answer
# Charcoal, 17 bytes

```
ＦＮＦ⊕ι«Ｉ⊕✂⟦ικ⟧¬κ»1

```

Try it online! Link is to verbose version of code. Explanation: Port of @DominicvanEssen's Nibbles answer.

```
ＦＮ

```

Input `n` and loop `i` from `0` until `n`.

```
Ｆ⊕ι«

```

Loop `k` from `0` until `i` inclusive.

```
Ｉ⊕✂⟦ικ⟧¬κ

```

If `k` is `0` then just output `k+1` otherwise output both `i+1` and `k+1`.

```
»1

```

Output a trailing `1`.
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
LLεZ.ý}˜Ć

```

Port of *@alephalpha*'s Husk answer, but reversed.

Try it online or verify the first 5 test cases.

**Explanation:**

```
L       # Push a list in the range [1, (implicit) input]
 L      # Convert each value in this list to a list in the range [1,value]
  ε     # Map over each inner list:
   Z    #  Push the list's maximum (without popping the list itself)
    .ý  #  Intersperse the list with this maximum as delimiter
  }˜    # After the map: flatten it to a single list
    Ć   # Enclose; appending its own head (which is always 1)
        # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Python 3, 51 bytes

```
f=lambda n,i=1:n*[1]and f(n-i//n,i%n+1)+[n,i][i-n:]

```

Try it online!

This uses a similar method as alephalpha's answer, except it orders segments in reverse.

Using `n=4` as an example, the list is built recursively, as a sum of segments `[1,1] + [2,2,1] + [3,3,2,3,1] + [4,4,3,4,2,4,1]`, where the last segment is concatenated to `f(n-1)`.

The segments are also built recursively, as `[4,4]+[4,3]+[4,2]+[4,1]` with the `[i-n:]` to slice off the beginning of the second term (`[4,3] => [3]`).
> 2 votes

# Answer
# Brachylog, 13 bytes

```
<~l.&⟦₁gjẋ~sᵛ

```

Try it online!

### Explanation

```
<~l.            length(output) > input
    &⟦₁         Take the range [1, …, input]
       gj       Juxtapose to itself [[1, …, input], [1, …, input]]
         ẋ      Cartesian product
          ~sᵛ   Each sublist of the cartesian product is a connex sublist of the output
                (the output gets filled in with the right values to match this constraint)

```
> 1 votes

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


# Question
Title: Split string into n pieces (or pieces of length n)
# The Challenge

In this challenge you have to do two different (but related) tasks depending of the order of the input.
Your program will recieve a string `s` and an integer `n` as input and will

* split `s` into pieces of length `n` if `s` comes first. The last element will be shorter if necessary.
* split `s` into `n` pieces of equal length if `n` comes first. If `len(s)` is not a multiple of `n` the first `len(s) mod n` elements will be one longer.

You may only take those 2 inputs. `s` will never contain only digits.

### Notes

* You may use the reverse mapping. Note this in your answer if you do that.
* `s` will only contain printable ASCII characters (no newlines).
* You may not use any builtins that solve either those two tasks directly. All other builtins are allowed.
* You have to take both arguments from the same source.
* You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous.
* You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them.
* `n` will always be equal or less than the length of `s` and greater than zero.
* You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order.

# Example

**Input:** `programming, 3`
The last element contains only 2 characters, because 11 is not divisible by 3.
**Output:** `["pro", "gra", "mmi", "ng"]`

**Input:** `3, programming`
11 is not a multiple of 3, so the first 2 elements will be one longer:
**Output:** `["prog", "ramm", "ing"]`

# Rules

# Test cases

The test cases got generated with this Pyth program (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that!

```
3, helloworld -> ['hell', 'owo', 'rld']
helloworld, 3 -> ['hel', 'low', 'orl', 'd']
1, programming -> ['programming']
programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g']
programming, 8 -> ['programm', 'ing']
9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f']
code golf, 9 -> ['code golf']
4, 133tspeak -> ['133', 'ts', 'pe', 'ak']
133tspeak, 4 -> ['133t', 'spea', 'k']

```

**Happy Coding!**

# Answer
> 3 votes
# MATL, ~~46~~ ~~26~~ ~~21~~ ~~27~~ ~~29~~ 42 bytes

```
jtU?jtbUe!tn2Gn>?0t(]tgbw(}ie]!2t$X{Oc''Zt

```

**Try it Online!** (Updated slightly to work with the latest version of the language)

**Explanation**

```
j           % Explicitly grab the first input as a string
t           % Duplicate
U           % Attempt to convert it to a number
?           % If the conversion to a number was successful
    j       % Explicitly grab the second input as a string
    t       % Duplicate the value
    b       % Bubble-up the first element in the stack
    U       % Convert to a number from a string
    e       % Reshape the string into a nGroup x nPerGroup matrix
    !       % Take the transpose
    t       % Duplicate the result
    n       % Number of characters in the repmat result
    2Gn     % Number of characters in the string
    >?      % If chars in repmat > chars in string
        O   % Zero
        t   % Duplicate
        (   % Assign the last element to a null character (bug in MATL)
    ]       % End if statement
    t       % Duplicate this matrix
    g       % Convert to a logical matrix
    b       % Bubble-up the original string
    w       % Flip the top two elements
    (       % Assign the non-empty characters to the chars from the input string
}           % Else the string comes first
    i       % Explicitly grab the second input (the number)
    e       % Reshape the characters into an nPerGroup x nGroup 2D array
]           % End of if statement
!           % Take the transpose so it reads left-to-right
2           % Number literal
t           % Duplicate
$X{         % Call num2cell to convert to a cell array
Oc          % Null character
''          % Empty string
Zt          % Replace null chars with empty strings
            % Implicit display of stack contents

```

# Answer
> 4 votes
# JavaScript (ES6), 132 bytes

```
(s,t)=>+t?[...Array(-~(~-s.length/+t))].map((_,i)=>s.substr(i*t,t)):[...Array(s=+s)].map(_=>t.slice(p,p-=~((t.length-p-1)/s--)),p=0)

```

This is probably hopelessly over-engineered.

# Answer
> 4 votes
# JavaScript (Firefox), ~~88~~ 87 bytes

```
a=>b=>(s=+b?a:b,i=x=0,l=s.length,[for(c of s)if(r=s.slice(x,x+=+b||l/a+(i++<l%a)|0))r])

```

Call it like `(...)("programming")(3)` using Firefox 30+.

# Answer
> 2 votes
## AWK, 121 130 128 122 Bytes

```
$1~/^[0-9]+$/{s=1}{a=$(s+1)
b=s?$1:$2
$0=""
for(j=-b;j<=c=length(a);)$0=$0 substr(a,j+=b+s,b+(s=s&&j<c%b*(b+1)?1:0))" "}1

```

The only issue is if the first entry is a string that starts with a numeric value. This would cause `AWK` to see the string as that number and the second entry as the string.

OK... fixed the numeric issue, but it added 9 bytes :(.

Reworked a bit to save a couple bytes.

Almost back to the original length. :)

# Answer
> 2 votes
# Ruby, 119 bytes

```
->x,y{r=[t=0];x.to_s==x ?(r.push x[t...t+=y]while x[t]):x.times{r.push y[t...t+=y.size/x+(r[y.size%x]? 0:1)]};r[1..-1]}

```

And I take first place by 2 bytes...

# Answer
> 1 votes
## Haskell, 131 bytes

```
import Data.Lists
q(d,m)=splitPlaces$(d+1<$[1..m])++[d,d..]
a#b|all(`elem`['0'..'9'])a=q(divMod(length b)$read a)b|1<2=q(read b,0)a

```

Usage example:

```
*Main> "8" # "programming"
["pr","og","ra","m","m","i","n","g"]
*Main> "programming" # "8"
["programm","ing"]

```

How it works: the main work is done by the helper function `q` which takes a pair of numbers `(d,m)` and a string `s`. It first builds a list of `m` times `d+1` followed by infinite many `d` (e.g `(1,3)` -\> `[2,2,2,1,1,1,1,1,...]`). It then uses `splitPlaces` to split `s` into chunks of lengths given by the list. `splitPlaces` stops if `s` runs out of elements, so an infinite list is fine.

The main function `#` checks which parameter is the number `n` / string `str` and calls `q` with either `(div (length str) n, mod (length str) n)` or `(n, 0)` plus `str`.

# Answer
> 0 votes
## Pyth, 181 bytes

Let's pretend the longest code in bytes wins \o/

```
DyGK@G0J:@G1"."1=YJV%lJKW<l@YN.EclJK=YXYN+@YN@YhN=Y.DYhN)FNr%lJK/-lJ%lJK/-lJ%lJKKW<l@YNsclJK=YXYN+@YN@YhN=Y.DYhN))RY)DPG=K@G1=J:@G0"."1=YJV/lJKW<l@YNK=YXYN+@YN@YhN=Y.DYhN))RY).xyQPQ

```

Try it here ! (The online interpreter seem to have a bug, it displays the input while it should not)

Here's the output from the terminal:

```
» pyth split.pyth <<<'["helloworld", 3]'
['hel', 'low', 'orl', 'd']
» pyth split.pyth <<<'[3, "Helloworld"]'
['Hell', 'owo', 'rld']

```

Seriously, I am open to new approach. I'm new to python, so I probably missed a few shorthands.

I mean, I think my answer is deseperate from the point it is longer than the javascript answer...

# Answer
> 0 votes
# C# (LINQPAD) - 335 bytes

```
var y=Util.ReadLine().Split(',');int x,j=0;var t=int.TryParse(y[0].Trim(),out x);x=x==0?int.Parse(y[1].Trim()):x;var i=t?y[1].Trim():y[0];var z="";if(!t){while(i.Substring(j).Length>x){z+=i.Substring(j).Length>x?i.Substring(j,x)+", ":"";j+=x;}z+=i.Substring(j);}else z=string.Join(", ",i.Split(x).Select(s=>string.Concat(s)));z.Dump();

```

The input reading part took up a bit of space. Winner of longest answer.

Usage #1:

```
$ 3, helloworld

>> hell, owo, rld

```

Usage #2:

```
$ helloworld, 3

>>hel, low, orl, d

```

# Answer
> 0 votes
# PHP, 114 bytes

```
[$t,$n,$p]=$argv;for(@+$p?$s=$n:$f=$n*($p=strlen($s=$p)/$n)%$n;$t;)echo$t=substr($s,$a+=$e,$e=$p+($i++<$f)|0),"
";

```
* String should not start with digits.
(Replace `+@$p` with `is_numeric($p)` to fix.)
* Output should not contain a chunk "0".
(Insert `~` for printable ASCII, `a&` for any ASCII before `$t;` to fix.)
* Run with `-nr` or try it online.

# Answer
> 0 votes
# PowerShell, ~~122~~ 118 bytes

```
param($a,$b)if($a-is[int]){$a,$b=$b,((($l=$b|% Le*)-($c=$l%$a))/$a)}$a-split("(..{$b})"*$c+"(.{0,$b})"*$a.Length)-ne''

```

Try it online!

Less golfed:

```
param($a,$b)
if($a-is[int]){
    $length=$b|% Length
    $c=$length%$a
    $a,$b=$b,(($length-$c)/$a)  # recalc length and swap
}
$pattern="(..{$b})"*$c+"(.{0,$b})"*$a.Length
$parts=$a -split $pattern       # pattern like '(..{3})(..{3})(.{0,3})(.{0,3})(.{0,3})'
$parts -ne ''                   # output not empty parts

```

# Answer
> 0 votes
# Ruby, 69 bytes

```
->a,b{a.scan /.{1,#{b}}/ rescue b.scan /.{1,#{b.size.fdiv(a).ceil}}/}

```

Attempt This Online!

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


title: Code Golf Measurer © 2019

text:
# Question
Title: Code Golf Measurer © 2019
# Code Golf Measurer © 2019

Hexdumps used with `xxd` look something like this:

```
00000000: 666f 6f20 6261 7220 7370 616d 2065 6767  foo bar spam egg
00000010: 730a                                     s.

```

Your task is to convert a hexdump in this form in to the number of bytes used.

## Rules:

* Usual loopholes forbidden.
* This is , so shortest valid answer in bytes wins.
* You may or may not include the newline at the end of text (`0a`). This means that if the hexdump ends in a newline (`0a`), that input may have it's output reduced by one.
* An empty input (literally nothing: empty list/string/etc.) must output 0.
* Input can be taken in any form
* Input will be valid ASCII with no control characters
* The input must contain the whole hexdump

## Test cases:

```
00000000: 4865 6c6c 6f2c 2077 6f72 6c64 2120 4865  Hello, world! He
00000010: 6c6c 6f2c 2077 6f72 6c64 210a            llo, world!.

```

returns 28 or 27

```
00000000: 0a                                       .

```

returns 1 or 0

```
00000000: 6368 616c 6c65 6e67 650a                 challenge.

```

returns 10 or 9

```
00000000: 4865 6c6c 6f2c 2077 6f72 6c64 21         Hello, world!

```

returns 13

```

```

returns 0 *(This is literally nothing: empty list/string/etc.)*

Explanations would be nice for non-standard languages.

# Answer
> 13 votes
# tcsh, 12 bytes

```
xxd -r|wc -c

```

Try it online!

# Answer
> 13 votes
# Retina 0.8.2, 8 bytes

```
.{51}

.

```

Try it online! Explanation:

```
.{51}

```

Delete the first 51 characters of each line. (Lines can only have between 52 and 67 characters, so this always matches once per line.)

```
.

```

Count the remaining non-newline characters.

7 bytes if empty input did not have to be supported:

```
.{52}

```

Try it online! Explanation:

```
.{52}

```

Delete the first 52 characters of each line. (Lines can only have between 52 and 67 characters, so this always matches once per line.)

```

```

Count 1 more than the number of remaining characters (including newlines).

# Answer
> 8 votes
# V (vim), 7 bytes

```
Î51x
Ø.

```

Try it online!

Explanation:

```
Î       " On every line...
 51x    "   Delete the first 51 characters
Ø.      " Count the number of remaining characters on any line

```

Hexdump:

```
00000000: ce35 3178 0dd8 2e                        .51x...

```

# Answer
> 7 votes
# Retina, 7 bytes

This counts the total number of single-line strings of length 52. It might be possible to do something similar to `%52,`.`, but I failed to find a way to fix that.

```
w`.{52}

```

Try it online!

# Answer
> 5 votes
# APL (Dyalog Extended), 18 bytes

Full program. Prompts for list of strings (i.e. of lists of characters).

```
2÷⍨≢∊(1↓≠⊆⊢)¨49↑¨⎕

```

Try it online!

prompt

`49↑¨` take the first 49 characters from each

`(` apply the following tacit function to each:

the argument

chop into runs of characters that are

different from the padding character (space)

`1↓` drop the first "word"

**ϵ**nlist (flatten)

tally

`2÷⍨` divide by two

# Answer
> 5 votes
# C (gcc), ~~64~~ ~~55~~ ~~45~~ 39 bytes

```
s[];f(l){l=gets(s)?strlen(s)-51+f():0;}

```

Try it online!

9 bytes shaved off thanks to YSC, 10 thanks to jdt, and 6 thanks to c--!

# Answer
> 4 votes
# Jelly, 5 bytes

```
Ẉ_51S

```

A monadic Link accepting a list of lines which yield the integer byte count.

**Try it online!**

### How?

```
Ẉ_51S - Link: list of lists of characters, H
Ẉ     - length of each (line in H)
  51  - literal fifty-one
 _    - subtract (vectorises)
    S - sum

```

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

```
lambda s:(len(s)or 51)+1-52*len(s.split('\n'))

```

Input is passed as a string to the function. The function increments the length of the input (including newlines), then subtracts 52 for each line.

Try it online

# Answer
> 2 votes
# 05AB1E, ~~8~~ 6 bytes

```
€g51-O

```

Try it online!

Input as a list of strings.

```
€g     get lengths of each line
51-    subtract 51 from each
O      push the sum of the resulting list
       implicitly print

```

# Answer
> 2 votes
# Japt `-x`, 5 bytes

Input as an array of lines.

```
®Ê-51

```

Try it

```
®Ê-51     :Implicit input of array
®         :Map
 Ê        :  Length
  -51     :  Subtract 51
          :Implicit output of sum of resulting array

```

# Answer
> 2 votes
# Perl 6, 18 bytes

```
{.join.comb-51*$_}

```

Try it online!

Anonymous Whatever lambda that takes a list of lines and returns the sum of the number of characters, subtracting 51 for each line

# Answer
> 2 votes
# IBM/Lotus Notes Formula Language, 53 bytes

```
@Sum(@Length(@Explode(@Right(@Left(i;"  ");": ")))/2)

```

There is no TIO for Formula so here are screenshots of the test cases:

The formula is in the computed field that provides the value after "Returns".

**Explanation**

This is a good demonstration of the way that Formula will recursively apply a function to a list without needing a loop. The formula is in a computed field on the same form as editable input field \`i'.

1. Start in the middle. `@Left` and `@Right` allow a string delimiter or a number of characters to be used. We therefore search to the right of `:`  and then to the left of the first occurrence of two spaces. Since Formula sees the newline as a list separator it will apply this to each line in the input.
2. `@Explode` is Formula's equivalent of a `split` function and defaults to space, `,` or `;`. Again it is applied to each line in the field but this time the results are combined into a single list.
3. `@Length` will then be applied to each member of the list. In each case we divide it's return value by 2.
4. `@Sum` the whole list and output the result.

# Answer
> 1 votes
# Red, ~~81~~ 55 bytes

```
func[s][n: 0 foreach l s[n: n - 51 + length? l]max 0 n]

```

Try it online!

Takes the input as a list of strings.

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

```
s=>(n=s.length)&&(n/68<<4)+n%68-51

```

Try it online!

### Commented

```
s =>                // s = input string
  (n = s.length) && // n = length of s; return 0 right away if n = 0 (special case)
  (n / 68 << 4) +   // otherwise compute the number of full lines and multiply it by 16
  n % 68 - 51       // add the length of the last line minus 51

```

# Answer
> 1 votes
# JavaScript, ~~33~~ 32 bytes

```
a=>a.map(x=>a=~~a+x.length-51)|a

```

Try it Online!

Saved 1 byte thanks to Arnauld.

# Answer
> 1 votes
# Ruby, ~~39~~ ~~29~~ 28 bytes

-10 bytes thanks to south
-1 byte thanks to Sʨɠɠan

```
p$<.sum{_1=~/.{52}/;$'.size}

```

Attempt This Online!

# Answer
> 0 votes
# Befunge-98 (FBBI), 16 bytes

```
"c- cw|r- dxx"=@

```

Try it online!

# Answer
> 0 votes
# Stax, 5 bytes

```
ôφß→ê

```

Run and debug it

# Answer
> 0 votes
# Zsh, 36 bytes

With zsh's default flags:

```
for l (${(f)1})((c+=$#l-52))
<<<$[c]

```

Try it online!

`${(f)1}` splits `$1` on newlines, and discards empty lines. The `$[ arithmetic expansion ]` guards against the empty case, when the loop never sets `$c`.

# Zsh, 28 bytes

With `-o extendedglob`:

```
<<<${#${(F)${(f)1}#?(#c52)}}

```

Try it online!

`(f)` Split on newlines, `${ #?(#c52)}` remove leading 52 characters, `(F)` join on newlines so that counting is characterwise instead of listwise, `${# }` count characters.

# Answer
> 0 votes
# asm2bf, 135 bytes

Golfed version:

```
lbl 3
mov r2,51
lbl 1
in_ r1
dec r2
jz_ r1,4
jnz r2,1
lbl 2
in_ r1
jz_ r1,4
sub r1,10
jz_ r1,3
inc r3
jmp 2
lbl 4
out r3

```

Commented version:

```
lbl 3               ; Main loop - the kinda entry point

    mov r2, 51      ; Loop 51 times.
    lbl 1           ; Loop start.
        in_ r1      ; Read character
        dec r2      ; Decrement the loop accumulator.
        jz_ r1, 4   ; If zero was read, end.
        jnz r2, 1   ; If we still loop, loop again.

    lbl 2           ; Second loop, accumulating the result.
        in_ r1      ; Read a character.
        jz_ r1, 4   ; If character is zero, end the loop and print result.
        sub r1, 10  ; Decrement r1 by 10 for next check.
        jz_ r1, 3   ; If the character - 10 (the newline) is zero, jump to 3
        inc r3      ; Increment character read amount.
        jmp 2
lbl 4
    out r3          ; Print out the result as an ASCII character.

```

# Answer
> 0 votes
# PHP, 22 bytes

```
fn()=>strlen(`xxd -r`)

```

Doesn't work on ATO unfortunatly

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


title: Sort a difference list

text:
# Question
Title: Sort a difference list
The difference list of a list of integers is the list differences of consecutive members.

For example the difference list of

```
1, 3, 2 ,4

```

is

```
2, -1, 2

```

Your task is to take as input a difference list and output what the difference list would look like if the original list were sorted.

For example the difference list

```
2, 1, -2, -1

```

Might represent a list

```
2 4 5 3 2

```

Which when sorted is

```
2 2 3 4 5

```

Which has a difference list of

```
0 1 1 1

```

---

This is so answers will be scored in bytes with less bytes being better.

# Answer
> 16 votes
# 05AB1E, 4 bytes

```
.¥{¥

```

Try it online!

### Explanation

```
.¥{¥
.¥   # Undelta the input list
  {  # Sort it
   ¥ # And get the deltas

```

# Answer
> 9 votes
# Python 3 with Numpy, ~~56~~ ~~54~~ 53 bytes

*2 bytes off thanks to @Artyer (Numpy's `sort` instead of standard `sorted`). 1 byte off thanks to @notjagan (moving `0` into `cumsum`)*

```
lambda x:diff(sort(cumsum([0]+x)))
from numpy import*

```

The code defines an anonymous function that inputs a list or a Numpy array and outputs a Numpy array.

Try it online!

# Answer
> 5 votes
# Mathematica, 40 bytes

```
Differences@Sort@Accumulate@Join[{1},#]&

```

# Answer
> 4 votes
## JavaScript (ES6), ~~57~~ 56 bytes

*Saved 1 byte thanks to @ETHproductions*

```
a=>a.map(n=>t-=n,p=t=0).sort((a,b)=>b-a).map(n=>p-(p=n))

```

### Demo

```
let f =

a=>a.map(n=>t-=n,p=t=0).sort((a,b)=>b-a).map(n=>p-(p=n))

console.log(JSON.stringify(f([2, 1, -2, -1])))
```

# Answer
> 4 votes
# Jelly, 6 bytes

```
0;+\ṢI

```

Try it online!

# Answer
> 4 votes
# Husk, 4 bytes

```
Ẋ-O∫

```

Try it online!

### Explaination

```
      -- implicit input, e.g                               [2,1,-2,-1]
   ∫  -- cumulative sum                                    [0,2,3,1,0]
  O   -- sort                                              [0,0,1,2,3]
Ẋ     -- apply function to all adjacent pairs in the list  [(0,0),(0,1),(1,2),(2,3)]
 -    --   subtract                                        [0,1,1,1]

```

# Answer
> 4 votes
# Pyth, 9 bytes

*-1 byte thanks to @EriktheOutgolfer*.

```
.+S+0sM._

```

**Test Suite.**

# Pyth, 10 bytes

```
.+S.u+YNQ0

```

Try it online! or Try more test cases.

# Answer
> 3 votes
# Java 8, 123 bytes

The standard solution: cumulative sum input, sort, then diff. No substantial implementation tricks either.

```
l->{int s=l.length,d[]=new int[s+1],i=0;while(i<s)d[i+1]=d[i]+l[i++];for(java.util.Arrays.sort(d);i-->0;)l[i]=d[i+1]-d[i];}

```

Cast to `Consumer<int[]>`. Output is mutated input.

Try It Online

## Ungolfed lambda

```
l -> {
    int
        s = l.length,
        d[] = new int[s + 1],
        i = 0
    ;
    while (i < s)
        d[i + 1] = d[i] + l[i++];
    for (java.util.Arrays.sort(d); i-- > 0; )
        l[i] = d[i + 1] - d[i];
}

```

## Acknowledgments

* -3 bytes thanks to *Olivier Grégoire*, master of unholy autoincrementation
* -1 byte thanks to *Nevay*

# Answer
> 2 votes
# , ~~31~~ 32 bytes

*-4 bytes thanks to @user2390246 for* `diffinv`

*+5 bytes from Jarko for `cat`*

```
cat(diff(sort(diffinv(scan()))))

```

Reads from stdin, writes to stdout. `diffinv` is an inverse of `diff` for a given starting value (0 by default). Since it's `diff`ed again, it doesn't matter what that value is.

As pointed out by Jarko Dubbeldam, I needed to properly output the result, at the cost of five bytes. Alas.

Try it online!

# Answer
> 2 votes
# Brachylog, 15 bytes

```
a₀ᶠ+ᵐ,0o{s₂↔-}ᶠ

```

Try it online!

# Answer
> 1 votes
# Perl 6, 46 bytes

```
{[\+](0,|@_).sort.rotor(2=>-1).flat.map(*R-*)}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit signature :(*@_)

  [\+](         # triangle reduce using &infix:«+»
    0,          # start with 0
    |@_         # Slip in the arguments from the outer block
  )             #                  (0, 2, 3, 1, 0)

  .sort         # sort the results (0,0,1,2,3)
  .rotor(2=>-1) # group in twos    ((0,0),(0,1),(1,2),(2,3))
  .flat         # flatten          (0,0,0,1,1,2,2,3)
  .map(*R-*)    # grab 2 values at a time, and subtract first from second
                # (0, 1, 1, 1)
}

```

# Answer
> 1 votes
# Python 2, 83 bytes

```
l,r=input(),[1]
for i in l:r+=[r[-1]+i]
r.sort()
print[b-a for a,b in zip(r,r[1:])]

```

Try it online!

*Horrible* solution.

# Answer
> 1 votes
# VB.NET (.NET 4.5), 109 bytes

```
Sub A(n)
Dim c=n.count-1
For i=1To c
n(i)+=n(i-1)
Next
n.Sort()
For i=c To 1 Step-1
n(i)-=n(i-1)
Next
End Sub

```

A function that expects a list as input and modifies it directly. The original parameter can then be used for output

1. Recreates an original list by adding forwards through the list (assumes an implicit 0 as the first element)
2. Sorts the original list
3. Gets the differences by going backwards (so I don't need to keep track of a different list) (the implicit first element of 0 means the first difference is the same as the smallest element)

Try it online!

# Answer
> 1 votes
# Haskell, 74 bytes

```
import Data.List
g=sort.scanl(+)0
h l|k<-g l=map(\(x,y)->x-y)$zip(tail$k)k

```

Try it online!

Straightforward.

# Answer
> 1 votes
# TI-Basic (TI-84 Plus CE), 23 bytes

```
Prompt X
augment({0},cumSum(<sub>L</sub>X→X
SortA(<sub>L</sub>X
ΔList(<sub>L</sub>X

```

Prompts for user input. The list must be input with a leading `{`, with numbers separated by `,`, and with an optional trailing `}`.

TI-Basic is a tokenized language; `ΔList(` and `cumSum(` are two-byte tokens, all other tokens used are one byte each.

Example run (with `NAME` as the program name and `{4,-2,7,-4,0}` as the input):

```
prgmNAME
X=?{4,-2,7,-4,0}
               {2 2 1 0 4}

```

Explanation:

```
Prompt X                  # 3 bytes, get list input, store in <sub>L</sub>X
augment({0},cumSum(<sub>L</sub>X→X   # 12 bytes,
          # store the list ({0} prepended to the cumulative sum of <sub>L</sub>X) to <sub>L</sub>X
SortA(<sub>L</sub>X                  # 4 bytes, sort <sub>L</sub>X ascending
ΔList(<sub>L</sub>X                  # 4 bytes, implicitly print the difference list of <sub>L</sub>X

```

# Answer
> 1 votes
# C++ (gcc), 136 bytes

As unnamed generic lambda, assuming input to be like `std::list` and returning via reference parameter.

```
[](auto&L){auto r=L.begin(),l=L.insert(r,0);while(r!=L.end())*r+++=*l++;for(L.sort(),l=r=--L.end();--l!=L.begin();*r---=*l);L.erase(l);}

```

Try it online!

Ungolfed:

```
[](auto&L){
 auto r=L.begin(),
      l=L.insert(r,0); //adds a zero right in front
 while(r!=L.end())
   *r++ += *l++;       //sum left to right
 for(
  L.sort(),            //sorting invalidates the iterators
  l=r=--L.end();       //so, reinit
  --l!=L.begin();      //decrement l beforehand
  *r-- -= *l           //diff right to left
 );
 L.erase(l);           //l==L.begin(), so this removes the temporary 0
}

```

# Answer
> 1 votes
# Pyth, 8 bytes

```
.+S+M.uP

```

Demonstration

```
.+S+M.uP
.+S+M.uPNQ    Implicit variables
     .u  Q    Apply the following function to the input repeatedly until it
              stops changing, then output the list of values, including the
              starting value.
       PN     Remove the last element. No-op if the list is empty.
   +M         Sum each list. This gives the cumulative sums in reverse order,
              including a 0 at the end for the empty list.
  S           Sort
.+            Deltas

```

# Answer
> 1 votes
# TI-Basic, 20 bytes

```
cumSum(augment({0},Ans->L1
SortA(L1
ΔList(L1

```

# Answer
> 1 votes
# Perl 5, 87 + 1 (-a) = 88 bytes

```
$a[0]=1;push@a,$a[-1]+$_ for@F;@a=sort{$a<=>$b}@a;print$a[0]-$_,$"while($_=shift@a)&&@a

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog), ~~15~~ 14 bytes

-1 byte thanks to ngn.

```
(¯2-/⍋⊃¨⊂)0,+\

```

`+\` cumulative sum

`0,` prepend a zero

`(``)` apply the following tacit function on that:

enclose (so we can pick multiple items)

`⍋⊃¨` let each of the indices that would sort the argument pick from that

`¯2-/` reversed pairwise difference

Try it online!

---

Original solution found by the Code Golf Hackathon participants at the Dyalog '17 User Meeting:

```
¯2-/l[⍋l←+\0,⎕]

```

Try it online!

prompt for input

`0,` prepend a zero

`+\` cumulative sum

`l←` store as `l`

find the indices that will sort `l`

`l[``]` use that to index into `l`

`¯2-/` reversed pairwise difference

# Answer
> 1 votes
# MATL, 6 bytes

```
0hYsSd

```

Try it online!

```
0       # push 0
 h      # horizontal concatenate with implicit input
  Ys    # cumulative sum
    S   # sort
     d  # diff (implicit output)

```

# Answer
> 1 votes
# J, 10 bytes

```
/:~&.(+/\)

```

# explanation

"sort under scan sum": In J, the Under conjunction `&.` applies the transformation to its right to the input, then applies the verb to its left (in this case sort `/:~`) and then does the reverse transformation. That is, J understands how to invert a scan sum, which is exactly what's needed here: the successive differences are the input that, when scan-summed, will produce that scan-sum.

Try it online!

# Answer
> 1 votes
# Vyxal, 6 bytes

```
ÞRs¯0p

```

Try it Online!

# Answer
> 0 votes
# Gaia, 7 bytes

```
1¤++⊣ȯọ

```

Try it online!

### Explanation

```
1¤+      Prepend 1
   +⊣    Cumulative sums
     ȯ   Sort
      ọ  Deltas

```

# Answer
> 0 votes
# , 16 bytes

```
1_-':{x@<x}@+\0,

```

Try it online!

```
              0, /prepend a 0
            +\   /cumulative sum
     {x@<x}@     /sort
1_-':            /differences list

```

# Answer
> 0 votes
# Japt, 10 bytes

```
iT å+ n än

```

Test it

# Answer
> 0 votes
# Röda, 42 bytes

```
{i=0{[0];[i]if i+=_}|sort|slide 2|[_2-_1]}

```

Try it online!

This is similar to the Perl 6 answer. `.sort` is `|sort`, `.rotor(2=>-1).flat` is `|slide 2` and `.map(*R-*)` is `|[_2-_1]`.

Explanation:

```
{
  i=0 /* initialize variable i */
  /* the following block recreates the original list from differences: */
  {
    [0];       /* push 0 to the stream */
    [i]if i+=_ /* add every number in the stream to i and push i back */
  }|
  sort|    /* sort the numbers */
  slide 2| /* for values i1, i2, i3, ... in the stream
              push pairs i1, i2, i2, i3, ... */
  [_2-_1]  /* calculate difference of numbers in each pair in the stream */
}

```

The statement `[i]if i+=_` is equivalent to

```
for sfv do
  if i += sfv do
    push(i)
  done
done

```

The `+=` operator does not push values to the stream, so it is truthy. I could also have used some kind of block (eg. `{|j|i+=j;[i]}_`) to tie the addition and pushing statements together, but `if` is shorter.

# Answer
> 0 votes
## Julia 0.6.0 (34 bytes)

Pretty much a copy of what has been done in R and Python 3

`x->diff(sort(cumsum(vcat([0],x))))`

# Answer
> 0 votes
# Factor, 45 bytes

```
[ 0 prefix cum-sum natural-sort differences ]

```

Try it online!

Add a 0 to the start of the input, cumulative sum, sort, differences.

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


title: 'Add' up the letters in a word

text:
# Question
Title: 'Add' up the letters in a word
My dad is a retired teacher, and he used to give combined spelling and math quizzes, where the student would spell a word, and then 'score' the word by adding up the letters, where a=1, b=2, etc. (e.g. cat = 3+1+20=24). This made grading the quizzes easier, as he would just have to check for incorrect 'scores' rather than incorrectly spelled words, and had the added benefit of testing 2 skills at once.

He hired a friend of mine to write a program that would score words for him, so he could generate lengthy answer keys without error. This problem is inspired by that program.

Requirements:

1. Accept any word with uppercase and lowercase letters
2. Return an error for any special characters, i.e. spaces, hyphens, @^%# etc.
3. a=1, b=2,... and A=1, B=2,...
4. Print the score of the word
5. (Optional) check that the word is in a dictionary after scoring, and print a warning if it is not.
6. No importing an external letter-\>number dictionary. You must generate it yourself.

Any language is acceptable. This is similar to the 'digital root battle,' but much simpler.

# Answer
## Golfscript - 23 chars

```
0\{.31&.(.26%=@64///+}/

```

Ensure there are no trailing newlines in input (e.g. use `echo -n`).
> 8 votes

# Answer
## Ruby, 43 characters

```
$_=gets.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/

```

The error message this generates isn't exactly helpful, though. Both solutions posted here assume the input has no trailing linebreak, so to test them, use `echo -n`.

## Ruby, 76 characters with dictionary check

```
l=STDIN.gets;$_=l.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/;[*$<].index(l)||$><<?W

```

The warning message consists of the single character "W". The path to the dictionary has to be supplied via ARGV. Example usage:

```
$ echo -n asd | ruby addletters.rb /usr/share/dict/words
24
W
$ echo -n cat | ruby addletters.rb /usr/share/dict/words
24

```
> 9 votes

# Answer
# Python (65 64)

```
print sum(['',ord(i)-64]['@'<i<'[']for i in raw_input().upper())

```

This raises an error if the word contains non-letter characters, but not a helpful or informative one. (Edit: tip of the hat to st0le for the indexing trick.)
> 8 votes

# Answer
# Python 2.6 (72 Chars) Without dictionary check

```
print sum(map(" abcdefghijklmnopqrstuvwxyz".index, raw_input().lower()))

```

# Python 2.6 (178 Chars\*) With dictionary check

```
w=raw_input().lower()
print sum(map(" abcdefghijklmnopqrstuvwxyz".index, w))
if w not in open('/usr/share/dict/american-english').read().split():
 print('Word not in dictionary')

```

\*Can be lowered to 156 with a less helpful error message. :-)

Thanks to all commenters for helping improve this.
> 5 votes

# Answer
# Java + Google Guava libraries, 347 characters, with dictionary check

**Unreadable 1 long string version :-)**

```
import java.io.*;import com.google.common.base.*;import com.google.common.io.*;class C{public static void main(String[]a)throws Exception{int s=0;for(int c:a[0].toUpperCase().toCharArray()){assert(c>64&&c<91);s+=c-64;}String d=Files.toString(new File(a[1]),Charsets.UTF_8);if(StringUtils.containsIgnoreCase(d,a[0]))System.out.println("w");System.out.println(s);}}

```

**Human-readable version (sort of :-))**

```
import java.io.*;

import com.google.common.base.*;
import com.google.common.io.*;

class C {
    public static void main(String[] a) throws Exception {
        int s=0;

        for(int c : a[0].toUpperCase().toCharArray()) {
            System.out.println(c);
            assert(c > 64 && c < 91);
            s += c - 64;
        }

        String d = Files.toString(new File(a[1]), Charsets.UTF_8);

        if (d.contains(a[0])) System.out.println("w");

        System.out.println(s);
    }
}

```

The dictionary path is now passed in via `a[1]`, for assertions to work you have to use the `-ea`flag (+3 more chars). As for the dictionary, the dict `/usr/share/dict/words` (should be available on most \*nix systems) has been used.
> 4 votes

# Answer
## Scala: 59 chars, 7 of them payload, no dict:

```
(0/:"Payload".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
67

```

No dictionary so far. Negative result means: Negative!

```
(0/:"Pay!wall?".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
-1915

```

Handles German Umlaute gracefully, by the way:

```
(0/:"Müllrößchen".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
155

```
> 4 votes

# Answer
## Python (80)

```
w=raw_input().lower()
s=0
for l in w:s+=range(97,123).index(ord(l))+1
print s

```

## Python v2 (65 but char \` will get accepted)

```
print sum(map(range(96,123).index,map(ord,raw_input().lower())))

```

## v3 (60 chars, @ will be accepted but not counted, thanks jloy)

```
print sum(map(range(64,91).index,map(ord,input().upper())))

```
> 4 votes

# Answer
## Python 3, 95 chars with dictionary

```
d=input().lower()
print(d in open("d").read()and sum(['',ord(c)-96]['`'<c<'{']for c in d)or'f')

```

The dictionary has to be in a file called d.

### Python 3, 61 without dictionary, but stolen idea

```
print(sum(['',ord(c)-96]['`'<c<'{']for c in input().lower()))

```
> 4 votes

# Answer
# VB.NET, ~~84~~ ~~82~~ ~~73~~ 71

```
Console.Write(Console.ReadLine.Sum(Function(c)Asc(Char.ToUpper(c))-64))

```

**Edit:** With validation is:

```
Dim r=Console.ReadLine
Console.Write(If(r.All(AddressOf Char.IsLetter),r.Sum(Function(c)Asc(Char.ToUpper(c))-64),"Invalid input."))

```

129 characters. In which case:

# C#, 118

```
var r=Console.ReadLine();Console.Write(r.All(char.IsLetter)?r.Sum(c=>char.ToUpper(c)-64).ToString():"Invalid input.");

```
> 3 votes

# Answer
## Perl (52) (48)

golfed even more thanks to Timwi

`perl -lpe "($w=uc)=~/[^A-Z]/&¨$w=~s/./$_-=64-ord$&/ge"`
> 3 votes

# Answer
# Improving slightly on John's answer: Python (90)

```
s=0
for i in raw_input().lower():
 s+=("abcdefghijklmnopqrstuvwxyz".index(i)+1)
print(s)

```
> 3 votes

# Answer
# **Erlang, 104**

```
a()->
a(string:to_lower(io:get_line([])),0).
a([_|[]],S)->
S;
a([C|R],S) when C<${, C>=$`->
a(R,S+C-$`).

```
> 3 votes

# Answer
**Golfscript - 39 chars**

```
n%~{.96>{96}{64}if-..26>\0<|{0/}*}%{+}*

```

The error it throws is not exactly the best, but hey, it aborts execution.
> 3 votes

# Answer
## PYTHON ~~62~~ 68\* Characters

```
print sum(map(chr,range(65,91)).index(c)+1 for c in input().upper())

```

Requires user to input strings using quotes, and is not safe (`input` executes code), but, as I said in a comment to another post, "user-friendly" and "not a security risk" ain't in the spec!

---

* I forgot about `print`, dammit.
> 3 votes

# Answer
# Husk, 17 bytes

```
?osṁo%32c¹¨eŻ→¨Λ√

```

Try it online!

Returns 'error' for invalid input, score of word otherwise.

```
?              Λ√       # if every element is a letter
 os                     # return the string of
   ṁ    c¹              # the sum of all their ASCII values
    o%32                # MOD 32
          ¨eŻ→¨         # otherwise, return the compressed string
                        # "error"

```

---

If it's acceptable to return '0' as the 'error' for invalid input, we can have a ~~11 byte~~ ~~10 byte~~ 9 byte solution:

```
§&ṁ%32Πm√

```
> 3 votes

# Answer
# 05AB1E, 15 bytes

```
lvAyk>})D0åi0ëO

```

Try it online! Returns `0` on error.

```
lvAyk>})D0åi0ëO  # full program
 v               # for y in...
                 # implicit input...
l                # lowercased...
    k            # push 0-based index of...
   y             # y...
    k            # in...
  A              # the lowercase alphabet...
    k            # or -1 if not found...
     >           # plus 1
      }          # end loop
           i     # if...
         0       # 0...
          å      # is in...
       )         # stack...
            0    # push 0
             ë   # else...
              O  # push sum...
        D        # of stack
                 # implicit output

```
> 3 votes

# Answer
## Ruby 1.9, 69

```
w=gets.chop.upcase
w[/[^A-Z]/]&&fail
p w.bytes.inject(0){|s,b|s+b-64}

```
> 2 votes

# Answer
## Perl (71)

```
($a)=lc<>;$a=~/[^a-z]/i&¨$x+=ord$_ for split//,$a;die$x-96*length$a;

```
> 2 votes

# Answer
# GolfScript, 50(53)

Gives an error on bad characters, but not a very good one (50 characters):

```
);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{@}if

```

Gives "E" on error instead (53 characters):

```
);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{;"E"}if

```

The alphabet-generating snippet `123,97>+` is stolen from Ventero .
> 2 votes

# Answer
# J (55)

```
+/64-~-&32`]@.(<&97)`_:@.(<&65)`_:@.(>&122)"0,I.a.&e."0

```

This satisfies all the conditions except the dictionary one. As an error condition, it returns "infinity" (the underscore symbol in J) for words that contain anything but letters.
> 2 votes

# Answer
# Haskell (127)

(raises an error on weird characters)
(also: the space between `toUpper.` and `\x` is needed otherwise it parses it as`(toUpper)` `.\` `(x)`)

```
import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper. \x->if x`elem`['A'..'Z']++['a'..'z']then x else error"")

```

# Haskell (70)

(does not raise an error, but 45% shorter)

```
import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper)

```
> 2 votes

# Answer
## C++ (~~111~~ 107)

```
void main(){int a=0;s8*b=new s8[99];for(cin>>b;*b;)if(isalpha(*b))a+=tolower(*b++)-96;else return;cout<<a;}

```

---

The "set up"/etc:

```
#include <iostream>
#include <cstdio>
#include <cctype>

#ifdef _MSC_VER
    typedef __int8 s8;
#else
    typedef signed char s8;
#endif

```

---

"Undefined" behavior (It's more 'bad practice' than 'undefined', but oh well):

* `void main()` That says it all.
* I'm using `new` without `delete`.
> 2 votes

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

```
ŒuØAiⱮoµS

```

Try it online!

Seemingly, it turns out a byte shorter to actually error than to return 0.

```
Œu           Uppercase the input,
    i        find the index (or 0 if not found)
     Ɱ       of each letter from the input
  ØA         in "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
      o      replace any 0 with the corresponding character of the input,
       µS    then take the sum.

```

Jelly errors if it attempts to add integers and strings together, and although two strings can be added together by `+`, this still errors in the case of a fully symbolic input because `S` is defined specifically as a reduce starting from zero.
> 2 votes

# Answer
## JavaScript 1.8, 80 chars

Surprisingly readable!

```
alert(Array.reduce(prompt().toLowerCase(),function(a,b)a+b.charCodeAt(0)-96,0))

```
> 1 votes

# Answer
## APL (34)

```
+/{⍵∊⍳26:⍵}¨{64-⍨A-32×96<A←⎕UCS⍵}⍞

```

Gives either the score, or a `VALUE ERROR` if there are non-alphabetic characters in the input.

Explanation:

* : read a line of input
* `{`...`}`: function applied to every character of input
* `A←⎕UCS⍵`: store the ASCII value of the current character in `A`
* `A-32×96<A`: make character uppercase: from `A` is subtracted 32 if `96<A` (so, if it's uppercase), otherwise 0
* `64-⍨`: subtract 64 from this, giving A=1, B=2 ...
* `¨`: apply this function to every character:
* `⍵∊⍳26`: if the character is between 1 and 26...
* `:⍵`: then return ⍵ (and since there's no else clause there will be a `VALUE ERROR` if it's not between 1 and 26)
* `+/`: sum all the values together (and this value is automatically outputted because it's the final result).
> 1 votes

# Answer
# F# (no validation) 79 57 chars

```
let a w=w|>Seq.fold(fun a b->a+(int b)-65)0|>printfn"%i"

```
> 1 votes

# Answer
# C, 98 bytes

```
 int a(char *s){int b=0;while(*s){if(!isalpha(*s))throw 1;b+=(toupper(*(s++))-64);}printf("%d",b);}

```
> 1 votes

# Answer
# C# with validation: 108 chars (with 12 for error message):

```
var s=Console.ReadLine();Console.Write(s.All(Char.IsLetter)?s.Sum(x=>x&'_'-'@').ToString():"Invalid input");

```

# C# without validation: 60 53 chars:

```
Console.Write(Console.ReadLine().Sum(x=>x&'_'-'@'));

```
> 1 votes

# Answer
# JavaScript, 60 bytes

```
s=>[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)

```

If the program **must** return an error on invalid inputs, then 80 bytes:

```
s=>/[^a-z]/i.test(s)?_:[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)

```

If an input is invalid, then the console will say that `_` is not defined (there must not already be a variable defined called `_`).
> 1 votes

# Answer
# JavaScript, 68 Bytes

This can almost certainly be golfed more

```
w=>[...w.toLowerCase()].map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b)

```

## With dictionary check (Node.js & Unix Descendants only) 195 Bytes

Uses `/usr/share/dict/words`, and can definitely be shortened (see the warn message)

```
w=>(require("fs").readFile("/usr/share/dict/words",(e,t)=>!(t+"").split`
`.includes(w=w.toLowerCase())&&console.warn(w+" not found in dict")),[...w].map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b))

```
> 1 votes

# Answer
# Python 3, ~~58~~ 55

```
print(sum(ord(x)%32for x in input()if x.isalpha()or z))

```

without dictionary or stolen idea but still unhelpful error ;)

thx @Eᴀsᴛᴇʀʟʏ

Test here.
> 1 votes

# Answer
## JavaScript (V8), 51 bytes

```
w=>w.split``.reduce((a,l)=>a+parseInt(l,36)-9,0)||x

```

Surprised nobody's made this golf yet.

Explanation:

```
w =>                // Function with w as argument
w.split``           // Split w into an array of characters
.reduce((a,l)=>a+   // Take the sum of...
parseInt(l,36)-9    // The value of the letter in base 36, then subtract nine (gives the number of the letter)
,0)||x              // Error if it's NaN (there was a special character), because x is not defined

```
> 1 votes

# Answer
# Perl 5 `-pF`, 26 bytes

```
/\PL/||map$\+=037&ord,@F}{

```

Try it online!

Outputs nothing as its error condition
> 1 votes

# Answer
# Forth, 48 bytes

`0 -rot bounds [do] [i] c@ 32 xor 64 - + [loop] .`

(takes arguments from the stack)

a version that reads from stdin:

`0 pad pad pad stdin read-line 2drop bounds [do] [i] c@ 32 xor [if] 64 - + [loop] .`

the second version, but commented:

```
0 pad \ used later
pad \ where to put the bytes
pad \ how many bytes (it's an address, so it's a big number, and forth doesn't have types)
stdin \ where to get the bytes
read-line \ get the bytes (also returns the number of bytes got)
2drop \ ignore IO errors
bounds \ turn an address and a length into a start and end address
[do] \ iterate over all the address in said range
[i] \ get the current address
c@ \ get the character at the current address
32 xor \ make it uppercase
64 - \ letter to number (eg a -> 1)
+ \ add number to total (this is what the 0 is for)
[loop] \ end loop
. \ print resulting number

```
> 1 votes

# Answer
# Vyxal, 9 bytes

```
ʀA[⁰øA∑|u

```

Try it Online! Ties with jelly but pushes -1 if there is an error.

```
ʀA             # check if every character is in the alphabet
  [⁰øA∑        # if true, sum the character values of the input string
        |u     # else, return -1

```
> 1 votes

# Answer
# C, 97 Chars

```
int r(c*z){int x=0;while(*z){char w=tolower(*(z++));if(w<96|w>122)return-1;x+=w-96;}return x;}

```

It returns -1 if there's an invalid character.
> 0 votes

# Answer
# K, 44

```
{$[=/x in\:a:.Q.a,.Q.A;+/(a!,/2#,1+!26)x;`]}

```

Returns \` for any non alphabetic input
> 0 votes

# Answer
## VBA 120

```
Sub s(t)
For i=1 To Len(t)
a=Asc(Mid(t,i,1))-64
a=IIf(a>32,a-32,a)
If a<1 Or a>26 Then Print
b=b+a
Next
MsgBox b
End Sub

```

`Print` does not cause a compile-time error, though the syntax is invalid, which causes an exception to be thrown and the program to exit if, and only if, the character is not an upper- or lower-case letter.
> 0 votes

# Answer
# Perl (~~42~~ 31)

```
perl -F -pale '$c+=ord(uc$_)-64for@F;$_=$c'

```

I hope counting F, p, a and l as 1 character was correct.
> 0 votes

---
Tags: code-golf, word
---