title: Count Consecutive Characters

text:
# Question
Title: Count Consecutive Characters
Given a string containing only letters, output the length of the longest run of consecutive alphabetical letters the word contains, where order does not matter. An example algorithm may sort the word, remove duplicates, and then output the length of the longest run.

## Test Cases

```
watch -> 1
stars -> 3
antidisestablishmentarianism -> 3
backdoor -> 4
a -> 1
tutorials -> 4

```

For example, `antidisestablishmentarianism` contains the letters `abdehilmnstr`. The longest runs are `lmn` and `rst`, both of length 3.

## Notes

You may take all lowercase, all uppercase, or mixed-case letters as input, but the case cannot encode information about the word (i.e. you cannot make the first `n` characters capitalized where `n` is the length of the longest run).

This is , so shortest answer in bytes wins.

# Answer
> 10 votes
# Jelly,  ~~10 9 8 7~~  6 bytes

```
OṬṣ0ZL

```

**Try it online!**

<sup>9 was using Sok's method: `ṢQẆẇƇØaṪL`</sup>

### How?

```
OṬṣ0ZL - Link: list of (single-case) characters  e.g.  codegolf
O      - ordinal (vectorises)           [99,111,100,101,103,111,108,102]
 Ṭ     - untruth (1s at those indices)  [0,0,0,...,1,1,1,1,1,0,0,0,0,1,0,0,1]
       -                                 ^         ^       ^         ^     ^
       -                   i.e. indices: 1        99     103       108   111
   0   - literal zero
  ṣ    - split at                       [[],[],[],...,[1,1,1,1,1],[],[],[],[1],[],[1]]
    Z  - transpose                      [[1,1,1],[1],[1],[1],[1]]
     L - length                         5

```

# Answer
> 8 votes
# , ~~44~~ 43 bytes

Works on an array of lowercase characters. Edit: changed it from testing True values to multiplying by the T/F for a byte.

```
function(x,r=rle(letters%in%x))max(r$l*r$v)

```

Try it online!

Does a run length encoding on letters that are in the supplied characters then return the max value for the trues.

# Answer
> 7 votes
# APL (Dyalog Classic), ~~10~~ 9 bytes

-1 byte thanks to H.PWiz

```
≢⍉↑⊆⍨⎕a∊⍞

```

Try it online!

inputs a string

`⎕a` is the uppercase English alphabet

`⎕a∊⍞` a boolean length-26 vector - which letters occur in the string?

`⊆⍨` form vectors of consecutive 1s

`≢⍉↑` mix into a matrix, transpose, and return its height - effectively, find the length of the longest vector of 1s

# Answer
> 6 votes
# JavaScript (Node.js), 51 bytes

The case of the input string doesn't matter.

```
s=>(g=_=>s&&1+g(s&=s*2))(Buffer(s).map(c=>s|=1<<c))

```

Try it online!

### How?

We first convert the input string into a bitmask of encountered letters with:

```
Buffer(s).map(c => s |= 1 << c)

```

The bitwise shift is processed with an implicit modulo 32.

Example:

```
"feedback" --> 100001111110
               kjihgfedcba-

```

We then 'reduce' runs of consecutive 1's in the bitmask by repeatedly AND'ing it with a left-shifted copy of itself until all bits are cleared:

```
0100001111110 AND 1000011111100 --> 0000001111100
0000001111100 AND 0000011111000 --> 0000001111000
0000001111000 AND 0000011110000 --> 0000001110000
0000001110000 AND 0000011100000 --> 0000001100000
0000001100000 AND 0000011000000 --> 0000001000000
0000001000000 AND 0000010000000 --> 0000000000000

```

The number of consecutive letters in alphabetical order is the number of iterations of the above process. Hence the recursive function:

```
g = _ => s && 1 + g(s &= s * 2)

```

# Answer
> 6 votes
# Perl 6, 41 bytes

```
{max values bag .ords.sort.squish Z-0..*}

```

Test it

## Expanded:

```
{  # bare block lambda with implicit param $_

  max       # find the max
    values  # get the values from the following Bag (repeat counts)
      bag   # find the repeats

          .ords.sort.squish # get the unique ordinals (method call on $_)
        Z-                  # zip subtract with
          0 .. *            # Range starting with 0
}

```

Given `'stars'`, `.ords.sort.squish Z-0..*` would return `(97,113,113,113)`

# Answer
> 6 votes
# Haskell, 35 bytes

```
f[]=0
f s=1+f[c|c<-s,elem(succ c)s]

```

Try it online!

# Haskell, 50 bytes

```
f s=maximum$scanl(\x c->sum[x+1|elem c s])0['a'..]

```

Try it online!

# Answer
> 5 votes
# Pyth, 9 bytes

```
le}#G.:S{

```

Input is assumed to be a lower case string. Try it out online here, or verify all the test cases at once here.

```
le}#G.:S{Q   Q=eval(input()), G=lowercase alphabet. Trailing Q inferred.

        {Q   Deduplicate input string
       S     Sort it
     .:      Take all substrings (these are generated in length order)
  }#G        Filter out those that aren't found in the alphabet
le           Find the length of the last remaining element

```

# Answer
> 5 votes
# MATL, 10 bytes

```
2Y2imY'*X>

```

Input is in lowercase.

Try it online! Or verify all test cases.

This uses a mix of @Sundar's (old) and @ngn's approaches.

### Explanation

Consider input `'tutorial'` as an example.

```
2Y2   % Push predefind literal 'abcdefghijklmnopqrstuvwxyz'
      % STACK: 'abcdefghijklmnopqrstuvwxyz'
i     % Push input
      % STACK: 'abcdefghijklmnopqrstuvwxyz', 'tutorials'
m     % Ismember: true for letters present in the input
      % STACK: [1 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0]
Y'    % Run-length encoding
      % STACK: [1 0 1 0 1 0 1 0 1 0], [1 7 1 2 1 2 1 2 4 5]
*     % Multiply, element-wise
      % STACK: [1 0 1 0 1 0 1 0 4 0]
X>    % Maximum. Implicitly display
      % STACK: 4

```

# Answer
> 5 votes
# Python 3, 55 bytes

```
f=lambda s:s and-~f({*s}&{chr(ord(c)+1)for c in s})or 0

```

Try it online!

---

# Python 2, 58 bytes

```
f=lambda s,c=99,r=0:c and max(r,f(s,c-1,-~r*(chr(c)in s)))

```

Try it online!

---

# Python 2, 63 bytes

```
n=t=0
for c in input():n|=2**ord(c)
while n:n&=n/2;t+=1
print t

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 6 bytes

Saved 1 byte thanks to Adnan: taking the contiguous substrings, then sorting by length (`Œ...é`) \\$\to\\$ using the powerset built-in instead (`æ`).

```
êæAÃθg

```

Try it online!

### Also 6 bytes

Saved 2 bytes, again thanks to Adnan: using `ASå` instead `êÇ¥Θ`, thus also removing the need to increment the maximum at the end. See the revision history to compare the beviours of the two methods.

```
ASåγOà

```

Try it online!

### How those works

I like challenges like this one which lead to a variety of different approaches.

```
êæAÃθg | Full program.
ê      | Push a sorted and without duplicates version of the input.
 æ     | Powerser.
  AÃ   | Keep those that also occur in the lowercase alphabet.
    θg | Take the length of the last one. θ and ` can be used interchangeably.
-------+-------------------------------------------------------------------------------
ASåγOà | Full program.
A      | Push the lowercase alphabet.
 S     | Listify it (i.e. convert it to a sequence of characters).
  å    | Replace each char in the alphabet by 1 if its in the input, else by 0.
   γ   | Split into chunks of equal adjacent elements.
    O  | Sum each part.
     à | Extract the maximum of this list. Again, à and Z can be used interchangeably.

```

# Answer
> 4 votes
# C (gcc), ~~58~~ 56 bytes

*Saved 2 bytes thanks to @gastropner*

Uses the same approach as my Node.js answer. The case of the input string doesn't matter.

```
m,i;f(char*s){for(i=0;*s?m|=1<<*s++:(i++,m&=m*2););s=i;}

```

Try it online!

### Commented

```
m,                   // m = bitmask of encountered letters
i;                   // i = counter of max. consecutive letters
f(char *s) {         // f = function taking the input string s
  for(               // main loop:
    i = 0;           //   start with i = 0 and assume m = 0 on first call
                     //   (it is forced back to 0 when the program terminates)
    *s ?             //   if we haven't reached the end of the string:
      m |= 1 << *s++ //     update m by setting the appropriate bit for this character
                     //     (with implicit modulo 32) and advance the string pointer
    : (              //   else:
        i++,         //     increment i
        m &= m * 2   //     'reduce' runs of consecutive 1's in m by AND'ing it with a
      );             //     left-shifted copy of itself (e.g. 11101 & 111010 -> 11000;
                     //     11000 & 110000 -> 10000); we stop when m = 0
  );                 // end of for()
  s = i; }           // return i

```

# Answer
> 4 votes
# TSQL (Microsoft SQL Server), 206 bytes

```
WITH C AS (SELECT 1p,SUBSTRING(@,1,1)c UNION ALL SELECT p+1,SUBSTRING(@,p+1,1)FROM C WHERE p<LEN(@)),R AS(SELECT c d,1r FROM C UNION ALL SELECT c,r+1FROM R JOIN c ON ASCII(d)+1=ASCII(c))SELECT MAX(r)FROM R

```

For input, use the following `DECLARE` statement before the code:

```
DECLARE @ varchar(200) = 'propinquities';

```

