title: Solve a Linear Equation

text:
# Question
Title: Solve a Linear Equation
This challenge but with a better spec.

## Spec

Your program will take a linear equation containing a single variable `x` and output the value of `x`.

### Input / Parsing

* The input will only contain numbers, operators, parenthesis (`()`), `x`, and an `=` sign (this means no whitespace).
* Parenthesis will always be balanced.
* There will always be at least 1 `x`. An `x` may be preceded by a number.
* All equations will exactly have one result.

---

A **number** can be defined by following these steps. A number can be defined by the regex: `-?(\d+(\.\d+)?|\.\d+)`.

---

If you don't speak regex: A digit is defined as `0-9`

1. It may have a `-` at the beginning of it signifying negative
2. Then there *may* be some digits. If they aren't any digits there will be a decimal point
3. If a decimal point exists, at least one digit will follow it

The biggest a number / value will be is defined by your language's capabilities.

---

An **operator** is any of: `+-*/`, they will always appear between numbers, and or parenthesis

this means `(5)(5)` is not a valid input for the sake of simplicity.

---

Parenthesis will always contain a valid expression (a valid combination of numbers and/or operators) inside them. "Balanced" parenthesis is defined as every `(` will have an associated closing `)`

### Evaluation

* Order of operations should be followed and the precedences are (highest to lowest):
    + Parenthesis (most deeply nested first)
    + Multiplication & Division
    + Addition & Subtraction
* If two operators with the same precedence are occurred you should prefer going left -\> right

### Output

You should output the result in some way. If you don't output just number result, clarify in your answer how the output is outputted. Your output format should be consistent. Output may be a decimal, but it will always be rational, the precision is limited to your language's precision. **Only** if your language does not support floating point arithmetic, you do not need to support it.

## Rules

* Built-ins trivializing this task are allowed **but**, you must clearly add `[uses built-in]` clearly to the header of the answer. This exempts your answer from winning
* A "Built-ins trivializing this task" is any of:
    + Something which takes in an equation and outputs the value for a/the variable
    + Something which will completely simplify an equation
    + Using `eval` or a related function to do a significant amount of the parsing. Use of `eval` and related functions are disallowed if they are used to (with minimal modification to the input) solve linear equations.
    + If you're in doubt, just ask in a comment.
* Built-ins which parse the equation are allowed

## Examples

```
3+4=x
7

4+x=5
1

3+3*3=x
12

3x-4=7+2x
11

3--1=x
4

3*(2+4x)=7x-4
-2

1.2+2.3x=5.8
2

10=4x
2.5

```

**INVALID** Inputs:

```
(5)(4)=x  no operator between (5) and (4)
5(x+3)=2  no operator 5 and (...)
x=y       the only variable is x
4=3       there is no x
x+3=x-7   no solution
x=x       infinite solutions
+5=x      + is not an unary operator. -5=x would be valid though
1/(x-3)=5 Nonlinear
3/x       Nonlinear

```

# Answer
> 4 votes
# JavaScript ES6, 246 bytes

Still some golfing to be done, but at least it's a solution!

```
C=a=>new Function("x","return "+a.replace(/(\d)x/g,"$1*x"));n=>{n=n.split("=");t=Math.abs,r=C(n[0]),c=C(n[1]),a=0,i=r(a)-c(a);a++;v=r(a)-c(a);o=t(i)<t(v)?-1:1;for(u=1/0;r(a)!==c(a);)a+=o,e=t(r(a)-c(a)),e>u&&(u=1/0,o/=10),u=Math.min(e,u);return a}

```

Name the function `n=>{n=n.split("=")...` to use it.

Hyper-ungolfed:

```
function solveLinear(equation){
    equation = equation.split("=");
    var abs = Math.abs;
    var LHS = convertToFunction(equation[0]), RHS = convertToFunction(equation[1]);
    var pivot = 0;
    var dir;
    var dir1 = LHS(pivot) - RHS(pivot);
    pivot++;
    var dir2 = LHS(pivot) - RHS(pivot);
    if(abs(dir1)<abs(dir2)) dir = -1;
    else dir = 1;
    var dif, minDif = Infinity;
    while(LHS(pivot) !== RHS(pivot)){
        pivot += dir;
        dif = abs(LHS(pivot) - RHS(pivot));
        if(dif > minDif){
            minDif = Infinity;
            dir /= 10;
        }
        minDif = Math.min(dif, minDif);
        console.log(pivot,dir,dif,minDif);
    }
    return {
        x: pivot,
        LHS: LHS,
        RHS: RHS
    };
}

```

This uses a pivot approach. (I'm not sure if this is what the algorithm is called, just a name I invented.) It first gathers which direction to search for from zero (i.e., which way the slopes of the two sides of the equations will intersect) and looks for the value. Once it finds a point of minimal difference, it goes to that point and decreases the search increment. This eventually yields as precise of a solution we need.

# Answer
> 3 votes
# JavaScript (Node.js), ~~106~~ 93 bytes

```
a=>eval(`f=x=>${a[R='replace'](/(\d)x/g,"$1*x")[R]("=","-(")[R](/-/g,"+-")})`)(0)/(f(0)-f(1))

```

Try it online!

-13 bytes thanks to @tsh

Ungolfed:

```
var h=a=>{
  a=a.replace(/(\d)x/g,"$1*x").replace("=","-(").replace("--","- -"); //get into an eval-able form
  var f=x=>eval(a+")");
  var df=(f(1)-f(0))/(1-0) //derivative or slope of the function
  var x=0;
  return x-(f(x)/df); //newton's method
}

```

Explaination:

