title: Build me a castle Stairway!

text:
# Question
Title: Build me a castle Stairway!
You will be given a String consisting of printable ASCII (without newlines). Your task is to build a nice Stairway for my Castle.

# How to build a nice Stairway?

* First off, you should get all the rotations of the String. For example, the String `abcd` has the following rotations: `abcd, bcda, cdab, dabc` (each character is moved to the end until we reach the last character).
* We now place each rotation on top of each other:

```
abcd
bcda
cdab
dabc

```
* We can't really climb on a straight wall, so we must build stairs. That means you should add a number of spaces before each rotation corresponding to its index in the rotation list:

```
abcd
 bcda
  cdab
   dabc

```
* You also need a Stairway that links to the other side of my castle, so you should build one like below, reversing each rotation and adding some spacing:

```
abcd      dcba
 bcda    adcb
  cdab  badc
   dabccbad

```

This is , hence the shortest code in bytes wins and standard rules for the tag apply.

---

# Test Cases

* Input: `abcd`, Output:

```
abcd      dcba
 bcda    adcb
  cdab  badc
   dabccbad

```
* Input: `aaaa`, Output:

```
aaaa      aaaa
 aaaa    aaaa
  aaaa  aaaa
   aaaaaaaa

```
* Input: `Code golf`, Output (Notice the spaces):

```
Code golf                flog edoC
 ode golfC              Cflog edo
  de golfCo            oCflog ed
   e golfCod          doCflog e
     golfCode        edoCflog
     golfCode        edoCflog
      olfCode g    g edoCflo
       lfCode go  og edoCfl
        fCode gollog edoCf

```

# Answer
> 10 votes
# 05AB1E, 12 bytes

### Code:

```
vDNúsÀ}\».B∞

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
v     }        # Length input times, do.. (N = iteration count)
 DNú           #   Duplicate and prepend N spaces
    sÀ         #   Swap and rotate one to the left
       \       # Discard the top of the stack
        »      # Join the stack by newlines
         .B    # Pad with spaces into a rectangle
           ∞   # Mirror the string

```

# Answer
> 4 votes
# Jelly, 16 bytes

```
J’ɓ⁹⁶ẋ;"ṙz⁶Zm€0Y

```

Try it online!

Of course, -1 using Jonathan Allan's `ɓ`!

# Answer
> 4 votes
# Python 3, 85 bytes

```
x=input()
l=len(x)
for i in range(l):y=x[i:]+x[:i];print(' '*i+y+'  '*(l+~i)+y[::-1])

```

Try it online!

-1 byte thanks to ovs
-1 byte thanks to Lynn
-4 bytes thanks to p1131

# Answer
> 3 votes
# Retina, 47 bytes

```
.
$.`$* $&$'$`$.'$* ¶
%(`^
$_¶
O$^`.(?=.*$)

¶

```

Try it online! Explanation: The first stage creates the left stairway by considering each character and creating spaces equal to the current position, then the remainder of the string, then the start of the string, then spaces equal to the remainder of the string. The rest of the script runs over each line just generated in turn. First the line is duplicated, then the characters in the duplicate are reversed, then the line and its duplicate are concatenated.

# Answer
> 3 votes
# , 27 bytes

```
[:(,.|.)i.@#(|.,~' '#~[)"{]

```

Try it online!

# Answer
> 2 votes
# Charcoal, 23 21 20 bytes

```
ＦＬθ«ＦＬθ§θ⁺κι↘ＭＬθ←»‖Ｃ

```

Try it online!

Can probably be golfed more, but I'm posting from the mobile app. Link to the verbose version.

# Answer
> 2 votes
# C (gcc), 126 bytes

```
i,j,k,l;f(char*s){for(l=strlen(s),i=0;i<l;i++,puts(""))for(j=0;j<4*l-2;j++,putchar(i<=k&k<i+l?s[k%l]:32))k=j<2*l-1?j:4*l-3-j;}

```

Try it online!

# Answer
> 2 votes
## Haskell, ~~80~~ 79 bytes

```
(s:u)#t|q<-(t>>" ")++s:u++t++(u>>" ")=q++reverse q++'\n':u#(t++[s])
u#_=u
(#"")

```

Try it online!

How it works

```
(#"")                      -- start with the input string and an empty accumulator

(s:u)#t                    -- let s be the first char and u the rest of the input
                           -- string, and t the accumulator
    |q<-                   -- let q be half of the current line, i.e.
        (t>>" ")++         --   length of t times spaces
        s:u++              --   s and u (aka the input string)
        t++                --   the accumulator
        (u>>" ")           --   length of u times spaces
    = q ++ reverse q ++    -- the current line is q and q reversed
        '\n' :             -- and a newline
        u#(t++[s])         -- and a recursive call with u as the new input
                           -- string and s put at the end of t
_#_=[]                     -- base case: stop if the input string is empty

```

Edit: Thanks to @Ørjan Johansen for a byte.

# Answer
> 2 votes
# Vyxal, ~~26 24 23~~ 20 bytes

```
L(DL‹n-ð$*+mðn*$+,1Ǔ

```

Try it Online!

Thanks to lyxal for -3 bytes

# Answer
> 1 votes
# Pyth, 19 bytes

```
jms_BdC.tm+*d;.<QdU

```

Try it online!

# Answer
> 1 votes
# Japt, 22 bytes

```

l
VÇç +UéZn)+´Vç)ê1Ã·

```

Leading newline is part of the program.

Try it online!

Run all test cases using my WIP CodePen.

## Explanation

Implicit: `U` = input string. First line is blank to not overwrite `U`.

Second line implicitly assigns the length (`l`) of `U` to `V`.

Third line:

```
VÇç +UéZn)+´Vç)ê1Ã·
VoZ{Zç +UéZn)+--Vç)ê1} · Ungolfed
VoZ{                 }   Create array [0, V) and map by...
    Zç                      The current value (Z) times " "
       +UéZn)               Concatenated with U rotated Z times left
             +--Vç)         Concatenated with --V times " ". This decrements V
                   ê1       Palindromize with repeated last char
                       · Join with newlines and implicitly output

```

# Answer
> 1 votes
# Python 2, ~~85~~ 83 bytes

* Thanks @ovs for 2 bytes: `l+~i` and helped me spot a unwanted space

```
x=input()
l=len(x)
for i in range(l):r=i*' '+x[i:]+x[:i]+(l+~i)*' ';print r+r[::-1]