It is expected that input is all the same case (upper or lower doesn't matter, but mixed case would not work).

**Ungolfed:**

```
DECLARE @data varchar(200) = 'propinquities'

;WITH CTE AS (
    SELECT
        1 as CharacterPosition,
        SUBSTRING(@data,1,1) as Character
    UNION ALL
    SELECT
        CharacterPosition + 1,
        SUBSTRING(@data,CharacterPosition + 1,1)
    FROM
        CTE
    WHERE CharacterPosition < LEN(@data)
), Runs AS
(
    SELECT Character, 1 rc
    FROM CTE
    UNION ALL
    SELECT b.Character, rc + 1
    FROM Runs r
    JOIN CTE b ON ASCII(r.Character) + 1 = ASCII(b.Character)
)
SELECT max(rc)
from runs

```

**Explanation:**

Splits the string into a a row for each character (adapted from https://stackoverflow.com/a/27623321/1474939) in the `CTE` cte.

Then, finds runs of consecutive letters by converting to the ASCII code in the `Runs` cte.

Lastly, it picks the largest run and reports back in the select statement.

# Answer
> 3 votes
# K (ngn/k), ~~17~~ 15 bytes

```
#1_{x^x^x+1}\-:

```

Try it online!

`-` is there only to convert the chars to numbers (it doesn't matter if they are negative)

`{` `}\` applies a function until convergence, preserving intermediate results

`x+1` add 1 to each number in `x`

`^` "without" - the list on the left without elements that occur in the list on the right

`x^x^x+1` means `x` intersected with `x+1`

`1_` drop the first element

`#` count

# Answer
> 3 votes
# MATL, ~~12~~ 10 bytes

```
91:wX-dX>q

```

Try it online!

### Explanation:

`91:` \- Create the list of numbers from 1 to 91. 91 is character '\[', which comes after 'Z'. So this effectively creates the list of all characters from '\x1' to '\['. (We mainly want those in the range \['A'-1 : 'Z'+1\], but having the rest doesn't hurt, and needs less bytecount.)

`w` \- Implicit input, bring input to top of stack (assume 'TUTORIALS')

`X-` \- Set difference. This leaves only the characters that were *not* found in the input string, in their original order ('stable'). Stack: `' !"#$%&'()*+,-./0123456789:;<=>?@BCDEFGHJKMNPQVWXYZ['`

`d` \- Difference between successive elements in that list. Stack: `[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 2 1 2 1 2 1 5 1 1 1 1 1]`

`X>` \- Get the maximum of those differences i.e. the max number of consecutive alphabets missing from the set difference.

`q` \- Decrement to get actual character count

---

Older:

### 12 bytes

```
Sud1=Y'*X>sQ

```

Try it online!

# Answer
> 3 votes
# C (gcc), 100 bytes

```
c,o,u;n(t,e,r)char*r,*e,*t;{for(u=0,e=t;c=*t++;u=u<o?o:u)for(o=0,r=e;*r;*r++-c||(c++,r=e,++o));o=u;}

```

Try it online!

# Explanation

```
c,o,u;n(t,e,r)    // setup, function declaration
char*r,*e,*t;{    // K&R style
 for(u=0,e=t;     // initialize global maximum u to 0, write string start to e
 c=*t++;          // look at every character in the string
 u=u  <o?o:  u)   // funny face
  for(o=0,r=e;*r; // initialize local maximum o to 0, look at entire string again
  *r++-c||(c++,   // equal character found, search for next one
   r=e,++o));     // reset local pointer, increment local maximum
o=u;}             // return maximum character streak

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 54 bytes

```
O`.
D`.
.
$&$&¶
T`l`_l`¶.
(.)¶\1
$1
.(.+)
$.1
O#^`
1G`

```

Try it online! Link includes test cases. Explanation:

```
O`.

```

Sort the letters into order.

```
D`.

```

Deduplicate the letters.

```
.
$&$&¶

```

Duplicate each letter on separate lines.

```
T`l`_l`¶.

```

Decrement the first of each pair.

```
(.)¶\1
$1

```

If this now matches the previous character, join them back together.

```
.(.+)
$.1

```

Count the lengths of all the runs.

```
O#^`

```

Sort them in reverse numerical order.

```
1G`

```

Take the first (largest).

# Answer
> 2 votes
# C (gcc), 98 92 bytes

Thanks to Jonathan Frech for the suggestions.

Uppercase-only.

```
f(char*s){int a[99]={0},i,j,k=j=i=0;for(;*s;a[*s++]++);for(;i<99;j=!!a[i++]*++j,k=j>k?j:k);}

```

Try it online!

# Answer
> 2 votes
# J, 16 bytes

*-7 bytes thanks to FrownyFrog*

```
[:>./a.#;._1@e.]

```

Try it online!

## explanation

```
[: >./ a. #;._1@e. ]
       a. (    )e. ]    is the ascii alphabet an element of the input:
                        this will transform the alphabet into a 1-0 array,
                        the ones representing the letters in the input
          #;._1@        split that 1-0 list up into pieces, using 0
                        as the delimiter, and transforming each chunk
                        into its length. now we have a list of ints
[: >./                  take the max

```

# Answer
> 2 votes
# Japt `-h`, 9 bytes

Case insenstive, takes input as a string or an array of characters.

```
;CôkU mÊn

```

Try it or run multiple tests (the second line serves as a replacement for the `-h` flag so the flag can be used to process multiple inputs instead)

---

## Explanation

```
              :Implicit input of string/array U
;C            :The lowercase alphabet
  ô           :Partition at characters returning truthy
   kU         :  Remove all characters in U from the current letter
              :  This will return a non-empty string (truthy) if the current letter ISN'T in U
     m        :Map
      Ê       :  Length
       n      :Sort
              :Implicitly output the last element in the array

```

# Answer
> 2 votes
## Perl 5, 68 bytes

```
$"=<>;map{$"=~/$_/i&&++$$_||last for$_..z;$.=$$_ if$$_>$.}a..z;say$.

```

Try it online.

Ungolfed:

```
use feature 'say';

my $s = <>;
my $r;
for ('a' .. 'z') {
    my $c = 0;
    for ($_ .. 'z') {
        last if $s !~ /$_/i;
        $c++;
    }
    $r = $c if $c > $r;
}
say($r);

```

# Answer
> 2 votes
## Perl 5, 62 + 2 (`-nF` flag) = 64 bytes

```
$c[ord lc$_]=1for@F;$y[y///c]++for"@c "=~/((1 )+)/g}{say@y/2|0

```

Try it online.

## Perl 5, 68 bytes

```
<>=~s/./$c[ord lc$&]=1/gre;$y[y///c]++for"@c "=~/((1 )+)/g;say@y/2|0

```

Try it online.

# Answer
> 2 votes
# C (gcc), ~~66~~ ~~65~~ 63 bytes

Assumes input only contains lowercase letters. First, it loops over the string and sets bits in an integer according to which letters are seen. Next, it counts the longest streak of 1 bits in the integer.

Edit: `a` is global, so will be initialised to 0 at first call. The second loop makes sure it is reset to 0 before returning. Therefore, we can avoid resetting it manually.

```
a,l;f(char*s){for(l=0;*s;)a|=1<<*s++-97;for(;a;l++)a&=a*2;s=l;}

```

Try it online!

# Answer
> 2 votes
# SQLite 265

```
WITH w AS(SELECT'a'w),n AS(SELECT 1 n UNION ALL SELECT n+1 FROM n LIMIT(SELECT length(w)FROM w)),l AS(SELECT substr(w,n,1)l FROM n,w)SELECT max(v)FROM(SELECT min(n)v FROM(SELECT*FROM l,n EXCEPT SELECT l.l,unicode(l.l)-unicode(b.l)d FROM l,l b WHERE d>0)GROUP BY l);

```

Ungolfed:

```
WITH w AS (SELECT 'antidisestablishmentarianism' w)
   , n AS (SELECT 1 n
           UNION ALL
           SELECT n+1 FROM n
           LIMIT (SELECT length(w) FROM w) )
   , l AS (SELECT DISTINCT substr(w,n,1) l FROM n,w ORDER BY l)
   , d AS (
           SELECT l,n FROM l,n
           EXCEPT
           SELECT a.l l, unicode(a.l) - unicode(b.l) d
           FROM l a, l b
           WHERE d > 0
           )

SELECT max(v) FROM ( SELECT min(d.n) v FROM d GROUP BY d.l );

```

# Answer
> 2 votes
# Brachylog, ~~14~~ ~~13~~ 12 bytes

```
{⊇pS∧ẠsSl}ᶠ⌉

```

Try it online!

```
{        }ᶠ    % Find all values that satisfy this predicate
           ⌉   % And get their maximum
               % The predicate being:
 ⊇pS           % There exists a permutation of a subset of the input
               %  Call it S
    ∧          % And,
      sS       % S is a substring of
     Ạ         %  the set of alphabets, Ạ,
        l      % Then, the length of that substring is the return value of the
               %  predicate

```

Slow enough that it doesn't finish for input "antidisestablishmentarianism" on TIO. Relatively much faster one for +1 byte:

### 13 bytes

```
{dosS∧ẠsSl}ᶠ⌉

```

Try it online!

Use `dos` instead of `⊇p`: S is a `d`eduplicated s`o`rted `s`ubstring of the input, instead of just some permutation of some subset.

# Answer
> 2 votes
# Ruby, ~~63~~ 59 bytes

Not very golfy.

-4 bytes thanks to manatwork

```
->s{s.bytes.uniq.sort.slice_when{_2!=_1+1}.map(&:size).max}

```

Attempt This Online!

# Answer
> 2 votes
# Vyxal, 7 bytes

```
CÞǔ0€∩L

```

Try it Online!

Port of Jelly.

# Answer
> 2 votes
# Ruby, 43 characters

```
->s{(?a..?z).map{$.=s=~/#{_1}/?$.+1:0}.max}

```

Sample run:

```
bash-5.1$ ruby -e 'p ->s{(?a..?z).map{$.=s=~/#{_1}/?$.+1:0}.max}["backdoor"]'
4

```

Attempt This Online!

# Answer
> 1 votes
# Haskell, 87 bytes

```
import Data.List
maximum.map length.filter(`isInfixOf`['a'..'z']).subsequences.nub.sort

```

Try it online!

Expects lowercase characters

Explanation:

```
maximum.map length.filter(`isInfixOf`['a'..'z']).subsequences.nub.sort
                                                                  sort {- sort the characters -}
                                                              nub      {- remove duplicates -}
                                                 subsequences          {- all subsequences -}
                   filter(`isInfixOf`['a'..'z'])                       {- all characters are adjacent -}
        map length                                                     {- length of filtered subsequences -}
maximum                                                                {- maxmimum length -}

```

# Answer
> 1 votes
# Python 2, 95 bytes

```
lambda s:max(reduce(lambda(p,v),c:(c,v+[v[-1]*(c==p+1)+1]),map(ord,sorted(set(s))),(0,[0]))[1])

```

Try it online!

# Answer
> 1 votes
# Pyth - 11 bytes

```
le@.:G).:S{

```

Input must be wrapped in quotes. If not allowed:

# Pyth - 12 bytes

```
le@.:G).:S{z

```

Explanation:

```
l(
  e(
    @(
      .:(G),
      .:(
         S(
           {(Q)
         )
      )
    )
  )
)
length(
    last element(
        intersection(
            all positive length substrings(the alphabet as string),
            all positive length substrings(
                sorted(
                    uniquified(input)
                )
            )
        )
    )
)

```

# Answer
> 1 votes
# Kotlin, 97 bytes

```
{w:String->{var s=0
var m=0
for(c in 'a'..'z')if(c in w)s++
else{if(s>m)m=s
s=0}
if(s>m)m=s
m}()}

```

Try it online!

# Answer
> 1 votes
# Java 8, 77 bytes

```
int i,j,m;
c->{for(i=j=0;(m=j<c.length?m|1<<c[j++]:m&m*2+0*++i)>0;);return i;}

```

Port of Arnauld's C answer. Try it online here.

Ungolfed:

```
int i, j, m; // instance variables of the surrounding class - initialised to 0
c -> { // lambda - c is of type char[]; return type is int
    for(i = j = 0; // i is the length of the longest run, j is used to step through c - both start at 0
        (m = j < c.length // work with the bitmask of all the letters present in c: if we have not reached the end of c ...
             ? m | 1 << c[j++] // ... set the bit corresponding to the current character, advance one character ...
             : m & m * 2 + 0 * ++i) > 0 ;) ; // ... else reduce runs of consecutively set bits in m by AND-combining it with a left-shifted copy of itself until m hits 0
    return i; // return the result - by now m is back to 0
}

```

# Answer
> 1 votes
# \>\<\>, 63 bytes

Reads lowercase characters from stdin, outputs a number to stdout.

```
0l55*)?\
8/?(0:i<]r1~r[-*c
~/00
}</?)@:{:*+1/?(3l
  \~:03. ;n~/

```

Try it online!

```
0l55*)?\             Push 26 zeroes onto the stack

Record which characters are used
      i              Read a character from the input
 /?(0:               Check if it is -1, marking the end of the input
8             -*c    Subtract 96 from the character code,
                         giving 1 for 'a', 2 for 'b' etc.
            r[       Pop that many values on to a new stack and reverse
                         it, putting that character's value at the top of
                         the stack
          1~         Write 1 to that value
        ]r           Return the stack back to it's normal state

Count the longest run of ones in the stack
  00                 Push values for currentRun = 0, and bestRun = 0
}                    Move bestRun to the bottom of the stack
            /?(3l    Check if there are only 2 values left on the stack
          +1         Increment currentRun
         *           Multiply currentRun by the next value in the stack,
                         resetting it to 0 if the run is broken
  /?)@:{:            Check if currentRun > bestRun
  \~:                Overwrite bestRun if so
     03.             Jump back to the start of loop
         ;n~/        Once all values have been consumed,
                         print bestRun and exit

```

# Answer
> 1 votes
# Husk, 7 bytes

```
L►Lġ≈Ou

```

Try it online!

First time I've used `simil(≈)`, and it works really well!

## Explanation

```
L►Lġ≈Ou
     Ou order and deduplicate
   ġ≈   group by absolute difference ≤ 1
 ►L     max by length
L       take the length of that

```

# Answer
> 1 votes
# Mathematica, 63 bytes

```
Length[Alphabet[]~LongestCommonSubsequence~Union@Characters@#]&

```

View it on Wolfram Cloud!

Mathematica's verbosity is a blessing and a curse, as usual. `LongestCommonSubsequence` is exactly the right tool for the job, but its an astounding 24 bytes! (Also, as usual, strings being atoms is frustrating.)

# Answer
> 1 votes
# Thunno 2 `G`, 5 bytes

```
Ạ€Ƈġʂ

```

Try it online!

Port of Adnan's 05AB1E answer.

#### Explanation

```
Ạ€Ƈġʂ  # Implicit input
Ạ      # Push the lowercase alphabet
 €     # For each letter in this string:
  Ƈ    #  Is it in the input string?
   ġ   # Group consecutive items together
    ʂ  # Sum each inner group
       # Implicit output of maximum sum

```

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


title: Days in indexed month

text:
# Question
Title: Days in indexed month
This simple challenge is very similar to this one: How many days in a month? The only difference is you **yield the number of days in a month given the index of the month** instead of its name.

The reason I ask this near-duplicate is curiosity about mathematical patterns in the sequence of numbers. For example, a simple observation is that even-indexed months have 31 until August and then it flips — but golf that observation and/or make better ones that yield better strokes...

**INPUT**: Integer indicating the month; `1` through `12`. (Optionally, you can accept `0`-indexed month numbers from `0` to `11`.)

**OUTPUT**: Number of days in that month. February can return `28` or `29`.

**Complete I/O table:**

```
INPUT   :   OUTPUT
  1          31
  2          28 or 29
  3          31
  4          30
  5          31
  6          30
  7          31
  8          31
  9          30
 10          31
 11          30
 12          31

```

# Answer
# APL (Dyalog Unicode), ~~13~~ 12 bytesSBCS

Anonymous tacit prefix function. 0-indexed. February is 29.

```
31-1∘=+2|7∘|

```

Try it online!

`31-` thirty-one minus…

`1∘=` the equal-to-one'ness…

`+` plus…

`2|` the two-mod of…

`7∘|` the seven-mod'ness

> The reason I ask this near-duplicate is curiosity about mathematical patterns in the sequence of numbers. For example, a simple observation is that even-indexed months have 31 until August and then it flips — but golf that observation and/or make better ones that yield better strokes...

This solution implements the following mathematical pattern:

$$f(x)=31-\[x=1\]-\big((x\mod 7)\mod 2\big)$$

or

$$f(x)=31-x-\left\[x=1\right\]+7\left\lfloor\frac{x}7\right\rfloor+2\left\lfloor x-7\left\lfloor\frac{x}7\right\rfloor\over2\right\rfloor$$
> 27 votes

# Answer
# Poetic, 706 bytes

```
counting a day,one month<t-o>twelve
i got frustrated doing a list
i do say,o,i edited a list,a month&a day count
in twelve(in December)to one(January)i listed a day"s count,then the numeral months
and once i am ready,o,i think i got a number to say
a number,o,i know a count
o,i say i am thirty if one"s short
i am ready,o,i know a count is not a thirty if we switch it
a long,a short,a etc.i switch
i do think i want a count of Febr-u"ry=two n eight:a case of a month"s age as shorter than the others"s
a day"s a day,i reckon
i know,i am clever
o,a date"s count at min=a thirty-day,or affix a one,i think
i do start&i produce threes if ever i am thirty
P.S.note:i index by one,i receive any-format numbers

```

Try it online!

As noted in the final line of the program, this program takes months as 1-based indices, and can take both simple numbers and numbers with a leading 0. (How's *that* for code comments?)

In pseudocode, my approach was basically like this:

```
N = input(); // Poetic doesn't support native numerical input, only input as ASCII codes; I basically have to write myself a number input routine every time
DIGIT = 49 // ASCII value for "1"; I would set it to 3, but that would be slightly longer
if (N>7) N++; // this accounts for the July->August parity shift
if (N!=2) { // if not February...
    DIGIT += 2; // now it's "3"
    print(DIGIT); // output: "3"
    DIGIT -= 3; // and now it's "0"...
    if (N%2==1) THREE++; // ...unless N is odd
    print(DIGIT); // output: "30" if short month, "31" if long month
} else { // if February...
    DIGIT += 1; // now it's "2"
    print(DIGIT); // output: "2"
    DIGIT += 6; // now it's "8"
    print(DIGIT); // output: "28"
}

```
> 13 votes

# Answer
# Pyke, 4 bytes

```
~%R@

```

I have no idea how does this work (actually, after reading the source, I think I do, but Pyke seems **extremely** weird to me) as I simply used the second half of the Pyke answer by @Blue in the related question OP linked to. Try it online!
> 12 votes

# Answer
# JavaScript (ES6), 16 bytes

All solutions expect a 0-indexed input and output 29 days for February.

Using a decimal modulo.

```
n=>n%1.7+!~-n^31

```

Try it online!

---

Using a single integer modulo.

```
n=>30-!~-n|n%7^1

```

Try it online!

---

Same approach as Adám with 2 integer modulos.

```
n=>31-n%7%2-!~-n

```

Try it online!
> 10 votes

# Answer
# C (gcc), 27 bytes

0-indexed.

Instead of indexing into a string, I get the day offset (from 28) for the month from a packed bit array. Luckily all the offsets fit in a two-bit representation, so the bit array fits in an integer: I just shift and mask the offset and add 28.

```
f(m){m=0xEEFBB3>>m*2&3|28;}

```

Try it online!
> 10 votes

# Answer
# Gaia, 3 bytes

```
∂k=

```

Yep, there's a built-in.

Try it online!

```
∂k   List containing days in each month
  =  Index into it (implicit input)

```
> 8 votes

# Answer
# x86 Machine Code, 14 bytes

```
B8 B3 FB EE 00
01 C9
D3 E8
24 03
04 1C
C3

```

This is a straight port of ErikF's C answer. The above bytes define a function that accepts a zero-indexed month (in the `ECX` register), and outputs the number of days (in the `AL` register, the lower-order bytes of the `EAX` register). The result is calculated by adding 28 to a fix-up parameter obtained from a sequenced vector of 2-bit values.

```
B8 B3 FB EE 00   mov    eax, 0x00EEFBB3    ; load bit vector into EAX
01 C9            add    ecx, ecx           ; \ index into the bit vector
D3 E8            shr    eax, cl            ; |   by shifting it right
24 03            and    al,  3             ; /   and keeping only the lowest 2 bits
04 1C            add    al,  28            ; add 28
C3               ret

```

**Try it online!**

Note that we can do the `AND` and `ADD` on byte-sized operands, which results in 2-byte instructions, rather than the 3-byte instructions required to operate on double-words.

The big bloat here is that initial 32-bit `MOV` instruction required to load the bit vector, but this implementation is still significantly smaller than a solution implementing the mathematical algorithm cited by Adam: `(31 - ((month % 7) % 2) - (month == 1))`.
> 6 votes

# Answer
# Python 3, 24 bytes

```
lambda n:31-n%7%2-(n==1)

```

Try it online!

Adaptation of Adám's APL answer

---

Original answer:

# Python 3, 29 bytes

```
lambda n:31^n%2^n//7^2*(n==1)

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 9 bytes

```
7%É31αsΘ-

```

Same formula as *@Adám*'s APL (Dyalog Unicode) answer, which I've also partially used in this earlier answer of mine.

Try it online.

**Explanation:**

```
7%         # Take the (implicit) input-integer modulo-7
  É        # Check whether it is odd (short for modulo-2)
   31α     # Take the absolute difference with 31
      s    # Swap to take the (implicit) input-integer again
       Θ   # 05AB1E truthify; 1 if n==1; 0 otherwise
        -  # And subtract this from the earlier number
           # (after which the result is output implicitly)

```
> 5 votes

# Answer
# Turing Machine Code, 197 bytes

```
0 0 _ * j
0 1 _ r F
0 2 _ * j
0 3 2 * F
0 4 _ * j
0 5 2 * F
0 6 _ * j
0 7 _ * j
0 8 2 * F
0 9 _ * j
h * * * halt
j _ 3 r ǰ
ǰ _ 1 * h
F _ 2 r Ƒ
Ƒ _ 8 * h
F 0 2 * F
F 1 _ r j
N _ 0 * h
F 2 3 r N

```

Try it online!
> 5 votes

# Answer
# Python 3, 58 45 bytes

```
lambda x:'312831303130313130313031'[x*2:][:2]

```

Try it online!

* A weak solution to get it started with an "unanalyzed" solution space
* Saved a few bytes by functionizing thanks to Jo King
> 4 votes

# Answer
# PHP, 31 bytes

```
<?=date(t,mktime(0,0,0,$argn));

```

Try it online!

Just using builtins really. Input month via STDIN, 1-indexed.
> 4 votes

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

```
x=>""[x]

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~42~~ ~~39~~ 35 bytes

```
lambda i:(30+(i%2==(i<8)),28)[i==2]

```

Try it online!

Not the shortest Python solution but an alternative approach (1 indexed).

Shorter but not very interesting:

# Python 2, 34 bytes

```
lambda i:int("303232332323"[i])+28

```

Try it online!
> 4 votes

# Answer
# Retina, ~~29~~ 28 bytes

```
^o$
x
o{7}|oo

^
31*
__x|_o

```

Explanation:

```
^o$      match input equal to "o"
x        replace it with x
o{7}|oo  match 7 or 2 "o"s, whichever the regex engine prefers
         replace them with nothing (this happens to compute a%7%2)
^        match the beginning of string
31*      and replace it with 31 times the default character (_)
__x|_o   match __x or _o literally
         and erase them (that is, "x" means "erase two _" and "o" means "erase one _")

```

Try it online!
> 4 votes

# Answer
# Red, 46 bytes

```
func[m][b:(a: to now[1 m 1])+ 31 b/4: 1 b - a]

```

Try it online!

A verbose solution that literally calculates the number of days in the given month (28 for february - year 1 AD)

## Explanation:

```
Red[]
f: func[m][
    a: to now [1 m 1]   ; make a date dd-mm-yyyy (1st of the "month" year 1 AD)
    b: a + 31           ; add 31 days to it
    b/4: 1              ; and go back to the 1st day of the new month
    b - a               ; subtract the initial date from the new one
]

```
> 3 votes

# Answer
As suggested by @Xcali it can be even shorter:

# Perl 5, 35 bytes

```
$_=substr"3128".3130313031x2,$_*2,2

```

Try it online!

As suggested by @manatwork this can be shortened substantial:

# Perl 5, 39 bytes

```
("3128".3130313031x2)=~/(..){$_}/;$_=$1

```

Try it online!

~~Perl (And because I like regex, a first humble attempt):~~

~~Perl 5, 60 bytes
```
print $1 if "312831303130313130313031" =~ /(..){$ARGV[0]}/g;

```
Try it online!
~~

~~Invoke via `perl -e` and user supplied input, e.g. `2` for the month, at command line argument with index 0.~~
> 3 votes

# Answer
# Haskell, 37 bytes

Not in any way clever, but there you go. Pretty much checks all the non-31-day months and if it isn't any of them it falls back on 31.

```
f 2=28;f m|elem m[4,6,9,11]=30;f _=31

```

Try it online!
> 3 votes

# Answer
## Excel, 29 bytes

```
=DAY(EOMONTH(DATE(0,B1,1),0))

```

Where `B1` is the month number (1-based).
> 3 votes

# Answer
# z80 Machine Code, 13 bytes

```
47 1F 1F 1F A8 E6 01 05 10 01 3D C6 30

```

Takes input (starting at 1) in the A register and stores output in the same register. This was manually assembled from the ez80 manual and is not yet tested, therefore it might contain some mistakes.

**Explanation:**

```
47        ld b, a         ; Copy the value to the B register
1F 1F 1F  rra   (3 times) ; \ Set A to ((A >> 3) ^ B) & 1, which is
A8        xor a, b        ; | equal to 1 on all months with 31 days
E6 01     and a, 1        ; /
05        dec b           ; \ Decrement the B register twice and skip the next instruction if
10 01     djnz $+3        ; / the resulting value is not zero (if the month is not february)
3D        dec a           ; Decrement A (if february)
C6 30     add a, 30       ; Add 30 to A

```
> 3 votes

# Answer
# C++ (g++), ~~60~~ ~~54~~ ~~47~~ 40 bytes

1-indexed. f(2)==29.

```
int f(int n){return(n^n/8)%2-(n==2)+30;}

```

Solution from k-map, which simplified to A=w+x+z and B=zw'+z'w. A was negated and became a subtraction.

```
int f(int n){      //N is a 4-digit binary number wxyz.
return (n^n/8) %2  //Add 1 if (w XOR z)
     - (n==2)      //Subtract 1 if !(w OR x OR z), which simplifies to (w'x'z'),
                   //which is only satisfied when N is 0000 or 0010.
                   //Since n is never 0, this condition is only satisfied when n==2.
     + 30;         //Add 30, the base month length.
}

```

At first I tried adding 1 or 2 instead of 1 or 1, but my solution was 87 bytes (if I remember correctly). I tried that with 0-indexing and 1-indexing, but they ended up being the exact same length.

47 bytes: `int f(int n){return(n/8|n/4|n)%2+(n^n/8)%2+29;}`

54 bytes: `int f(int n){return((n>>3|n>>2|n)&1)+((n^n>>3)&1)+29;}`

60 bytes: `int f(int n){return(n>>3&1|n>>2&1|n&1)+((n&1)^(n>>3&1))+29;}`

Edit: Thanks to Herman L. for the improvement to 54 bytes, I'm glad someone found my approach interesting even though it's clearly not the shortest!

Edit 2: Thank you to ceilingcat for the improvement to 47 bytes. This uses division instead of bit shifting, which saves one byte in each of three places. It also replaces `&1` with `%2` in two places. Both of these functionally return the last byte of the integer, but the modulo operator has precedence over addition. This means that two pairs of parentheses can be removed, saving four bytes. In total, by mixing arithmetic and bitwise operators, ceilingcat managed to improve the answer by seven bytes!

Edit 3: Another improvement by ceilingcat brings it down six bytes by doing bitwise comparison with 13, `-!(n&13)`. Since this is only true in one case, simplified to an equality check.
> 3 votes

# Answer
# Javascript, 23 bytes

```
n=>15662007>>~-n*2&3|28

```

This is utilizing a binary map 15662007 which is

```
111011101111101110110111
11.10.11.10.11.11.10.11.10.11.01.11
 3. 2. 3. 2. 3. 3. 2. 3. 2. 3. 1. 3

```

You just add each item to 28 and see that it provides a proper mapping to each month.
> 3 votes

# Answer
# Keg, `-rr`, ~~17~~ ~~16~~ ~~14~~ 13 bytes

```
$:&1=-&7%2%-

```

Try it online!

Simply a port of Adams APL answer.
> 2 votes

# Answer
# Ruby, 18 bytes

```
->n{31-n%7%2-2[n]}

```

Try it online!

0-based, basically the same formula as Adam, adapted to ruby.
> 2 votes

# Answer
# Jelly, 10 bytes

```
%7Ḃ31__1⁼$

```

Try it online!

Pretty much just a translation of Adám and Kevin Cruijssen's APL and 05ab1e answers, respectively. There's probably some way I could cut out the `$`.
> 2 votes

# Answer
# Pyth, 10 8 bytes

0-indexed, February is 29.

```
C@.""

```

Try it online! TIO doesn't seem to like the UTF-8 conjoined character, but it works in the official interpreter. Consider TIO a glorified pastebin for this.

Previous version, 10 bytes:

```
C@."Îï»

```

Try it online!
> 2 votes

# Answer
# , 19 bytes

```
(31-0 2 0,#:330){~]

```

For fun, here's a J translation of Adam's APL answer (also 12 bytes):

```
31-1&=+2|7&|

```

Jonah's comment saves another 4 bytes, due to:

1. better use of J's hook: `({...)` instead of `(...{~])`
2. better choice of starting binary values, adjusting the arithmetic as necessary (`30+1 _1,...` rather than `31-0 2 0,...`):

```
| expr    | result               |
|---------|----------------------|
| 0,#:330 | 0 1 0 1 0 0 1 0 1 0  |
| #:693   | 1 0 1 0 1 1 0 1 0 1  |

```

Try it online!
> 2 votes

# Answer
# T-SQL 61 bytes

```
declare @ int set @=2print DAY(EOMONTH(DATEFROMPARTS(1,@,1)))

```

40 bytes if we put the input directly to the query:

```
print DAY(EOMONTH(DATEFROMPARTS(1,2,1)))

```
> 2 votes

# Answer
# Pyth, 12 bytes

```
--31%%Q7 2q1

```

Try it online!

Port of @Adám's answer

# Pyth, 22 18 bytes

```
-+30@+*4U2t*3U2Qq2

```

Try it online!

Uses 1-indexed months and 29 as February. Theres probably a more refined solution somewhere Saved 4 bytes by using U2 instead of ,Z1 and replacing the logic with -1 if input is 2

## How it works

```
-+30@+*4U2t*3U2Qq2
 +30               - 30 plus...
    @          Q   - The index Q=input
     +*4U2         - Of 4 times the list [0,1] -> [0,1,0,1,0,1,0,1]
          t*3U2    - Plus 3 times the list [0,1] minus the first element
-               q2 - Minus [2 == input], with input added implicitly

```
> 1 votes

# Answer
# Wren, 27 bytes

-3 bytes thx to Jo King for putting all into a tertiary statement.

```
Fn.new{|x|1==x?28:31-x%7%2}

```

Try it online!

# Wren, 35 bytes

-4 bytes thx 2 Jo King for noticing that `.bytes[x]` would work.

```
Fn.new{|x|" ".bytes[x]}

```

Try it online!
> 1 votes

# Answer
# C (gcc), 22 bytes

```
f(n){n=31-n%7%2-!~-n;}

```

Try it online!

Stealing from @Arnaulds / @Adám

---

~~29~~ 26 bytes

```
f(x){x=""[x];}

```

Port of @Embodiment of Ignorance answer
> 1 votes

# Answer
# C# (Visual C# Compiler), 28 bytes

```
x=>DateTime.DaysInMonth(1,x)

```

Try it online!
> 1 votes

# Answer
# Haskell, 27 bytes

```
f 1=28;f m=31-mod m 7`mod`2

```

Try it online!

0-indexed. Handles February the same way that Andrew Ray's answer does, but otherwise uses the mod-7-mod-2 approach.
> 1 votes

# Answer
# C# .NET, 98 bytes

```
class P{static void Main(string[]a){System.Console.Write((int)" "[int.Parse(a[0])]);}}

```

Try Online
Uses Ascii control characters (RS, US and FS) and gets their absolute character value.
> 1 votes

# Answer
# TI-Basic, 18 bytes

```
31-(Ans=1)-2fPart(3.5fPart(Ans/7

```

Takes input in `Ans` as a 0-indexed month. Returns 29 for February.

### 18 bytes

```
101+Ans(Ans≠11
dbd(Ans,Ans+1

```

Alternative solution using a different approach. Takes input in `Ans` as a 0-indexed month. Returns 29 for February.
> 1 votes

# Answer
# Thunno 2, 9 bytes

```
7%ɗ$ḅ+31_

```

Try it online!

Port of Adám's APL answer.

#### Explanation

```
7%ɗ$ḅ+31_  # Implicit input
      31_  # 31 - (
7%ɗ        #   (input % 7 % 2)
     +     #   +
   $ḅ      #   (input == 1)
           # )
           # Implicit output

```
> 1 votes

---
Tags: code-golf, date
---


# Question
Title: Pick a random number between 0 and n using a constant source of randomness
**Task**

Given a positive integer `n` less than `2^30` specified as input in any way you choose, your code should output a random integer between `0` and `n`, inclusive. The number you generate should be chosen *uniformly at random*. That is each value from `0` to `n` must occur with equal probability (see Rules and Caveats).

**Rules and Caveats**

Your code can assume that any random number generator built into your language or standard library that claims to be uniformly random is in fact uniform. That is you don't have to worry about the quality of the random source you are using. However,

* You do have to establish that if the random source you are using is uniform then your code correctly outputs a uniform random integer from `0` to `n`.
* **Any arguments when calling a built in or library random function must be constant. That is they must be completely independent of the input value.**
* Your code may terminate with probability 1 rather than being guaranteed to terminate.

**Notes**

* `randInt(0,n)` is not valid as it takes the input as an argument to a builtin or library function.
* `rand()%n` will **not** give a uniform random number in general. As an example given by betseg, if `intmax == 15` and `n = 10`, then you will be much more likely to get `0-5` than `6-10`.
* `floor(randomfloat()*(n+1))` will also not give a uniform random number in general due to the finite number of different possible floating point values between 0 and 1.

# Answer
> 26 votes
## x86 machines with `rdrand` instruction, 10 bytes

```
BITS 64

_try_again:

 rdrand eax
jnc _try_again

 cmp eax, edi
ja _try_again

 ret

```

machine code

```
0FC7F0 73FB 39F8 77F7 C3

```

---

The input is in the register `rdi` and the output in `rax`.
This respects the SYS V AMD64 ABI so the code effectively implement a C function

```
unsigned int foo(unsigned int max);

```

with 32-bit ints.

The instruction `rdrand` is described by Intel

> `RDRAND` returns random numbers that are supplied by a cryptographically secure, deterministic random bit generator DRBG. The DRBG is designed to meet the NIST SP 800-90A standard.

Dealing with CSRNG it is implicit that the distribution is uniform, anyway, quoting the NIST SP 800-90A:

> A random number is an instance of an unbiased random variable, that is, the output produced by a **uniformly** distributed random process.

---

The procedure generates a random number and if it is non-strictly greater than the input it is returned.
Otherwise, the process is reiterated.

Since `eax` is 32-bit, `rdrand` returns a number between 0 and 232-1, so for every *n* in \[0, 232-1\] the number of expected iterations is 232/(n+1) which is defined for all *n* in \[0, 230).

# Answer
> 21 votes
# Jelly, ~~7~~ 6 bytes

```
⁴!!X%‘

```

*Thanks to @JonathanAllan for golfing off 1 byte!*

Cannot be run on TIO because **(16!)!** is a *huge* number.

### How it works

```
⁴!!X%‘  Main link. Argument: n

⁴       Set the return value to 16.
 !!     Compute (16!)!.
   X    Pseudo-randomly choose an integer between 1 and (16!)!.
        Since (16!)! is evenly divisible by any k ≤ 2**30, it is evenly divisible
        by n+1.
    %‘  Take the result modulo n+1.

```

# Answer
> 12 votes
## Mathematica, 29 bytes

*Based on Dennis's Jelly answer.*

```
RandomInteger[2*^9!-1]~Mod~#&

```

I wouldn't recommend actually running this. `2e9!` is a pretty big number...

It turns out to be shortest to generate a huge number that is divisible by all possible inputs and the map the result to the required range with a simple modulo.

### Rejection Sampling, 34 bytes

My old approach that led to somewhat more interesting code:

```
13!//.x_/;x>#:>RandomInteger[13!]&

```

Basic rejection sampling. We initialise the output to **13!** (which is larger than the maximum input **230**) and then repeatedly replace it with a random integer between **0** and **13!** as long as the value is bigger than the input.

# Answer
> 9 votes
# Brachylog, 9 bytes

```
≥.∧13ḟṙ|↰

```

Try it online!

This uses `13!` like in Martin Ender's answer (`13ḟ` is one byte less than `2^₃₀`).

is implemented using `random_between/3`, which, when digging its source, uses `random_float/0` which is linked to `random/1` which uses the Mersenne Twister algorithm which is uniform for our purposes.

### Explanation

```
≥.           Input ≥ Output
  ∧          And
   13ḟṙ      Output = rand(0, 13!)
       |     Else
        ↰    Call recursively with the same input

```

# Answer
> 7 votes
# Python, 61 bytes

```
from random import*
lambda n,x=2.**30:int(randrange(x)*-~n/x)

```

Edit: Updated to avoid forbidden form

Edit2: Saved 2 bytes, thanks @JonathanAllan

Edit3: Paid 2 bytes for a fully functional solution - thanks again @JonathanAllan

Edit4: Removed `f=`, saving 2 bytes

Edit5: Saved 1 more byte thanks to @JonathanAllan

Edit6: Saved 2 more bytes thanks to @JonathanAllan

By now, git blame would point at me for the bad things, and JonathanAllan for the stuff that helps.

Edit7: When it rains, it pours - another 2 bytes

Edit8: And another 2 bytes

# Answer
> 7 votes
# Prolog (SWI), 38 bytes

```
X*Y:-Z is 2^31,random(0,Z,Y),Y=<X;X*Y.

```

Works by rejection sampling.

Generate a random number between *0* and *2^31-1* = *2147483647* until one less than or equal to the input has been found.

I feel as if I should be able to use a cut instead of the else, but I can't see how.

# Answer
> 7 votes
## Labyrinth, 63 bytes

```
 ?
 #00}__""*_
 ;    #"  _
{-{=  } "><)
!{ : ;"({ +
@  }}:  >`#

```

*(Thanks to @MartinEnder for help with some heavy golfing here.)*

Labyrinth is a 2D language, and its only source of randomness is in a situation like the following:

```
   x
  "<)
 " "
 " "

```

Assume the instruction pointer is on the `x` and moving downwards. It next lands on the `<`, which if the top of stack is 0 (which is always the case in the actual program above) shifts the current row left by 1:

```
   "
 "<)
 " "
 " "

```

The instruction pointer is now on the `<` moving downwards. At a junction, Labyrinth turns based on the top of stack - negative is turn left, positive is turn right and zero is move forward. If the top of stack is still zero at this point, we can't move forward or backward since there's no path, so Labyrinth will randomise between turning left or turning right with equal probability.

Essentially what the program above does is use the randomness feature to generate 100-bit numbers (100 specified by `#00` here) and continue looping until it generates a number `<= n`.

For testing, it'll probably help to use `#0"` instead for 10-bit numbers, with the `"` being a no-op path. Try it online!

Rough explanation:

```
 ?            <--- ? is input and starting point
 #0"}__""*_   <--- * here: first run is *0, after that is *2 to double
 ;    #"  _
{-{=  } "><)  <--- Randomness section, +0 or +1 depending on path.
!{ : ;"({ +        After <, the >s reset the row for the next inner loop.
@  }}:  >`#

 ^    ^
 |    |
 |    The " junction in this column checks whether the
 |    100-bit number has been generated, and if not then
 |    continue by turning right into }.
 |
 Minus sign junction here checks whether the generated number <= n.
 If so, head into the output area (! is output as num, @ is terminate).
 Otherwise, head up and do the outer loop all over again.

```

# Answer
> 6 votes
# Python 2, 61 bytes

```
from random import*
lambda n:map(randrange,range(1,2**31))[n]

```

Pseudo-randomly chooses integers between **0** and **k** for all values of **k** between **0** and **231 \- 2**, then takes the integer corresponding to **k = n**.

# Answer
> 5 votes
## Batch, 64 bytes

```
@set/ar=%random%*32768+%random%
@if %r% gtr %1 %0 %1
@echo %r%

```

`%random%` only gives 15 bits of randomness, so I have to combine two random numbers. Loops until the random value lies within the desired range, so slow for low `n`; 98 bytes for a faster version:

```
@set/a"n=%1+1,m=~(3<<30)/n*n,r=%random%*32768+%random%
@if %r% geq %m% %0 %1
@cmd/cset/a%r%%%%n%

```

# Answer
> 5 votes
# MATL, 12 bytes

*Thanks to @AdmBorkBork and to @Suever for telling me how to disable TIO cache.*

```
`30WYrqG>}2M

```

Try it online!.

This uses a rejection method: generate a random integer from `0` to `2^30-1`, and repeat while it exceeds the input `n`. This is guaranteed to terminate with probability `1`, but the average number of iterations is `2^30/n`, and so it takes very long for `n` significantly smaller than `2^30`.

```
`         % Do...while
  30W     %   Push 2^30
  Yr      %   Random integer from 1 to 2^30
  q       %   Subtract 1
  G>      %   Does it exceed the input? If so: next iteration. Else: exit
}         % Finally (execute right before exiting the loop)
  2M      %   Push the last generated integer
          % End (implicit). Display (implicit)

```

# Answer
> 5 votes
# Bash (+coreutils), 44 bytes

/dev/urandom based solution

```
od -w4 -vtu4</d*/ur*|awk '($0=$2)<='$1|sed q

```

Will read unsigned 32 bit integers from `/dev/urandom`, and filter them out with `awk` until it finds one within a given range, then `sed q` will abort the pipe.

# Answer
> 4 votes
# Jelly, 9 bytes

```
⁴!Ẋ’>Ðḟ⁸Ṫ

```

**Try it online!** \- code above wont run on TIO since a range of size 16! must be built first (not to mention the fact that they then need to be shuffled and then filtered!), so this is the same thing on a much smaller scale, repeated 30 times for an input of 3 with a bound of 10.

### How?

```
⁴!Ẋ’>Ðḟ⁸Ṫ - Main link: n
⁴         - 16
 !        - factorial: 20922789888000
  Ẋ       - shuffle random: builds a list of the integers 1 through to 16! inclusive and
          - returns a random permutation via Python's random.shuffle (pretty resource hungry)
   ’      - decrement (vectorises - a whole pass of this huge list!)
     Ðḟ   - filter out if: (yep, yet another pass of this huge list!)
    >     -     greater than
       ⁸  -     left argument, n
        Ṫ - tail: return the rightmost remaining entry.

```

*Note:* it would be over a thousand time more efficient for the same byte-count if `ȷ⁵` would do what one would naively expect and return ten to the ten, but that is not the case since the  is not evaluated as a literal ten to be used by the number literal `ȷ...` but rather two separate literals are parsed, `ȷ` with it's default exponent of three yielding one thousand, and  yielding ten.

# Answer
> 4 votes
## JavaScript (ES6), ~~55~~ 54 bytes

```
f=(n,m=1)=>m>n?(x=Math.random()*m|0)>n?f(n):x:f(n,m*2)

```

Generates integers in the range **\[0 ... 2k \- 1\]**, where **k** is the smallest integer such that **2k** is greater than **n**. Repeats until the result falls into **\[0 ... n\]**.

### Why?

This is based on the following assumptions:

* Internally, the pseudo-random integer values generated by the JS engine to feed `Math.random()` are uniform over any interval **\[0 ... 2k-1\]** (with **k \< 32**).
* Once multiplied by an exact power of 2, the IEEE 754 float values returned by `Math.random()` are still uniform over such intervals.

If anyone can confirm or refute these hypotheses, please let me know in the comments.

### Demo

Generates 1 million values in **\[0 ... 2\]** and displays the outcome statistics.

```
f=(n,m=1)=>m>n?(x=Math.random()*m|0)>n?f(n):x:f(n,m*2)

for(i = 0, stat = []; i < 1000000; i++) {
  r = f(2);
  stat[r] = (stat[r] || 0) + 1;
}
console.log(stat.join` `)
```

# Answer
> 4 votes
# PowerShell, 35 bytes

```
for(;($a=Random 1gb)-gt"$args"){}$a

```

Try it online!

Another rejection sampling method. This is an infinite `for` loop, setting the value of `$a` to be a `Random` integer between `0` and `1gb` (`= 1073741824 = 2^30`), and keeps looping so long as that integer is `-g`reater`t`han the input `$args`. Once the loop is complete, we just put `$a` on the pipeline and output is implicit.

Note: This will take a ***long*** time if the input is a small number.

# Answer
> 4 votes
# Haskell, 70 bytes

```
import System.Random
g n=head.filter(<=n).randomRs(0,2^30)<$>getStdGen

```

Not a very efficient algorithm but it works. It generates an infinite list of integers (or floats if needed, because of Haskell's type system) bounded by \[0,2^30\] and takes the first one less than or equal to n. For small n this can take a long time. The random numbers should be uniformly distributed, as specified in the documentation for randomR so all numbers in the interval \[0,2^30\] should have the same probability (1/(2^30+1)) therefore all the numbers in \[0,n\] have the same probability.

Alternate Version:

```
import System.Random
g n=head.filter(<=n).map abs.randoms<$>getStdGen

```

This version is terrible but it saves a whole byte. `randoms` uses an arbitrary range defined by the type to generate an infinite list of numbers. This may include negatives so we need to map it with `abs` to force them positive (or zero). This is extremely slow for any values of n that aren't absurdly large. **EDIT**: I realized later that this version isn't uniformly distributed because the probability of getting 0 is worse than the other numbers due to the use of `abs`. To produce some number `m` the generator could produce `m` or `-m` but in the case of 0 only 0 itself will work, therefore its probability is half of the other numbers.

# Answer
> 4 votes
# JDK 9 on jshell, ~~75~~ 59 bytes

```
n->(new Random()).ints(0,1<<30).dropWhile(x->x>n).findAny()

```

### Usage

```
((IntFunction)(n->(new Random()).ints(0,1<<30).dropWhile(x->x>n).findAny())).apply(<n>)

```
* -16 bytes: Thanks Jakob!
* Assumes that we consider jshell to be a valid runtime environment.
* jshell itself, as a runtime environment, doesn't require explicit imports for core libraries and doesn't require semicolons.
* Returns an `OptionalInt`. Rules don't specify that return type must be a primitive and I'm considering an `OptionalInt` to be a valid representation of the result.

# Answer
> 3 votes
# Java 8, ~~84~~ ~~83~~ ~~80~~ ~~71~~ 62 bytes

```
n->{int r;for(;(r=(int)(Math.random()*(1<<30)))>n;);return r;}

```

-1 byte thanks to *@OliverGrégoire*.
-3 bytes thanks to *@Jakob*.
-9 bytes converting Java 7 to Java 8.
-9 bytes by changing `java.util.Random().nextInt(1<<30)` to `(int)(Math.random()*(1<<30))`.

**Explanation:**

Try it here.

```
n->{        // Method with integer parameter and integer return-type
  int r;    //  Result-integer
  for(;(r=(int)(Math.random()*(1<<30)))>n;);
            //  Loop as long as the random integer is larger than the input
            //  (the random integer is in the range of 0 - 1,073,741,824 (2^30))
  return r; //  Return the random integer that is within specified range
}           // End method

```

NOTE: May obviously take very long for small inputs.

**Example output:**

```
407594936

```

# Answer
> 3 votes
# PHP, 30 bytes

```
    while($argn<$n=rand());echo$n;

```

Run with `echo <N> | php -Rn '<code>'`.

picks a random number between 0 and `getrandmax()` (2\**31-1 on my 64 bit machine);
repeats while that is larger than the input.

This *may* take a while ... my AMD C-50 (1 GHz) needed between 0.3 and 130 seconds for `N=15`.

A faster way for average `N` (**46 bytes**):

```
for(;++$i<$x=1+$argn;)$n+=rand()%$x;echo$n%$x;

```

or

```
for(;++$i<$x=1+$argn;$n%=$x)$n+=rand();echo$n;

```

takes `N+1` random integers, sums them up and takes the modulo with `N+1`.
The C-50 needs approx. 8 seconds for 1 million runs.

An invalid solution for **19 bytes**:

```
echo rand(0,$argn);

```

# Answer
> 3 votes
# Python 2, ~~72~~ 69 bytes

-3 bytes thanks to xnor (override the `id` built-in as a variable)

```
from random import*
n=input()
while id>n:id=randrange(2**30)
print id

```

**Try it online!**

`randrange(2**30)` produces a pseudo-uniformly distributed number (Mersenne Twister **219937-1**) from the range **\[0,230)**. Since `n` is guaranteed to be below **230** this can simply be called repeatedly until it is not greater than the input. It will take a long expected time for very low values of `n`, but usually works within the a minute even for inputs as low as 50.

# Answer
> 3 votes
# Python 3, 51 bytes

Here is a python solution with an unorthodox random source.

```
print(list(set(map(str,range(int(input())+1))))[0])

```

Try it online!

So to break this down.

```
int(input())+1

```

Gets the input number, and adds `1` to it.

```
set(range(...))

```

Creates the set `{0, 1, 2, 3, 4, ... n}` for all possible results.

```
print(list(...)[0])

```

Takes the set, converts it to list, and grabs the first item.

This works because in Python 3, the order of `set()` is established by PYTHONHASHSEED (can't be obtained but is established on script execution).

Admittedly, I am guessing that this is a uniform distribution, as the `hash()` value is randomly assigned and I am looking at randomly picking the value with a specific `hash()`, rather then just returning the `hash(input())` itself.

If anyone knows whether this is a uniform distribution, or how I could test that, please comment.

# Answer
> 2 votes
# Python 2, 89 bytes

```
l=range(2**31)
import random
random.shuffle(l)
n=input()
print filter(lambda x:x<=n,l)[0]

```

## Explanation

```
L=range(2**31)      # Create a list from 0 to 2^31 exclusive. Call it <L>.
import random       # Import the module <random>.
random.shuffle(L)   # Use 'shuffle' function from <random> module,
                    # to shuffle the list <L>.
n=input()           # Take the input -> <n>.

print
    filter(         # Create a new sequence,
    lambda x:x<=n   # where each element is less than or equal to <n>.
    ,L)             # from the list <L>.
    [0]             # Take the first element.

```

This is *very* inefficient, as it creates **2^31** integers, shuffles and filters them.

I see no point in sharing a TIO link, where it's creating such large lists, so here is a TIO link for `n` = 100.

Try it online!

# Answer
> 2 votes
# Perl 6, 29 bytes

```
{first 0..$_,^2**30 .roll(*)}

```

Inspired by Martin Ender's Mathematica solution.

Generates a lazy infinite sequence of random integers between 0 and 2^30-1, and takes the first one that is between 0 and the input.

Try it online!

# Answer
> 2 votes
# 05AB1E, 11 bytes

```
žIÝ.rDI›_Ï¤

```

Try it online!

**Explanation**

```
žIÝ          # push the inclusive range [0 ... 2^31]
   .r        # get a random permutation (pythons random.shuffle)
     D       # duplicate this list
      I      # push input
       ›_Ï   # keep only elements from the list not greater than input
          ¤  # take the last one

```

As the list `[0 ... 2147483648]` is too large for TIO, the link uses `1.000.000` instead.

**Alternate (on average) much faster 11 byte solution**

```
[žIÝ.RD¹›_#

```

Try it online

**Explanation**

```
[             # start loop
 žIÝ          # push the inclusive range [0 ... 2^31]
    .R        # pick a random integer (pythons random.chiose)
      D       # duplicate
       ¹      # push input
        ›_#   # break if random number is not greater than input
              # implicitly output top of stack (the random number)

```

# Answer
> 2 votes
# , 37 bytes

```
which.min(sample(2^30)[0:scan()+1])-1

```

Takes `n` from stdin. First it generates a random sample of all the integers in the range, then selects the first `n+1` values, finds the index of the minimum, and then subtracts one, to generate a number between `0` and `n`, inclusive. It won't run on TIO because it can't allocate an array of size `2^30` to sample from.

I'm fairly confident this is uniformly random.

Try it online!

# Answer
> 2 votes
# Python 3, 51 bytes

```
lambda n:randrange(1<<31)*n>>31;from random import*

```

Attempt this online! Includes a test suite.

Here is a proof that this is fair: https://arxiv.org/abs/1805.10941. It's also much faster than a typical modulo reduction because it's just a multiplication and a shift. (although this isn't as noticeable in Python...)

Uses an interesting approach, is O(1), and is the shortest Python answer yet!

# Answer
> 1 votes
# C#, 57 bytes

```
n=>{int x=n+1;while(x>n)x=new Random().Next();return x;};

```

Anonymous function which returns an integer between 0 and n inclusive.

The smaller the input number, the longer the time to return a random value.

Full program:

```
using System;

class RandomNumber
{
    static void Main()
    {
        Func<int, int> f =
        n=>{int x=n+1;while(x>n)x=new Random().Next();return x;};

        // example
        Console.WriteLine(f(100000));
    }
}

```

# Answer
> 1 votes
## Ruby, ~~23 15 23 32~~ 29 bytes

```
->n{1while n<q=rand(2**30);q}

```

### How it works:

* `1while [...];` executes the statement at least once: `1` before `while` acts as a nop
* Get a random number in the range 0..2^30-1 (*lower than 2^30*, as specified)
* Repeat if the number is higher than the input parameter (Could take some time when n is small)

# Answer
> 1 votes
# SmileBASIC, 38 bytes

```
INPUT N@L
R=RND(1<<30)ON N<=R GOTO@L?R

```

Generates random numbers until it gets one that is smaller than the input.

# Answer
> 1 votes
# Golang, ~~84~~ ~~78~~ 71 bytes

```
import."math/rand"
func R(n int)int{q:=n+1;for;q>=n;q=Int(){};return q}

```

Simple rejection sampling.

Note: since the math/rand seed is a constant 1, the caller must seed unless a constant result is desired.

~~Test: https://play.golang.org/p/FBB4LKXo1r~~  No longer practically testable on a 64-bit system, since it's returning 64-bit randomness and using rejection testing.

```
package main

import "fmt"
import "time"

/* solution here *//* end solution */

func main() {
    Seed(time.Now().Unix())
    fmt.Println(R(1073741823))
}

```

# Answer
> 1 votes
# Ohm, 26 bytes

```
IΩ
D31º#╬D0[>?D-+∞;,

```

Explanation:

```
IΩ                 ■Main wire
IΩ                 ■Call wire below

D31º#╬D0[>?D-+∞;,  ■"Real main" wire
D                  ■Duplicate input
 31º#╬D            ■Push random_int in [0..2^31] twice
       0[          ■Push input again
         >?    ;   ■If(random_int > input){
           D-+     ■  remove the random_int
              ∞    ■  recursion
               ;   ■}
                ,  ■Print random_int

```

# Answer
> 1 votes
# Go, ~~63~~ 61 bytes

```
import."math/rand"
var n=0;func R(){q:=n;for;q<n+1;n=Int(){}}

```

Use it like this:

```
func main() {
    n = 5000
    R()
    print(n)
}

```

Test it live at the go playground

# Answer
> 1 votes
# Braingolf, 16 bytes

```
Uv2.# ,-^r[R>v]R

```

Try it online!

Takes longer than 60 seconds on TIO, but will terminate in a finite amount of time

## Explanation

```
Uv2.# ,-^r[R>v]R  Implicit input from commandline args
U                 Pop top of stack and push range 0...n
 v                Switch to stack 2
  2.              Push two 2s
    #<space>      Push 32 (codepoint of space)
      ,           Swap top 2 items on stack
       -          Subtract top of stack from 2nd to top
        ^         Raise 2nd to top of stack to top of stack
                  This whole bit makes 2^30 on the 2nd stack
         r        Pops top of stack and pushes a random integer <= to popped item
                  This uses Python3's randrange, between 0 and the popped item
          [...]   While loop runs X times where X is the previously generated random number
           R>     Move top of stack1 to bottom of stack1
             v    Switch back to stack2 for loop counting
               R  Switch back to stack1 for implicit output
                  Implicit output of top of stack

```

So in short, this generates range `[0...n]`, then generates a random number less than or equal (`<=`) to 2^30, it then rotates the range that number of times, and outputs the top of the stack at the end.

# Answer
> 1 votes
# CBL(not COBOL), 4 5 bytes

CBL is a 2d array-based language that I am working on. It has no interpreter (yet), but I plan to make one soon. The code that I have created may not be up to date with the current progress on the language, but I will try. I will also explain the code.

CBL has gone through some major changes recently. This is the updated version.

`’0’ſr`

A breakdown of this is as follows:

```
'0'ſr

'0'   «--numeric literal 0
   ſ  «--previous value (not the 0. it is the value from the previous link
    r «--random function takes the first two as input

```

This should solve the problem with rule no.2

As long as the interpreter uses uniform randomness (which it will), this should count. If you have any questions or suggestions, leave a comment.

# Answer
> 1 votes
# MMIX, 36 bytes (9 instrs)

Obvious rejection sampling method (Java version). Assumes `TRAP 82,78,71` gets a randomly generated `uint64_t` from the OS.

(jxd)

```
00000000: 36010000 f7010000 00524e47 1e02ff00  6¢¡¡ẋ¢¡¡¡RNGœ£”¡
00000010: fe020006 26ffff02 32ffff01 45fffffb  “£¡©&””£2””¢E””»
00000020: f8030000                             ẏ¤¡¡

```

Disassembly:

```
rndr    NEGU $1,0,$0        // y = 2^64 - n
        PUT  rD,0
0H      TRAP 82,78,71       // loop: tmp = sysrand()
        DIVU $2,$255,$0
        GET  $2,rR          // z = tmp % n
        SUBU $255,$255,$2   // tmp -= z
        CMPU $255,$255,$1
        BP   $255,0B        // if(tmp > y) goto loop
        POP  3,0            // return n

```

Bonus: version from https://arxiv.org/pdf/1805.10941.pdf (except that we always calculate the remainder):

```
00000000: f7010001 e3010000 1e010100 fe010006  ẋ¢¡¢ẉ¢¡¡œ¢¢¡“¢¡©
00000010: 00524e47 1aff00ff 32ffff01 41fffffd  ¡RNGȷ”¡”2””¢A””’
00000020: fe000003 f8010000                    “¡¡¤ẏ¢¡¡

```

```
rndr    PUT  rD,1
        SET  $1,0
        DIVU $1,$1,$0
        GET  $1,rR          // r = 2^64 % n
0H      TRAP 82,78,71       // loop: tmp = sysrand()
        MULU $255,$0,$255   // rH:tmp = tmp * n
        CMPU $255,$255,$1
        BN   $255,0B        // if(tmp < r) goto loop
        GET  $0,rH
        POP  1,0            // return rH

```

# Answer
> 0 votes
# Bash + coreutils, 20 bytes

**Golfed**

seq 0 $1|shuf|sed 1q

> shuf - generate random permutations

Shuf will use the following code: to generate permutations:

```
permutation = randperm_new (randint_source, head_lines, n_lines);

```

which ends up in `randint_genmax`

```
/* Consume random data from *S to generate a random number in the range
0 .. GENMAX.  */

randint
randint_genmax (struct randint_source *s, randint genmax)
{
      ...

      randread (source, buf, i);

      /* Increase RANDMAX by appending random bytes to RANDNUM and
         UCHAR_MAX to RANDMAX until RANDMAX is no less than
         GENMAX.  This may lose up to CHAR_BIT bits of information
         if shift_right (RANDINT_MAX) < GENMAX, but it is not
         worth the programming hassle of saving these bits since
         GENMAX is rarely that large in practice.  */
      ...
}

```

which, in turn, will read a few bytes of the random data from the low-level source of randomness:

```
/* Consume random data from *S to generate a random buffer BUF of size
   SIZE.  */

void
randread (struct randread_source *s, void *buf, size_t size)
{
  if (s->source)
    readsource (s, buf, size);
  else
    readisaac (&s->buf.isaac, buf, size);
}

```

i.e. at the low-level, there is no direct dependency between the `shuf` input value and the data read from the source of randomness (aside from computing the required byte buffer capacity).

# Answer
> 0 votes
# Thunno 2 `+`, 5 bytes

```
ƓwwɼŒ

```

Try it online!

Port of Dennis's Jelly answer. Just like that answer, this won't finish for a very long time since \\$(16!)!\\$ is so big.

#### Explanation

```
ƓwwɼŒ  # Implicit input
       # Increment implicitly
Ɠ      # Push 16 to the stack
 ww    # Take the factorial twice
   ɼ   # Random item from [1..that]
    Œ  # Modulo by (input + 1)
       # Implicit output

```

---
Tags: code-golf, number, random, probability-theory
---


# Question
Title: bfcat - encode a file as a brainf*** program
# Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

1. Assume all inputs are encoded as ASCII.
2. Assume the outputted BF program will execute in an environment with an infinite tape.
3. Assume the pointer starts at cell 0 with every cell initialized to a value of zero.
4. Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.
5. The tape is doubly infinite.
6. All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

## Examples

### Space string

Given the input  , your program/function could return:

```
+++++ +++++
+++++ +++++
+++++ +++++
++ .

```

### Exclamation point

Given the input `!` , your program/function could return:

```
+++++ +++++
+++++ +++++
+++++ +++++
+++
.

```

### Two letters

Given the input `hi` , your program/function could return:

```
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.

```

This is , so the code with the smallest number of bytes wins. Good luck.

# Answer
# Jelly, 8 bytes

```
O”+ẋp“.>

```

Try it online!

### Sample run

For input `hi`, this program prints

```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++>

```

(without the linefeeds) which, in turn, prints `hi`.

### How it works

```
O”+ẋp“.>  Main link. Argument: s (string)

O         Ordinal; convert each character in s into its code point.
 ”+       Yield the character '+'.
   ẋ      Repeat '+' k times, for each k in the code points.
     “.>  Yield the string ".>".
    p     Take the Cartesian product of both results.

```
> 19 votes

# Answer
## Brainfuck, ~~55~~ 51 bytes

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

```

Try it online!

Example output for `hi` (without the linefeeds):

```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

```

### Explanation

This moves across the tape while writing the program. The surrounding `,[...,]` is a standard input loop. For each character, we use four cells:

```
[... x a b c ...]

```

where `x` is the cell we write the input to.

```
>+++[>+++++++<-]

```

This part uses cell `a` to write a `21` into cell `b` via a standard multiplication of `3` and `7`.

```
>[<++>>+++<-]

```

Now we use that `21` to write `42` into `a` and `63` into `c` by multiplying by `2` and `3` respectively. Then `<+<` moves back to cell `x` while turning the `42` into a `43` (the code point of `+`). Recap:

```
[... x 43 21 63 ...]

```

Now the main output loop:

```
[>.<-]

```

That is, while decrementing `x` we print one `+` each time.

```
>+++.

```

After we're done we reuse the `+` cell, by adding `3` to give `.`.

```
>>-.

```

Finally, we move to the `63`, decrement it to `62` (`>`) and output that as well. The next iteration will use this cell as `x`.
> 62 votes

# Answer
# Brainfuck, ~~39~~ ~~33~~ ~~32~~ 31 bytes

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

```

The algorithm that places **45** on the tape is taken from Esolang's Brainfuck constants.

This answer assumes that the output program's interpreter has wrapping, bounded cells; and that `,` zeroes the current cell (implying that the output program is run without input). Try it online!

For a (longer) solution that works unconditionally, see my other answer.

### Test run

For input `Code Golf`, the following output is generated.

```
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------.,--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------------.,

```

Try it online!

### How it works

We begin by putting the integer **45** (character code of `-`) into a cell of the tape. The following code achieves this.

```
-      Decrement cell 0, setting it to 255.
[      While the cell under the head in non-zero:
  [>]    Advance to the next zero cell.
  <--    Decrement the cell to its left.
  <--    Decrement the next cell to the left.
]

```

Before we enter the loop, the tape looks like this.

```
         v
000 000 255

```

These three cells – **-2**, **-1**, and **0** – are the only ones we'll use in this program.

In the first each iteration of the loop, the rightmost cell is, then that cell and middle cell are decremented twice, leaving the following state.

```
     v
000 254 252

```

In the next 126 iterations, the initial `-` decrements the middle cell, `[>]<` jumps to the rightmost cell, and `--<--` decrements the middle and the right cell. As a result, **3** is subtracted from the middle cell (modulo **256**) and **2** is subtracted from the rightmost cell.

Since **254 ÷ 3 (mod 256) = (254 + 256) ÷ 3 = 510 ÷ 3 = 170** and **252 ÷ 3 = 84**, the rightmost cell is zeroed out before the middle one, leaving the following state.

```
     v
000 132 000

```

Similarly to the first iteration of the loop, the next iteration now subtracts **3** from the middle cell and **2** from the leftmost cell, placing the head on the leftmost cell.

```
 v
254 129 000

```

Subsequent iterations, as in the 126 iteration before them, subtract **3** from the leftmost cell and **2** from the rightmost cell.

Since **254 ÷ 3 (mod 256) = 170** and **129 ÷ 2 (mod 256)** is undefined, this is done 170 times, leaving the following state.

```
 v
000 045 000

```

The cell under the head is zero; the loop ends.

Now we're ready to generate output.

```
,      Read a character from STDIN and put it the leftmost cell.
[        While the leftmost cell is non-zero:
  [        While the leftmost cell is non-zero:
    >.     Print the content of the middle cell ('-').
    <-     Increment the leftmost cell.
  ]      If the leftmost cell held n, the above will print 256 - n minus signs
         which, when executed, will put n in cell 0 of the output program.
  >      Increment the middle cell, setting it to 46 ('.').
  .      Print its content ('.').
  --     Decrement the middle cell twice, setting it to 44 (',').
  .      Print its content (',').
         When executed, since the output program receives no input, the above
         will zero cell 0 of the output program.
  +      Increment the second cell, setting it back to 45 ('-').
  <,     Go back to the leftmost cell and read another character from STDIN.
]      Once EOF is reached, this will put 0 in the leftmost cell, ending the loop.

```
> 37 votes

# Answer
# Brainfuck, ~~3513~~ 43 bytes

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

```

This answer makes *no assumptions* about the interpreter of the output program. Try it online!

For a shorter solution (which works only with some interpreters), see my other answer.

### Test run

For input `Code Golf`, the following output is generated.

```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.----------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++.--------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++.---------------------------------

```

Try it online!

### How it works

We begin by putting the integer **43** (character code of `+`) in the second cell of the tape. The following code achieves this.

```
++         Increment the first cell twice, setting it to 2.
[          While the first cell in non-zero:
  >+         Increment the second cell.
  <------    Decrement the first cell six times.
]

```

This essentially performs the modular division **2 ÷ 6 (mod 256)**. Since **(2 + 256) ÷ 6 = 258 ÷ 6 = 43**, the result is **43**, as intended.

Now we're ready to generate output.

```
,      Read a character from STDIN and put it the first cell.
[        While the first cell is non-zero:
  [        While the first cell is non-zero:
    >.     Print the content of the second cell ('+').
    >+     Increment the third cell.
    <<-    Decrement the first cell.
  ]      If the first cell held n, the above prints n plus signs
         and puts n in the third cell.
  >+++   Add three to the second cell, setting it to 46 ('.').
  .      Print its content ('.').
  -      Decrement, setting it to 45 ('-').
  >      Advance to the third cell.
  [      While the third cell is non-zero:
    <.     Print the content of the second cell ('-').
    >-     Decrement the third cell.
  ]      If the first cell held n, the above prints n minus signs,
         thus negating the plus signs and zeroing the cell of the output program.
  <--    Subtract 2 from the second cell, setting it back to 43.
  <,     Go back to the first cell and read another character from STDIN.
]      Once EOF is reached, ',' will put 0 in the first cell, ending the loop.

```
> 12 votes

# Answer
# Pyth - 11 bytes

```
sm+*\+Cd".>

```

Try it online here.
> 5 votes

# Answer
## 05AB1E, ~~12~~ 11 bytes

```
vyÇ`'+×„.>J

```

**Explained**

```
v             # for each char in input string
 yÇ`          # convert to its ascii value
    '+×       # push the char '+' that many times
       „.>J   # push string ".>" and join with the plus signs
              # implicitly print combined string

```

Try it online

Saved 1 byte thanks to @Adnan
> 4 votes

# Answer
# Java, 98 bytes

```
class a{String A(char[]b){String z="";for(char B:b){for(int c=B;c-->0;)z+="+";z+=".>";}return z;}}

```

`String`s are nothing more than immutable `char[]`s with a bunch of utility methods, so let's use the array!

Ungolfed:

```
class a {
    void A(char[] b) {
        for (char B : b) {
            for (int c = B; c-- > 0;)
                 System.out.print('+');
            System.out.print(".>");
        }
    }
}

```

Equivalent standalone program that is 138 bytes long:

```
interface a{static void main(String[]A){for(char b:A[0].toCharArray()){for(int B=b;B-->0;)System.out.print('+');System.out.print(".>");}}}

```

**Bonus:**

```
interface a{static void main(String[]A){for(char b:new java.util.Scanner(new java.io.File(A[0])).useDelimiter("\\Z").next().toCharArray()){for(int B=b;B>0;B--)System.out.print('+');System.out.print(".>");}}}

```

This 207-byte app actually encodes a file as a BF program, just as said in the title.
> 4 votes

# Answer
# Brainfuck, 29 bytes

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

```

Try it online!

**Explanation**:

```
,[                  loop over all characters on input
  [+                output number of minuses based on input
    >+[---------.]< print characters including -
  ]
  --[--.]           print all even characters in reverse equal to .,
,]

```

This solution expects classic 8-bit wrapping interpreter and uses the fact that other characters than `+-,.<>[]` are ignored by brainfuck interpreter. It also expects that generated program will be run with no input and thus receives null bytes as input - reading of input is used to clear the cell.

Statement generating `-` actually generates following string: `øïæÝÔËÂ¹°§zqh_VMD;2) üóêáØÏÆ½´«¢~ulcZQH?6-$` , where the only interpretable character is `-`.

Statement generating `.,` actually generates `üúøöôòðîìêèæäâàÞÜÚØÖÔÒÐÎÌÊÈÆÄÂÀ¾¼º¸¶´²°®¬ª¨¦¤¢ ~|zxvtrpnljhfdb`^\ZXVTRPNLJHFDB@><:86420.,*(&$"`  where following characters are interpreted `><.,`. The `><` moves pointer right and then left, so it actually doesn't do anything.
> 3 votes

# Answer
# Sesos, 12 bytes

Hexdump:

```
0000000: 28cbf6 02e83d 655bae 243901                       (....=e[.$9.

Size   : 12 byte(s)

```

Try it online!

## Assembler

```
add 43,fwd 1,get
jmp
  jmp,sub 1,rwd 1,put,fwd 1,jnz
  add 46,put,add 16,put
  get

```
> 2 votes

# Answer
# Vitsy, ~~19~~ 17 bytes

```
I\[&'>.+'i1-\Du]Z

I                     Get the length of the input stack.
 \[            ]      Pop n, repeat this block of code n times.
   &                  Push a new stack and move to it.
    '>.+'             Push the string '+.>' to the stack.
         i            Pop an item from the input stack and push it to the current
                      program stack.
          1-          Subtract one from the top program stack item.
            \D        Duplicate the '+' in the stack that many times.
              u       Merge the current program stack with the previous.
                Z     Output the entire current stack as a string.

```

Note that this answer is one of the few times that I've ever used `I` and `u`. :D

Try it online!
> 2 votes

# Answer
# K6, 16 bytes

```
,/{|">.",x#"+"}'

```

## Usage

```
,/{|">.",x#"+"}'"some string"

```

## Explanation

```
  {           }'  For each character in the string...
         x#"+"    Repeat "+" as many times as the character's ASCII code.
        ,         Combine that with...
    ">."          The code to print it and move on.
   |              But we put the string together backwards...so now it gets reversed.
,/                Combine all the substrings into one BIG string.

```
> 2 votes

# Answer
# , 13 bytes

```
i{'+n#*".>"}d

```

Explanation:

```
i              Read standard input into a string and push it onto the stack.
 {         }d  For each character in the string...
  '+           Push "+".
    n#         Convert the character (n) to its ASCII code.
      *        Multiply the "+" by the character code to get the number of +'s needed.
       ".>"    Push the string ".>".
               In O, the stack is printed after execution, so this prints out the result.

```
> 2 votes

# Answer
# Python 3, 43 bytes

```
lambda s:''.join('+'*ord(c)+'.>'for c in s)

```

The Python puts a number of pluses equivalent to the ASCII code of each character, followed by `.>` to print and move to the next cell. The brainfuck increments up to the correct value, prints, and moves on to the next cell.

Output for `hi` (with newlines for clarity):

```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

```

That program's output:

```
hi

```
> 2 votes

# Answer
## Perl, 25 bytes

```
s/./"+"x ord($&).".>"/eg

```

## Usage

```
echo -n hi | perl -pe 's/./"+"x ord($&).".>"/eg'

```

## Explanation

Uses a regular expression replace operation to replace every character in every line given on standard input with a number of `+` calculated from the ordinal value of that character, then outputs `.>` to print and advance to the next character.

Uses the perl `-p` flag to automatically read the input and print the result, adding 1 extra to the bytecount.
> 2 votes

# Answer
# Java, 91 bytes

```
String b(char[] f){String k="";for(char b:f){for(int u=b;u>0;u--)k+="+";k+=".>";}return k;}

```

Props to dorukayhan for beating me to it :)
> 2 votes

# Answer
## Lua, ~~67~~ ~~66~~ 61 Bytes

Simply iterate over each characters in the argument, and print a line for each one with `n` `+`s followed by `.>` where `n` is the value of this character in the ASCII Table.

**Uses gmatch as @LeakyNun advised in the comment for saving 1 Bytes over the the gsub solution**

```
for c in(...):gmatch"."do print(("+"):rep(c:byte())..".>")end

```

**Old solution using gsub**

```
(...):gsub(".",function(c)print(c.rep("+",c:byte())..".>")end)

```

**Old 67**

```
(...):gsub(".",function(c)print(string.rep("+",c:byte())..".>")end)

```

To run it, just save it as a file (`golf.lua` for instance) and run it with `lua golf.lua "hi"`. For `hi`, it should output

```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

```
> 2 votes

# Answer
# C, ~~72~~ ~~64~~ 60 bytes

```
main(c){for(;c=~getchar();)for(;printf(~c++?"+":".>")^2;);}

```

Ungolfed version:

```
main( c )
{
    for ( ; c = ~getchar( ); )
        for ( ; printf( ~c++ ? "+" : ".>" ) ^ 2; );
}

```

Compile and test with:
`gcc -o bfcat bfcatgolf.c && cat 1.txt | ./bfcat > o.txt && beef o.txt`

### Results
> 2 votes

# Answer
# CJam, 12 bytes

Converts each character to its ASCII value, and increments the current cell by that number of times before printing it. Since we have infinite tape we can just move to the right after processing each character.

```
q{i'+*'.'>}%

```

Try it online!
> 2 votes

# Answer
# brainfuck, 27 bytes

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

```

Try it online! Try result

Optimized from Jiří's solution

# JavaScript (V8), 49 bytes

```
x=>[...x].map(c=>'+'.repeat(c.charCodeAt())+.1)+0

```

Try it online!
> 2 votes

# Answer
# Ruby, ~~40~~ 38 bytes

```
gets.chop.each_byte{|o|puts"+"*o+".>"}

```
> 1 votes

# Answer
# J, 28 bytes

```
[:;[:('.>',~'+'#~])"0[:]3&u:

```

Simple enough. `3&u:` converts chars to char codes. The rest is just repeat `'+'` that number of times, then concatenating with `.>` at the end of each line, and `;` flattens the result.

## Some results

```
   bf =: [:;[:('>.',~'+'#~])"0[:]3&u:
   bf 'hi'
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.
   bf ' !'
++++++++++++++++++++++++++++++++>. +++++++++++++++++++++++++++++++++>.
   bf ' ~'
++++++++++++++++++++++++++++++++>.
                 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.

```
> 1 votes

# Answer
## Pyke, 11 bytes

```
F.o\+*".>"+

```

Try it here!
> 1 votes

# Answer
## Actually, 13 bytes

```
O`'+*".>"@`MΣ

```

Try it online!

The strategy used here is the same as in many of the other solutions - for each character, output enough `+`s to increment a zero-initialized cell to the proper ASCII ordinal, output it with `.`, and move to the next cell with `>`.

Explanation:

```
O`'+*".>"@`MΣ
O              list of ordinals (technically this is Unicode code points, but code points 0-127 are the same for Unicode and ASCII)
 `'+*".>"@`M   for each ordinal:
  '+*            push a string containing that many +s
     ".>"@       push ".>" and swap (putting it before the +s)
            Σ  concatenate all the strings (if "[", "]", and "," weren't meaningful characters in BF, this technically wouldn't be necessary)

```
> 1 votes

# Answer
# ES6, ~~119~~ 115 bytes

`f=s=>{a='';for(i in[...s]){b=s[c='charCodeAt'](i)-(s[c](i-1)|0);a+=(b>0?'+'.repeat(b):'-'.repeat(-b))+'.'}return a}`

Saved 4 bytes, thanks to @Leibrug
> 1 votes

# Answer
# Mouse-2002, 27 bytes

```
(?'l:l.^(l.^"+"l.1-l:)".>")

```

This works in theory and according to the language's documentation, but the reference implementation of Mouse's interpreter seems to have a bug where string input appends a `'`, so for `a` this outputs

```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++.>

```

Which in turn outputs `a'`. That may or may not be okay, so here's a **39 byte** long one which doesn't output `'` ever and thus is likely *more* invalid.

```
(?'l:l.39=l.0=+0=^(l.0>^"+"l.1-l:)".>")

```

Which gives right output in the reference impl. as long as there are no `'`s :)

Explained:

```
(              ~ while (true) {
  ?' l:        ~   l = getchar()
  l. ^         ~   if (! (l) ) { break }
  (            ~   while (true) {
    l. ^       ~     if (! (l) ) { break }
    "+"        ~     puts("+")
    l. 1 - l:  ~     l-- // l = l - 1
  )            ~   }
  ".>"         ~   puts(".>")
)              ~ }

```
> 1 votes

# Answer
# Factor, 58 bytes

```
[ [ [ 43 ] ""replicate-as ".>"append ] { } map-as ""join ]

```

Works like:

```
[
  [
    [ 43 ] "" replicate-as  ! ``+'' * code point, clone-like a string ""
    ".>" append             ! append ".>"
  ]
  { } map-as                ! for each char in string and clone-like an array { }
  "" join                   ! join array of str into str by ""
]

```

Since Factor comes with a Brainfuck interpreter, it's simple to test.

**bfcat.factor**

```
USING: sequences ;
IN: bfcat

: string>brainfuck ( s -- bf )
  [ [ 43 ] "" replicate-as ".>" append ]
  { } map-as "" join ;

```

**bfcat-tests.factor**

```
USING: tools.test bfcat brainfuck ;
IN: bfcat.tests

{ "a"  } [ "a"  string>brainfuck get-brainfuck ] unit-test
{ "ab" } [ "ab" string>brainfuck get-brainfuck ] unit-test
{ "+++++++++++++" } [ "+++++++++++++" string>brainfuck get-brainfuck ] unit-test
{ "Code Golf" } [ "Code Golf" string>brainfuck get-brainfuck ] unit-test

```

**output**

```
Unit Test: { { "a" } [ "a" string>brainfuck get-brainfuck ] }
Unit Test: { { "ab" } [ "ab" string>brainfuck get-brainfuck ] }
Unit Test: {
    { "+++++++++++++" }
    [ "+++++++++++++" string>brainfuck get-brainfuck ]
}
Unit Test: {
    { "Code Golf" }
    [ "Code Golf" string>brainfuck get-brainfuck ]
}

```

Yay! they all pass.
> 1 votes

# Answer
# GNU Bash, ~~100~~ 85 bytes

```
while IFS= read -rn1 c;do printf '+%.0s' $(seq 1 $(printf %d \'$c));echo '.>';done<$1

```

Thanks @cat for saving me 15 bytes!

### Postramble

1. Assumes input string is represented as-is in a file passed as first argument.
2. Usage: `bash bfcat.sh <path to file containing string>`
3. Usage (with named pipe): `bash bfcat.sh <(echo -n '<string>')`

### Ungolfed

```
while IFS= read -r -n1 c # Read file byte by byte [1]
do
    n=$(printf "%d" \'"$c") # `ord` of a char in bash [2]
    printf '+%.0s' $(seq 1 $n) # emit character $n times [3]
    echo '.>' # Emit output and shift command for bf. I love infinite memory.
done <"$1"

```

### References in Ungolfed version

1. Read file byte by byte
2. `ord` of a char in bash
3. emit character $n times
> 1 votes

# Answer
# Sidef, 38 bytes

Hey, the same length as Ruby! just that Sidef isn't Ruby :D

```
read().bytes.each{|c|say"+"*c;say".>"}

```

Read some chars, then for each byte do that thing.
> 1 votes

# Answer
# Haskell 50 Bytes

```
f[]=[]
f(x:y)=replicate(fromEnum x)'+'++".>"++f y

```
> 1 votes

# Answer
# \>\<\>, ~~39~~ 41 bytes

```
0i:@:0(?;\~~o!
v?:+"Ā"-$/'.'~
/.13-1o'+'

```

## Explanation

Add 256 to each char code, then print that many `+`, then `.`
> 1 votes

# Answer
# Ruby, 26 bytes

```
gsub(/./){?+*$&.ord+'.>'}

```

\+ 1 byte for the `p` command line option. To e.g get the brainfuck code for `ABC xyz` you can run

```
$ ruby -p -e 'gsub(/./){?+*$&.ord+".>"}' <<< "ABC xyz"

```

and get

```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

```
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
Ç'+×„.>«J

```

Try it online!

```
Ç'+×„.>«J  # full program
        J  # join...
   ×       # runs of...
Ç          # codepoints of...
           # (implicit) each character in...
           # implicit input...
 '+        # literals...
       «   # with...
    „.>    # literal...
       «   # appended to...
           # (implicit) each element
           # implicit output

```
> 0 votes

# Answer
# Nim, 69, 67 bytes

```
import strutils;for i in readLine stdin:echo repeat("+",i.int)&".>"
```

Attempt This Online!

*Wow, I beat ES6, that is a shock. Nim usually does a lot worse!*
> 0 votes

# Answer
# BinaryFuck, 12 bytes

`0x071cbb2593eeca31d084c0ef`

Technically, 11.5 bytes . But who counts fractions of bytes, anyways?

Yeah, I just took the shortest solution in Brainfuck and substituted it. (Hey, I shortened it by 19 bytes!) Here's a hex to binary converter to convert the hexadecimal to binary.
> 0 votes

# Answer
# Rattle, 25 bytes

```
|R2I=@P[$n[b"+"]`b".>">]`

```

Try it Online!

# Explanation

```
|                  parse input
 R2                reformat as string
   I               split into chars and save into consecutive memory slots, move pointer to end
    =@             set top of stack to pointer value
      P            set pointer to 0
       [...]`      loop n times where n is the top of the stack (the old pointer)

$                  swap top of stack with value in storage at the pointer
 n                 get ASCII value of top of stack
  [....]`          loop n times where n is the top of the stack
   b"+"            add "+" to the print buffer
         b".>"     add ".>" to the print buffer
              >    move pointer to next slot

```
> 0 votes

# Answer
# Thunno 2 `JB`, 7 bytes

```
'+×`.>+

```

Try it online! or verify the resulting BF program

#### Explanation

```
'+×`.>+  '# Implicit input
          # Cast to ordinals
'+×      '# Multiply by "+"
   `.>+   # Add ".>" to each
          # Join into a string
          # Implicit output

```
> 0 votes

---
Tags: code-golf, brainfuck
---