This solution works by Newton's method for finding roots. The code subtracts the right hand side of the equation from the left hand side, such that when `f(x)=0`, `x` will equal the value we are solving for. Therefore, when we find the root of this new function, it will be our desired `x` value. Then it finds the derivative `f'(x)` by finding the slope between two points on the function. Then, the values are simply inserted into Newton's method which states for an approximation of the root `x`, `x=x-(f(x)/f'(x))` (in the code, we use 0 as an initial `x` value). Since this finds the roots, it finds our `x` value. And since the equation is guaranteed to be linear, the approximation will be exact.

# Answer
> 1 votes
# Mathcad, \[uses built-in\]

Mathcad has two built-in methods of solving such equations:

* Symbolic solver (uses the keyword solve)
* Solve Block (which works in both numeric and symbolic modes). A Solve Block starts with the keyword Given, followed a set of expressions defining the conditions of interest, and closed by one of the solving keywords, such as Find (which finds an exact solution) or MinErr (which minimizes the error between the target and any solution).

The symbolic solver is quite happy with y=x and returns the solution x = y.

For those unfamiliar with Mathcad, the image below is taken directly from the WYSIWYGish Mathcad 15 workbook. Changing any of the expressions where they are written will cause Mathcad to reevaluate its answer and update the display accordingly.

# Answer
> 1 votes
# Axiom, 214 bytes \[uses built-in\]

```
q(t:EQ POLY FLOAT):Any==(a:=[variables(lhs t),variables(rhs t)];a.1~=[x]and a.1~=[]=>%i;a.2~=[x]and a.2~=[]=>%i;a.1=[]and a.2=[]=>%i;a.1=[x]and degree(lhs t,x)>1=>%i;a.2=[x]and degree(rhs t,x)>1=>%i;rhs solve(t).1)

```

For some error would return %i, for other type of errors the function is stopped from the system, something else as 1--2 seems out of language... test:

```
(72) -> q(x+3=9)
   (72)  6.0
                                  Type: Complex Fraction Polynomial Float
(73) -> q(3+4=x)
   (73)  7.0
                                  Type: Complex Fraction Polynomial Float
(74) -> q(4+x=5)
   (74)  1.0
                                  Type: Complex Fraction Polynomial Float
(75) -> q(3+3*3=x)
   (75)  12.0
                                  Type: Complex Fraction Polynomial Float
(76) -> q(3*x-4=7+2*x)
   (76)  11.0
                                  Type: Complex Fraction Polynomial Float
(77) -> q(3--1=x)
  Line   1: q(3--1=x)
           .AB
  Error  A: Missing mate.
  Error  B: syntax error at top level
  Error  B: Possibly missing a )
   3 error(s) parsing
(77) -> q(3*(2+4*x)=7*x-4)
   (77)  - 2.0
                                  Type: Complex Fraction Polynomial Float
(78) -> q(1.2+2.3*x=5.8)
   (78)  2.0
                                  Type: Complex Fraction Polynomial Float
(79) -> q(10=4*x)
   (79)  2.5
                                  Type: Complex Fraction Polynomial Float
(80) -> q((5)(4)=x)
   Cannot find a definition or applicable library operation named 5
      with argument type(s)
                           PositiveInteger

  Perhaps you should use "@" to indicate the required return type,
  or "$" to specify which version of the function you need.
(80) -> q(5(x+3)=2 )
   (80)  %i
                                                    Type: Complex Integer
(81) -> q(x=y)
   (81)  %i
                                                    Type: Complex Integer
(82) -> q(4=3)
   (82)  %i
                                                    Type: Complex Integer
(83) -> q(x+3=x-7)
   >> Error detected within library code:
   inconsistent equation
protected-symbol-warn called with (NIL)
(83) -> q(x=x)
   >> Error detected within library code:
   equation is always satisfied
protected-symbol-warn called with (NIL)

```

# Answer
> 1 votes
# Vyxal, 6 bytes \[uses built-in\]

```
\=/÷∆q

```

Try it Online!

As a bonus, it can even handle some of the invalid input cases.

## Explained

```
\=/÷∆q
\=/÷   # Split the input on "=" and dump to the stack
    ∆q # Pop two items a and b and solve x in a = b

```

# Answer
> 0 votes
# Python, 134 bytes \[uses built-in\]

```
import re
def f(e):
    l,r=re.sub(r"(?<=\d)x","*x",e).split("=")
    a,b=[eval(f"{l}-({r})",{"x":x})for x in[0,1]]
    return a/(a-b)

```

Attempt This Online!

This preprocesses the string, turns it into an expression where \\$x\\$ is the root, then uses `eval` to find two points plus basic algebra to find the root.

---
Tags: code-golf, math, parsing, linear-algebra
---


title: Length-encode a string

text:
# Question
Title: Length-encode a string
Suppose we use the following rules to pull a single string from another string, one containing only ASCII printable characters and called an `*`-string. If the string runs out before the process halts, that is an error, and the result of the process is undefined in that case:

1. Start with `d=1, s=""`
2. Whenever you encounter a `*`, multiply `d` by 2. Whenever you encounter another character, concatenate it to the end of `s` and subtract 1 from `d`. If now `d=0`, halt and return `s`

**Defined Examples**:

```
d->d
769->7
abcd56->a
*abcd56->ab
**abcd56->abcd
*7*690->769
***abcdefghij->abcdefgh

```

**Undefined Examples**: (note that the empty string would be one of these as well)

```
*7
**769
*7*
*a*b
*

```

Your job is to take a string and return the shortest `*`-string that produces that string.

**Program Examples**:

```
7->7
a->a
ab->*ab
abcd->**abcd
769->*7*69

```

Your program should handle any string containing at least one character and only non-`*` ASCII printable characters. You can never return strings for which the process is undefined, since by definition they cannot produce ANY strings.

Standard loopholes and I/O rules apply.

# Answer
> 3 votes
# Pyth (36 27 bytes)

Thanks to Jakube for a 9 byte improvement! Currently not as good as muddyfish's answer, but whatever

```
KlzJ1VzWgKyJp\*=yJ)pN=tK=tJ

```

Test Suite

Translation to python:

```
                            | z=input() #occurs by default
Klz                         | K=len(z)
   J1                       | J=1
     Vz                     | for N in z:
       WgKyJ                |   while K >= J*2:
            p\*             |     print("*", end="")
               =yJ          |     J=J*2
                  )         |     #end inside while
                   pN       |   print(N, end="")
                     =tK    |   K=K-1
                        =tJ |   J=J-1

```

# Answer
> 5 votes
# JavaScript (ES6), 61 bytes

```
f=(s,d=2)=>s?d>s.length?s[0]+f(s.slice(1),d-2):'*'+f(s,d*2):s

```

Recursive function that does the following:

* If `d` is less than or equal to remaining string length divided by 2:

Append `*` to output and multiply `d` by 2
* Else:

Shift the string and append to output, subtract 1 from `d`.

See it in action:

```
f=(s,d=2)=>s?d>s.length?s[0]+f(s.slice(1),d-2):'*'+f(s,d*2):s

input.oninput = e => output.innerHTML = f(input.value);
```

```
<input id="input" type="text"/>
<p id="output"></p>
```

# Answer
> 4 votes
## Pyth, ~~29~~ ~~27~~ (Noticed broken) ~~27~~ ~~26~~ 25 bytes

```
+*\*sKllzXJ-^2.EKlzz?J\*k

```

Explanation to come.

Test Suite

# Answer
> 2 votes
## C, 125 bytes

```
main(int q,char**v){++v;int i=1,n=strlen(*v);while(n>(i*=2))putchar(42);for(i-=n;**v;--i,++*v)!i&&putchar(42),putchar(**v);}

```

This takes advantage of the very regular pattern of star positions to output the correct encoding. Initially I tried a bruteforce recursive solution, but in retrospect it should have been obvious that there was a simpler mathematical solution.

Essentially you will always have `2^floor(log_2(length))` stars at the start of your output, and a final star after `2^ceil(log_2(length)) - length` characters (if that works out to at least 1 character).

The (slightly) ungolfed version is as follows

```
main(int q,char**v){
   ++v;                         // refer to the first command line argument
   int i=1, n=strlen(*v);       // set up iteration variables

   while(n > (i*=2))            // print the first floor(log2(n)) '*'s
      putchar(42);

   for(i-=n;  **v;  --i, ++*v)  // print the string, and the final '*'
      !i&&putchar(42),putchar(**v);
}

```

# Answer
> 1 votes
## JavaScript (ES6), ~~88~~ 77 bytes

```
f=(s,l=s.length,p=2)=>l<2?s:p<l?"*"+f(s,l,p*2):s.slice(0,p-=l)+"*"+s.slice(p)

```

At first I thought that `abcde` had to be `*a**bcde` but it turns out that `**abc*de` works just as well. This means that the output is readily constructed using floor(log₂(s.length)) leading stars, plus an additional star for strings whose length is not a power of two.

Edit: Saved 8 bytes by calculating the number of leading stars recursively. Saved a further 3 bytes by special-casing strings of length 1, so that I can treat strings whose length is a power of 2 as having an extra leading star.

# Answer
> 1 votes
**Haskell, 68 bytes**

```
f d[]=""
f d xs|length xs>=d*2='*':f(d*2)xs
f d(x:xs)=x:f(d-1)xs

```

Same as the other answers, really. If EOF, output an empty string. If length remaining is more than twice `d`, output a star and double `d`. Otherwise, output the next character and subtract one from `d`.

Ungolfed:

```
f d (  [])                    = ""
f d (  xs) | length xs >= d*2 = '*' : f (d*2) xs
f d (x:xs)                    =  x  : f (d-1) xs

```

# Answer
> 1 votes
# Ruby, 58 bytes

```
F=->a,s="",d=1{x,*y=a
d<1?s:x==?*?F[y,s,d*2]:F[y,s+x,d-1]}

```

Attempt This Online!

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


# Question
Title: Output Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo
# Challenge

The goal is to output `Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo`.

Context. (Maybe another interesting challenge could be printing all of the other examples? This would probably use similar logic but involve either a function or just a for loop.)

# Rule(s)

1. You cannot output anything other than the string with correct casing and spacing. Trailing new lines are allowed, trailing spaces are not.

This is , so fewest bytes win!

# Answer
> 98 votes
# Buffalo, ~~2711~~ ~~2571~~ ~~2517~~ ~~2447~~ ~~2279~~ 2183 bytes

*It takes 304 buffalo to produce 8 buffalo?!* Yep, you herd that right.

```
BuffaloBuffaloBuffaloBuffaloBuffaloBuffalo(buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo(buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo(buffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffalobuffalobuffalo)buffaloBuffalobuffalobuffalobuffaloBuffaloBuffaloBuffalobuffaloBuffalobuffalobuffalobuffaloBuffalobuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffalobuffalobuffalo)Buffalobuffalobuffalobuffalo)buffaloBuffalobuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo.buffaloBuffalo.buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo..buffaloBuffalobuffalobuffalobuffalobuffalo.buffaloBuffalo.buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo.buffaloBuffalobuffalobuffalobuffalobuffalobuffalobuffalobuffalobuffalo.BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffaloBuffalo.BuffalobuffaloBuffalobuffalo.buffaloBuffalo..buffaloBuffalobuffalobuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffalo.buffaloBuffalo.buffaloBuffalo..buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo(BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffaloBuffalo.BuffalobuffaloBuffalobuffalo.buffaloBuffalo..buffaloBuffalobuffalobuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalobuffalobuffalo)BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffalo.buffaloBuffalo.buffaloBuffalo..buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffaloBuffalo.BuffalobuffaloBuffalobuffalo.buffaloBuffalo..buffaloBuffalobuffalobuffalo.buffaloBuffalo.buffaloBuffalo.

```

Try it online! Link is to a Buffalo interpreter written in PHP (the header is copied from GitHub). You can also copy-and-paste the code above into the official online interpreter.

Buffalo is a cell-based language like brainfuck or COW. It has seven instructions:

* `Buffalobuffalo` and `buffaloBuffalo` move the pointer to the left and right, respectively,
* `BuffaloBuffalo` and `buffalobuffalo` increment and decrement the current cell value, respectively,
* `(` and `)` begin and end loops, and
* `.` outputs the ASCII character corresponding to the current cell value.

Aiming to get the ASCII codes of `Bufalo`  into successive cells, we first do a coarse initialisation using three nested loops. A correction is then applied to each cell (outside the loops) as necessary. The selected iteration counts (3 for the outer and middle loops and 4 for the inner loop) are apparently optimal. The ASCII code for the lowercase `b` does not get its own cell; rather, we generate it on the fly in the `a` cell.

Once the ASCII codes have been generated, the output is printed character-by-character as `Buffalo buffalo Buffalo (buffalo )Buffalo buffalo`, where the segment in parentheses represents a loop that runs 3 times.

# Answer
> 61 votes
# Bash, 28 bytes

```
echo {B,b,B,b,b,b,B,b}uffalo

```

Try it online!

Brace expansion (Bash Reference Manual)

Same length, slightly more interesting:

```
echo {B,b,B,b{,,},B,b}uffalo

```

# Answer
> 29 votes
# Python 2, 36 bytes

```
for c in'BbBbbbBb':print c+'uffalo',

```

Try it online!

Relies on the Python 2 print magic that automagically adds a space before a printed object if it thinks it's not at the beginning of a line.

## Python 2 (anagol), 36 bytes

```
print'uffalo '.join('BbBbbb'*2)[:63]

```

Try it online!

A trivial modification of the anagol solution is the same length.

## Python 3, 38 bytes

```
print(*[x+'uffalo'for x in'BbBbbbBb'])

```

Try it online!

## Python 3, 41 bytes

```
print(*map("{}uffalo".format,'BbBbbbBb'))

```

Try it online!

# Answer
> 20 votes
# Husk, 14 bytes

```
wM?Im_ḋ162¨Ḃ=F

```

Try it online!

This was a simple challenge but fun :)

### Explanation

```
wM?Im_ḋ162¨Ḃ=F
          ¨Ḃ=F    Taking the compressed string "Buffalo" (uppercase B)
 M                For each digit in
      ḋ162         the binary digits of 162 ([1,0,1,0,0,0,1,0]):
  ?               if the digit is 1
   I               return the string itself
                  if the digit is 0
    m_             convert each character to lowercase
w                 Join all strings with spaces

```

# Answer
> 13 votes
# Perl 5, 32 bytes

```
@_=<{,b,B,b}uffalo>;say"B@_ b@_"

```

Try it online!

Beats the best anagol answer by one byte:

```
@_=($_=Buffalo,lc)x2,print"@_ \l@_." # Mithran
@_=<{,b,B,b}uffalo>;print"B@_ b@_."  # Sisyphus

```

# Answer
> 12 votes
# 05AB1E, 13 bytes

*Inspired by @Leo'sanswer, so make sure to upvote him!* and me too please ;)

```
Ƶzbε'±ˆsi™]ðý

```

Try it online!

```
Ƶzbε'±ˆsi™]ðý  # full program
            ý  # join...
    '±ˆ        # "buffalo"...
   ε           # for map over all digits of...
Ƶz             # 162...
  b            # in binary...
         ™     # in title case...
        i      # if...
       s       # current digit in...
   ε           # map over all digits of...
Ƶz             # 162...
  b            # in binary...
        i      # is 1...
           ð   # by spaces
          ]    # exit if statement and map
               # implicit output

```

# Boring, trivial alternative, 64 bytes

```
"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

```

Try it online!

```
"...  # full program
"...  # literal
      # implicit output

```

**EDIT**: I have stood unbeaten for three months... Brownie points to anyone who outgolfs me.\* Oh, and possibly some rep if I like your answer. ;)

\*Just to clarify, outgolfs in any language will be accepted. It doesn't have to be 05AB1E.

# Answer
> 10 votes
# V (vim), 20 bytes

```
8ibuffalo <esc>xbb~5b~0~

```

Try it online!

* `8ibuffalo <esc>`, write "buffalo " 8 times. cursor at end of line.
* `x` remove current character (the space at end of line).
* `bb` move to the 2nd words beginning from cursor (move left).
* `~` toggle letter case, and also move cursor 1 char right.
* `5b~` move to the 5th words beginning from cursor (move left). And toggle case.
* `0~` move to line beginning. And toggle case.

# Answer
> 9 votes
# Retina 0.8.2, 25 bytes

```

BbBbbbBb
.
$&uffalo
 $

```

Try it online! Explanation:

```

BbBbbbBb

```

Insert the `b`s in the correct capitalisation.

```
.
$&uffalo

```

Expand the buffalo (buffaloes?).

```
 $

```

Remove the trailing space.