```

Try it online!

# Answer
> 1 votes
# Mathematica, 119 bytes

```
b=StringRotateLeft;j=Table;Column@j[""<>{" "~j~i,b[s=#,i],j["  ",t-i],b[StringReverse@s,-i]},{i,0,t=StringLength@#-1}]&

```

# Answer
> 1 votes
# PHP, 95 bytes

```
for($e=strlen($s=$argn);$i<$e;$s.=$s[$i],$s[$i++]=" ")echo$t=str_pad($s,2*$e-1),strrev($t),"
";

```

Run as pipe with `-nR` or try it online.

**breakdown**

```
for($e=strlen($s=$argn);    # import input
    $i<$e;                  # loop length times
    $s.=$s[$i],                 # 2. append current character
    $s[$i++]=" ")               # 3. set current character to space
    echo$t=str_pad($s,2*$e-1),  # 1. print string padded with length-1 spaces
        strrev($t),             #    print reverse
        "\n";                   #    print newline

```

# Answer
> 1 votes
# Pyth, 20 bytes

```
jms_B.>+.<Qd*\ tlQdl

```

Try it online!

# Answer
> 1 votes
# 8th, ~~173~~ 168 bytes

**Code**

```
s:len n:1- ( >r dup s:len n:1- "" ( " " s:+ ) rot times dup 0 r@ s:slice -rot r> -1 s:slice s:+ s:+ dup s:rev swap . . cr null s:/ a:shift a:push "" a:join ) 0 rot loop

```

**Ungolfed version with comments**

```
: shifter \ s -- s
  null s:/     \ convert string into array
  a:shift      \ remove the first item in the array and put it on TOS
  a:push       \ append the former 1st item to array
  "" a:join    \ convert array into string
;

: stairway \ s -- s
  s:len n:1-
  (
    >r                       \ save loop index
    dup                      \ duplicate input string
    s:len n:1-               \ get string length
    "" ( " " s:+ ) rot times \ make filler
    dup                      \ duplicate filler
    0 r@ s:slice             \ make left filler
    -rot                     \ put left filler at proper position
    r> -1 s:slice            \ make right filler
    s:+ s:+                  \ build string ( 1st half of stairway )
    dup s:rev                \ build 2nd half
    swap . . cr              \ print it
    shifter                  \ shift rotate 1st character
  ) 0 rot loop               \ loop from 0 to len(string)-1
;

```

**Usage and examples**

```
ok> "abcd" s:len n:1- ( >r dup s:len n:1- "" ( " " s:+ ) rot times dup 0 r@ s:slice -rot r> -1 s:slice s:+ s:+ dup s:rev swap . . cr null s:/ a:shift a:push "" a:join ) 0 rot loop
abcd      dcba
 bcda    adcb
  cdab  badc
   dabccbad

```

Or more clearly

```
ok> "Code golf" stairway
Code golf                flog edoC
 ode golfC              Cflog edo
  de golfCo            oCflog ed
   e golfCod          doCflog e
     golfCode        edoCflog
     golfCode        edoCflog
      olfCode g    g edoCflo
       lfCode go  og edoCfl
        fCode gollog edoCf

```

# Answer
> 1 votes
# Javascript (ES6), 118 bytes

```
s=>[...s].map((_,y)=>Array(l=(j=s.length)*4-2).fill().map((_,x)=>(x=x<l/2?x:l-x-1)>=y&y+j>x?s[x%j]:" ").join``).join`
`

```

Example code snippet:

```
f=
s=>[...s].map((_,y)=>Array(l=(j=s.length)*4-2).fill().map((_,x)=>(x=x<l/2?x:l-x-1)>=y&y+j>x?s[x%j]:" ").join``).join`
`
o.innerText=f("Code golf")
```

```
<pre id=o>
```

# Answer
> 1 votes
# APL (Dyalog Unicode), 29 bytes

```
{w←⍵⋄(⊢,⌽)↑{(-⍵+⍴w)↑⍵⌽w}¨⍳⍴⍵}

```

Try it online!

## Explanation

```
{w←⍵⋄(⊢,⌽)↑{(-⍵+⍴w)↑⍵⌽w}¨⍳⍴⍵} ⍵ → input
 w←⍵                          assign original input to w
                         ⍳⍴⍵  range from 0 to length of ⍵
           {           }¨     map range to function, loop var i
                    ⍵⌽w       input rotated i characters
            (-⍵+⍴w)           i + length of input, negated
                   ↑          take that much from the rotated string
                              (prepends spaces)
          ↑                   mix the array to create one side of the pattern
     (⊢,⌽)                    append the reverse of the matrix to itself

```

# Answer
> 1 votes
# Perl 5 \+ `-lF -M5.10.0`, 57 bytes

```
@F=@F[1..$#F,!say$"x$-,@F,"  "x($#F-$-++),reverse@F]for@F

```

Try it online!

## Explanation

Using `-F` (specifying the `-F` switch without an argument, `-F` controls how a string is split into `@F`) the input is split into a list of singular chars. `for` each char in `@F`, `@F` is then set to the slice of index `1` to `$#F` (which is the last index in `@F`) followed by the item at index `!say...` which equates to `0`. The effectively shifts the list content backwards by one index each iteration. `say` is called within the indexing operation to produce the output before the list is re-indexed and is provided with `$"x$-` (`$-`, which is a special int only variable that is preinitialised to `0`, copies of `$"`, which is the special list separator variable, preinitialised to space) followed by `@F`, followed by `" "x($#F-$-++)` (two spaces repeated by the final index of `@F` with the current value of `$-` times - `$-` is post-incremented here so will increase on the next iteration), finally followed by the `reverse` of `@F`.

# Answer
> 1 votes
# Python 2, 82 bytes

```
x=input()
i=l=-len(x)
while i:s=x[i:]+x[:i];i+=1;print' '*(~l+i)+s+'  '*-i+s[::-1]

```

Try it online!

# Answer
> 1 votes
# Pip `-l`, 21 bytes

```
aMERF:sX#aRA_a@Y_+,#a

```

Try it online!

### Explanation

```
                       a is command-line argument; s is space (implicit)
aME                    Map this function to each number in 0 .. len(a)-1:
                  ,#a   Range(len(a))
                _+      Add the function's argument: Range(_, _+len(a))
               Y        Yank that range (just to get the precedence right)
             a@         Use the range as the (modular) indices to slice into the string
      sX#a              Get a string of spaces of the same length as the input string
          RA_           Replace the space at index _ with the slice calculated above
   RF:                  Reflect the string, appending its reverse to it
                       Output the result list one item per line (-l flag)

```

# Answer
> 0 votes
# Japt `-R`, 15 bytes

```
¬£éYn)iYçÃú mê1

```

Try it

```
¬£éYn)iYçÃú mê1     :Implicit input of string U
¬                   :Split
 £                  :Map each character at 0-based index Y
  é                 :  Rotate U right
   Yn               :    -Y times
     )              :  End rotate
      i             :  Prepend
       Yç           :    Space repeated Y times
         Ã          :End map
          ú         :Right pad with spaces to the length of the longest
            m       :Map
             ê1     :  Mirror
                    :Implicit output joined with newlines

```

---
Tags: code-golf, ascii-art
---


title: Couch 2048: How much more till 2048?

text:
# Question
Title: Couch 2048: How much more till 2048?
I have just tried a game called Couch 2048.
(Note: You should have a look to better understand this question.)
Since it wasn't very exciting for me, I've been asking myself *'How much more till 2048!?'*
That inspired me to post a challenge, because calculating this in not as easy as I thought.

**Your goal:**
Given a list of balls on the sofa, you have to output how many balls with a value of 2 have to fall from the sky so that one can win the game (by reaching the 2048 ball).

* Assume the input is valid.
* Assume the player won't drop any balls.
* Assume the balls which fall from the sky always have a value of 2, as I've said.
* Valid output examples: 3, "4", \[5\], \["6"\]

**Edit:**
I should clarify something:
\- You have to print the *smallest* amount of 2s needed.

**Test cases:**
`[2048] -> 0` You've already won
`[1024,1024] -> 0` You don't need any more balls to win
`[1024,512,256,128,64,32,16,8,4,2] -> 1` One ball required to *'activate the chain'*
`[512] -> 768`
`[512,2] -> 767`
`[4,16,64] -> 982`

**Notes**:
I'm not a native speaker - Tell me if you spotted a typo or some non-grammatical text.
If something's unclear, ask in comments.

# Answer
> 11 votes
# Java 8, 17 bytes

```
s->1024-s.sum()/2

```

Port of *@LuisFelipeDeJesusMunoz*' JavaScript answer.

Try it online.

**Explanation:**

```
s->           // Method with IntStream parameter and int return-type
  1024-       //  Return 1024, minus:
   s.sum()    //   The sum of the input-IntStream
          /2  //   Divided by 2

```

# Answer
> 8 votes
# Brain-Flak, 72 bytes

```
({{}})({<({}[()()])>()}{})([{}]((((((((()()()()){}){}){}){}){}){}){}){})

```

Try it online!

```
({{}})                     # Sum entire stack
      (                  ) # Push:
       {<          >()}{}  #   The number of times you can...
         ({}[()()])        #   Subtract 2 before reaching 0

([{}]                                        ) # Subtract that from...
     ((((((((()()()()){}){}){}){}){}){}){}){}  # 1024

```

# Answer
> 6 votes
# Python 2, 22 bytes

```
lambda x:4**5-sum(x)/2

```

Y'know, I *just* realized that `4**5` is the same length as `1024`.

Try it online!

# Answer
> 6 votes
# MathGolf, ~~6~~ 5 bytes

```
Σc/◘+

```

First MathGolf answer. :)

Try it online or verify all test cases.

**Explanation:**

```
Σ         # Sum of the (implicit) input-list
 c/       # Divide it by -2
   ◘+     # Add 1024 to it (and output implicitly)

```

# Answer
> 5 votes
# 05AB1E, 5 bytes

```
O;žBα

```

Port of *@LuisFelipeDeJesusMunoz*' JavaScript answer.

Try it online or verify all test cases.

**Explanation:**

```
O        # Sum of the (implicit) input-list
 ;       # Halved
  žB     # Push 1024
    α    # Absolute difference between the two (and output implicitly)

```

# Answer
> 3 votes
# JavaScript (Node.js), 25 bytes

Based on @Shaggys' comment and answer

*-3 bytes from @Arnauld =D*

```
_=>1024-eval(_.join`+`)/2

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), 10 bytes

```
2÷⍨2048-+/

```

Try it online!

# Answer
> 2 votes
# , 10 bytes

```
2048-:@-+/

```

Try it online!

## Alternative:

# , 10 bytes

```
1024-1#.-:

```

Try it online!

# Answer
> 2 votes
# Ruby, 17 bytes

```
->l{1024-l.sum/2}

```

Try it online!

# Answer
> 2 votes
# Catholicon, 5 bytes

```
-`L̇½Ṗ

```

Explanation:

```
-      subtract
 `L̇    1024
       from
   ½   half of the
    Ṗ  sum [of the input]

```

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

```
4^5-.5sum(Ans

```

# Answer
> 1 votes
# Japt, ~~7~~ 6 bytes

```
xz nH²

```

Try it or verify all test cases

```
 z         :(Floor) divide each by 2
x          :Reduce by addition
   n       :Subtract from
    H      : 32
     ²     : Squared

```

# Answer
> 1 votes
# JavaScript, 28 bytes

```
a=>a.map(n=>x-=n/2,x=1024)|x

```

Try it online

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

```
HSạ⁽¡ç

```

Try it online!

**Explanation:**

```
HSạ⁽¡ç    Example input: [4,16,64]
H         Halve input. [2, 8, 32]
 S        Sum. 42
   ⁽¡ç    Number 1024.
  ạ       Difference. 982

```

<sub> -1 byte by using a base-250 number</sub>

# Answer
> 1 votes
# perl -aE, 27 bytes

```
$"=$:;say eval"(2048-@F)/2"

```

This reads a line with numbers (whitespace separated) from `STDIN`, and writes the answer to `STDOUT`.

What it does is subtract all the numbers from the input from 2048, and it divides the remainder by 2. The `-a` switch puts the in the array `@F` (one number per element). If we interpolate an array into a string (which is what we are doing here), perl puts the value of `$"` between the elements. The little used variable `$:` is be default `\n-`; and since white space between tokens is ignored, the result is subtracting all the numbers from 2048. The `eval` does the calculation.

# Answer
> 1 votes
# Vyxal, 5 bytes

```
∑k¦ε½

```

Try it Online!

```
∑     # Sum
 k¦   # 2048
   ε  # Abs. diff.
    ½ # halved

```

# Answer
> 0 votes
# JavaScript (Node.js), 33 bytes

```
a=>!a.map(n=>x-=n/2,x=1024)>x?0:x

```

Try it online!

Why you don't do on `[1024,1024,1024]`?

# Answer
> 0 votes
# , 17 bytes

```
4^5-sum(scan())/2

```

Try it online!

# Answer
> 0 votes
# TeaScript, 11 bytes

```
4p5)-(xx)/2

```

Try it online!

# Answer
> 0 votes
# Stax, 6 bytes

```
ë3i─♠÷

```

Run and debug it

# Answer
> 0 votes
# Perl 6, 12 bytes

```
1024-*.sum/2

```

Try it online!

Anonymous Whatever lambda that takes a list and returns a number.

# Answer
> 0 votes
# AWK, 26 bytes

```
{s+=$1}END{print 1024-s/2}

```

Input numbers are separated by newlines (i.e. one per line)

# Answer
> 0 votes
# Neim, 6 bytes

Pretty new to Neim but got it working

```
ᚺςᚫᛦ

```

Explanation:

```
           : Sum input
   ᚺ        : Divide by 2 (stack now [input summed and divided by 2])
    ς       : Variable set to 16 pushed to stack
     ᚫ      : Multiply by 2
      ᛦ     : Square (stack now [input summed and divided by 2, 1024])
           : Subtract then absolute

```

Try it online!

# Answer
> 0 votes
**JAVA, 30 bytes**

```
2048-IntStream.of(a).sum()/2;

```

# Answer
> 0 votes
# RAD, 10 bytes

```
1024-+/ω÷2

```

Try it online!

# Answer
> 0 votes
# Clojure, 24 bytes

```
#(- 1024(/(apply + %)2))

```

Try it online!

# Answer
> 0 votes
# Haskell, 16 bytes

```
(1024-).(/2).sum

```

An anonymous function, takes a list and returns a float.

Try it online!

# Answer
> 0 votes
# F#, 24 bytes

```
fun f->1024-List.sum f/2

```

1024 minus the sum divided by 2.

---
Tags: code-golf
---


title: Implement cowsay

text:
# Question
Title: Implement cowsay
# Introduction

`cowsay` is a Unix command made by Tony Monroe, written in Perl. It outputs a picture of a cow saying given text. For example:

```
 ________________________
< Typical cowsay output! >
 ------------------------
       \   ^__^
        \  (oo)\_______
           (__)\       )\/\
               ||----w |
               ||     ||

```

# Challenge

Given a multiline string as input, output a cow saying the inputted string.

The output is made like so:

* Start with one space
* Append the length of the longest line of the input plus \\$2\\$ underscores
* Append a newline
* Append a `<` if the input is a single line, else append a `/`
* Append a space
* Append the first line of input
* Append the length of the longest line, minus the length of the current line, plus \\$1\\$, spaces
* Append a `>` if the input is a single line, else append a `\`
* Append a newline
* While there are still lines left in the input:
    + Append a `\` if this is the last line, else append a `|`
    + Append a space
    + Append the current line of input
    + Append the length of the longest line, minus the length of the current line, plus \\$1\\$, spaces
    + Append a `/` if this is the last line, else append a `|`
    + Append a newline
* Append a space
* Append the length of the longest line of the input plus \\$2\\$ hyphens
* Append a newline
* Append the cow and speech bubble line:

```
       \   ^__^
        \  (oo)\_______
           (__)\       )\/\
               ||----w |
               ||     ||

```

# Test cases

```
Input

...becomes...

Output
====================
Typical cowsay output!

...becomes...

 ________________________
< Typical cowsay output! >
 ------------------------
       \   ^__^
        \  (oo)\_______
           (__)\       )\/\
               ||----w |
               ||     ||
====================
Two
Lines

...becomes...

 _______
/ Two   \
\ Lines /
 -------
       \   ^__^
        \  (oo)\_______
           (__)\       )\/\
               ||----w |
               ||     ||
====================
This is the first line of input.
This is the second line. It is the longest, so the bubble should stretch to fit it.
This is the third line.
Hello world!
(;;"''{<<['"

Empty lines shouldn't cause any problems.

...becomes...

 _____________________________________________________________________________________
/ This is the first line of input.                                                    \
| This is the second line. It is the longest, so the bubble should stretch to fit it. |
| This is the third line.                                                             |
| Hello world!                                                                        |
| (;;"''{<<['"                                                                        |
|                                                                                |
|                                                                                |
|                                                                                |
\ Empty lines shouldn't cause any problems.                                           /
 -------------------------------------------------------------------------------------
       \   ^__^
        \  (oo)\_______
           (__)\       )\/\
               ||----w |
               ||     ||

```

# Rules

* Standard loopholes are forbidden.
* Any amount of trailing whitespace is allowed on any line. Trailing newlines are also allowed.
* If possible, please link to an online interpreter (e.g. TIO) to run your program on.
* Please explain your answer. This is not necessary, but it makes it easier for others to understand.
* Languages newer than the question are allowed. This means you could create your own language where it would be trivial to do this, but don't expect any upvotes.
* You may assume only printable ASCII is given as input.
* Please, don't submit `cowsay` in Bash. It's boring and you'll lose rep quickly.
* This is , so shortest code in bytes wins!

# Reference implementation

# Note

The cow is one space too close to the left, but I've kept it this way so people don't need to update their answers. But I will accept the correct version.

# Answer
# Canvas, ~~92~~ ~~87~~ ~~86~~ ~~83~~ ~~81~~ 80 bytes

```
ｌ╷？/ω┤|＊\∔∔］<｝ ＋↔ω┘＋×Ｌ┤_×α-×└∔∔ｒ ７×“;ｙB¾‾≡＊ｈsＮMｎJS=ｆ≤）ｇ＜◂ＡX↓ＺxＬh？╷r┌╴\⁵n╪.cE＾‟＋∔

```

Try it here!

Takes input surrounded by `````.
> 4 votes

# Answer
# Charcoal, 95 bytes

```
≔⌈Ｅ⪪θ¶⁺²ＬιηＰ×_ηＭ↙ＥＩ⁺²Ｘχ№θ¶§|/\<Ｉι η‖ＢＯηＭ⁷¦¹↘²Ｍ²↗”{‴ＪＣεχ(J7ＷＳ⊙u#←Ｌ⌈η‽=Ykc8¿№➙Q⎚⊗\`ê:ＶI✂e≡8s”Ｊ¹¦¹θ

```

Try it online! Link is to verbose version of code. Note that multiline input with empty lines is an awkward input format for Charcoal, so you'll have to use Pythonic format. Explanation:

```
≔⌈Ｅ⪪θ¶⁺²Ｌιη

```

Find out the length of the longest line in the text.

```
Ｐ×_ηＭ↙

```

Print the top row of underscores, then move down and left so that the next output appears to the left of the underscores.

```
ＥＩ⁺²Ｘχ№θ¶§|/\<Ｉι

```

Print the left-hand side of the speech bubble. Each row is coded according to whether it is the first (+1) or last (+2) row, with a row that is both first and last therefore having a value of 3, which is then indexed to find the appropriate character.

```
 η

```

Print the row of dashes aligned with the underscores.

```
‖ＢＯη

```

Reflect the left side to complete the speech bubble.

```
Ｍ⁷¦¹↘²Ｍ²↗

```

Print the diagonal line joining the speech bubble to the cow.

```
”{‴ＪＣεχ(J7ＷＳ⊙u#←Ｌ⌈η‽=Ykc8¿№➙Q⎚⊗\`ê:ＶI✂e≡8s”

```

Print the cow as a compressed string.

```
Ｊ¹¦¹θ

```

Jump back to the bubble to print the input text.
> 11 votes

# Answer
# Python 2, 249 bytes

*-1 byte thanks to @ovs*
*-3 bytes thanks to @Jonathan Allan*

A relatively straight-forward implementation. One thing to note is that the cow contains a lot of spaces, which allows us to save a couple bytes by using `replace`.

```
s=input().split('\n')
m=max(map(len,s))+2
l=len(s)-2
z=-l*'<>'or'/\\'+'||'*l+'\/'
print'','_'*m
for c in s+['-'*m,'''? \   ^__^
?   \  (oo)\_______
?? (__)\?  )\/\\
???||----w |
???||?||'''.replace('?',' '*5)]:print z[:1],c.ljust(m-2),z[1:2];z=z[2:]

```

Try it online!
> 11 votes

# Answer
# 05AB1E, ~~116~~ ~~112~~ 105 bytes

-7 bytes thanks to Kevin Cruijssen!

```
.BDgi„><€S`ëDgÍ'|и'\š'/ªÂ}Š)ø¬Jg'_×ðìš¬¤'-:ª•˜©ã€õĆWõ½*¸cÀΓý¼oº₁%<Yë;Gá“•" \^_
(o)/|-w"ÅвJ¶¡•–ãö•28вjÅ\«»

```

Try it online!

**Speech bubble:**

```
                           # add sides:
.B                         # Squarify: split input by newlines and pad each line to the same length with spaces
  Dg                       # duplicate the list and get the number of lines
    i                      # if this equals 1:
     „><€S`                #   push [">"] and ["<"]
                           #   stack layout: ["Single line"], [">"], ["<"]
    ë                      # else (more than one line of input):
     DgÍ                   #   number of lines - 2
        '|и                #   repeat "|" this many times in a list
           '\š'/ª          #   prepend "\" and append "/"
                           #   the list is now ["\", "|", ..., "|", "/"]
                 Â         #   keep this list and push the reverse
                           #   stack layout: ["multi-line", ..., "input"], ["\", "|", ..., "|", "/"], ["/", "|", ..., "|", "\"]

                           # add top and bottom:
Š)ø                        # triple-swap, wrap stack into a list and transpose to assemble the lines
   ¬Jg                     # get the length of the first complete line (without the spaces)
      '_×                  # create a string of this many "_"
         ðì                # prepend a space
           š¬              # prepend this string to the list of lines
             ¤'-:          # push another copy of the "_" string and replace "_" with "-"
                 ª         # append to the list of lines

```

**Cow:**

```
•˜...á“•" \^_\n(o)/|-w"ÅвJ # base-compressed cow without leading spaces
•–ãö•28в                   # compressed list of line lengths: [15, 23, 27, 24, 24]
        jÅ\                # pad each line to desired length with spaces in the front
           «»              # concatenate the cow lines to the other lines and join the lines by newlines

```
> 6 votes

# Answer
# Jelly, 117 bytes

```
L⁾||ẋṫ5“/\“\/”jµ⁾<>Ḋ?⁶ẋ4¤s2¤js1s2
j@€⁾  z⁶⁾_-jⱮZj@"Ç;“¡{+Ṁ“#ßɗ⁾ŀ`m“¬ṖȥƇʂẆEẒẓ“¡ɲÇ⁹E⁸ċ⁷“¡ɲÇ⁹D⁹{Ṅ’ṃ“\ ^_(o)/|-w”¤⁶;$8¡€¤

```

Try it online!

-26 bytes using base + integer compression (thanks to Bubbler for the idea)
-2 bytes thanks to caird coinheringaahing
-1 byte thanks to Nick Kennedy
thanks to Jonathan Allan for finding a bug; also -4 bytes from fixing it
-1 byte thanks to Jonathan Allan

## Explanation

```
L⁾||ẋṫ5“/\“\/”jµ⁾<>Ḋ?⁶ẋ4¤s2¤js1s2  Helper Link - generates the side borders
                    ?              If
                   Ḋ               list[1:] (basically, if the length is not 1)
L⁾||ẋṫ5“/\“\/”jµ                   Sublink; generate the side borders for the non-edge case
L                                  Take the length
 ⁾||ẋ                              Repeat "||" that many times
     ṫ5                            Tail; remove the first 4 elements
       “/\“\/”j                    Use that result to join ["/\", "\/"]
                ⁾<>                Otherwise, return "<>"
                     ⁶ẋ4¤          " " * 4
                         s2¤       split into slices of size 2
                            j      Prepend and append (Extra spaces are needed because the top and bottom borders don't have side borders)
                             s2    Slices of length 2 (separate the left and right border components)
                               s2  Slices of length 2 (group the left and right border components into pairs)

j@€⁾  z⁶⁾_-jⱮZj@"Ç;“...’ṃ“ \_(o)/|-w^”¤⁶;$8¡€¤     Main Link
j@€⁾                                               join "  " with each row (surround in spaces)
      z⁶                                           Zip, using space as filler
            Ɱ                                      For each column
        ⁾_-j                                       Join ["_", "-"] using it (prepend _ and append -)
             Z                                     Zip
              j@"Ç                                 Vectorized swapped join with the helper link (basically, for each row, prepend and append the borders)
                  ;                                Append: {{
                   “...’                           [23386201, 8811166311836860, 134563374682941922730, 101089407352370886, 101089407336781202]
                        ṃ“ \_(o)/|-w^”             Base decompressed with " \_(o)/|-w^" - this is the cow without leading spaces
                                            €      For each row
                                       ⁶;$         Prepend " "
                                          8¡       8 times
                                             ¤     }}

```
> 5 votes

# Answer
# JavaScript, ~~342~~ ~~299~~ 307 bytes

```
n=>[' '+'_'.repeat(e=Math.max(...(s=n.split`
`).map(l=>l.length))+2),...s.map((i,l,_,x=i.padEnd(e-1))=>1 in s?l?l>s.length-2?`\\ ${x}/`:`| ${x}|`:`/ ${x}\\`:`< ${x}>`),' '+'-'.repeat(e),''].join`
`+[(n='       ')+"\\   ^__^"," \\  (oo)_______",`    (__)${n})\\/\\`,n+` ||----w |`,n+" ||     ||"].join(`
`+n)

```

Try it online.

# Explanation

This builds an array of strings which are joined with a newline.

## What each element does

* element 1: underscore string
* next few elements: each line of the inputted string with the added limiters
* next element: hyphen string
* then, add the cow string.

*-43 bytes thanks to A username*

*+8 bytes due to empty line bug*
> 5 votes

# Answer
# JavaScript (ES8),  ~~266~~  252 bytes

```
s=>` _2
 3
 -2
 5\\ 1^__^
 10\\  (oo)\\_5
 9(__)\\ 5)\\/\\
 13||-6w |
 13|| 7||`.replace(/.(\d+)/g,(s,n)=>n^3?s[i=0].repeat(n^2||w):a.map(s=>'|\\/<'[j=!i++*2|!a[i]]+s.padEnd(w)+'|/\\>'[j]).join`
`,a=s.split`
`.map(w=s=>` ${w>(v=s.length+2)?0:w=v,s} `))

```

Try it online!

### How?

We first split the input string into lines surrounded with 2 spaces and compute the width `w` of the biggest line (including said spaces):

```
a = s.split`\n`.map(w = s => ` ${w > (v = s.length + 2) ? 0 : w = v, s} `)

```

Each number `n` in the template string is interpreted as follows:

* `2`: repeat the preceding character `w` times (for the top and bottom borders of the text bubble)
* `3`: insert the text bubble:

```
a.map(s =>
  '|\\/<'[j = !i++ * 2 | !a[i]] +
  s.padEnd(w) +
  '|/\\>'[j]
)
.join`\n`

```
* anything else: repeat the preceding character `n XOR 2` times
> 3 votes

# Answer
# Jelly, 106 bytes

```
“¢Ʋėỵ“Œ\ė#İ²¿“¤e+ṂTƒƑ¶d“Ṫ©Ḋ9çṀṠ“Ṫ©Ḋ87⁹Ġ’ṃ“ \_)o|w-^/(”⁶;$8¡€
Ø^⁾><Ṗ?WẋLU0¦”|JṖḊƊ¦⁾  ©jṁ€2ɓ®jⱮz⁶⁾_-jⱮZj@";¢

```

A monadic Link that accepts a list of the lines and yields a list of lines. (Gives eight spaces before the cow, for seven change `8¡€` to `7¡€`)

**Try it online!**

### How?

```
Ø^⁾><Ṗ?WẋLU0¦”|JṖḊƊ¦⁾  ©jṁ€2ɓ®jⱮz⁶⁾_-jⱮZj@";¢ - Main Link: list, Lines
     Ṗ?                                       - if popped (Lines)? (i.e. > 1 line?):
Ø^                                            -    then: "/\"
  ⁾><                                         -    else: "><"
       W                                      - wrap (that) in a list, say "Corners"
         L                                    - length (of Lines)
        ẋ                                     - repeat (Corners that many times)
           0¦                                 - apply to rightmost:
          U                                   -   upend (reverse to "<>" or "\/")
                  Ɗ¦                          - apply to indices...
               J                              -   range of length (of Lines)
                Ṗ                             -   pop
                 Ḋ                            -   dequeue
             ”|                               - ... '|' (replaces all but first and last)
                    ⁾..                       - "  "
                       ©                      - (copy this to the register)
                        j                     - join
                         ṁ€2                  - mould each like 2 ("||" and "  " as needed)
                            ɓ                 - new dyadic chain - f(Lines,Edges=that)
                             ®                - recall from register -> "  "
                              jⱮ              - map (across Lines) with join
                                z⁶            - transpose with space as filler
                                  ⁾_-         - "_-"
                                     jⱮ       - map (across these columns) with join
                                       Z      - transpose (back to rows)
                                         @"   - zip with, with swapped arguments:
                                        j     -   (Edge-pair) join (Row)
                                            ¢ - call last Link as a nilad -> cow lines
                                           ;  - concatenate

“...’ṃ“ \_)o|w-^/(”⁶;$8¡€ - Link 1, Get cow lines: no arguments
“...’                     - list of integers (one per line of the cow)
      “ \_)o|w-^/(”       - " \_)o|w-^/(" (the cow's constituents)
     ṃ                    - base decompress
                        € - for each:
                      8¡  -   repeat this eight times:
                     $    -     last two links as a monad:
                   ⁶      -       ' '
                    ;     -       concatenate

```
> 3 votes

# Answer
# JavaScript (V8), ~~380~~ ~~354~~ 329 bytes

*-25 thanks to @A username*

```
t=>` ${"_".repeat(m=Math.max(...(l=t.split`
`).map(d=>d.length)))}__
${"/<"[j=+!l[1]]} ${l.shift().padEnd(m)} ${"\\>"[j]}
${j?'':l.map(d=>"|\\"[w=+!l[++j]]+' '+d.padEnd(m)+' '+"|/"[w]).join`
`+`
`} `+"-".repeat(m+2)+`
\\   ^__^
 \\  (oo)\\_______
    (__)\\${n='       '})\\/\\
 ${n}||----w |
 ${n}||     ||`.replace(/\n/g,`
`+n)

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 155 bytes

```
¶¡©éθgUð'_XÌ×¶®gΘ„/<èð®нðX®нg->×®gΘ„\>è¶[®¦©gĀ_#®gΘ„|\èð®нðX®нg->×®gΘ„|/è¶}ð'-XÌ×¶•1rΛKιØ²è{Ê¯4Þ₁ÐÃ5Λ^ÛиÏú!j™¨õ‰6æ≠ÓÍl¼ûÑ©kθJ*
Rèªùî¾&Σp•"\ ^_
(o)/|-w"ÅвJJ

```

Try it online!
> 2 votes

# Answer
# Retina, ~~156~~ 144 bytes

```
mP`^.*
¶
 \¶\
1,-2%`^.|.$
|
^
 $.%'*_¶/
$
 /¶ $.%`*-
¶/(.+)/¶
__¶<$1>¶
$
¶7* \   ^__^¶8* \  (oo)\7*_¶11* (__)\7* )\/\¶15* ||4*-w |¶15* ||5* ||

```

Try it online! Explanation:

```
mP`^.*

```

Pad all lines to the same length.

```
¶
 \¶\

```

Add `\`s on all the intermediate lines...

```
1,-2%`^.|.$
|

```

... but fix interior lines to use `|` instead.

```
^
 $.%'*_¶/
$
 /¶ $.%`*-

```

Insert the leading row of `_`s and trailing row of `-`s, plus the `/`s at the start and end of the bubble (still assuming a multiline bubble).

```
¶/(.+)/¶
__¶<$1>¶

```

Fix up a single-line bubble, not only to change the `/`s to `<>`s, but also because not enough `_`s are calculated for the initial row.

```
$
¶7* \   ^__^¶8* \  (oo)\7*_¶11* (__)\7* )\/\¶15* ||4*-w |¶15* ||5* ||

```

Append the cow using run length encoding.
> 2 votes

# Answer
# Vyxal, a 194-byte mess

```
□⁋↵:ƛL;G:£2+\_*\ +\ $+,L1=[‛< □‛ >++,|□L(n[n›□L=[`\\ `` /`|`| `` |`]|`/ `` \\`]□ni:L¥ε\ *+$++,)]\ ¥2+\-*\ ++,`  ?\\   ^__^
   ?\\  (oo)\_______
?? (__)\\  ?)\\/\\
???||----w |
???||?||
`\?\ 5*V,

```

Try it Online!

Explanation tomorrow.
> 2 votes

# Answer
# Julia 1.0, ~~243~~ 240 bytes

```
r=readlines()[(R=end;:)]
a=' '
l=maximum(length,r)+2
println.([a*'_'^l
["|/\\<"[(j=1+(i<2)+2(i==R);)]rpad(a*r[i],l)*"|\\/>"[j] for i=1:R]
a*'-'^l
replace(raw"?  \   ^__^
?   \  (oo)\_______
?? (__)\?  )\/\
???||----w |
???||?||",'?'=>a^5)])

```

Try it online!

I was trying to compress the cow but dingledooper's trick was more efficient
> 1 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: Output "Lorem ipsum" with minimal number of characters
I remember people saying that code size should be measured in bytes, and not in characters, because it's possible to store information with weird Unicode characters, which have no visual meaning.

How bad can it be?

In this challenge, you should output the following Lorem Ipsum text, taken from Wikipedia:

```
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Please specify the number of *characters* (not bytes) in your code. Code with the minimal number of characters wins.

Your code should only contain valid Unicode characters, as described here, that is:

* Code points up to U+10FFFF
* No surrogates (the range D800–DBFF is forbidden)
* No characters FFFE and FFFF
* No null characters (code 0)

If your code cannot be displayed, provide a version with offending characters redacted, and a hexdump.

Some notes:

* The output must be one long line (445 characters). If your system cannot do that (e.g. you're printing it on paper), output a closest approximation. Trailing linebreaks don't matter.
* Built-in functions that generate Lorem Ipsum text are not allowed
* Please specify a valid text encoding for your code, if relevant

# Answer
> 8 votes
# Dyalog APL, 123 characters

All but the final period are packed into 111 32-bit characters (UTF-32).

```
'.',⍨80⎕DR''

```

`'.',⍨` period appended to

`80⎕DR` the 8-bit (`8`) character (`0`) **D**ata **R**epresentation of

`'`...`'` the 111 Unicode characters U+**26F4C 9206D D7573 C6F64 32072 12074 C7465 E6F63 46365 27574 96461 37369 10676E 4696C 57320 F6420 56965 46F6D D6574 10726F 9636E 56469 52074 16C20 5726F 107465 F6C6F D2065 16E67 96C61 E6175 107455 D696E 106461 96E69 57620 D6169 57120 E2073 27473 52064 37265 46174 106E6F 16C6C 106F63 F6261 107369 97369 107475 1696C 107069 52078 F6320 46F6D F6320 16573 E7461 97544 56120 92065 57275 C6F64 92072 57220 86572 5646E 107469 6206E 10756C 57461 C6576 52074 106573 C6C69 4206D 26F6C 56520 77566 107461 C6C75 17020 46169 102E72 56378 56574 97320 F2074 56163 107461 97075 17461 F6E20 27020 56469 102C74 46E75 106E69 106C75 57120 66F20 96369 56420 57265 D2074 96C6C E6120 9206D 36520 16C20 5726F**, which all fall in the range 12074–10756C and thus inside the OP's all-permitted range 10000–10FFFF.

# Answer
> 14 votes
# JavaScript (ES7), ~~326~~ ~~283~~ ~~273~~ ~~249~~ ~~243~~ 242 chars

```
_=>""[r='replace'](/./gu,c=>(c.codePointAt()-4**8).toString(32))[r](/\d/g,d=>"  , exum. ".substr(d,2))[r](/^.|\. ./g,x=>x.toUpperCase())

```

### How it works

The first step in my compression technique is to convert the whole string to lowercase (not mandatory, but looks better), and replace each pair of chars in `, exum.` (as well as the trailing space by itself) with its index in the string plus 2. This makes the text a valid base-32 number:

```
lorem9ips69dolor9sit9amet2consectetur9adipiscing3lit2sed9do3iusmod9tempor9incididunt9ut9labore3t9dolore9magna9aliqua8ut3nim9ad9minim9veniam2quis9nostrud94ercitation9ullamco9laboris9nisi9ut9aliquip943a9commodo9consequat8duis9aute9irure9dolor9in9reprehenderit9in9voluptate9velit3sse9cill69dolore3u9fugiat9nulla9pariatur84cepteur9sint9occaecat9cupidatat9non9proident2sunt9in9culpa9qui9officia9deserunt9mollit9anim9id3st9laboru7

```

The next step is to convert each 4-char run to decimal, then get the character at that code point. This can be done with the following function:

```
f=s=>s.replace(/..../g,x=>(n=parseInt(x,32),String.fromCharCode(0xD800+(n>>10),0xDC00+(n&0x03FF))))

```

(**Note:** Since all digits are 2 or greater, the minimum possible value of four digits is 2222₃₂. This is equal to 95978₁₀, or 176EA₁₆; therefore, code points will never be in the restricted range.)

And now we have our compressed string:

```

```

That's 445 chars compressed into 106 chars. The decompression simply reverses this process:

1. Convert each char to its code-point in base-32, minus 65536.
2. Replace each digit `n` with `" , exum. ".substr(n,2)`.
3. Convert each letter after a period or at the beginning of the string to uppercase.

The only ES7 feature used is `**`. Replace `4**8` with `65536` to run in a browser that doesn't yet support ES7.

# Answer
> 8 votes
## Javascript (ES6), ~~261~~ ~~255~~ 254 characters

*Saved 1 byte, thanks to ETHproductions*

```
_=>'L'+"⫒㠰拳␰䨒堵̎⨦W䙨ⅶ嵷˘㥆姳䗨⠬巯堡Ŋɩ懪䨶尩个˒≎㥎䜩怷㰷䤆ŵ̊㹩⫒ᨠᩌ㳠抮f̅㩊ᠰ䀩㩎搰㩊ئ抠ˮ婱拗⠩啺巨㬆ɒ㸘∦㰲䤆姵㩀Ƕ̘㨆㬴⠳⠺…䈲䥒䤠⫱᬴w㬣ᠶ⬘嗠⫘䥀噯䗠⫀⫓䕭啩̎Ɏ㹹庘⬆⭀巯奠Ŷ㷨䌯䥀噯⠪ⰸ㦸̆㼱ï哳峮૘梠䵨慷堵幎≠⣨峨愠◳ᬆ䐷ɒ䫓⥎ܑ拠̑Ɏ㼨ó㬴⹠⇫î奩拊̑㹰巯䓠ȮŎ廪ᨀ噧ਸ".replace(/./g,c=>(s=" ,.DEUabcdefghilmnopqrstuvx")[(c=c.charCodeAt()-32)&31]+s[c>>5&31]+s[c>>10])

```

### Breakdown

Payload: 148 Unicode characters
Code: 107 bytes

### How it works

We first remove the leading `'L'` from the original message so that we're left with 444 = 148 * 3 characters.

Without the leading `'L'`, the character set is made of the 27 following characters:

```
" ,.DEUabcdefghilmnopqrstuvx"

```

Each group of 3 characters is encoded as:

```
n = 32 + a + b * 32 + c * 32^2

```

where a, b and c are the indices of the characters in the above character set.

This leads to a Unicode code point in the range U+0020 to U+801F, ending somewhere in the "CJK Unified Ideographs".

```
let f =
_=>'L'+"⫒㠰拳␰䨒堵̎⨦W䙨ⅶ嵷˘㥆姳䗨⠬巯堡Ŋɩ懪䨶尩个˒≎㥎䜩怷㰷䤆ŵ̊㹩⫒ᨠᩌ㳠抮f̅㩊ᠰ䀩㩎搰㩊ئ抠ˮ婱拗⠩啺巨㬆ɒ㸘∦㰲䤆姵㩀Ƕ̘㨆㬴⠳⠺…䈲䥒䤠⫱᬴w㬣ᠶ⬘嗠⫘䥀噯䗠⫀⫓䕭啩̎Ɏ㹹庘⬆⭀巯奠Ŷ㷨䌯䥀噯⠪ⰸ㦸̆㼱ï哳峮૘梠䵨慷堵幎≠⣨峨愠◳ᬆ䐷ɒ䫓⥎ܑ拠̑Ɏ㼨ó㬴⹠⇫î奩拊̑㹰巯䓠ȮŎ廪ᨀ噧ਸ".replace(/./g,c=>(s=" ,.DEUabcdefghilmnopqrstuvx")[(c=c.charCodeAt()-32)&31]+s[c>>5&31]+s[c>>10])

console.log(f())
```

# Answer
> 8 votes
# bash + coreutils + gzip + recode, 191 characters

```
echo -ne "ᾋࠀ㰟퍗\03㖐셱䌱ࡄ戋⪒宮⦀⃬〣ख़ʏ쬏湂삲מּ浊莎ᔍ얪䴬畐Ꮏ肭⽡តप㩴뇶ᮤ樶鞔岀梬昅⹭盖ꈥ먣Ვ빓ỢꞴꃑ괓꣪㷨삗䎺뛔䛓ﵸ摉篨䊷૤⦓헉픺ꉖ橬ꟲỒꗻ퉋則ใ⢍럴摧耼⒅୴䘺㦳櫇鐱窑駁愵䚞鎴鍉Ⅻक़毽➔脂ힸ⤹喝葁㎋頇㺞ⳃ┶왤惌⒜猜䌋吏젔掚ᛩ鯢⚕䜹鴛皽⨫ꇈ銹믍䄛逦軵융杻龇븁\0"|recode u8..utf16be|tr -d ٣ܣ|gunzip

```

The string is the gzip of the text interpreted as UTF-16BE, plus a few extra bytes to pair with the unpaired surrogate halves. The tr strips off the extra surrogate halves.

This script file (or the shell into which this command is typed) should interpret text as UTF-8, which is why the recode is needed.

# Answer
> 5 votes
# PHP ,247 Characters

combination of the 2 previous versions

```
echo gzuncompress(base64_decode(mb_convert_encoding("敊眱歍䙸兺䕉剆癚䅪礯極南慷潧楏㡷䥷汚䅯⽌䐸灐扫䱁獶猫扅煄橨啎硡灎䱈噑䔷⭂牓㥨䘴㡊䭪瀰獦夷灇漲氵剣杇楳婧啵扥卹摴慩䩢潪䡊圫啨㝩氷卧ぢご煏潪㙍䍮儷焲ㅅ扔⽘桭卥㉇别桃琫啺䍵公欹塊ㅔ煩噭灳氯䥥ぱ堷ぱ⭫橨祇啂灶㙣浵䅈湋䐷硴卑潘㙉砰捭塖橩汪祲昰䥪佄㔸晔慯眸䨲歮欰䱗䕲䑗⭫㡯䅷塏畃猵⭪慅兔佌流晥塹穄䩔扇婇䑍䩊硺䡅䵌⭤㝉䙇佡䙵浢㑩慖剺湱潊ぢ摰㝋卩楹婏㕵猷灴ぁ慫楗倹捙ㄲ⽁䍧塋啊","UTF-16")));

```

PHP, 261 Characters

```
echo mb_convert_encoding("䱯牥洠楰獵洠摯汯爠獩琠慭整Ⱐ捯湳散瑥瑵爠慤楰楳捩湧汩琬⁳敤漠敩畳浯搠瑥浰潲湣楤楤畮琠畴慢潲攠整潬潲攠浡杮愠慬楱畡⸠啴湩洠慤楮業⁶敮楡洬ⁱ畩猠湯獴牵搠數敲捩瑡瑩潮⁵汬慭捯慢潲楳楳椠畴汩煵楰砠敡潭浯摯潮獥煵慴⸠䑵楳畴攠楲畲攠摯汯爠楮⁲数牥桥湤敲楴渠癯汵灴慴攠癥汩琠敳獥楬汵洠摯汯牥甠晵杩慴畬污⁰慲楡瑵爮⁅硣数瑥畲⁳楮琠潣捡散慴異楤慴慴潮⁰牯楤敮琬⁳畮琠楮畬灡ⁱ畩晦楣楡敳敲畮琠浯汬楴湩洠楤獴慢潲畭.","UTF-16");

```

Encoding $s contains the string

```
foreach(str_split(bin2hex($s),4)as $c)eval('echo"\u{'.$c.'}";');

```

Old Version PHP , 386 Bytes|Characters

```
echo gzinflate(base64_decode("NZDBcUMxCERb2QI8v4rklmsKIIjvMCMJWQKPyw/KT25CwLL7PmxKg44VDcWqTSx1UBO/ga0vYRePCSo6dLH2O6RqNpeUXIBorGYFLm3ksnbWoiW6IxyVvlIe4pe0oNG9E6jqI+jAp0O6ttRG0/14ZknthkfoQrflMwrkJZPVydU6olZqbJfyHtKl+9KvpI4chlAab+nJrgB5yg+8bUkKF+iMdHJl1Y4pY8q39CIzg+fH02qMPCdpJ5NC1hKw1vpPKAMFzrgrOfo2hEEzi5gH3l8swyU2xmRgzCSccxxDC/neyBRjmhbpm+ImlUc56qCdG3aeykoosmTubrO6bdAGpIlj/XGNdvwA"));

```

# Answer
> 5 votes
# 05AB1E, 319 bytes

Uses CP-1252 encoding.

```
•9y†QHÚSe²ŒÓdéÓ#Ç§ÖN›Íˆž4GÏóREØån‡·JîÁØ£ÎÁ¥evÑRZ¶—¥1RËÒÆzçå"UNé¨v¯ÊcŒÔÝjðtrœÛeã&“SÁxÌ4Þá1N$ù?T(çÛbŸœfó˜lUž}Þß-©ÃMšBÈÑPàê#jÇÐ+n¼BDFý>–¸äFT×›qÜY³ö9ªòËùˆA‡¾p=‘¤ÚÞ{I¶Œ±Ål#¨5´Aq˜Àž,s<*Ï;‡õã¾»ðŽL´ÅuØö+Xi+S>»/8Kã~WÎ”ƒß”¤µðWluØa'cUÐeà¥ä…ž+œ6*0RU£›aÝQ_ñœoþÏð””Þã7ã¨sŒV`_É-´éÄèÆd¦úE5Í^Aá,‘‡™™¢äTHä0¥3±.}Søg•36B0„. :™J'yð:'z',:'.«

```

**Interpret the following string as a base 36 number and encode into base 214**

```
LOREMYIPSUMYDOLORYSITYAMETZYCONSECTETURYADIPISCINGYELITZYSEDYDOYEIUSMODYTEMPORYINCIDIDUNTYUTYLABOREYETYDOLOREYMAGNAYALIQUA0UTYENIMYADYMINIMYVENIAMZYQUISYNOSTRUDYEXERCITATIONYULLAMCOYLABORISYNISIYUTYALIQUIPYEXYEAYCOMMODOYCONSEQUAT0DUISYAUTEYIRUREYDOLORYINYREPREHENDERITYINYVOLUPTATEYVELITYESSEYCILLUMYDOLOREYEUYFUGIATYNULLAYPARIATUR0EXCEPTEURYSINTYOCCAECATYCUPIDATATYNONYPROIDENTZYSUNTYINYCULPAYQUIYOFFICIAYDESERUNTYMOLLITYANIMYIDYESTYLABORUM

```

**After that we**

```
36B                      # encode back into base 36
   0„. :                 # replace 0 with ". "
        ™J               # convert to titlecase and join
          'yð:           # replace "y" with <space>
              'z',:      # replace "z" with ","
                   '.«   # add a "." at the end

```

For some reason the encoding didn't work with a 0 at the end which is why need a special case for the final ".".

Try it online!

# Answer
> 4 votes
# C#, ~~337~~ ~~333~~ 331 characters

```
_=>{var q="";foreach(var c in"潌敲彭灩畳彭潤潬彲楳彴浡瑥弬潣獮捥整畴彲摡灩獩楣杮敟楬ⱴ獟摥摟彯楥獵潭彤整灭牯楟据摩摩湵彴瑵江扡牯彥瑥摟汯牯彥慭湧彡污煩慵弮瑕敟楮彭摡浟湩浩癟湥慩Ɑ煟極彳潮瑳畲彤硥牥楣慴楴湯畟汬浡潣江扡牯獩湟獩彩瑵慟楬畱灩敟彸慥损浯潭潤损湯敳畱瑡弮畄獩慟瑵彥物牵彥潤潬彲湩牟灥敲敨摮牥瑩楟彮潶畬瑰瑡彥敶楬彴獥敳损汩畬彭潤潬敲敟彵畦楧瑡湟汵慬灟牡慩畴ⅲ䕟捸灥整牵獟湩彴捯慣捥瑡损灵摩瑡瑡湟湯灟潲摩湥ⱴ獟湵彴湩损汵慰煟極潟晦捩慩摟獥牥湵彴潭汬瑩慟楮彭摩敟瑳江扡牯浵ਡ")q=q+(char)(c&255)+(char)(c>>8);return q.Replace("!",".").Replace("_"," ");};

```

*-4 characters by replacing the `.`s after "pariatur" and "laborum" with `!` before combining the chars to wide chars and adding a trailing new line.*

*-2 characters by re-assigning the output var rather than appending with `+=`.*

How it works:

The lorem ipsum string was converted to that mess by replacing `.` with `!`,  with `_` so when the ascii chars are placed next to each other to make a wide char each wide char is a single character.

```
/*Func<object, string> Lorem = */ _=> // unused parameter
{
    // Output var
    var q = "";

    // Enumerate each wide char
    foreach (var c in "潌敲彭灩畳彭潤潬彲楳彴浡瑥弬潣獮捥整畴彲摡灩獩楣杮敟楬ⱴ獟摥摟彯楥獵潭彤整灭牯楟据摩摩湵彴瑵江扡牯彥瑥摟汯牯彥慭湧彡污煩慵弮瑕敟楮彭摡浟湩浩癟湥慩Ɑ煟極彳潮瑳畲彤硥牥楣慴楴湯畟汬浡潣江扡牯獩湟獩彩瑵慟楬畱灩敟彸慥损浯潭潤损湯敳畱瑡弮畄獩慟瑵彥物牵彥潤潬彲湩牟灥敲敨摮牥瑩楟彮潶畬瑰瑡彥敶楬彴獥敳损汩畬彭潤潬敲敟彵畦楧瑡湟汵慬灟牡慩畴ⅲ䕟捸灥整牵獟湩彴捯慣捥瑡损灵摩瑡瑡湟湯灟潲摩湥ⱴ獟湵彴湩损汵慰煟極潟晦捩慩摟獥牥湵彴潭汬瑩慟楮彭摩敟瑳江扡牯浵ਡ")
        // Split each wide char into two ascii chars
        q = q + (char)(c&255) + (char)(c>>8);

    // Restore the replaced periods and spaces
    return q.Replace("!",".").Replace("_"," ");
};

```

# Answer
> 3 votes
# ISOLADOS, 44016 bytes

http://pastebin.com/raw/Y2aAhdpi

Push the ASCII code for every character in the Lorem Ipsum string, concatenate everything, and output.

# Answer
> 2 votes
## JavaScript (ES5), 342 characters

```
c="remo ipsudlta,cngbq.UvxDhfE";"L"+"Qq©Úu[Qsx7Ķz`¾ƅ&Øxø§Ëƴ%ţ¾÷öm¿Zw¥ſøûƠtĭĚǎmĭöđnŔơxēǮŗĭ*x÷;ƚ:ȸƚņţǮ{XĩámɓŏƙâĚDUĚǎÁƚÂtĭŎÝ¦1mňŽ8ZUŽƜ-äļÝÁŌĪqu[Qqƙ¢3*ôĭ[ÞĵĪ%mÄſĘÚu[Q#èĭƝĘň®ŏØȅ˔Ż#ÂƠoƈŅƆĭƂ§ÿĵĭƘƙ¢VôƠţÅƠqƙƂĔňǮjʨſňô¾Ơn[ēĭœq÷\"ĭĚǎI".split('').map(function(x){y=x.charCodeAt(0);return c[~~(y/27)]+c[y%27]}).join('')

```

Pretty straightforward, so I'm sure there's room for improvement. I encoded every pair of output characters as a single Unicode character.

# Answer
> 2 votes
# MATL, 354 characters

```
'8 sxAI($ltZ>2<xa`vYf:s2e9]c&^KtD%e{C*XEpQ]]>dwmi>2;{sUCIZ{V(}Yj 7K&)|,%JD/Pz^:3$*@vVJw)4pgvz4s_$,%pVGu~|PS/Qr7pz5Z2[VV{Lyq}{l!yGiKNg.zFJxL75 sT1]eL2f3iVe~11!|6c+O9.kMWFQYvEp^w0p oH,?Ey"nbV>0g`#)kqTq""" z_AYmyJutvg:o9&AT{#(<42wu.b7" QoOn\#])]ISdH$yc{eM> .[~/`"#2:7C4Mk@eRW8L*_!xjo\cO)!LHK=g:P?&Uc];KdnE(%K7J-z9:7&rhxHl/KZ8\t_C|rT#%28[%+#u.?'F2Y2' ,.DEL'hZa

```

This decodes from base-94 (using the printable ASCII chars except single quote; so only Unicode characters up to 126 are used) to the alphabet of required characters, formed by most lowercase letters, some uppercase letters, space, comma, and period.

It takes a few seconds in the online compiler.

Try it online!

# Answer
> 1 votes
# Jelly, 300 chars

```
“ḊḄr⁷ƤⱮx#y&Ọ¬½ẇṾƤẋRṠỊ/IṗIÞƝỊż,CA~ñ;ßɦ4ṿḷNVẸẆ`°ṄjJ⁽Ɱ!Æḋ"uƒ⁽ƙfƈÇœƓ®ḶẓƭƊȮ⁻w}Ġṙ(1€CÐ-ɼ#ȯjėȮoZœ°ȥạ_ẊƊaʠiẸṂṪẒ$ċⱮiẹOṠBṇḲ^*GƓŒA>żıWṭƤe&ėẠF6³ṂḲzlçÇṪġṂŻỵḢ⁴WJC⁽Ỵihıỵṃ¥ẏƬEỴ⁽#ḍʠḢ*^O[4)ỵZ5VoPĠƘṙḅß]<œ/ṅẸ% ḍ"Ɱ+¢¦ß÷⁵Ḍ³Ṅ¶2X|©dċÆṁḢƭṗM°`KÇ¦ɗỤɱṆȯƘkṅbṙ⁻l<t,ḟȮạżæ€ṠṣIȥCṘƥṁ©53ẒþØŻṁ£æƥ?¬ṿFæṘ⁴nụ’ṃ“Lrem ipsudlta,cngbq.UvxDhfEo

```

Try it online!

The encoding is Jelly.

Thanks to compressed strings, I was able to compress it by 3 bytes.

# Answer
> 1 votes
# Vyxal, 279 bytes

```
«;Jq×L↑yVx₅QȯZ3ẎhȦ¼_ø€ẋ°Q±3₀₈∑hṁ₃ø∧≤∆⌐>ʀ↵₌X⇧ƒ₀₆ḃ₅Ḣ~^9\6↓¾<₆≈Q‡‟ṄBḞUß¼ƈv→⟇ʀ7ė⟑∞~*Ṅ∩ꜝtW₴h⟨p&¥z%₇Jɖ⁋¥(₂⌐⌊mṖ⅛ɾṙ3±żð→Ṙq↳'ḭguIH?TLŻrhNɾwl꘍×ByÞkĿMτI□ǑΠȧ½Ḃ≬jȦ₂ṡ⇧j…0Ȧ₂wyẆ₈≠₂d„⟨>∵↔C7⟇≠∑¤ƈƛiḃṁ₍Q]*꘍ṡḂcu%İ∑lL5∧∴!qÞLOτxÞ≥€ṅQh₅Ṫ°₄B*ṫṘ:NḊεβ⋏ṫẎFpƈc⁰ŀqẏy↓{'Ǒ£ẏŻ@kżoƛg)K1cV⌈»ΠC¼⟩F^ȯ₌«\z‛. V‛  ‛, V¡

```

Try it Online! Uses Vyxal base-255 encoding, since it can only do lowercase and space, I convert ". " to z and "," to " ", so when I decompress I can easily add back in the punctuation. Finally, it reintroduces uppercase through the sentence-case operator.

# Answer
> 1 votes
# Pip, 139 UTF-8 characters

```
"EDUL ,.".z@:^A*""TB32FB:32

```

Try it online!

### Explanation

Observe that there are 28 distinct characters in the string. We can use characters up to character code U+10FFFF = \\$1,114,111\\$, and since \\$\sqrt\[4\]{1,114,111} \approx 32 \> 28\\$, we can pack four Lorem Ipsum characters into one Unicode character. (In theory, we might run into some forbidden characters within that range. In practice, that didn't happen.)

The decoder is a little longer than it should be because Pip's builtin base conversion generates strings (e.g. `"1RFP"`) rather than lists of numbers (e.g. `[1;27;15;25]`).

```
"EDUL ,.".z@:^A*"..."TB32FB:32
                "..."           String of 112 Unicode characters
              A*                 Codepoint of each
                      TB32       Convert each to a (4-digit) base 32 number
             ^                   Split each base 32 number into a list of its digits
                          FB:32  Convert each digit from base 32 to an integer
           @:                    Use those numbers to index into
"EDUL ,.".z                      Character lookup table: "EDUL ,." plus lowercase letters

```

# Answer
> 1 votes
# 05AB1E, 126 characters

A large integer is encoded in base 1114111, which is converted to custom base `" .,a..z"` and the resulting string is converted to sentence case.

```
"૵功剗儮"ÇćβA… .,ìÅвJ‡.ª

```

Try it online!

Or, with byte scoring:

# 05AB1E, 277 bytes

```
.•Jã‘éLõÝåʒ?ÿU
¤Ú¹αšt\Žαæ™4c\’ÑÑ[Ï!îèιáÜ¶§:ºÃbxxQΩù2ú²º„¶₄êy³Ôá‚ιüá‚ÖÆjηatÜÿ˜≠²Ÿ‹»BˆAÇλ—W?üÿ¾TP×¸Ë·]Δ…È¶ª¢X9âtç¨’ƶövY∞ʒE¯Š¿[¹|εÔgƵΣCõ÷yʒĆ7hZ`ĀÀAFнúO¡]îγÄ¬-Ðu†₂≠т,ÜÞör,™¨}м!s±ÑH—‘DθwO³¦&‚ÚøγF∊6∊7p×Ì"₄ôʒÛ₅,ÿÉ½OÏ¦Ã9-p¦»:nÒƶÙØ¶∊[₁?θsÑK„³½ζp÷‰oæB¤|λ·(θŒ¨”∍∊₄=Ýá¾ÉĆΓΓŒ*›αβ™•„wy„.,‡.ª

```

Try it online!

# Answer
> 0 votes
# Deadfish~, 3209 bytes

```
{{i}ddd}iiiiiic{iii}iiiiiciiic{d}dddc{i}ddc{{d}ii}iiic{{i}ddd}iiic{i}dddciiiciic{d}iic{{d}ii}iiic{{i}ddd}ddc{i}icdddciiiciiic{{d}ii}ddc{{i}dd}iiic{d}c{i}ic{{d}ii}ddddc{iiiiii}iiiiic{i}iic{d}iic{i}iiiiic{{d}iii}ddc{d}ddc{{i}ddd}dddc{i}iicdciiiiic{d}ddddcddc{ii}dddc{d}dddddc{i}iiiiicicdddc{{d}ii}ddc{iiiiii}iiiiiciiiciiiiic{i}dddc{d}iiic{i}c{d}ddddddciiiiiiciiiiic{d}iiic{{d}iii}dc{{i}ddd}dc{i}dddcdddc{i}ic{{d}iii}ddc{d}ddc{{i}dd}iiic{d}ddddcdc{{d}iii}iic{{i}ddd}ddc{i}ic{{d}ii}ic{{i}ddd}dciiiic{i}iicddcddddddciic{d}dc{{d}iii}iic{{i}dd}iiiic{d}dddddc{i}ddciiicdciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{d}dciiiiiicdddddciiiiicdddddc{ii}dddc{d}iiiciiiiiic{{d}ii}ddddc{{i}dd}iiiiicdc{{d}ii}ddddc{{i}ddd}iiiiiic{d}dcic{i}iiiciiic{d}dddc{{d}iii}ic{{i}ddd}dc{i}iiiiic{{d}ii}ddddc{{i}ddd}ddc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}dd}dddc{d}ddciiiiiic{i}dddc{d}dddc{dddddd}dddddc{iiiiii}iiiiic{i}icdddc{i}ddciiiic{dd}c{ddddd}dc{d}ddddc{iiiii}iiic{iii}ic{{d}ii}ddddc{{i}ddd}dc{i}dcdddddciiiic{{d}ii}iiic{iiiiii}iiiiiciiic{{d}iii}iic{{i}dd}dddcddddciiiiicdddddciiiic{{d}ii}iiic{{i}dd}iiiiiic{dd}iiic{i}dcdddddc{d}iic{i}iic{dddddd}dddddc{d}ddc{{i}dd}iciiiic{d}ddc{i}c{{d}ii}dddc{{i}dd}ddciciiiicicddciiic{dd}iiic{{d}iii}iic{{i}ddd}dc{ii}dc{dd}ic{i}iiic{d}dddddciiiiiic{i}ic{dd}ic{ii}dc{d}dciiiiiicdc{{d}ii}iic{{i}dd}iiiiic{d}icc{d}dc{i}iic{d}c{i}iic{{d}ii}ic{{i}ddd}iiiiiic{d}dcic{i}iiiciiic{d}ic{i}c{{d}ii}dddc{{i}dd}ddcdddddc{i}c{d}c{{d}iii}dddc{{i}dd}iiiiicdc{{d}ii}ddddc{iiiiii}iiiiic{i}icdddc{i}ddciiiic{d}ddc{i}dddc{{d}ii}c{{i}ddd}dc{ii}dc{{d}i}iic{{i}ddd}dcddddc{dddddd}dddddc{{i}ddd}dddc{i}iicddcciic{d}dc{i}ic{{d}ii}ic{{i}ddd}dddc{i}iicdciiiiic{d}ddddc{i}iiciiiic{dd}c{ii}dc{{d}iii}c{d}ddddc{iii}iiiiiic{iiiii}dc{d}ddc{i}c{{d}ii}dddc{iiiiii}iiiiic{ii}cdc{d}dddddc{{d}iii}ic{{i}ddd}iiic{i}dciiicdddc{d}dddc{{d}iii}ic{{i}ddd}ddc{i}icdddciiiciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iic{d}dddc{i}iciic{d}dddciiicdddc{i}dc{d}cic{i}iiic{d}ic{i}ic{{d}ii}ddddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiiiic{d}iiicdddc{i}dcdddddciiiic{dd}ic{ii}dc{d}dddddc{{d}iii}ic{{i}dd}iiiiiic{dd}iiic{i}dddcdddc{i}ic{{d}ii}ddddc{{i}ddd}dc{i}iiiicc{d}ddddc{{d}iii}ic{{i}ddd}dddciiiiiiciiicc{i}dc{d}iic{{d}ii}iiic{{i}ddd}ddc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}ddd}dc{i}iiiiiic{{d}ii}dddddc{{i}ddd}c{i}iiiiic{d}ddddciic{d}iic{ii}dc{{d}ii}ddddc{{i}dd}ddc{i}dddc{d}icc{d}dc{dddddd}dddddc{{i}dd}c{d}dddddc{ii}dddc{d}ic{d}iic{ii}dcicdddc{{d}iii}iic{d}ddddc{iiii}dddc{iiiii}ic{dd}dciic{i}iciiiic{d}dddddc{i}iiiiiicdddc{{d}ii}ddc{{i}dd}iiic{d}ciiiiiciiiiiic{{d}ii}ddddc{{i}dd}dc{d}ddccddciiiicddcddc{ii}dc{{d}ii}ddddc{{i}ddd}dddc{ii}ddcdddddc{d}iiicdddddcdddc{ii}dc{dd}ic{ii}dc{{d}ii}ddddc{{i}dd}ddcicdc{{d}ii}iic{{i}dd}ciicdddcddddddcdddddcic{i}dciiiiiic{{d}iii}ddc{d}ddc{{i}dd}iiiciic{d}iiiciiiiiic{{d}ii}ddddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddd}dddc{ii}ddc{d}iciiiic{d}dddddc{dddddd}dddddc{{i}dd}iciiiic{d}ddc{{d}iii}dddc{{i}dd}dc{d}icciiicddddddciiiiiic{d}iic{dddddd}dddddc{{i}ddd}ddcic{i}iiiic{d}ddddc{i}iiiciiic{d}iiiciiiiiic{{d}ii}ddddc{{i}dd}dddciicdddccdddc{i}ic{{d}ii}ddddc{iiiiii}iiiiic{i}iiicdddddciiiic{{d}ii}iiic{{i}ddd}iiicdddddc{{d}iii}iic{{i}ddd}dc{i}iiiicic{{d}ii}ddddc{{i}ddd}iiiiiic{d}dcic{i}iiiciiiciiic{d}iic{dddddd}dddc

```

Try it online!

Who cares about all that compression nonsense...

# Answer
> 0 votes
# Deadfish~, 3061 characters

```
{i}dsdddddc{{iii}d}iciiic{d}dddc{i}ddc{{ii}dd}dc{{i}ddd}iiic{i}dddciiiciic{d}iic{{ii}dd}dc{dd}ddsc{i}icdddciiiciiic{{d}ii}ddc{{i}dd}iiic{d}c{i}ic{{ii}ddd}iic{{iii}ii}ic{i}iic{d}iic{i}iiiiic{{d}iii}ddc{d}ddc{dd}ddsdc{i}iicdciiiiic{d}ddddcddc{ii}dddc{d}dddddc{i}iiiiicicdddc{{d}ii}ddc{{iii}ii}iciiiciiiiic{i}dddc{d}iiic{i}c{dd}iiiiciiiiiiciiiiic{d}iiic{{d}iii}dc{dd}ddsic{i}dddcdddc{i}ic{{d}iii}ddc{d}ddc{{i}dd}iiic{d}ddddcdc{{ii}d}ddc{dd}ddsc{i}ic{{d}ii}ic{dd}ddsiciiiic{i}iicddcddddddciic{d}dc{{ii}d}ddc{{i}dd}iiiic{d}dddddc{i}ddciiicdciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{d}dciiiiiicdddddciiiiicdddddc{ii}dddc{d}iiiciiiiiic{{ii}ddd}iic{dd}dsddddcdc{{ii}ddd}iic{{i}dd}ddddc{d}dcic{i}iiiciiic{d}dddc{{d}iii}ic{dd}ddsic{i}iiiiic{{ii}ddd}iic{dd}ddsc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}dd}dddc{d}ddciiiiiic{i}dddc{d}dddc{{ii}d}ic{{iii}ii}ic{i}icdddc{i}ddciiiic{dd}c{ddddd}dc{d}ddddc{{iii}i}dc{iii}ic{{ii}ddd}iic{dd}ddsic{i}dcdddddciiiic{{ii}dd}dc{{iii}ii}iciiic{{ii}d}ddc{{i}dd}dddcddddciiiiicdddddciiiic{{ii}dd}dc{dd}dsdddc{dd}iiic{i}dcdddddc{d}iic{i}iic{{ii}d}ic{d}ddc{{i}dd}iciiiic{d}ddc{i}c{{d}ii}dddc{{i}dd}ddciciiiicicddciiic{dd}iiic{{ii}d}ddc{dd}ddsic{ii}dc{dd}ic{i}iiic{d}dddddciiiiiic{i}ic{dd}ic{ii}dc{d}dciiiiiicdc{{d}ii}iic{dd}dsddddc{d}icc{d}dc{i}iic{d}c{i}iic{{d}ii}ic{{i}dd}ddddc{d}dcic{i}iiiciiic{d}ic{i}c{{d}ii}dddc{{i}dd}ddcdddddc{i}c{d}c{{ii}dd}iiic{dd}dsddddcdc{{ii}ddd}iic{{iii}ii}ic{i}icdddc{i}ddciiiic{d}ddc{i}dddc{{d}ii}c{dd}ddsic{ii}dc{{d}i}iic{dd}ddsicddddc{{ii}d}ic{dd}ddsdc{i}iicddcciic{d}dc{i}ic{{d}ii}ic{dd}ddsdc{i}iicdciiiiic{d}ddddc{i}iiciiiic{dd}c{ii}dc{{d}iii}c{d}ddddc{{iii}d}iic{iiiii}dc{d}ddc{i}c{{d}ii}dddc{{iii}ii}ic{ii}cdc{d}dddddc{{d}iii}ic{{i}ddd}iiic{i}dciiicdddc{d}dddc{{d}iii}ic{dd}ddsc{i}icdddciiiciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iic{d}dddc{i}iciic{d}dddciiicdddc{i}dc{d}cic{i}iiic{d}ic{i}ic{{ii}ddd}iic{{i}ddd}iiiciiiiic{{d}ii}iic{dd}dsdddc{d}iiicdddc{i}dcdddddciiiic{dd}ic{ii}dc{d}dddddc{{d}iii}ic{dd}dsdddc{dd}iiic{i}dddcdddc{i}ic{{ii}ddd}iic{dd}ddsic{i}iiiicc{d}ddddc{{d}iii}ic{dd}ddsdciiiiiiciiicc{i}dc{d}iic{{ii}dd}dc{dd}ddsc{i}icdddciiiciiic{d}dddc{{d}iii}ic{dd}ddsic{ii}ddddc{{ii}ddd}ddc{{i}ddd}c{i}iiiiic{d}ddddciic{d}iic{ii}dc{{ii}ddd}iic{{i}dd}ddc{i}dddc{d}icc{d}dc{{ii}d}ic{{i}dd}c{d}dddddc{ii}dddc{d}ic{d}iic{ii}dcicdddc{{ii}d}ddc{d}ddddc{iiii}dddc{iiiii}ic{dd}dciic{i}iciiiic{d}dddddc{ii}ddddcdddc{{d}ii}ddc{{i}dd}iiic{d}ciiiiiciiiiiic{{ii}ddd}iic{{i}dd}dc{d}ddccddciiiicddcddc{ii}dc{{ii}ddd}iic{dd}ddsdc{ii}ddcdddddc{d}iiicdddddcdddc{ii}dc{dd}ic{ii}dc{{ii}ddd}iic{{i}dd}ddcicdc{{d}ii}iic{{i}dd}ciicdddcddddddcdddddcic{i}dciiiiiic{{d}iii}ddc{d}ddc{{i}dd}iiiciic{d}iiiciiiiiic{{ii}ddd}iic{{i}ddd}iiiciiiiic{{d}ii}iic{dd}ddsdc{ii}ddc{d}iciiiic{d}dddddc{{ii}d}ic{{i}dd}iciiiic{d}ddc{{ii}dd}iiic{{i}dd}dc{d}icciiicddddddciiiiiic{d}iic{{ii}d}ic{dd}ddscic{i}iiiic{d}ddddc{i}iiiciiic{d}iiiciiiiiic{{ii}ddd}iic{{i}dd}dddciicdddccdddc{i}ic{{ii}ddd}iic{{iii}ii}ic{i}iiicdddddciiiic{{ii}dd}dc{{i}ddd}iiicdddddc{{ii}d}ddc{dd}ddsic{i}iiiicic{{ii}ddd}iic{{i}dd}ddddc{d}dcic{i}iiiciiiciiic{d}iic{{ii}d}iiic

```

The code is too long for the recursive Python implementation on tio.run. So here is another link which works (I took it from this other answer).

Try it online

Not sure it's optimal, but should be pretty close. It uses the `s` command. It also takes advantage of the overflow feature when it's useful - when the accumulator is equal to 256, it wraps around to 0.

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


# Question
Title: The highest prime factor of neighboring numbers
I think it's easiest to explain this challenge in a sequential manner. Start with an input number \\$N\\$ and:

1. Find its highest prime factor
2. Check numbers above and below \\$N\\$ and see if the highest prime factor is higher (i.e. the highest prime factor of \\$N-1\\$ and/or \\$N+1\\$ is higher than the factor of \\$N\\$.
3. Continue to check higher **and/or** lower numbers neighboring \\$N\\$ in the directions where the highest factors are increasing (\\$(N-2, N-3 ...)\\$ and/or \\$(N+2, N+3 ...)\\$ and so on)
4. Once there aren't any prime factors in either direction that are higher than the ones we've already found we stop and output the highest prime factor we have encountered.

Let's look at an example:

`245` has the prime factors `5, 7, 7`. Its neighbors are:

```
244 -> 2,  2,  61
245 -> 5,  7,  7
246 -> 2,  3,  41

```

The highest prime factor is increasing in both direction, so we must look at the next neighbor:

```
243 -> 3,   3,  3,  3,  3
244 -> 2,   2,  2,  61
245 -> 5,   7,  7
246 -> 2,   3,  41
247 -> 13,  19

```

The highest prime factors are now decreasing in both direction, so the highest prime factor we've encountered is `61`, and should therefore be returned.

Another example:

Let's look at `1024`. Its prime factors are `2, 2, 2, 2, 2, 2, 2, 2, 2, 2`. The prime factors of its nearest neighbors are:

```
1023 -> 3, 11, 31
1024 -> 2,  2,  2,  2,  2,  2,  2,  2,  2,  2
1025 -> 5,  5, 41

```

The highest prime factor are increasing in both direction, from `2` to `31` or `41`. Let's look at the neighbors:

```
1022 -> 2, 7,  73
1023 -> 3, 11, 31
1024 -> 2,  2,  2,  2,  2,  2,  2,  2,  2,  2
1025 -> 5,  5, 41
1026 -> 2,  3,  3, 19

```

The highest prime factor for `1022` is `73`, and the highest prime factor for `1026` is `19`. Since `19` is lower than `41` we're not interested in it. **It's still increasing for numbers smaller than \\$N\\$, so we'll check the next one in that direction**:

```
1021 -> 1021
1022 -> 2, 7,  73
1023 -> 3, 11, 31
1024 -> 2,  2,  2,  2,  2,  2,  2,  2,  2,  2
1025 -> 5,  5, 41
1026 -> 2,  3,  3, 19

```

`1021` is a prime, and the highest prime we've encountered, so it should be returned.

**Rules:**

* You will only get positive \\$N\\$ larger than \\$1\\$ and smaller than \\$2^{31}-2\\$.
* Input and output formats are optional, but the numbers must be in base 10.
* You should continue searching for higher primes as long as the highest value is increasing in that direction. The directions are independent of each other.

**Test cases:**

Format: `N, highest_factor`

```
2, 3
3, 3
6, 7
8, 11
24, 23
1000, 997
736709, 5417
8469038, 9431

```

# Answer
> 4 votes
# Mathematica, ~~82~~ 74 bytes

*Thanks to Martin Ender for saving 8 bytes!*

```
Max@@(±n_:=#//.x_/;l[t=x+n]>l@x:>t;l=FactorInteger[#][[-1,1]]&)/@{±-1,±1}&

```

Unnamed function taking an integer input and returning an integer.

`±n_:=#//.x_/;l[t=x+n]>l@x:>t` defines a unary function `±` which keeps increasing the global function's integer input by `n` as long as the largest prime factor is increasing. (The largest-prime-factor function is defined with `l=FactorInteger[#][[-1,1]]&`.) `{±-1,±1}` therefore applies that function twice to the input integer, with increment `-1` and again with increment `1`. Then, `Max@@(...l...)/@...` takes the larger of the two largest-prime-factors thus found.

Previous submission:

```
Max@@(l=FactorInteger[#][[-1,1]]&)/@(#//.x_/;l[t=x+#2]>l[x]:>t&@@@{{#,-1},{#,1}})&

```

# Answer
> 1 votes
## Perl, 137 bytes

122 bytes of code + 15 bytes for `-p` and `-Mntheory=:all`.

```
sub f{$t=(factor$_+pop)[-1]}$i=$j=1;while($i|$j){f++$c;($i&=$t>$h)&&($h=$t);f-$c;($j&=$t>$l)&&($l=$t)}$_=$h>$l?$h:$l?$l:$_

```

To run it:

```
perl -pMntheory=:all -e 'sub f{$t=(factor$_+pop)[-1]}$i=$j=1;while($i|$j){f++$c;($i&=$t>$h)&&($h=$t);f-$c;($j&=$t>$l)&&($l=$t)}$_=$h>$l?$h:$l?$l:$_' <<< 736709

```

If you don't have `ntheory` installed, you can install it by typing `(echo y;echo) | perl -MCPAN -e 'install ntheory'` in your terminal.

# Answer
> 0 votes
## Ruby, 99 bytes

```
->n{f=->n{i=2;n%i<1?n/=i:i+=1while i<n;n};g=->s,z{s+=z while f[s+z]>b=f[s];b};[g[n,1],g[n,-1]].max}

```

Explanation:

* f() is the highest prime factor
* g() is the function searching neighbors in one direction
* apply g to (n,-1) and to (n,+1) to search in both directions

# Answer
> 0 votes
# Jelly, 24 bytes

```
;‘ÆfṀ€>/
ÇÐḟṖ‘,Ç1#Ṫ€ÆfFṀ

```

Try it online!

Bleh

## How it works

```
;‘ÆfṀ€>/ - Helper link. Takes n on the left
 ‘       - Yield n+1
;        - Pair; [n, n+1]
  Æf     - Prime factors of each
    Ṁ€   - Maximum of each
      >/ - Is max(pf(n)) > max(pf(n+1))?

ÇÐḟṖ‘,Ç1#Ṫ€ÆfFṀ - Main link. Takes N on the left
ÇÐḟ             - Remove all integers 1 ≤ k ≤ N which return true under the helper link
   Ṗ            - Remove the last one (N)
    ‘           - Increment all
      Ç1#       - Find the first integer ≥ N which the helper link returns true
     ,          - Pair
         Ṫ€     - Get the last element of each
                   This returns [x, y] where
                    x is the lower neighbour with the highest prime factor,
                    y is the upper neighbour with the highest prime factor
           Æf   - Prime factors of each
             FṀ - Flatten and get the maximum

```

---
Tags: code-golf, math, primes
---


title: Convince me Gabriel's Horn is possible

text:
# Question
Title: Convince me Gabriel's Horn is possible
From Wikipedia, Gabriel's Horn is a particular geometric figure that has infinite surface area but finite volume. I discovered this definition in this Vsauce's video (starting at 0:22) where I took the inspiration for this problem.

You begin with a cake (a cuboid) of dimension \\$x \times y \times z\\$. In your first slice of the cake, you will end up with two smaller cakes of dimension \\$\frac{x}{2} \times y \times z\\$. Next, you will slice **only one** of the two pieces of cake you sliced previously, and so on. The picture below illustrates this:

# Task

I cannot believe that the surface area can grow infinitely even if the volume of the cake stays the same and your task is to prove me that! However, I trust you and if you show me that the first 10 slices of the cake that the surface area is really growing, I will believe you.

You will receive the initial \\$x \times y \times z\\$ dimension of the cake as input and will output a list of 10 values referring to the total surface area of all cuboids after each consecutive slice.

# Specs

* The cake will always be sliced in half and it will always be sliced in the same dimension.
* The surface area \\$S\\$ of a cuboid of dimension \\$x \times y \times z\\$ is: \\$S = 2xy + 2xz + 2yz\\$
* The outputted list should first start with the surface area after no slices (that is, the cuboid original surface area), then 1 slice and so on.
* The slices are going to be done in the \\$x\\$ dimension and the test cases below will assume this.
* The surface area you have to calculate includes all pieces of cake sliced in previous iterations.
* Input is flexible, read it however you see fit for you.
* Standard loopholes are not allowed.
* This is , so the shortest code in bytes wins

# Test Cases

```
Format:
x, y, z --> output

1, 1, 1 --> [6, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0]
1, 2, 3 --> [22, 34.0, 46.0, 58.0, 70.0, 82.0, 94.0, 106.0, 118.0, 130.0]
3, 2, 1 --> [22, 26.0, 30.0, 34.0, 38.0, 42.0, 46.0, 50.0, 54.0, 58.0]
7, 11, 17 --> [766, 1140.0, 1514.0, 1888.0, 2262.0, 2636.0, 3010.0, 3384.0, 3758.0, 4132.0]
111, 43, 20 --> [15706, 17426.0, 19146.0, 20866.0, 22586.0, 24306.0, 26026.0, 27746.0, 29466.0, 31186.0]
1.3, 5.7, 21.2 --> [311.62, 553.3, 794.98, 1036.6599999999999, 1278.3400000000001, 1520.02, 1761.6999999999998, 2003.38, 2245.06, 2486.74]

```

# Answer
# Jelly, ~~9~~ 8 bytes

```
ṙ1×æ.Ɱ⁵Ḥ

```

Try it online!

Takes input as `[z, y, x]` as allowed by OP.

-1 byte thanks to Nick Kennedy

We calculate

$$2\left( \begin{matrix} z\times y \\ y\times x \\ x\times z\end{matrix} \right) \cdot \left( \begin{matrix} i \\ 1 \\ 1 \end{matrix} \right) = 2(yzi + yx+xz)$$

for each \\$1 \le i \le 10\\$

## How it works

```
ṙ1×æ.Ɱ⁵Ḥ - Main link. Takes [z, y, x] on the left
ṙ1       - Rotate once left; [y, x, z]
  ×      - Product; [yz, xy, xz]
      ⁵  - Yield 10
     Ɱ   - For each integer 1 ≤ i ≤ 10:
   æ.    -   Dot product. Pad to [i, 1, 1] and calculate
              [yz, xy, xz] . [i, 1, 1] = yzi+xy+xz
       Ḥ - Double each

```
> 12 votes

# Answer
# Haskell, 37 bytes

```
(x#y)z=[2*(x*y+x*z+n*y*z)|n<-[1..10]]

```

Try it online!

The relevant function is `(#)`, which takes as input `x`, `y`, `z` in this order and outputs the areas of the first 10 iterations.
> 8 votes

# Answer
# \>= 4.1.0, ~~39~~ 28 bytes

```
\(x,y,z)2*(1:10*y*z+x*y+x*z)

```

Try it online!

Note the TIO link has `function` in place of `\` since TIO is running an older version of R. However, the functionality is identical.

A function taking `x`, `y` and `z` and returning a vector of the surface areas.

Saved 11 bytes by looking at Delfad0r’s Haskell answer (and so using a much similar formula with no non-operator functions!)
> 7 votes

# Answer
# Zsh, 43 bytes

```
eval '<<<$[2*($1*$2+$1*$3+$2*$3*'{1..10}\)]

```

Try it online!

`eval '...'{1..10}\)]`: evaluate the command `<<<$[2*($1*$2+$1*$3+$2*$3*N)]` repeated with `1` to `10` in place of `N`. No semicolons needed, because `<<<` can be chained implicitly.
> 5 votes

# Answer
# Factor, 56 bytes

```
[ 3dup [ * ] 2tri@ 10 [1,b] [ 4dup * + + 2 * nip ] map ]

```

Try it online!

*Data flow combinator version thanks to @Bubbler*

The interesting thing about Factor is you generally have four ways to approach golf: dataflow combinators, stack shuffling, local variables, and "sequence-y" (making heavy use of `math.vectors` and other sequence words). The thing about dataflow combinators is that despite keeping the data stack static and easier to reason about, they're almost always longer than the other three methods. However, once in a while they will win out over the others for some reason, and it's not always clear which will win until you give them all a try.

# Factor, 57 bytes

```
[| x y z | 10 [1,b] [ y z * * x z * x y * + + 2 * ] map ]

```

Try it online!

*Locals*

# Factor, 60 bytes

```
[ 10 [1,b] [ '[ 1 _ 1 ] over 1 rotate v* v. 2 * ] with map ]

```

Try it online!

*"Sequence-y"*
> 4 votes

# Answer
# Mathematica, 29 bytes

```
2*(#*#2+#*#3+#2*#3*Range@10)&

```

Try it online!
> 4 votes

# Answer
# JavaScript (SpiderMonkey), 48 bytes

```
(x,y,z)=>{for(i=22;i-=2;)print(2*x*(y+z)+i*y*z)}

```

Try it online!
> 3 votes

# Answer
# Python 3, 51 bytes

```
lambda x,y,z:[2*(x*y+x*z-~n*y*z)for n in range(10)]

```

Try it online!

-1 byte thanks to @dingledooper
> 2 votes

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

```
(x,y,z)=>[...Array(10)].map((_,i)=>2*(++i*y*z+x*y+x*z))

```

Try it online!

Someone will probably outgolf me with recursion, but I have not yet found a suitable way to do so yet. This is essentially just a port of most people's answers.

---

# JavaScript (Node.js), 53 bytes

```
(x,y,z)=>[...Array(i=10)].map(_=>2*(x*y+x*z+y*z*i--))

```

Try it online!

Outputs in reverse order
> 2 votes

# Answer
# JavaScript, 53 bytes

Output is a space delimited string with a leading space.

```
x=>y=>g=(z,n=11)=>--n?g(z,n)+` `+(n*y*z+x*y+x*z)*2:``

```

Try it online!

Or 52 bytes using commas instead of spaces:

```
x=>y=>g=(z,n=11)=>--n?g(z,n)+[,(n*y*z+x*y+x*z)*2]:[]

```

Try it online!
> 2 votes

# Answer
# , 23 bytes

```
(2*+/+i.@10*1&{)@:*1&|.

```

Try it online!
> 2 votes

# Answer
# C (gcc), <sup>~~70~~</sup> 69 bytes

Saved a byte thanks to EliteDaMyth!!!

```
f(x,y,z,i)float x,y,z;{for(;++i<11;)printf("%f ",2*(x*y+x*z+i*y*z));}

```

Try it online!

Prints out the surface areas starting at the beginning.
> 2 votes

# Answer
# APL (Dyalog Unicode), 41 bytes

```
{(A[1]×⍳10)++/1↓A←2×⍵×1⌽⍵}

```

Try it online!

* my 1st Apl answer, footer stolen.. Honestly I still can't completely understand it because haven't seen yet the SRC and THIS commands.
* input as Y Z X vector .

```
A←2×⍵×1⌽⍵   U store in A input rotated once and multiplied by input and then doubled
   Obtaining total a,b,c planes surfaces
+/1↓A   U sum of b,c planes which remains always the same
(A[1]×⍳10)+   U added to a plane multiplied by [1..10]range

```
> 2 votes

# Answer
# Julia 1.x, 32 bytes

```
(x,y,z)->2(x*y.+x*z.+(1:10)*y*z)

```

Try it online!
> 2 votes

# Answer
# Charcoal, 16 bytes

```
ＩＥχ⊗⁺Σ∕Πθθ×ιΠ…θ²

```

Try it online! Link is to verbose version of code. Takes an array `[z, y, x]` as input. Explanation:

```
  χ                 Predefined variable `10`
 Ｅ                  Map over implicit range
     Σ∕Πθθ          Half-area of initial cuboid
    ⁺               Plus
           ι        Number of cuts
          ×         Multiplied by
            Π…θ²    Half-area of each cut
   ⊗                Doubled
Ｉ                   Cast to string
                    Implicitly print

```
> 1 votes

# Answer
# Ruby 2.7+, 39 bytes

```
->x,y,z{(1..10).map{2.*_1*y*z+x*y+x*z}}

```

Requires ruby 2.7+ for numbered arguments to work.
> 1 votes

# Answer
# Raku, 63 bytes

```
{(^10 »*»([*] @_[1,2]) »+»[+] @_[0,0,1]Z*@_[1,2,2]) »*»2}

```

Hyper-operators galore here leveraging constant difference between consecutive slicings of `2*y*z`:

* `^10` generates `0..9` ...
* `»*»` multiplies each integer in the sequence by ...
* `[*] @_[1,2]` is `y*z`
* `»+»` then adds to each of element in the sequence ...
* `[+] @_[0,0,1] Z* @_[1,2,2]`, which computes `x*z + x*y + y*z`
* `»*»2` then multiplies the resultant list by 2
> 1 votes

# Answer
# Desmos, 28 bytes

```
f(x,y,z)=2(xz+xy+[1...10]yz)

```

Try It On Desmos!

Try It On Desmos! (Prettified)
> 1 votes

---
Tags: code-golf, math, geometry, 3d
---


title: Noisy Iterated Prisoner's Dilemma

text:
# Question
Title: Noisy Iterated Prisoner's Dilemma
In this challenge, you will play the noisy iterated prisoner's dilemma.

The Prisoner's dilemma is a scenario in game theory where there are two players, each with two options: cooperate, or defect. Each player does better for themself if they defect than if they cooperate, but both players would prefer the outcome where both players cooperate to the one where both players defect.

The iterated prisoner's dilemma is the same game, except you play against the same opponent repeatedly, and you know what your opponent has played in the past. Your objective is always to accumulate the highest score for yourself, regardless of how your opponent does.

The noisy iterated prisoner's dilemma introduces some noise into the communication. Your knowledge of what your opponent has played in the past will have some noise introduced. You will also know what moves you made in the past. The noise rate is constant over a round against the same opponent, but different between different rounds.

## Challenge

In this challenge, you will write a Python 3 program to play the noisy iterated prisoner's dilemma.

Your program will receive three inputs:

* Your own moves, *without* random flips applied.
* Your opponent's moves, with random flips applied.
* A state variable, which starts as an empty list each round, and which you can modify if you want. You can ignore this if you don't want to use it.

Your program should output `'c'` to cooperate or `'d'` to defect.

For instance, here's a program that cooperates if the opponent has cooperated at least 60% of the time in the past, after random flips were applied, and for the first 10 flips:

```
def threshold(my_plays, their_flipped_plays, state):
    if len(their_flipped_plays) < 10:
        return 'c'
    opp_c_freq = their_flipped_plays.count('c')/len(their_flipped_plays)
    if opp_c_freq > 0.6:
        return 'c'
    else:
        return 'd'

```

If you don't know Python, write your submission in pseudocode, and someone (me or another member of the site) can make the corresponding Python program.

## Gameplay

The tournament runner can be found here: noisy-game. Run `noisy-game.py` to run the tournament. I'll keep that repository updated with new submissions. Example programs can be found in `basic.py`.

A program's overall score is the total of its score over 100 plays of the game.

A game consists of round-robin matchups of each player against each player, including itself. A matchup consists of 100 rounds. A round consists of 300 moves, each of which involves outputting `'c'` or `'d'`.

Your submission will play a matchup against every submission, including your own. Each matchup will consist of 100 rounds. During each round, a flip probability will be chosen uniformly randomly from `[0, 0.5]`.

Each round will consist of 300 moves. On each move, both programs will receive all previous plays they have attempted, and all previous plays the other program has made, after flips are applied, and a state variable, which is a mutable list which the program can modify if it wants to. The programs will output their moves.

Moves are scored as follows: If a program plays a `'c'`, the opposing program gets 2 points. If a program plays a `'d'`, that program gets 1 point.

Then, each move is flipped independently with probability equal to the flip probability, and stored for showing to the opponent.

After all of the rounds have been played, we sum the number of points each player got in each matchup. Then, we use the following scoring system to calculate each player's score for the game. This scoring is performed after all of the matchups are complete.

## Scoring

We will use evolutionary scoring. Each program starts with equal weight. Then, weights are updated as follows, for 100 iterations, using the point totals from the game:

Each program's new weight is proportional to the product of its previous weight and its average point total, weighted by the weights of its opponents.

100 such updates are applied, and the final weights are each program's score for that run of the game.

The overall scores will be the sum over 100 runs of the game.

The players will be all valid answers to this challenge, plus six basic programs to get us started.

## Caveats

Do not modify the inputs. Do not attempt to affect the execution of any other program, except via cooperating or defecting. Do not make a sacrificial submission that attempts to recognize another submission and benefit that opponent at its own expense. Standard loopholes are banned.

EDIT: Submissions may not exactly duplicate any of the basic programs or any earlier submission.

If you have any questions, feel free to ask.

## Current results

```
nicht_genug: 40.6311
stealer: 37.1416
enough: 14.4443
wait_for_50: 6.947
threshold: 0.406784
buckets: 0.202875
change_of_heart: 0.0996783
exploit_threshold: 0.0670485
kickback: 0.0313357
tit_for_stat: 0.0141368
decaying_memory: 0.00907645
tit_for_whoops: 0.00211803
slider: 0.00167053
trickster: 0.000654875
sounder: 0.000427348
tit_for_tat: 9.12471e-05
stubborn_stumbler: 6.92879e-05
tit_for_time: 2.82541e-05
jedi2sith: 2.0768e-05
cooperate: 1.86291e-05
everyThree: 1.04843e-05
somewhat_naive: 4.46701e-06
just_noise: 1.41564e-06
growing_distrust: 5.32521e-08
goldfish: 4.28982e-09
vengeful: 2.74267e-09
defect: 3.71295e-10
alternate: 2.09372e-20
random_player: 6.74361e-21

```

Results with only answers to this question and basic programs that ignore the opponent's play:

```
nicht_genug: 39.3907
stealer: 33.7864
enough: 20.9032
wait_for_50: 5.60007
buckets: 0.174457
kickback: 0.0686975
change_of_heart: 0.027396
tit_for_stat: 0.024522
decaying_memory: 0.0193272
tit_for_whoops: 0.00284842
slider: 0.00153227
sounder: 0.000472289
trickster: 0.000297515
stubborn_stumbler: 3.76073e-05
cooperate: 3.46865e-05
tit_for_time: 2.42263e-05
everyThree: 2.06095e-05
jedi2sith: 1.62591e-05
somewhat_naive: 4.20785e-06
just_noise: 1.18372e-06
growing_distrust: 6.17619e-08
vengeful: 3.61213e-09
goldfish: 3.5746e-09
defect: 4.92581e-10
alternate: 6.96497e-20
random_player: 1.49879e-20

```

## Winning

The competition will stay open indefinitely, as new submissions are posted. However, I will declare a winner (accept an answer) based on the results 1 month after this question was posted.

# Answer
> 6 votes
# Genug ist nicht genug

(could also be called `enough2` or `stealback`)

```
def nicht_genug(m,t,s):
    if not s:
        s.append("c")
        return "c"
    if s[0]=="t":
        return "d"
    if m[-42:].count("d")>10 or len(t)+t.count("d")>300:
        s[0]="t"
        return "d"
    if t[-1]=="d":
        if s[0]=="d":
            s[0]="c"
            return "d"
        else:
            s[0]="d"
            return "c"
    else:
        if t[-3:].count("d")==0:
            s[0]="c"
        return "c"

```

I learned that the original *tit for two tats* did wait for two *consecutive* tats like `tit_for_whoops` does, and indeed it seems we should forgive and forget (well, almost...) earlier single tats. And a lot of players defect in the last rounds. I still prefer to be nice when everything has been fine so far, but the bot's tolerance bar keeps getting lower.

# Answer
> 10 votes
# Tit-For-Whoops

*Inspired by a strategy from ncase.me/trust*

```
def tit_for_whoops(m, t, s):
    if len(t) < 2:
        return 'c'
    else:
        return 'd' if all([x == 'd' for x in t[-2:]]) else 'c'

```

Defects only if the other player has defected twice in a row, to prevent misunderstandings.

# Answer
> 9 votes
## Change of Heart

```
def change_of_heart(m, t, s):
    return 'c' if len(t) < 180 else 'd'

```

Has a change of heart partway through. Does surprisingly well.

# Answer
> 9 votes
# Strategy Stealer

Inspired by enough, change\_of\_heart, and tit-for-whoops. Should be a little more forgiving. I tried to tweak the numbers for best results but they didn't want to change much.

```
def stealer(mine, theirs, state):
    if len(mine) == 0:
        state.append('c')
        return 'c'
    elif len(mine) > 250:
        return "d"
    elif state[0] == 't':
        return 'd'
    elif mine[-40:].count('d') > 10:
        state[0] = 't'
        return 'd'
    elif theirs[-1] == 'd':
        if state[0] == 'd':
            state[0] = 'c'
            return 'd'
        else:
            state[0] = 'd'
            return 'c'
    elif all([x == 'c' for x in theirs[-3:]]):
        state[0] = 'c'
        return 'c'
    else:
        return 'c'

```

# Answer
> 8 votes
## Tit-For-Time

```
def tit_for_time(mine, theirs, state):
    theirs = theirs[-30:]
    no_rounds = len(theirs)
    return "c" if no_rounds < 5 or random.random() > theirs.count("d") / no_rounds else "d"

```

If you've been spending most of the time hurting me, I'll just hurt you back. Probably.

# Answer
> 7 votes
# Growing Distrust

```
import random

def growing_distrust(mine, theirs, state):
    # Start with trust.
    if len(mine) == 0:
        state.append(dict(betrayals=0, trust=True))
        return 'c'

    state_info = state[0]

    # If we're trusting and we get betrayed, trust less.
    if state_info['trust'] and theirs[-1] == 'd':
        state_info['trust'] = False
        state_info['betrayals'] += 1

    # Forgive, but don't forget.
    if random.random() < 0.5 ** state_info['betrayals']:
        state_info['trust'] = True

    return 'c' if state_info['trust'] else 'd'

```

The more the opponent betrays me, the less I can trust it was just noise.

# Answer
> 7 votes
# Jedi2Sith

Starts off all nice and selfless, but with time the influence of the dark side grows steadily stronger, until the point of no return. There's no stopping this influence, but all the bad things it sees happening just contribute to the power of the dark side...

```
def jedi2sith(me, them, the_force):
  time=len(them)
  bad_things=them.count('d')
  dark_side=(time+bad_things)/300
  if dark_side>random.random():
    return 'd'
  else:
    return 'c'

```

Try it online!

# Answer
> 6 votes
# Stubborn Stumbler

```
def stubborn_stumbler(m, t, s):
    if not t:
        s.append(dict(last_2=[], last_3=[]))
    if len(t) < 5:
        return 'c'
    else:
        # Records history to state depending if the last two and three
        # plays were equal
        s = s[0]
        if t[-2:].count(t[-1]) == 2:
            s['last_2'].append(t[-1])
        if t[-3:].count(t[-1]) == 3:
            s['last_3'].append(t[-1])
    c_freq = t.count('c')/len(t)
    # Checks if you've consistently defected against me
    opp_def_3 = s['last_3'].count('d') > s['last_3'].count('c')
    opp_def_2 = s['last_2'].count('d') > s['last_2'].count('c')
    # dist func from 0 to 1
    dist = lambda x: 1/(1+math.exp(-5*(x-0.5)))
    # You've wronged me too much
    if opp_def_3 and opp_def_2:
        return 'd'
    # Otherwise, if you're consistently co-operating, co-operate more
    # the less naive you are
    else:
        return 'c' if random.random() > dist(c_freq) - 0.5 else 'd'

```

Based off of your exploit threshold strategy with only consistent plays kept track for switching between defect and mostly co-operate

UPDATE: Keeps track of both two consecutive and three consecutive plays, punishing only under harsher conditions and adding a random choice when not sure

UPDATE 2: Removed condition and added distribution function

# Answer
> 6 votes
## Slider

```
def slider(m, t, s):
    z = [[2, 1], [0, 1], [2, 3], [2, 1]]
    x = 0
    for y in t:
      x = z[x][y == 'c']
    return 'c' if x < 2 else 'd'

```

Starts off with 'c', and gradually slides towards or away from 'd'.

# Answer
> 6 votes
# Noise Bot

```
def just_noise(m,t,s):
    return 'c' if random.random() > .2 else 'd'

```

I'm definitely cooperate bot. That's just noise.

# Answer
> 6 votes
# Enough is Enough

```
def enough(m,t,s):
    if not s:
        s.append("c")
        return "c"
    if s[0]=="t":
        return "d"
    if m[-42:].count("d")>10:
        s[0]="t"
        return "d"
    if t[-1]=="d":
        if s[0]=="d":
            s[0]="c"
            return "d"
        else:
            s[0]="d"
            return "c"
    else:
        return "c"

```

Starts as *tit for two tats* where the two tats don't have to be consecutive (unlike `tit_for_whoops`). If it has to play `d` too often it goes `d`-total.

# Answer
> 6 votes
> ## trickster (reinstated again)
>
> Only the last 10 plays are accounted for, but divided into two blocks of five, which are averaged with each classified as good or bad.
>
> If the opponent plays on average "nice", the trickster plays less and less nice. If the results are ambiguous the trickster plays nice to lure the opponent into safety. If the opponent appears to be playing "bad" the trickster retaliates.
>
> The idea is to gather points now and then from naïve players, while catching deceitful ones early.
>
> ```
> import random
> def trickster(player,opponent,state):
>     pBad = 0.75
>     pNice = 0.8
>     pReallyBad =0.1
>     decay = 0.98
>     r = random.random()
>
> ```

```
    if len(player)<20: #start off nice
        return 'c'
    else: #now the trickery begins
        last5 = opponent[-5:].count('c')/5.0 > 0.5
        last5old = opponent[-10:-5].count('c')/5.0  > 0.5
        if last5 and last5old: #she is naive, punish her
            pBad = pBad*decay #Increase punishment
            if r<pBad:
                return 'c'
            else:
                return 'd'
        elif last5 ^ last5old: #she is changing her mind, be nice!
            if r<pNice:
                return 'c'
            else:
                return 'd'
        else: #she's ratting you out, retaliate
            pReallyBad = pReallyBad*decay #Retaliate harder
            if r<pReallyBad:
                return 'c'
            else:
                return 'd'

```

> Disclaimer: I have never posted here before, if I am doing something wrong \>please tell me and I'll correct.

# Answer
> 6 votes
# Goldfish Bot

```
def goldfish(m,t,s):
    return 'd' if 'd' in t[-3:] else 'c'

```

A goldfish never forgives, but it quickly forgets.

# Answer
> 5 votes
## Decaying Memory

```
def decaying_memory(me, them, state):
    m = 0.95
    lt = len(them)

    if not lt:
        state.append(0.0)
        return 'c'

    # If it's the last round, there is no reason not to defect
    if lt >= 299: return 'd'

    state[0] = state[0] * m + (1.0 if them[-1] == 'c' else -1.0)

    # Use a gaussian distribution to reduce variance when opponent is more consistent
    return 'c' if lt < 5 or random.gauss(0, 0.4) < state[0] / ((1-m**lt)/(1-m)) else 'd'

```

Weighs recent history more. Slowly forgets the past.

# Answer
> 5 votes
### Kickback

```
def kickback(m, t, s):
  if len(m) < 10:
    return "c"
  td = t.count("d")
  md = m.count("d")
  f = td/(len(t)+1)
  if f < 0.3:
    return "d" if td > md and random.random() < 0.1 else "c"
  return "c" if random.random() > f+2*f*f else "d"

```

Some vague ideas...

# Answer
> 4 votes
# Doesn't Really Get The Whole "Noise" Thing

```
def vengeful(m,t,s):
    return 'd' if 'd' in t else 'c'

```

Never forgives a traitor.

# Answer
> 4 votes
# sounder:

edit: added retaliation in probably low noise scenarios

basically, if all 4 first moves are cooperate, that means we should expect less noise than usual. defect a little bit every so often to make up for the less points we would get from never defecting, and have it be able to be blamed on noise. we also retaliate if they defect against us

if our opponent does a lot of defecting in those turns (2 or more) we just defect back at them. if it was just noise, the noise would affect our moves anyway.

otherwise, if only 1 move was defect, we just do simple tit for tat the rest of the game.

```
def sounder(my, their, state):
    if len(my)<4:
        if their.count("d")>1:
            return "d"
        return "c"
    elif len(my) == 4:
        if all(i == "c" for i in their):
            state.append(0)
            return "d"
        elif their.count("c") == 3:
            state.append(1)
            return "c"
        else:
            state.append(2)
    if state[0] == 2:
        return "d"
    if state[0] == 0:
        if not "d" in my[-4:]:
            return "d"
        return their[-1]
    else:
        return their[-1]

```

# Answer
> 3 votes
# Alternate

```
def alternate(m, t, s):
    if(len(m)==0):
        return 'c' if random.random()>.5 else 'd'
    elif(len(m)>290):
        return 'd'
    else:
        return 'd' if m[-1]=='c' else 'c'

```

Picks randomly in the first round, then alternates. Always defects in the last 10 rounds.

# Answer
> 3 votes
# Wait for 50

```
def wait_for_50(m, t, s):
  return 'c' if t.count('d') < 50 else 'd'

```

After 50 defects, let 'em have it!

# Answer
> 2 votes
**Somehwat naive**

```
def somewhat_naive(m, t, s):
    p_flip = 0.25
    n = 10
    if len(t) < n:
        return 'c' if random.random() > p_flip else 'd'
    d_freq = t[-n:].count('d')/n
    return 'c' if d_freq < p_flip else 'd'

```

I'll just assume that if you've defected less than the flip probability (roughly) in the last *n* turns, it was noise and not that you're mean!

Haven't figures out the best *n*, might look further into that.

# Answer
> 2 votes
# Every Three

```
def everyThree(me,him,s):
    if len(me) % 3 == 2:
        return "d"
    if len(me) > 250:
        return "d"
    if him[-5:].count("d")>3:
        return "d"
    else:
        return "c"

```

Defects every three turns regardless. Also defects the last 50 turns. Also defects if his opponent defected 4 out of 5 of the last rounds.

# Answer
> 2 votes
# Buckets

```
def buckets(m, t, s):
    if len(m) <= 5:
        return 'c'
    if len(m) >= 250:
        return 'd'
    d_pct = t[-20:].count('d')/len(t[-20:])
    if random.random() > (2 * d_pct - 0.5):
        return 'c'
    else:
        return 'd'

```

Plays nice to begin. Looks at their last 20, if \< 25% d, returns c, \> 75% d, returns d, and in between chooses randomly along a linear probability function. Last 50, defects. Had this at last 10 but saw lots of last 50 defects.

First time here so let me know if something needs to be fixed (or how I can test this).

# Answer
> 2 votes
# Tit-for-Tat (pseudocode)

I'm surprised no one has put a basic tit-for-tat

Also, is the challenge considered over because not a lot of people have posted, and is it against the stack exchanges rules to post on an old thread?

```
    def tit_for_tat (my-moves, op-moves) {
      if (op-moves[last] == 'D')
        return D
      else
        return C
    }

```

# Answer
> 1 votes
# Tit-For-Stat

Defects if the opponent has defected more than half the time.

```
def tit_for_stat(m, t, s):
  if t.count('d') * 2 > len(m):
    return 'd'
  else:
    return 'c'

```

---
Tags: game, king-of-the-hill, python
---


title: Dr. Lamport's Unfinished Business

text:
# Question
Title: Dr. Lamport's Unfinished Business
# Introduction

Dr. Leslie Lamport, of the eponymous Lamport one-time signature scheme, is getting rather old. But he can't die until his most famous algorithm gets all the kinks ironed out!

In particular, that scheme had one internal component he was never satisfied with:

> We hope that someone can find a more elegant method for constructing the function `G`

# Challenge

Today, we're helping him prepare to leave by constructing a function `R` that takes the output of our one-way function `φ` (likely a hash function), and injectively uses it to **select a subset** of the user's private key, according to the following specifications:

* Your function takes two arguments: the output of hash function `φ` (as a data blob, octet stream, or similar appropriate native datatype), and an ordered set (in your choice of appropriate native datatype).

+ If your language's **standard library** has a bitstring datatype \[ex: Java; *not* Python\], you **may** choose to take `d` as it with no penalty; if it does not, then unpacking the bytestring (or finding some clever way to avoid or vectorize the doing-of!) is your responsibility.
* The `n`th bit of `φ`'s output chooses whether the `2*n`th element or the `2*n+1`th element will be included in the subset. If `φ` outputs a 24-bit data blob, then 24 elements will be chosen.

+ FOR EXAMPLE: if the **second** bit of `φ(m)` is 1, then the **fourth** element of `pk` will be chosen. If this bit is, instead, 0, then the **third** element of `pk` will be chosen. (There are examples included below.)
    + Naturally, for 1-indexed languages, the `n`th bit chooses between the `2*n-1`th and `2*n`th elements.
    + behavior is **totally undefined** in the event that `φ` returns something with more bits than half the number of elements in `pk`; don't even consider this case.
* Your function returns the thus-chosen subset of `pk`.

+ While the *input* set is ordered, the *output* set does **not need to be ordered** (and, if it is an ordered datatype, all possible orderings are allowed with no penalty). The function merely has to identify a *subset* of the ordered input set, so any ordering on its output would be redundant anyway.
* This is a standard golfing challenge; shorter answers are better than longer answers.

# Example Input and Output

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

* φ = MD5, with the digest truncated to the first 24 bits
m = \[empty string\]
φ(m) -\> `\xd4\x1d\x8c`

+ R(φ(m), `N`) -\> `2, 4, 5, 8, 9, 12, 13, 15, 17, 19, 21, 24, 26, 28, 29, 32, 34, 35, 37, 39, 42, 44, 45, 47`
* φ = CRC32
m = "Hello, World" (ASCII)
φ(m) -\> `\x26\x5b\x86\xc6`

+ R(φ(m), `N`) -\> `1, 3, 6, 7, 9, 12, 14, 15, 17, 20, 21, 24, 26, 27, 30, 32, 34, 35, 37, 39, 41, 44, 46, 47, 50, 52, 53, 55, 57, 60, 62, 63}`
* d = `\x00\x00` = two bytes, with all bits "off"

+ R(d, `N`) -\> `1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31`
* d = `\xFF` = one byte, with all bits "on"

+ R(d, `N`) -\> `2, 4, 6, 8, 10, 12, 14, 16`
* φ = Constant function returning the single byte `\x1d`
m = \[any input\]

+ R(φ(m), `N`) -\> `1, 3, 5, 8, 10, 12, 13, 16`

---

## Python 3, 281 bytes:

(281 does not include comments, type hints, docstrings, or the example φ)

```
def _iterbits(data):
    yield from (((byte & (0b1 << k)) >> k) for byte in data for k in reversed(range(8)))

def R(digest: bytes, pk: OrderedSet | list | tuple) -> set:
    "Reference solution"
    included_indices = set(2 * n + bit for n, bit in enumerate(_iterbits(digest)))
    return set(k for i, k in enumerate(pk) if i in included_indices)

def φ(m):
    "Example hash function to help you run your own test cases\n\nReturns an MD5 digest truncated to 24 bits"
    return hashlib.md5(m).digest()[:3]

```

# Answer
# , ~~86~~ ~~83~~ 82 bytes

(or **64 bytes** with additional `NA` values in output when length of hash result is greater than half the length of the private key N)

```
function(f,N,d=seq(b<-sapply(f,function(b)b%/%2^(7:0)%%2))*2)N[(d-!b)*!d>sum(N|1)]

```

Try it online!

Input is an array `f` of single-byte integers (representing the output of the hash function phi) and an array `N` (representing the ordered array from which to select a subset).

```
G=function(f,N){            # G is function with args f=array of bytes, N=array of values
  bits=                     # calculate the bits of f:
    sapply(f,function(b)    #   for each byte b in f
      b%/%2^(7:0)%%2)       #   get its bits
  d=seq(bits)               # define d as 1..number of bits
  N[                        # now output the elements of N given by indices:
    (d*2-1+bits)            #   d*2-1+bits (these are the indices from the bytes of f)
             *!d>sum(N|1)/2 #   multiplied by zero (FALSE) for bits that exceed the length of N
    ]
}

```
> 3 votes

# Answer
# , ~~80~~ ~~62~~ ~~54~~ 52 bytes

```
function(d,N)N[seq(b<-rawToBits(rev(d)))*2-rev(b<1)]

```

Try it online!

As per OP we don't need to handle cases when bits from `φ` select elements outside `N`.

*-4 bytes thanks to @Dominic*

```
function               # a function
        (d,            # taking first input as raw bytes (one of R data types)
           N)          # and N as a vector
N[                     # subset N at following indices
  seq(                 # make sequence 1..length(l) - default behaviour for seq on a vector is seq_along
      b<-              # assign the following to b
     rawToBits(rev(d)) # get bits from bytes in d (in reverse order)
                       # as rawToBits returns bits from the least-significant first, we need to reverse the vector on output (to make most-significant bit first - later on), but also on input (to preserve byte order)
                   )*2 # double every index
-rev(b<1)              # decrement corresponding indices when bit is off (taking rev here to save parentheses)
                       # comparison is the shortest operator casting from raw to something `-` will handle
]

```
> 2 votes

# Answer
# JavaScript (ES6),  ~~56~~  55 bytes

Expects `(N)(b)`, where `b` is `φ(m)`.

```
N=>b=>N.filter((_,i)=>((q=b[i>>4])>>7.5-i/2%8^~i)&q>=0)

```

Try it online!

### Commented

```
N =>                // outer function taking N[]
b =>                // inner function taking b[]
N.filter((_, i) =>  // for each entry at position i in N[]:
  (                 //
    (               //
      q =           //   let q be the byte from b[]
        b[i >> 4]   //   at index floor(i / 16)
    ) >>            //   right shift it by
    7.5 - i / 2 % 8 //   0 to 7 positions, according to floor(i / 2) mod 8
    ^ ~i            //   XOR the result with i inverted
  )                 //
  &                 //   isolate the least significant bit, or force zero
  q >= 0            //   if q is undefined
)                   // end of filter()

```
> 2 votes

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