# Answer
> 9 votes
# , ~~40~~ 39 bytes

*Edit: -1 byte thanks to Dingus*

```
cat(c('buffalo','Buffalo')[1+!21%%1:8])

```

Try it online!

Chooses whether to output 'buffalo' or 'Buffalo' by indexing with the vector `2 1 2 1 1 1 2 1`, which is constructed as the zero values of `21` modulo each of `1...8`, plus one.

Sadly, trying to recycle the 'uffalo' is significantly longer (54 bytes) due to 's somewhat cumbersome string-manipulation functions (*Edit after reading the 'Anarchy Golf' link: still longer, but can be done in 46 bytes*)

# Answer
> 8 votes
# TI-BASIC, 47 bytes

```
"uffalo
Ans+" b"+Ans
Ans+" B"+Ans
"B"+Ans+" b"+Ans

```

Builds the sentence up in chunks to eliminate the need for string variables which are two byte tokens; Ans is always a single byte even when it holds a string. The strategy also minimizes use of the lowercase letters as they are two byte tokens. The final line is automatically output and you can scroll left-right for the full sentence.

# Answer
> 8 votes
## LabVIEW, 20 bytes

Graphical languages are harder to count, so here's my attempt:

* 1 byte loop termination
* 1 byte for the loop
* 1 byte for the integer we encode the capitalization in
* 6 bytes for the 'uffalo' string
* 1 byte for the mask we apply to the integer encoding
* 1 byte for the case structure
* 1 byte for the AND
* 1 byte for the left shift function
* 2 bytes for the capital and noncapital letters in the case structure
* 1 byte for the concatenate string function
* 2 bytes for format string spec
* 1 byte for the delimiter (space)
* 1 byte for the array to spreadsheet string function

And yes, how'd you know about my EE degree?

# Answer
> 7 votes
## Batch, ~~50~~ 49 bytes

```
@set s=B_b_B_b_b_b_B_buffalo
@echo %s:_=uffalo %

```

Batch's string handling is so poor it's golfier to explicitly include the last "buffalo" rather than trying to trim the trailing space at the end.

# Answer
> 7 votes
# JavaScript (ES6), 46 bytes

Builds the string recursively and in reverse order.

```
f=n=>(n>6?'':f(-~n)+' ')+"bB"[n&n!=3]+'uffalo'

```

Try it online!

### Alternate version

```
f=n=>(n>6?'':f(-~n)+' ')+"bB"[25/n&1]+'uffalo'

```

Try it online!

### Commented

```
f = n =>             // f is a recursive function taking a counter n,
                     // which is initially undefined (zero'ish)
  ( n > 6 ?          // if n is greater than 6 (last iteration):
      ''             //   append nothing
    :                // else:
      f(-~n)         //   append the result of a recursive call with n + 1
      + ' '          //   followed by a space
  )                  //
  + "bB"[n & n != 3] // append "B" if n is odd and not equal to 3,
                     // or "b" otherwise
  + 'uffalo'         // append "uffalo"

```

# Answer
> 7 votes
## x86-16 machine code, ~~43~~ ~~42~~ 41 bytes

* -1 byte thanks to @CodyGray.
* -1 byte thanks to @640KB.

```
0BED:0100  BA 19 01 BE 22 01 B4 09-B1 07 CD 21 AC A2 19 01   ...."......!....
0BED:0110  E2 F8 C6 44 F7 24 CD 21-C3 42 75 66 66 61 6C 6F   ...D.$.!.Buffalo
0BED:0120  20 24 62 42 62 62 62 42-62                         $bBbbbBb

```

Instruction listing (nasm syntax):

```
    org 100h      ;           | Execution of .COM files start at CS:0100

    mov dx, msg   ; BA 1B 01  | DX = offset of "Buffalo $" (for INT 21H)
    mov si, buf   ; BE 24 01  | SI = Address of "bBbbbBb"  (for LODSB)
    mov ah, 09h   ; B4 09     | AH = Opcode code INT 21H   (Output string up to '$')
    mov cl, 7     ; B1 07     | CX = 7 (we want to iterate 7 times before the last 'Buffalo')
loop:
    int 21h       ; CD 21     | Output string at msg
    lodsb         ; AC        | AX = [SI], ++SI
    mov byte [msg], al
                  ; A2 1B 01  | Set the first character of msg as the current character at buf
    loop loop     ; E2 F8     | Jump to tag 'loop' while CX >= 0
    mov byte [si - 9], "$"
                  ; C6 44 F7 24 | (After loop) Replace the last space with a '$'
    int 21h       ; CD 21     | Print the last 'buffalo'
    ret           ; C3        | Exit to DOS

msg:    db "Buffalo $"
buf:    db "bBbbbBb"

```

## Example run

```
C:\test>debug code.com
-g
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo
Program terminated normally

```

# Answer
> 6 votes
# C (gcc), ~~62~~ 61 bytes

Realised the 61 byte version was not compliant (outputted a space at the end). Reverted and updated it to be.

-1 byte thanks to Arnauld

```
f(n){for(n=8;n--;)printf("%cuffalo%s","bBbbbBbB"[n]," "+!n);}

```

Try it online!

# Answer
> 6 votes
# JavaScript (V8), 43 bytes

```
write(a=`B${b='uffalo'} b`+b,a,c='b'+b,c,a)

```

Try it online!

# Answer
> 6 votes
# Haskell, 30 bytes

```
init$"BbBbbbBb">>=(:"uffalo ")

```

Try it online!

(Cf. Are objects in Haskell valid if there is no input?)

# Answer
> 5 votes
# Charcoal, 16 bytes

```
Ｆ⍘¹⁶²bB«ιuffalo→

```

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

```
Ｆ⍘¹⁶²bB«

```

Convert 162 to base 2, but use `b` for 0 and `B` for 1, and loop over the "digits".

```
ι

```

Print the `b` or `B`.

```
uffalo

```

Print the rest of the buffalo.

Prepare to leave a space before the next `b`, if any.

# Answer
> 5 votes
# Perl 5, 38 bytes

```
$,=$";say$_=Buffalo,lc,$_,(lc)x3,$_,lc

```

Try it online!

# Answer
> 5 votes
# JavaScript (Node.js), 45 bytes

```
_=>[...'BbBbbbBb'].map(x=>x+'uffalo').join` `

```

Try it online!

# Answer
> 4 votes
# C (gcc), 63 bytes

-2 bytes thanks to @Arnauld

```
n=7;f(){printf("%cuffalo%c","bBbbbBbB"[n],9+!n),n--?f():(n=7);}

```

Try it online!

Could have been shorter if it wasn't for the reusability rule killing recursive functions.

# Answer
> 4 votes
# PowerShell, ~~39~~ 36 bytes

```
''+('BbBbbbBb'|% t*y|%{$_+'uffalo'})

```

Try it online!

-3 bytes thanks to @mazzy!

# Answer
> 4 votes
# Julia, 42 bytes

```
join(collect("BbBbbbBb").*"uffalo ")[1:63]

```

Very similar to what was done with Python above.

# Answer
> 4 votes
# Whispers v2, ~~86~~ 79 bytes

```
> "Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo"
>> Output 1

```

Try it online!

Well, this is embarrassing...

The first line alone could even be enough, as a function returning the string

For something a bit more interesting, here's my previous solution:

# Whispers v2, 86 bytes

```
> "Buffalo "
> "buffalo "
>> 1+2
>> 3+3
>> 2+2
>> 5+3
>> 4+6
> 63
>> 7ᶠ8
>> Output 9

```

Try it online!

First approach to the language of the month for me :) It looks like building the string by manually concatenating pieces is the best approach in Whispers.

### Explanation

Whispers starts the execution from the last line of the program, and then follows references from there. Any number in a line starting with `>>`  refers to the result of the corresponding line, while numbers in lines starting with `>`  have their normal value. We can only have a single operation per line (hence why so many lines).

Most lines here simply concatenate two strings, while line 9 takes the first `63` characters from the string in line 7, which is all except for the trailing space. It should be pretty easy to read, but here's the value computed by each line:

```
> "Buffalo "        1:"Buffalo "
> "buffalo "        2:"buffalo "
>> 1+2              3:"Buffalo buffalo "
>> 3+3              4:"Buffalo buffalo Buffalo buffalo "
>> 2+2              5:"buffalo buffalo "
>> 5+3              6:"buffalo buffalo Buffalo buffalo "
>> 4+6              7:"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo "
> 63                8:63
>> 7ᶠ8              9:"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo"
>> Output 9         10:prints out line 9

```

# Answer
> 4 votes
# TeX, 34 bytes

`\def~{uffalo }B~b~B~b~b~b~B~b~\bye`

# Answer
> 4 votes
# `awk`, 22- or 41-bytes. basic approach is 41-bytes:

```
echo Buffalo |

```

> ```
> mawk 'NF+=sub("  ",OFS=" "tolower($2=$4=$1)" ")'
>
> ```

```
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

```

but if we're going with the entirely hard-coded approach, that can massively cut it down to just 22-bytes (and that's already inclusive of the single quotes for `OFS`) :

```
echo BbBbbbBb |

```

> ```
> mawk NF++ FS= OFS='uffalo '
>
> ```

```
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

```

Trivia tidbit - if we view `"B"`'s as `"1"`'s and `"b"`'s as `"0"`'s,

then the requirement would appear 10100010, while its decimal form can be reached via either

> ```
>   2 * ( 3 ^ 4 )
>                 or
>   3  *  6 * 9
>
> ```

# Answer
> 3 votes
# Mathematica, 54 bytes

```
Print@@Riffle[#<>"uffalo"&/@Characters@"BbBbbbBb"," "]

```

Try it online!

# Answer
> 3 votes
# Jelly, 15 bytes

```
162Bị“¢OỊ“¦ȯø»K

```

Try it online!

(Alternatively, `162Bị“¢OỊ»,Œl¤K`)

I might be doing something wrong if this comes out two bytes shorter than title-casing dynamically...:

# Jelly, 17 bytes

```
Œt⁹¡
162B“¦ȯø»çⱮK

```

Try it online!

# Answer
> 3 votes
# APL+WIN, 21 bytes

```
'BbBbbbBb',¨⊂'uffalo'

```

Try it online! Thanks to Dyalog Classic

This could be shortened to 5 bytes if the two strings were given as input rather than being hard coded.

# Answer
> 3 votes
# K (ngn/k), ~~27~~ 25 bytes

-2 bytes thanks to ngn!

```
" "/"BbBbbbBb",\:"uffalo"

```

Try it online!

# , 30 bytes

```
echo}:,/'BbBbbbBb',"{'uffalo '

```

Try it online!

# Answer
> 3 votes
# Java (JDK), 49 bytes

```
v->"B b B b b b B b".replaceAll("\\w","$0uffalo")

```

Try it online!

## Credits

# Answer
> 3 votes
# Whispers v2, 98 bytes

```
> 81
> 2
>> 1⊥2
> "Buffalo "
> "buffalo "
> "buffalo"
>> If L 4 5
>> Each 7 3
>> 8+6
>> Output 9

```

Try it online!

# Answer
> 3 votes
# Ohm v2, 20 bytes

```
‥bB.¢`b}®:_”cåχíð”↔ù

```

Try it online!

# Answer
> 3 votes
# Python 3, 39 bytes

```
print('uffalo '.join('BbBbbbBb ')[:-2])

```

Try it online!

## Potentially invalid, 35 bytes

```
print('uffalo '.join('BbBbbbBb\b'))

```

Try it online!

# Answer
> 3 votes
# brainfuck, 370 bytes

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

```

Try it online!

Not exactly the most optimized answer and could probably be golfed much further. Makes lots of use of copying cells, as well as repeadedly performing the same print function near the end.

Original un-minified version (sadly uncommented) can be found here.

# Answer
> 3 votes
# T-SQL, ~~45 51~~ 47 bytes

```
PRINT REPLACE('B0 B0 b0 B0',0,'uffalo buffalo')

```

`PRINT` is shorter than `SELECT`. Using a numeral in the `REPLACE` eliminates a set of quotes and saves 2 bytes.

**EDIT**: Fixed trailing space, at the cost of 6 bytes. Saved 4 by replacing a longer phrase, thanks @Giuseppe

# Answer
> 3 votes
# x86-16 machine code, IBM PC DOS, ~~35~~ ~~33~~ 32 bytes

```
00000000: b820 09b1 e7ba 1801 cd21 d0e9 7409 7303  . .......!..t.s.
00000010: 3044 19cd 29eb f1c3 4275 6666 616c 6f24  0D..)...Buffalo$

```

Listing:

```
B8 0920     MOV  AX, 0920H          ; AH = 9 DOS string function, AL = ' '
B1 E7       MOV  CL, 11100111b      ; magic buffalo number 11100111
BA 0118     MOV  DX, OFFSET BUF     ; 'Buffalo' pointer for display
        STAMPEDE:
CD 21       INT  21H                ; write our *uffalo to screen
D0 E9       SHR  CL, 1              ; LSB of magic buffalo number into CF
74 09       JZ   BYE_BUFFALO        ; loop until CL is 0
73 03       JNC  HI_BUFFALO         ; if LSB bit is a 0, don't change case
30 44 19    XOR  [SI+BUF-100H], AL  ; swap case on first letter
        HI_BUFFALO:
CD 29       INT  29H                ; if not last of the buffalo, display a space
EB F1       JMP  STAMPEDE           ; keep 'em coming
        BYE_BUFFALO:
C3          RET                     ; return to DOS
        BUF:
            DB   'Buffalo$'         ; the real Buffalo

```

Try it online!

**Explanation:**

Uses the byte `0xe7` (`1110 0111` binary) to determine if the case should be swapped. Each `[Bb]uffalo` corresponds to the next least significant bit of the byte where a `1` means to change the case and a `0` means don't change.

The case of the first character can be alternated by doing an `xor 0x20` on the ASCII value. Now `0x20` just happens to be the ASCII value for a space character, so we can put that in `al` and use for both the `xor` and to write the space character.

**Props:**

* -1 byte thx to @peter ferrie!

# Answer
> 3 votes
# PHP, ~~47~~ 45 bytes

```
while($x<8)echo~_[!$x],BbBbbbBb[$x++],uffalo;

```

Try it online!

*-2 bytes thx to @manatwork!*

# Answer
> 3 votes
# Java (JDK), 49 bytes

```
v->"B b B b b b B b".replaceAll("b|B","$0uffalo")

```

Try it online!

# Answer
> 3 votes
# PowerShell, 41 38 bytes

-3 bytes thanks to @mazzy

```
'BbBbbbBb'-replace'.',' $0uffalo'|% *m

```

Try it online!

# Answer
> 3 votes
# QBasic, 43 bytes

```
u$="uffalo buffalo
?"B"u$" B"u$" b"u$" B"u$

```

Abuses a couple tricks with the autoformatter (besides the standard `?` for `PRINT` shortcut): the missing double quote is added at the end of line 1, and semicolons are inferred in the print statement whenever a literal string is next to a variable. After expansion, the code becomes

```
b$ = "uffalo buffalo"
PRINT "B"; b$; " B"; b$; " b"; b$; " B"; b$

```

The semicolon trick, plus the fact that string variables need the `$` sigil, meant that approaches using more variables to build the string ended up longer.

# Answer
> 3 votes
# brainfuck, ~~190~~ 179 bytes

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

```

Try it online!

The ASCII codes are initialised using a similar method to my Buffalo answer, though here both `b` and the second `f` get their own cells. Printing the output requires fewer instructions in brainfuck compared with Buffalo because of a key difference in the way that loops are handled: brainfuck uses the currently active cell to decide whether a loop ends, whereas Buffalo refers back to the cell that was originally active when the loop was entered. Consequently, we can print runs of letters in successive cells with a simple `[.>]` loop in brainfuck, a construction that isn't possible in Buffalo.

# Answer
> 2 votes
# Red, 57 bytes

```
prin collect[foreach b"BbBbbbBb"[keep rejoin[b"uffalo"]]]

```

Try it online!

## Alternative:

## Red, 60 bytes

```
parse s:"B b B b b b B b"[any["b"insert"uffallo"|" "]]prin s

```

Try it online!

# Answer
> 2 votes
# Stax, 16 bytes

```
Æ▼.#t!♦ΩÿN+╪\7êI

```

Run and debug it

Uses mixed base conversion and some zipping.

Made with a lot of @recursive's help.

# Answer
> 2 votes
# C++11, 126 bytes

```
#include<random>
#include<cstdio>
int main(){std::knuth_b g(7);for(char i{},s[]=" buffalo";i-8;++i)s[1]^=*s&g(),printf(s+!i);}

```

Try it online!

Not a serious contender for shortest program — but I was inspired by the (original, now-deleted) requirement not to use a random number generator. ;)

# Answer
> 2 votes
# Perl 5, 37 bytes

```
say"@{[map{(21%$_?b:B).uffalo}1..8]}"

```

Try it online!

# Answer
> 2 votes
# Python 3, 117 bytes

```
o=['buffalo']
for x in ['B' if int(i) else 'b' for i in bin(69)[:1:-1]]:
  o.insert(0,x+o[-1][1:])
print(' '.join(o))

```

Try it online!

69 is the reverse of the binary representation of the capitalization pattern.

# Answer
> 2 votes
# Bubblegum, 17

Obligatory bubblegum answer generated with `zopfli --deflate --i1000 -c buffalo.txt | xxd`

```
00000000: 732a 4d4b 4bcc c957 4882 d2e8 fc24 fcf2  s*MKK..WH....$..
00000010: 00                                       .

```

Try it online!

# Answer
> 2 votes
# Raku, ~~33~~ 30 bytes

```
put "BbBbbbBb".comb X~"uffalo"

```

Try it online!

# Answer
> 2 votes
# Rattle, ~~51~~ ~~46~~ 42 bytes

Rattle just hit release today - this is my first golf with the released version! If you're interested in learning a fun and easy new language, I would highly recommend checking it out!

```
B&b&uffalo& |I=[b0[2b^b1]b2b3b1b2[3q]b3+]4

```

Try it online!

Try to out-golf me! You'll probably want to consult the documentation

## Explanation

```
B&b&uffalo&      creates an array of hard-coded strings: ["B","b","uffalo"," "]
    |            syntax for taking input
     I           stores this data in first memory slots
      =          sets top of stack to 0
       [ ... ]4  loops 4 times
    b0           adds item in slot 0 to buffer
      [2 ... ]   executes statements inside if top of stack is equal to 2
        b^       deletes last item from buffer
          b1     adds item in slot 1 to buffer
    b2b3b1b2     adds item in slot 2, 3, 1, 2 to buffer
    [3 ... ]     executes statement inside if top of stack is equal to 3
      q          ends program - buffer is implicitly printed
    b3           adds item in slot 3 to buffer
      +          adds 1 to top of stack

```

# Answer
> 2 votes
# Regenerate, 27 bytes

```
B((uffalo) b$2 B$2 b$2) b$1

```

Attempt This Online!

Pretty simple: golf repeated substrings using capture groups.

# Answer
> 2 votes
# sed, ~~35~~ 33 bytes

*-2 bytes thanks to user41805*

```
s/^/BbBbbbBb/
s/./ &uffalo/g
s///

```

Attempt This Online!

34B solution:

*-1 byte thanks to user41805*

```
s/^/B b B b b b B b/
s/\>/uffalo/g

```

Attempt This Online!

35B solution: *(The regex matches empty string at first and then is reused for the second `s` command)*

```
s/b*/B b B b b b B b/i
s//&uffalo/g

```

Attempt This Online!

# Answer
> 2 votes
# MathGolf, 18 bytes

```
9G*âx{ûbB§╕«Γ╢ô };

```

Try it online.

`âx{ûbB§╕«Γ╢ô` could alternatively be `à{ENR**╦\i╛δ` for the same byte-count: try it online.

**Explanation:**

```
9G*               # Push 9*18=162
   â              # Convert it to a binary list
                  # (which is unfortunately in reversed order due to a bug)
    x             # Reverse it to the correct order
     {            # Loop over each of these bits as integers:
      ûbB         #  Push string "bB"
         §        #  (0-based) index the current bit into it
          ╕«Γ     #  Push compressed string "uffa"
             ╢ô   #  Push compressed string "lo"
                  #  Push a space character " "
     };           # After the loop: discard the final space
                  # (after which the entire stack is joined and output implicitly)

   à              # Convert it to a binary string (in correct order..)
    {             # Loop over each of these bits as characters:
     ENR**        #  Push 15*25*29=10875
          ╦       #  Get the dictionary word at this index: "buffalo"
           \      #  Swap so the current bit is at the top of the stack
            i     #  Convert it from a character to an integer
             ╛    #  If it's truthy:
              δ   #   Titlecase the string

```

# Answer
> 2 votes
# Scratch, 8 blocks

Try it on scratch!

I tried to refrain from doing anything too illegal like setting the costume as `Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo` or setting a variable as that.

Here is the scratchblocks code (102 bytes):

```
when gf clicked
for each[i v]in(8){set[B v]to(join(B)(join(letter(i)of[BbBbbbBb])[uffalo ])
}::control

```

Usually when people submit scratch, they submit Tosh (https://tosh.blob.codes/), which is Scratch but text-based or an image of the blocks compiled on scratchblocks (https://scratchblocks.github.io). I would’ve done both, but the `for each [i v] in (8)` block is old and removed and I can’t figure out how to do it on Tosh.

# Answer
> 1 votes
# Vyxal `S`, 11 bytes

```
⁺>bƛḃ‛ḋ¤$ßǐ

```

Try it Online!

## Explained

```
⁺>bƛḃ‛ḋ¤$ßǐ
⁺>           # Push 163
  b          # and convert it to binary
   ƛ         # for each digit:
    ḃ        #   push whether the digit is "truthy"
     ‛ḋ¤     #   and push the string "buffalo"
        $    #   swap those two values
         ßǐ  #   and if the digit actually is truth, title case it

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 48 bytes

```
##<>#&//"B"~Print~#["uffalo"~#~b~#~" B",b=" b"]&

```

Try it online!

Port of TiKevin83's TI-BASIC solution.

# Answer
> 1 votes
# Clojure, 60 bytes

```
(clojure.string/join " " (map #(str % "uffalo") "BbBbbbBb"))

```

# Answer
> 1 votes
# JavaScript (V8), ~~57~~ 50 bytes

```
a='uffalo';b='B'+a+' b'+a;c='b'+a;print(b,b,c,c,b)

```

Try it online!

You have to run these at `Try it online!` because running it in a browser console will try to print this webpage

57 bytes:

```
a='uffalo ';b='B'+a+'b'+a;c='b'+a;print(b+b+c+c+b.trim())

```

47 bytes but `Try it online!` doesn't understand `String.replaceAll` and it outputs a trailing space:

```
print('B'+('bBbbbBb'.replaceAll('','uffalo ')))

```

46 bytes but it outputs a trailing space (thanks to @lm42):

```
print('B'+('bBbbbBb'.replace(/|/g,'uffalo ')))

```

This is my first golf.

# Answer
> 1 votes
# Julia REPL, 33 bytes

`join("BbBbbbBb ","uffalo ")[1:63]`

## Julia, 40 bytes

`print(join("BbBbbbBb ","uffalo ")[1:63])`

# Answer
> 1 votes
# Pyth, 23 22 bytes

Save a byte thanks to @Scott!

```
V"BbBbbbBb"p+N"uffalo

```

Try it online!

---

I wanted to be smart and encode the state of the upper- and lowercase letters as bits, but that ended up taking a byte more. Here's the code and explanation anyway!

### 24 bytes

```
FNj162 2p+?N\B\b"uffalo

```

```
FN                         # loop with N
  j162 2                   # convert 162 into binary as list of bits
        p                  # print without newlines
         +                 # concatinate strings
          ?N\B\b           # ternary operator, checks if the bit is falsey (0)
                "ufallo    # note the trailing space

```

# Answer
> 1 votes
# Ruby, ~~49~~ 39 bytes

-10 bytes thanks to Dingus

```
$><<('BbBbbbBb '.chars*'uffalo ').strip

```

Try it online!

# Answer
> 1 votes
## C#, 131 bytes

```
using System.Linq;using System;class A{static void Main(){Console.Write($"{String.Join("uffalo ", "BbBbbbBb".ToArray())}uffalo");}}

```

Try it online!

# Answer
> 1 votes
# Pyth, 22 bytes

```
jdm+d"uffalo""BbBbbbBb

```

Try it online!

# Answer
> 1 votes
# jq, 35 characters

```
"BbBbbbBb "/""|join("uffalo ")[:-2]

```

Sample run:

```
bash-5.0$ jq -nr '"BbBbbbBb "/""|join("uffalo ")[:-2]'
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

```

Try it online!

# Answer
> 1 votes
# Javascript, 57 bytes

```
console.log('BbBbbbBb'.replace(/./g, '$&uffalo ').trim())

```

Try it online!

If a trailing space is allowed, it can be 50 bytes:

```
console.log('BbBbbbBb'.replace(/./g, '$&uffalo '))

```

Try it online!

# Answer
> 1 votes
# brainfuck, 226 bytes

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

```

Try it online!

The cells are set to `<space>Bbuffalo`

```
<[<]> Goto the space cell
.  (dot = print a space)
>. (dot = print B)
>. (dot = print b)
>[.>] print uffalo

```

`Buffalo` is printed using `<[<]>.>.> >[.>]` but is this if it is the first time, we use `<[<]> >.> >[.>]`

`buffalo` is printed using `<[<]>.> >.>[.>]` but we can golf this to `<[<]>.> > [.>]`

The only thing that I can think of that could probably be better golfed is the preparation part.

If you put the B before the space you might be able to save some bytes.

# Answer
> 1 votes
# ThumbGolf, 31 bytes

Machine code (little endian pairs):

```
a005 22ba 0852 bf2c 2162 2142 de11 de00
d001 de3b d1f6 4770 6675 6166 6f6c 00

```

Commented assembly:

```
        // Include ThumbGolf wrapper macros
        .include "thumbgolf.inc"
        .globl main
        .thumb_func
main:
        // r0 = "uffalo"
        adr     r0, .Luffalo
        // Bitmask representing the case of the B.
        // 0 = B, 1 = b, little endian bit order.
        // Also allows us to determine the length.
        // This fits perfectly into a narrow movs.
        //             bBbbbBbB
        movs    r2, #0b10111010
.Lloop:
        // Read a bit from the bitmask into the carry flag by shifting right.
        // Also detects when we have read all of the bits: lsrs will set the
        // zero flag.
        lsrs    r2, r2, #1
        // r1 = (r2 & 1) ? 'b' : 'B'
        ite     cs
        movcs   r1, #'b'
        movcc   r1, #'B'
        // print either 'b' or 'B'
        putc    r1 // udf #0021
        // print "uffalo" (w/o newline)
        puts    r0 // udf #0000
        // Yes, none of the output instructions affect the flags despite using
        // stdio AND executing the stdio call on the main thread (since stdio in
        // signal handlers is unsafe), and this is proof.
        //
        // If the bitmask is zero, exit.
        it      eq
        bxeq    lr
        // Use the "put special" instruction to print a space.
        putspc  ' ' // udf #0073
        // More flexing that the flags are preserved, it is just as good to do
        // `b .Lloop`.
        // The proof is that this won't crash, since the ASCII as code will store
        // random garbage to uninitialized registers.
        bne     .Lloop
        // string literal
.Luffalo:
        .asciz "uffalo"

```

Mostly a demo to show how ThumbGolf preserves the condition flags on output instructions.

I could do the same thing with `cbz` and an unconditional `b`, but this is a nice party trick.

As I explained in the code, I use a bitmask to control whether `Buffalo` or `buffalo` is printed. It just happens to be a perfect 8-bit constant for `movs`.

# Answer
> 1 votes
# Kotlin, 63 bytes

```
fun main(){"BbBbbbB".map{print(it+"uffalo ")};print("buffalo")}

```

Kotlin Playground

I used the fairly common strategy of concatenating the first letter to `"uffalo"`, but I had to print the last one to avoid trailing white space, I'm yet to find a better solution.

# Answer
> 1 votes
# AWK, 52 bytes

```
BEGIN{B="Buffalo";b="buffalo";print B,b,B,b,b,b,B,b}

```

Try it online!

I could not come up with a shorter example.

# Answer
> 1 votes
# Whispers v2, 69 bytes

```
> "BbBbbbBb"
> "uffalo "
> -1
>> L+2
>> Each 4 1
>> 5ᶠ3
>> Output 6

```

Try it online!

# Answer
> 1 votes
# Deadfish~, 463 bytes

```
{{i}dddd}iiiiiic{{i}ddddd}ic{d}dddddccdddddc{i}iciiic{{d}ii}ic{{i}dddd}iiiiiic{i}{i}dc{d}dddddccdddddc{i}iciiic{{d}ii}ic{i}{i}{i}iiiic{{i}ddddd}ic{d}dddddccdddddc{i}iciiic{{d}ii}ic{{i}dddd}iiiiiic{i}{i}dc{d}dddddccdddddc{i}iciiic{{d}ii}ic{{i}dddd}iiiiiic{i}{i}dc{d}dddddccdddddc{i}iciiic{{d}ii}ic{{i}dddd}iiiiiic{i}{i}dc{d}dddddccdddddc{i}iciiic{{d}ii}ic{i}{i}{i}iiiic{{i}ddddd}ic{d}dddddccdddddc{i}iciiic{{d}ii}ic{{i}dddd}iiiiiic{i}{i}dc{d}dddddccdddddc{i}iciiic

```

Try it online!

# Answer
> 1 votes
## BBC BASIC, 55 bytes

```
F.I%=1TO8:P.CHR$(98+32*((I%AND(I%+1))=0));"uffalo ";:N.

```

Try it online!

# Answer
> 1 votes
# R, 48 bytes

Similar to Dominic van Essen's recycling solution, but with `paste0`.

```
cat(paste0(scan(,''),'uffalo'))
B
b
B
b
b
b
B
b

```

Try it online!

Same idea, also 48 bytes

```
cat(paste0(scan(,''),'uffalo buffalo'))
B
B
b
B

```

Try it online!

# Answer
> 1 votes
# Pascal, 84 B

This program complies to ISO standard 7185 “Pascal” (level 0 sufficient):

```
program p(output);const s='uffalo buffalo B';begin write('B',s,s:15,'b',s,s:14)end.

```

# Answer
> 1 votes
# C (gcc), 60 bytes

```
f(n){for(n=8;n--;)printf("%cuffalo%*.s","bBbbbBbB"[n],!!n);}

```

Try it online!

# Answer
> 0 votes
# JavaScript ES6, 51 bytes

```
(c=n=>n?c(n>>1)+'bB'[n&1]+'uffalo ':'')(162).trim()

```

Made sure to trim a trailing space. If we don't trim it, we get 44 bytes (but of course that violates the problem description).

# Answer
> 0 votes
# C (gcc), 62 bytes (using binary properties)

```
n=8;f(){while(n--)printf("%cuffalo%c",98^(n==3^n&1)<<5,9+!n);}

```

Explanations:

* 98 is 'b'
* If we clear bit `1<<5` (32) from 'b' we obtain 'B': `'b' ^ (1 << 5) = 'B')`. This property is true for all letters.
* We want to clear this bit when n = 7, 5 and 1, which means when n is odd: `n&1` with the exception iteration: 3 `n==3^`
* `9+!n` allows to have spaces (horizontal tab) except when n == 0: `!n`, then this expression will equal to 10 which is a new line return `'\n'`.
* When n == 0 the `while(n--)` loop will automatically stops.

Try it online!

Thanks to caird coinheringaahing for catching the superfluous extra newline ;)

# Answer
> 0 votes
# StupidStackLanguage, ~~89~~ 84 bytes

```
avvqmddlblbqaviqvmlblblqqqaviqvmlblblaviqvmlblbtfavvdqvdmfwwwffwfvvifiiifbvvvvdfbbbu

```

Try it online!

# Answer
> 0 votes
# VBScript, 68 bytes

```
s="'BbBbbbBb'":k=""
For i=1 To Len(s)
k=k&Mid(s,i,1)&"uffalo "
Next

```

# Answer
> 0 votes
# BRASCA, 30 bytes

```
`bBbbbBbB`[o` olaffu`7[aoA{]x]

```

Try it

## Explanation

```
`bBbbbBbB`                     - Push the first letters of each [Bb]uffalo
          [                  ] - While non-zero:
           o                   -   Output the b/B
            ` olaffu`          -   Push "uffalo "
                     7[aoA{]x  -   Output it and clean up the counter

```

# Answer
> 0 votes
# Excel, 49 bytes

```
=TEXTJOIN(" ",,CHAR(98-{4;4;0;4}*{8,0})&"uffalo")

```

## Explanation

```
98-{4;4;0;4}*{8,0} =>  66 98 CHAR()=> B b
                       66 98          B b
                       98 98          b b
                       66 98          B b

```

## Shortest Alternative, 51 bytes

```
=TEXTJOIN(" ",,MID("BbBbbbBb",ROW(1:8),1)&"uffalo")

```

# Answer
> 0 votes
# Julia 1.0, 38 bytes

```
show(join(["BbBbbbBb"...].*"uffalo "))

```

Try it online!

# Answer
> 0 votes
# Knight (v2), 30 bytes

```
O S^+@'BbBbbbBb.''uffalo '63T@

```

Try it online!

# Answer
> -9 votes
# Python 3, 72 bytes

```
print('Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo')

```

I mean, that works.

Try it online!

---
Tags: code-golf, kolmogorov-complexity
---


title: What ROT is this? - decrypt ROT-n

text:
# Question
Title: What ROT is this? - decrypt ROT-n
Here are the letters of the English alphabet in order by frequency:

```
e t a o i n s h r d l c u m w f g y p b v k j x q z

```

That is, `e` is the most frequently used letter, and `z` is the least common. (Data from Wikipedia.)

Your challenge is to take some ROT-n'd text, such as:

```
ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz

```

This is the text "thisisaverysecretmessagethatisverysecureandsafe" that is "encrypted" through ROT-21 (half of 42). Your program, using the frequency table above, should be able to determine by how much each character was rotated and the original text.

(If you are not familiar with ROT-n, it is essentially shifting each character by `n`. For example, in ROT-2, `a -> c, b -> d, ..., x -> z, y -> a, z -> b`.)

How, you ask? The (very naive) algorithm you must use is:

* for each `n` from `0` to `25` inclusive, apply ROT-`-n` to the input string. (Negative `n` because we want to *reverse* the encryption. ROT-`-n` is equivalent to ROT-`26-n`, if that's any easier.)
* convert each input string to a number by adding up the relative frequencies of the characters. `e` is `0`, `t` is `1`, `a` is `2`, etc. For example, the corresponding number for the string `"hello"` is 7 + 0 + 10 + 10 + 3 = 30.
* find the string that has the lowest corresponding number.
* output that string and its corresponding `n`.

Rules:

* input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)
* you may use a different algorithm, as long as it always produces identical results. For example, having `z` be 0 and `e` be 25 and choosing the highest number is also okay.
* if two strings have identical scores, you can choose to output either one (or both) of them. This is an edge case and you do not have to account for it.
* this is , so the shortest code in bytes will win!

Test cases:

Input: `ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz`
Output: `21 thisisaverysecretmessagethatisverysecureandsafe`

Input: `pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom`
Output: `8 hellopeopleofprogrammingpuzzlescodegolfstackexchange`

Input: `ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq`
Output: `12 thiswasencryptedwithrottwelvesoitmustbeperfectlysafe`

Input: `jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv`
Output: `2 hereisthefinaltestcasethatyoumustdecrypt`

In case you were wondering, here is a JSFiddle of the JavaScript test code I wrote, which successfully decrypted all the test cases I threw at it.

# Answer
> 6 votes
# GolfScript - 87

The cheat here is to build every rotation simultaneously. Since we need to loop over every ROT then every character, let's just loop over every character, slice the whole alphabet, then zip it up. From there proceed as expected: count the score for each ROT and choose the minimum.

Extra golfed:

```
{97- 26,{97+}%.+''+>}/]{27<}%zip:d{{"etaoinshrdlcumwfgypbvkjxqz"?}%{+}*}%.$0=?.26\-\d=

```

Only a little golfed:

```
# the alphabet, and by frequency
26,{97+}%.+''+:a;
"etaoinshrdlcumwfgypbvkjxqz":f;

# build evey ROT decryption
{97-a>}/]{27<}%zip:d

# calculate likelihood
{{f?}%{+}*}%.

# find min
$0=

# output rotation factor and decryption
?.26\-\d=

```

# Answer
> 8 votes
## Haskell - ~~192~~ 175

```
f y=sum.map(\x->length.fst$break(==x)y)
main=interact(\s->snd$minimum$[(f"etaoinshrdlcumwfgypbvkjxqz"r,show(26-n)++" "++r)|n<-[0..25],let r=map(\x->([x..'z']++['a'..])!!n)s])

```

Running

```
% ./rot-n <<< "pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom"
8 hellopeopleofprogrammingpuzzlescodegolfstackexchange

```

# Answer
> 7 votes
# GolfScript, ~~112~~ ~~108~~ ~~102~~ 100 characters

```
{{}/]{97-}%}:b~:|;"etaoinshrdlcumwfgypbvkjxqz"b:f,:&,{:x[|{&x-+&%f?}%{+}*\]}%$0=1=:x|{&x-+&%97+}%''+

```

I'm not happy about the repetition with the re-decrypting at the end, but meh.

Ungolfed (if that makes any sense :P) and slightly older version:

```
# store input IDs (a = 0, b = 1, etc.) in s
[{}/]{97-}%:s;
# store frequency data IDs in f (blah, repetition)
"etaoinshrdlcumwfgypbvkjxqz"[{}/]{97-}%:f

# for each number from 0 to 26 (length of previous string left unpopped)...
,,{
  # the number is x
  :x;
  # return an array of...
  [
    # the score
    s{x 26\-+26%f?}%{+}*
    # and the n
    x
  ]
}%

# use $ort to find the n to output
$0=1=:x

# get the string that the n corresponded to (blah, more repetition)
s{x 26\-+26%97+}%''+

```

# Answer
> 6 votes
## JavaScript (205)

```
f='zqxjkvbpygfwmucldrhsnioate';a='abcdefghijklmnopqrstuvwxyz';for(s=prompt(o=m=n=0)
,i=27;i--;w>m&&(m=w,n=i,o=u))for(u='',w=c=0;c<s.length;w+=f.indexOf(x))u+=x=(a+a)[a
.indexOf(s[c++])+i];alert((26-n)+' '+o)

```

I think it can still be golfed a bit more, so suggestions welcome!

Some notes to help understand the solution

* `m`, `n`, and `o` track the highest score.
* `u` and `w` track the character and value result, respectively for the current `i`
* `(a+a)` helps prevent overflow when wrapping around past `z`, and is shorter than doing `%26`
* I have the frequency in reverse order so I can search max instead of min.

Proof: http://jsfiddle.net/J9ZyV/5/

# Answer
> 4 votes
## C# + Linq - ~~273~~ 264

As a function which takes the input string and returns the decoded string & offset (as per requirements):

```
static Tuple<string,int> d(string s){var r=Enumerable.Range(0,25).Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))).OrderBy(x=>(from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c)).Sum()).First();return Tuple.Create(r,(s[0]-r[0]+26)%26);}

```

Ungolfed with comments:

```
static Tuple<string,int> d(string s)
{
    var r=Enumerable.Range(0,25)                                               // for every possible offset i
          .Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))) // calculate rot_i(input string)
          .OrderBy(                                                            // order these by their score
              x=>(
              from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c)       // lookup frequency of each character
              ).Sum()                                                          // and sum each frequency to get the score
           ).First();                                                          // get the first one (lowest score)

    return Tuple.Create(r,(s[0]-r[0]+26)%26);                                  // compute offset and return results
}

```

---

Little test driver (remember to compile referencing `System.Core` for Linq):

```
using System;
using System.Linq;

namespace codegolf
{
    class Program
    {
        static Tuple<string,int> d(string s){var r=Enumerable.Range(0,25).Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))).OrderBy(x=>(from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c)).Sum()).First();return Tuple.Create(r,(s[0]-r[0]+26)%26);}

        static void Main(string[] args)
        {
            while (true)
            {
                var input = Console.ReadLine();
                if (input == null) break;
                var retval = d(input);
                Console.WriteLine(String.Format("{0} {1}", retval.Item2, retval.Item1));
            }
        }
    }
}

```

Giving:

```
$ mcs /reference:System.Core.dll main.cs && mono ./main.exe
ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz
21 thisisaverysecretmessagethatisverysecureandsafe
pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom
8 hellopeopleofprogrammingpuzzlescodegolfstackexchange
ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq
12 thiswasencryptedwithrottwelvesoitmustbeperfectlysafe
jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv
2 hereisthefinaltestcasethatyoumustdecrypt
thisisaverysecretmessagethatisverysecureandsafe
0 thisisaverysecretmessagethatisverysecureandsafe

```

# Answer
> 4 votes
# dg - 137 130 129 128 bytes

```
f=t->min key:(t->sum$map 'etaoinshrdlcumwfgypbvkjxqz'.index$snd t)$map(n->n,''.join$map(c->chr$((ord c + 7-n)%26+ 97))t)(0..26)

```

Examples:

```
>>> f 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz'
(21, 'thisisaverysecretmessagethatisverysecureandsafe')
>>> f 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom'
(8, 'hellopeopleofprogrammingpuzzlescodegolfstackexchange')
>>> f 'ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq'
(12, 'thiswasencryptedwithrottwelvesoitmustbeperfectlysafe')
>>> f 'jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv'
(2, 'hereisthefinaltestcasethatyoumustdecrypt')

```

Ungolfed code:

```
func = t ->
  #: Compute the score of the text `t` with respect to the frequency table.
  #: score :: (int, str) -> int
  score = t ->
    sum $ map 'etaoinshrdlcumwfgypbvkjxqz'.index $ snd t

  #: Compute rot-n of the string `t`. Return the offset and the shifted text.
  #: rot :: int -> (int, str)
  rot = n ->
    n, ''.join $ map (c->chr $ ((ord c + 7 - n) % 26 + 97)) t

  # return the minimum (computed by `score`) amongst all shifted messages
  min key: score $ map rot (0..26)

```

# Answer
> 4 votes
# J - 92 char

A bit of an ugly duckling, but it works. Outputs the number and then the string, on two lines.

```
(26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:)

```

If you want them to be on the same line, space separated, this only goes up to **93 char**, but takes an uglier route.

```
((":@],[:u:32,97+26|-)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])@(7+3&u:)

```

An explanation for `(/:'ctljapqhewvknfdsyigbmuoxrz')`: In this verb, we operate on the letter values as A=0, B=1, C=2, etc. To encode the letter values of the string `etaoinshrdlcumwfgypbvkjxqz`, the shortest way is actually to take the sort permutation for this weird string. This is because A is at index 4, B at index 19, C at 0, D at 14, and so on; hence the sort permutation is `4 19 0 14 8 13 ...` when you grade (`/:`) it, and you get exactly the number values for `etaoin...`.

Usage:

```
   (26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:) 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz'
21
thisisaverysecretmessagethatisverysecureandsafe

   NB. naming for convenience
   f =: (26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:)
   f 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom'
8
hellopeopleofprogrammingpuzzlescodegolfstackexchange
   f 'wtaad'
0
wtaad

```

# Answer
> 3 votes
# q, 97

```
{(w;m w:g?min g:(+/')("etaoinshrdlcumwfgypbvkjxqz"!t)m:(t!u!/:rotate[;u:.Q.a]'[(-)t:(!)26])@\:x)}

```

.

```
q) tests:(
    "ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvazocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz";
    "pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom";
    "ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq";
    "jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv")

q) f:{(w;m w:g?min g:(+/')("etaoinshrdlcumwfgypbvkjxqz"!t)m:(t!u!/:rotate[;u:.Q.a]'[(-)t:(!)26])@\:x)}

q) f each tests
21 "thisisaverysecretmessagethatisverysecureandsafethisisaverysecretmessagethatisverysecureandsafe"
8  "hellopeopleofprogrammingpuzzlescodegolfstackexchange"
12 "thiswasencryptedwithrottwelvesoitmustbeperfectlysafe"
2  "hereisthefinaltestcasethatyoumustdecrypt"

```

# Answer
> 2 votes
# APL - 70 characters

```
F←{↑⍋+/'etaoinshrdlcumwfgypbvkjxqz'⍳⊃(⍳26){l[(⍺⌽l←⎕UCS 97+⍳26)⍳⍵]}¨⊂⍵}

```

Example:

```
      F 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz'
21
      F 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom'
8
      F 'ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq'
12
      F 'jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv'
2

```

I'm sure there are ways to compress this further, and I invite any other APL users to come up with solutions for that.

# Answer
> 2 votes
# Python 188

```
x="abcdefghijklmnopqrstuvwxyz"
y=input()
r=lambda n:"".join(x[x.find(i)-n]for i in y)
s={sum("etaoinshrdlcumwfgypbvkjxqz".find(b)for b in r(a)):(a,r(a))for a in range(26)}
print(s[min(s)])

```

# Answer
> 1 votes
Perl: 256 char (plus newlines for readability) including the frequency table:

```
@f=unpack("W*","etaoinshrdlcumwfgypbvkjxqz");
@c=unpack("W*",<>);$m=ord("a");$b=1E10;
for$n(0..25){$s=0;$t="";
for$x(0..scalar@c){$r=($c[$x]-$n-$m)%26+$m;$t.=chr($r);
for(0..scalar@f){if($r==$f[$_]){$s+=$_}}}
if($s<$b){$b=$s;$w=$t;$a=$n}}
printf"%d %s\n",$a,$w;

```

Text is provided like so:

```
echo "ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz" | perl ./freq.pl
21 thisisaverysecretmessagethatisverysecureandsafewm

```

Take off 12 char if you want to bake-in the values of ord(a) and the length of @f

# Answer
> 1 votes
# Elm - 465

Not going to win any golfing awards, but it makes a static webpage which displays a list of the form `[(rotation number, rotated string)]` as you type.

*Note: not yet working here but you can copy-paste it into the official editor and run it.*

```
import String as S
import Char (..)
import Graphics.Input (..)
import Graphics.Input.Field (..)
f="ETAOINSHRDLCUMWFGYPBVKJXQZ"
r s n=let t c=mod(toCode c-65+n)26+65 in map(fromCode . t)(S.toList s)
w s=case s of
 ""->0
 s->sum(S.indexes(S.left 1 s)f)+w(S.dropLeft 1 s)
b s=sort<|map(\x->((w . S.fromList . r s)x,(26-x,S.fromList<|r s x)))[0..25]
c=input noContent
main=above<~(field defaultStyle c.handle id""<~c.signal)~(asText . b . .string<~c.signal)

```

# Answer
> 1 votes
# Python 2, 171

```
f,R,i='zqxjkvbpygfwmucldrhsnioate',{},raw_input();a=sorted(f)*2
for n in range(26):_=''.join(a[ord(x)-71-n]for x in i);R[sum(2**f.index(x)for x in _)]=n,_
print R[max(R)]

```

# Answer
> 1 votes
# Ruby, 142 bytes

```
->s{(0..25).map{|i|[*s.map{["etaoinshrdlcumwfgypbvkjxqz".chars.index(c=((_1.ord-97-i)%26+97).chr),c]}.transpose.map{_1.reduce:+},i]}.min[1..]}

```

Attempt This Online!

# Answer
> 0 votes
# Python \+ `golfing-shortcuts`, ~~165~~ 161 bytes

A port of gcq's answer.

```
from s import*
def F(Y):R=lambda N:sj("",(Sl[Sl.find(I)-N]for I in Y));S={s("etaoinshrdlcumwfgypbvkjxqz".find(B)for B in R(A)):(A,R(A))for A in r(26)};p(S[q(S)])

```

# Answer
> 0 votes
# , 140 bytes

```
\(e,u=utf8ToInt,x=u(e)-97)c(n<-which.min(sapply(25:0,\(z)sum(match((x+z)%%26,u("etaoinshrdlcumwfgypbvkjxqz")-97)))),intToUtf8((x-n)%%26+97))

```

Attempt This Online!

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


title: Unslice a string

text:
# Question
Title: Unslice a string
Given an input of a list of slices of a string, output the original string.

Each slice will be given as a list of length 2, containing the start position of the slice (an integer ≥0) and the slice itself. If your language does not support arrays of arbitrary types, you may also take this as a struct or similar, or simply a string consisting of the number, a space, and then the slice.

The order of the two elements of each slice is up to you. Furthermore, if you choose to use the representation of slices as a length-2 array, you may take input as either a 2-dimensional array or a single flat array. Finally, the integer representing position may be either zero-indexed or one-indexed (all the examples here are zero-indexed).

The input will always be sufficient to determine the entire string up to the highest position given. That is, there will be no "holes" or "gaps." Therefore, the output must not contain any extra trailing or leading characters (other than the typical optional trailing newline). The input will always be consistent, and no slices will conflict with each other.

Since this is , the shortest code in bytes will win.

Test cases:

```
In                                                Out
-----------------------------------------------------------
[[2, "CG"], [0, "PP"], [1, "PC"]]               | PPCG
[[0, "foobarbaz"]]                              | foobarbaz
[[0, "foobar"], [6, "baz"]]                     | foobarbaz
[[2, "ob"], [5, "rba"], [0, "fooba"], [8, "z"]] | foobarbaz
[[0, "fo"], [0, "fooba"], [0, "foobarbaz"]]     | foobarbaz

```

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

```
Ḣ0ẋ;Fµ€o/

```

Try it online!

### How it works

```
Ḣ0ẋ;Fµ€o/  Main link. Input: A (list of pairs)

     µ€    Convert the chain to the left into a link, and apply it to each pair.
Ḣ          Pop the first element.
 0ẋ        Yield a list of that many zeroes.
   ;F      Concatenate the list of zeroes with the popped, flattened pair.
       o/  Reduce the generated lists by logical OR.
           Since all characters are truthy, this overwrites zeroes with characters,
           but never characters with zeroes.

```
> 5 votes

# Answer
## Python 2, 49 bytes

```
lambda l:`map(max,*[' '*n+s for n,s in l])`[2::5]

```

First, lines up the strings by padding their offsets with spaces (shown as underscores for clarity)

```
[[2, "CG"], [0, "PP"], [1, "PC"]]

__CG
PP
_PC

```

Then, uses `map` to `zip` and take the maximum of each column, which ignores the smaller values of spaces (the smallest printable character) and `None`s where some strings were too short.

```
__CG
PP
_PC

PPCG

```

Finally, `''.join` to a string using the `[2::5]` trick.
> 15 votes

# Answer
## JavaScript (ES6), 61 bytes

```
a=>a.map(([o,s])=>[...s].map(c=>r[o++]=c),r=[])&&r.join``

```

Edit: Saved 4 bytes thanks to @edc65.
> 8 votes

# Answer
## Haskell, 57 bytes

```
import Data.List
map snd.sort.nub.(>>= \(n,s)->zip[n..]s)

```

Usage example:

```
*Main> map snd.sort.nub.(>>= \(n,s)->zip[n..]s) $ [(2,"CG"),(0,"PP"),(1,"PC")]
"PPCG"

```

How it works: make pairs of `(index,letter)` for every letter of every slice, concatenate into a single list, remove duplicates, sort by index, remove indices.
> 8 votes

# Answer
# Perl, 25

Added +2 for `-lp`

Get the input from STDIN, e.g.

```
perl -lp slices.pl
2 CG
0 PP
1 PC

```

(Close with ^D or ^Z or whatever closes STDIN on your system)

`slices.pl`:

```
/ /;$r|=v0 x$`.$'}{*_=r

```
> 8 votes

# Answer
# Factor, 64 40 bytes

```
[ sbuf new tuck '[ _ copy ] assoc-each ]

```

Attempt This Online!

This answer makes use of the fact you can set arbitrary indices of a growable sequence (in this case a string buffer) and the sequence will expand appropriately with default values. `copy` copies one sequence to another starting at an index; a perfect fit for this problem.
> 5 votes

# Answer
# MATL, 15 bytes

```
''i"@Y:Y:tn:b+(

```

Works with current version (13.0.0) of the language/compiler.

Input is with curly braces and single quotes. (Curly braces in MATLAB/MATL define *cell arrays*, which are lists that can have contents of arbitrary, possibly different types.) The test cases are thus:

```
{{2, 'CG'}, {0, 'PP'} {1, 'PC'}}
{{0, 'foobarbaz'}}
{{0, 'foobar'}, {6, 'baz'}}
{{2, 'ob'}, {5, 'rba'}, {0, 'fooba'}, {8, 'z'}}
{{0, 'fo'}, {0, 'fooba'}, {0, 'foobarbaz'}}

```

**Try it online!**

```
''      % push empty string. This will be filled with the slices to produce the result
i       % take input: cell array of cell arrays. For example: {{0, 'foobar'}, {6, 'baz'}}
"       % for each (1st-level) cell
  @     %   push that cell. Example: {{0, 'foobar'}}
  Y:    %   unpack (1st-level) cell, i.e. push its contents. Example: {0, 'foobar'}
  Y:    %   unpack (2nd-level) cell array: gives number and substring. Example: 0, 'foobar'
  tn:   %   duplicate substring and generate vector [1,2,...,n], where n is length of
        %   current substring (in the example: 6)
  b+    %   add input number that tells the position of that substring within the whole
        %   string (in the example: 0; so this gives [1,2,...,6] again)
  (     %   assign substring to the total string, overwriting if necessary. Note that
        %   MATL uses 1-indexing
        % end for each
        % implicit display

```
> 4 votes

# Answer
# , 24 bytes

```
[:u:3>./@u:-@(+#&>){.&>]

```

Try it online!

## alternative, 24 bytes

```
[:u:[:>./(#&0@[,3 u:])&>

```

Try it online!
> 4 votes

# Answer
# DUP, 14 bytes

```
[0[$;$][,1+]#]

```

`Try it here.`

Anonymous lambda. Usage:

```
2"CG"0"PP"1"PC"[0[$;$][,1+]#]!

```

NOTE: DUP does not really have arrays, so I hope this input format is okay.

# Explanation

Well, DUP's string comprehension is... interesting. Strings are stored as a series of number variables, each of which holds a charcode from the string. Something like `2"CG"` works as pushing 2 to the stack, then creating a string with index starting from 2.

Because these indexes are really variables, they can be overwritten. That's what the input is really doing: overriding! Try pressing `Step` on the interpreter site to get a better idea for this. After this, we get an unsliced string.

This is where the outputting comes in.

```
[            ] {lambda}
 0             {push 0 to the stack as accumulator}
  [   ][   ]#  {while loop}
   $;$         {duplicate, get var at TOS value, see if that var is defined}
        ,1+    {if so, output charcode at TOS and increment accumulator}

```
> 3 votes

# Answer
# PHP, 146 chars

Note: Evaling user input is *always* a good idea.

## Golfed

```
<?$a=[];$f=0;eval("\$b={$argv[1]};");foreach($b as$d){$f=$d[0];$e=str_split($d[1]);foreach($e as$c){$a[$f++]=$c;}}ksort($a);echo join('',$a)."\n";

```

## Ungolfed

```
<?php
$array = array();
$p = 0;
eval("\$input = {$argv[1]};");
foreach($input as $item)
{
    $p = $item[0];
    $str = str_split($item[1]);
    foreach($str as $part)
    {
        $array[$p++] = $part;
    }
}
ksort($array);
echo join('', $array)."\n";
?>

```

You can see that I'm just writing the input into an array with the specific key each char has and then output it all.

## Tests

`php unslice.php '[[0, "foobar"], [6, "baz"]]'` -\> foobarbaz

`php unslice.php '[[2, "CG"], [0, "PP"], [1, "PC"]]'` -\> PPCG

`php shorten.php unslice.php` -\> Shortened script by 107 chars. :D
> 2 votes

# Answer
# Ruby, 40 bytes

```
->a{s=""
a.sort.map{s[_1,_2.size]=_2}
s}

```

Attempt This Online!
> 2 votes

# Answer
# Japt `-mh`, ~~15~~ 12 bytes

```
P=úUÎÄ hUÎUÌ

```

Try it

```
P=úUÎÄ hUÎUÌ     :Implicit map of each array U in input array W
P=               :Assign to P (an empty string, initially)
  ú              :Right pad P with spaces to length
   UÎ            :  First element of U
     Ä           :  Add 1
       h         :Replace the characters starting at index
        UÎ       :  First element of U
          UÌ     :  With last element of U
                 :Implicit output of last element of resulting array

```
> 2 votes

# Answer
# Vyxal `s`, 6 bytes

```
∩÷-∩vG

```

Try it online! (test suite) Input as a list of `[num, str]`.

**Explanation:**

```
∩÷-∩vG # whole program

∩      # transpose (num and str in their own groups)
 ÷     # split into each item
  -    # prepend '-' to str num amount of times (vectorises)
   ∩   # transpose
    v  # for each item (i.e. vectorise next element)
     G # get max char
       # s flag: concatenate list into a string, then print

```
> 2 votes

# Answer
# Python, 91 bytes.

Saved 1 byte thanks to cat.

It's a bit long. I'll golf it down more in a bit.

```
def f(x):r={j+i:q for(i,s)in x for j,q in enumerate(s)};return"".join(map(r.get,sorted(r)))

```
> 1 votes

# Answer
## Seriously, 48 bytes

```
,`i@;l(;)+(x@#@k`M;`i@X@M`MMu' *╗`iZi`M`i╜T╗`MX╜

```

Seriously is *seriously* bad at string manipulation.

Try it online!

Explanation:

```
,`i@;l(;)+(x@#@k`M;`i@X@M`MMu' *╗`iZi`M`i╜T╗`MX╜
,                                                 get input
 `              `M;                               perform the first map and dupe
                   `     `MM                      perform the second map, get max element
                            u' *╗                 increment, make string of that many spaces, save in reg 0
                                 `   `M           third map
                                       `    `M    fourth map
                                              X╜  discard and push register 0

```

Map 1:

```
i@;l(;)+(x@#@k
i@;l            flatten, swap, dupe string, get length
    (;)+(       make stack [start, end, str]
         x@#@k  push range(start, end), explode string, make list of stack

```

Map 2:

```
i@X@M
i@X     flatten, swap, discard (discard the string)
   @M   swap, max (take maximum element from range)

```

Map 3:

```
iZi  flatten, zip, flatten (make list of [index, char] pairs)

```

Map 4:

```
i╜T╗  flatten, push reg 0, set element, push to reg 0

```

In a nutshell, this program makes a string with `n` spaces, where `n` is the minimum length the string can be based on the input. It determines the index in the result string of each character in each slice, and sets the character in the result string at that index to the character.
> 1 votes

# Answer
## Python, ~~119~~ 115 bytes

```
def f(x,s=""):
 x.sort()
 for e in x:
  a=e[0];b=e[1]
  for i,c in enumerate(b):
   if len(s)<=(i+a):s+=c
 return s

```

### Test cases
> 1 votes

# Answer
# Japt, 16 bytes

```
ñÎrÈ+S hYÌYg)x}P

```

Try it

Explanation:

```
ñÎrÈ+S hYÌYg)x}P
               P # Starting with an empty string X
  r           }  # For each item Y in:
ñ                #  Input sorted by
 Î               #  The first item in each sub-array
   È             # Apply the following to X:
    +S           #  Add a space to the end
       h    )    #  Overwrite:
          Yg     #   Starting index is the first item in Y
        YÌ       #   New characters are the last item in Y
             x   #  Trim any leftover whitespace

```

Unfortunately `h` wraps its index, so attempting to write new characters at the end of a string with it instead writes them back at the start.
> 1 votes

# Answer
# QBasic, ~~127~~ 114 bytes

```
INPUT n
FOR j=1TO n
INPUT i
LINE INPUT s$
l=LEN(s$)
e=LEN(r$)-i-l
r$=r$+SPACE$(e*(e<0))
MID$(r$,i+1,l)=s$
NEXT
?r$

```

You can try it at Archive.org. The input format is: first, the number of slices; then, for each slice, the (0-based) index and the string on separate lines. Here's what running the first test case would look like:

```
? 3
? 2
CG
? 0
PP
? 1
PC
PPCG

```

### Explanation

```
INPUT n

```

Input the number of slices as `n`.

```
FOR j = 1 TO n
...
NEXT

```

Loop `n` times:

```
INPUT i

```

Input the starting index of the next slice as `i`.

```
LINE INPUT s$

```

Input the contents of the slice as `s$`. `LINE INPUT` is used to make sure that any printable ASCII character can be included in the input; if characters like `,` and `"` could be excluded, the two input statements could be combined as `INPUT i,s$`, saving 11 bytes.

```
l = LEN(s$)

```

Store the length of the slice as `l`.

```
e=LEN(r$)-i-l

```

The result string is stored in `r$` (initially empty by default). If merging this slice would extend `r$` beyond its current length, the number of characters we would need to add is given by `i` plus `l` minus the current length of `r$`. Calculate this amount, negated (see below for why), and store it as `e`.

```
r$ = r$ + SPACE$(e * (e < 0))

```

Pad `r$` as necessary by appending spaces to it. Comparison operators in QBasic return -1 for true and 0 for false. Thus, if `e < 0`, we append `-e` spaces; otherwise, we append `0` spaces.

```
MID$(r$, i + 1, l) = s$

```

Overwrite `l` characters of `r$`, starting at index `i + 1` (since `MID$` uses 1-based indexing), with the contents of `s$`.

```
PRINT r$

```

After the loop finishes, print the final value of `r$`.
> 1 votes

# Answer
# Pyth, 13 bytes

```
meSd.Tm+*;hde

```

Test suite

Takes input as a list of elements of the structure `[index, string]`. Outputs a list of characters.

##### Explanation:

```
meSd.Tm+*;hde   | Full code
meSd.Tm+*;hdedQ | with implicit variables
----------------+------------------------------------------------
      m       Q | Map over the input:
       +    ed  |  Prepend the string with
        *;hd    |   <index> spaces
    .T          | Ragged transpose
meSd            | Take the lexicographically last element of each

```
> 1 votes

# Answer
# 05AB1E (legacy), 7 bytes

```
ε`ú}ζ€à

```

Output as a list of characters.

Try it online or verify all test cases.

**Explanation:**

Uses the legacy version of 05AB1E instead of the new one for two reasons:

1. The zip/transpose builtins work on a list of strings, whereas the new version would require a list of lists of characters.
2. The minimum/maximum builtins work on characters (using their codepoint), which doesn't work in the new version.

```
ε     # Map over each pair of the (implicit) input-list:
 `    #  Pop the pair and push both values separated to the list
  ú   #  Pad the string with the integer amount of leading spaces
}ζ    # After the map: zip/transpose the strings, swapping rows/columns, using a default
      # space " " filler if strings are of unequal length
  €   # Map over each string
   à  #  Only leave its maximum character
      # (after which the resulting list of characters is output implicitly)

```
> 1 votes

# Answer
## CJam, 26 bytes

```
q~{~0c*\+}%{.{s\s|}}*e_0c-

```

Try it online!. Takes input in form `[["CG"2]["PP"0]["PC"1]]`.

Explanation:

```
q~           Read and eval input

{~0c*\+}%    Convert input strings into workable format
{      }%     Map onto each input
 ~            Evaluate
  0c          Null character
    *\+       Multiply by input number and concat to string

{.{s\s|}}*   Combine strings
{       }*    Fold array
 .{    }       Vectorize, apply block to corresponding elements of arrays
   s\s         Convert elements to strings
      |        Set Union

e_0c-        Remove null characters

```
> 0 votes

# Answer
## R, 181 bytes

```
n=nchar;m=matrix(scan(,'raw'),ncol=2,byrow=T);w=rep('',max(n(m[,2])+(i<-strtoi(m[,1]))));for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],''));cat("",w,sep="")

```

With line breaks:

```
n=nchar
m=matrix(scan(,'raw'),ncol=2,byrow=T)
w=rep('',max(n(m[,2])+(i<-strtoi(m[,1]))))
for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],''))
cat("",w,sep="")

```

Works in R Gui (single line one, or sourcing for the multi-line one) but not in ideone, example:

```
> n=nchar;m=matrix(scan(,'raw'),ncol=2,byrow=T);w=rep('',max(n(m[,2])+(i<-strtoi(m[,1]))));for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],''));cat("",w,sep="")
1: 2 ob 5 rba 0 fooba 8 z
9:
Read 8 items
foobarbaz

```

Note on the input method:

> or simply a string consisting of the number, a space, and then the slice.

I assume I comply with this part of the spec with this kind of input, it can be given on multiple lines, this has no impact as long as there a blank line to end the input.

I think 2 chars can be saved by removing the +1 and using 1 based indexing but I started with challenge input.
> 0 votes

# Answer
# C, 110 bytes

```
c,i,j;char s[99];main(){while(~scanf("%i ",&i))for(;(c=getchar())>10;s[i++]=c);for(;s[j]>10;putchar(s[j++]));}

```

This program takes the slice after its index in one line of input each.

Ungolfed:

```
c,i,j;char s[99];

main(){
    while(~scanf("%i ",&i))
        for(;(c=getchar())>10;s[i++]=c);
    for(;s[j]>10;putchar(s[j++]));
}

```

Test on ideone.com
> 0 votes

# Answer
## Lua, 113 bytes

```
z=loadstring("return "..io.read())()table.sort(z,function(a,b)return a[1]<b[1]end)for a=1,#z do print(z[a][2])end

```

This is probably some of the more secure code I've written. The idea is simple. The user will enter an array formatted as so: `{{1, "1"}, {3, "3"}, {2, "2"}}` and then the table will be sorted by the first index and the second index will be printed.
> 0 votes

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