# Question
Title: Print the full conjugation of a French verb
Given a string ending in either "er", "ir", or "re" (the "infinitive"), output the full conjugation of the string as a French verb in the seven simple tenses. For each tense (in the order given below), output each subject pronoun in the following order: *je*, *tu*, *il*, *elle*, *nous*, *vous*, *ils*, *elles*; followed by a space, the verb conjugated according to that pronoun, and a newline. If the verb begins with a vowel (`aeiou`) or `h`, *je* becomes *j'* and the space is omitted.

In all the examples, I will use the regular verbs *exister*, *invertir*, and *rendre* to demonstrate. French has a great many irregular verbs, which we shall ignore to make the specification and challenge easier.

# The tenses

## Present tense

Remove the *er/ir/re* from the infinitive and add the following endings:

* *er*: *j'exist**e**, tu exist**es**, il exist**e**, elle exist**e**, nous exist**ons**, vous exist**ez**, ils exist**ent**, elles exist**ent***.
* *ir*: *j'invert**is**, tu invert**is**, il invert**it**, elle invert**it**, nous invert**issons**, vous invert**issez**, ils invert**issent***.
* *re*: *je rend**s**, tu rend**s**, il rend, elle rend* (no endings), *nous rend**ons**, vous rend**ez**, ils rend**ent**, elles rend**ent***.

## Imperfect

Remove the *er/ir/re* from the infinitive and add the following endings:

* *er* and *re*: *j'exist**ais**, tu exist**ais**, il exist**ait**, elle exist**ait**, nous exist**ions**, vous exist**iez**, ils exist**aient**, elles exist**aient***.
* *ir*: *j'invert**issais**, tu invert**issais**, il invert**issait**, elle invert**issait**, nous invert**issions**, vous invert**issiez**, ils invert**issaient***.

## Simple past

Remove the *er/ir/re* from the infinitive and add the following endings:

* *er*: *j'exist**ai**, tu exist**as**, il exist**a**, elle exist**a**, nous exist**âmes**, vous exist**âtes**, ils exist**èrent**, elles exist**èrent***.
* *ir* and *re*: *je rend**is**, tu rend**is**, il rend**it**, elle rend**it**, nous rend**îmes**, vous rend**îtes**, ils rend**irent**, elles rend**irent**.*

## Future

For all verbs, add these endings directly to the infinitive (though *re* verbs drop the *e*):

* *j'invertir**ai**, tu invertir**as**, il invertir**a**, elle invertir**a**, nous invertir**ons**, vous invertir**ez**, ils invertir**ont**, elles invertir**ont***.

## Conditional

For all verbs, add these endings directly to the infinitive (though *re* verbs drop the *e*):

* *j'invertir**ais**, tu invertir**ais**, il invertir**ait**, elle invertir**ait**, nous invertir**ions**, vous invertir**iez**, ils invertir**aient***, elles invertir**aient\***.

## Present subjunctive

Remove the *er/ir/re* from the infinitive and add the following endings:

* *er* and *re*: *j'exist**e**, tu exist**es**, il exist**e**, elle exist**e**, nous exist**ions**, vous exist**iez**, ils exist**ent**, elles exist**ent***.
* *ir*: *j'invert**isse**, tu invert**isses**, il invert**isse**, elle invert**isse**, nous invert**issions**, vous invert**issiez**, ils invert**issent**, elles invert**issent***.

## Imperfect subjunctive

Remove the *er/ir/re* from the infinitive and add the following endings:

* *er*: *j'exist**asse**, tu exist**asses**, il exist**ât**, elle exist**ât**, nous exist**assions**, vous exist**assiez**, ils exist**assent**, elles exist**assent***.
* *ir* and *re*: *je rend**isse**, tu rend**isses**, il rend**ît**, elle rend**ît**, nous rend**issions**, vous rend**issiez**, ils rend**issent**, elles rend**issent***.

# Sample output

For an *er* verb, `aller`, your output should be:

```
j'alle
tu alles
il alle
elle alle
nous allons
vous allez
ils allent
elles allent
j'allais
tu allais
il allait
elle allait
nous allions
vous alliez
ils allaient
elles allaient
j'allai
tu allas
il alla
elle alla
nous allâmes
vous allâtes
ils allèrent
elles allèrent
j'allerai
tu alleras
il allera
elle allera
nous allerons
vous allerez
ils alleront
elles alleront
j'allerais
tu allerais
il allerait
elle allerait
nous allerions
vous alleriez
ils alleraient
elles alleraient
j'alle
tu alles
il alle
elle alle
nous allions
vous alliez
ils allent
elles allent
j'allasse
tu allasses
il allât
elle allât
nous allassions
vous allassiez
ils allassent
elles allassent

```

For an *ir* verb, `avoir`, your output should be:

```
j'avois
tu avois
il avoit
elle avoit
nous avoissons
vous avoissez
ils avoissent
elles avoissent
j'avoissais
tu avoissais
il avoissait
elle avoissait
nous avoissions
vous avoissiez
ils avoissaient
elles avoissaient
j'avois
tu avois
il avoit
elle avoit
nous avoîmes
vous avoîtes
ils avoirent
elles avoirent
j'avoirai
tu avoiras
il avoira
elle avoira
nous avoirons
vous avoirez
ils avoiront
elles avoiront
j'avoirais
tu avoirais
il avoirait
elle avoirait
nous avoirions
vous avoiriez
ils avoiraient
elles avoiraient
j'avoisse
tu avoisses
il avoisse
elle avoisse
nous avoissions
vous avoissiez
ils avoissent
elles avoissent
j'avoisse
tu avoisses
il avoît
elle avoît
nous avoissions
vous avoissiez
ils avoissent
elles avoissent

```

For an *re* verb, `faire`, your output should be:

```
je fais
tu fais
il fai
elle fai
nous faions
vous faiez
ils faient
elles faient
je faiais
tu faiais
il faiait
elle faiait
nous faiions
vous faiiez
ils faiaient
elles faiaient
je faiis
tu faiis
il faiit
elle faiit
nous faiîmes
vous faiîtes
ils faiirent
elles faiirent
je fairai
tu fairas
il faira
elle faira
nous fairons
vous fairez
ils fairont
elles fairont
je fairais
tu fairais
il fairait
elle fairait
nous fairions
vous fairiez
ils fairaient
elles fairaient
je faie
tu faies
il faie
elle faie
nous faiions
vous faiiez
ils faient
elles faient
je faiisse
tu faiisses
il faiît
elle faiît
nous faiissions
vous faiissiez
ils faiissent
elles faiissent

```

(These are *not* the true conjugations of the above verbs. In reality they are highly irregular.)

This is code golf. The shortest submission wins.

# Answer
> 2 votes
# Charcoal, ~~488~~ 276 bytes

```
Ｆ⪪§⪪”}∨>↓⁷8lυW!M\ηX↨%]ν÷g×D\﹪3}Þ1Xζ÷Ｓ¹.m×Ｋ⦄}.}◧TI¡νυOＡ×∨´ＴE…8λ→Ｙ×⁶⁰⟦αＬi↓↶⎚⦃ω>◧‴κv≦｜≕…K⊕Yλ⎇＆✳⍘ςθＡ⪪@₂)¦Hg@»‽Ｈ2.⁵÷-⁸n¬u⊘¡″βEＮ≡x↔÷Wyⅈ(Ｊ\`﹪◨⁸｜|kU_ ←%Zσ¤«⊟Ｑ§!χ⁰⸿¤:\`α´↖±↔5À⊗I¡o⊞⁵cp✳ιg«“/_$↖↧↧⪫,↗A”¶¶⌕er§θ±²¶Ｆ⁶Ｆ⎇›№aehiou§θ⁰κ⟦j'⟧⁺⪪§⪪”↶↥ζ⊟pW↔,⦄≡ＷA→÷⪫$Ａⅉ⟦v⎇” κ¶¦ «λ…θ⁻Ｌθ²⭆§⪪ι κ§⁺âèîμ⌕AEIμ⸿

```

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

```
Ｆ⪪§⪪”...”¶¶⌕er§θ±²¶

```

A very long compressed string is split into paragraphs, each paragraph representing the endings for a particular verb ending. The appropriate ending is selected depending on the second last letter in the verb. The paragraph is split into lines representing the endings for each tense in turn. The tenses are then looped over.

```
Ｆ⁶

```

Loop over the three persons and their plurals.

```
Ｆ⎇›№aehiou§θ⁰κ⟦j'⟧⁺⪪§⪪”↶↥ζ⊟pW↔,⦄≡ＷA→÷⪫$Ａⅉ⟦v⎇” κ¶¦ «

```

Loop over the pronouns for those persons (third person has two genders), but special-casing `["j'"]` where necessary.

```
λ

```

Print the pronoun.

```
…θ⁻Ｌθ²

```

Print the verb stem.

```
⭆§⪪ι κ§⁺âèîμ⌕AEIμ

```

Print the suffix, but translate `AEI` to `âèî` as Charcoal can't compress accented letters.

```
⸿

```

Start a new line.

# Answer
> 5 votes
# JavaScript (ES6),  ~~507~~  504 bytes

Returns an array of 7 tenses, where each tense is an array of 8 forms.

```
(v,[a,b]=v.split(/(..)$/),g=b>'r'?2:b<'i')=>[...S='0123456'].map(x=>'je/tu/il/elle/nous/vous/ils/elles'.split`/`.map((s,n)=>(!n*/^[aehiou]/.test(a)?"j'":s+' ')+a+(x>2&x<5?g>1?'r':b:'')+[...S+'789ABCD'].reduce((p,c)=>(l=p.split(c)).join(l.pop()),'55e91D4D3D7/s//9eC0s00tBai72AA/âm5âtes/èr1/îm5îtes8r72AA9oC/55e8483/7DeDeDeB76e65ât6i46i367DeD5îtB7D8ssCn2s22t848327BDi4Di3DA/a9/4/3/8/i7en6Ass5e/4on3ez2Ai178s88t0Dai').split`/`[(n-=n>2,n-=n>5)+('0x'+'102433656777888A99CBC'[x*3+g])*6]+['sst'[~-n/2]]))

```

Try it online! (regular verbs)

Try it online! (grammatical disaster using the irregular verbs suggested in the challenge)

# Answer
> 3 votes
# Retina, ~~2051~~ 1891 bytes (UTF-8)

```
(.+)er$
je $1e0tu $1es0il $1e0elle $1e0nous $1ons0vous $1ez0ils $1ent0elles $1ent0je $1ais0tu $1ais0il $1ait0elle $1ait0nous $1ions0vous $1iez0ils $1aient0elles $1aient0je $1ai0tu $1as0il $1a0elle $1a0nous $1âmes0vous $1âtes0ils $1èrent0elles $1èrent0je $1erai0tu $1eras0il $1era0elle $1era0nous $1erons0vous $1erez0ils $1eront0elles $1eront0je $1erais0tu $1erais0il $1erait0elle $1erait0nous $1erions0vous $1eriez0ils $1eraient0elles $1eraient0je $1e0tu $1es0il $1e0elle $1e0nous $1ions0vous $1iez0ils $1ent0elles $1ent0je $1asse0tu $1asses0il $1ât0elle $1ât0nous $1assions0vous $1assiez0ils $1assent0elles $1assent
(.+i)r$
je $1s0tu $1s0il $1t0elle $1t0nous $1ssons0vous $1ssez0ils $1ssent0elles $1ssent0je $1ssais0tu $1ssais0il $1ssait0elle $1ssait0nous $1ssions0vous $1ssiez0ils $1ssaient0elles $1ssaient0je $1s0tu $1s0il $1t0elle $1t0nous avoîmes0vous avoîtes0ils $1rent0elles $1rent0je $1rai0tu $1ras0il $1ra0elle $1ra0nous $1rons0vous $1rez0ils $1ront0elles $1ront0je $1rais0tu $1rais0il $1rait0elle $1rait0nous $1rions0vous $1riez0ils $1raient0elles $1raient0je $1sse0tu $1sses0il $1sse0elle $1sse0nous $1ssions0vous $1ssiez0ils $1ssent0elles $1ssent0je $1sse0tu $1sses0il avoît0elle avoît0nous $1ssions0vous $1ssiez0ils $1ssent0elles $1ssent
(.+)re$
je $1s0tu $1s0il fai0elle fai0nous $1ons0vous $1ez0ils $1ent0elles $1ent0je $1ais0tu $1ais0il $1ait0elle $1ait0nous $1ions0vous $1iez0ils $1aient0elles $1aient0je $1is0tu $1is0il $1it0elle $1it0nous $1îmes0vous $1îtes0ils $1irent0elles $1irent0je $1rai0tu $1ras0il $1ra0elle $1ra0nous $1rons0vous $1rez0ils $1ront0elles $1ront0je $1rais0tu $1rais0il $1rait0elle $1rait0nous $1rions0vous $1riez0ils $1raient0elles $1raient0je $1e0tu $1es0il $1e0elle $1e0nous $1ions0vous $1iez0ils $1ent0elles $1ent0je $1isse0tu $1isses0il $1ît0elle $1ît0nous $1issions0vous $1issiez0ils $1issent0elles $1issent
je ([aeiouh].+)
j'$1
S`0

```

To the point implementation. Will try to golf it down from here.

Try it online.

**Explanation:**

Handle all words ending with `er`, with a `0` as line separator:

```
(.+)er$
je $1e0tu $1es0il $1e0elle $1e0nous $1ons0vous $1ez0ils $1ent0elles $1ent0je $1ais0tu $1ais0il $1ait0elle $1ait0nous $1ions0vous $1iez0ils $1aient0elles $1aient0je $1ai0tu $1as0il $1a0elle $1a0nous $1âmes0vous $1âtes0ils $1èrent0elles $1èrent0je $1erai0tu $1eras0il $1era0elle $1era0nous $1erons0vous $1erez0ils $1eront0elles $1eront0je $1erais0tu $1erais0il $1erait0elle $1erait0nous $1erions0vous $1eriez0ils $1eraient0elles $1eraient0je $1e0tu $1es0il $1e0elle $1e0nous $1ions0vous $1iez0ils $1ent0elles $1ent0je $1asse0tu $1asses0il $1ât0elle $1ât0nous $1assions0vous $1assiez0ils $1assent0elles $1assent

```

Handle all words ending with `ir`, with `0` as line separator:

```
(.+i)r$
je $1s0tu $1s0il $1t0elle $1t0nous $1ssons0vous $1ssez0ils $1ssent0elles $1ssent0je $1ssais0tu $1ssais0il $1ssait0elle $1ssait0nous $1ssions0vous $1ssiez0ils $1ssaient0elles $1ssaient0je $1s0tu $1s0il $1t0elle $1t0nous avoîmes0vous avoîtes0ils $1rent0elles $1rent0je $1rai0tu $1ras0il $1ra0elle $1ra0nous $1rons0vous $1rez0ils $1ront0elles $1ront0je $1rais0tu $1rais0il $1rait0elle $1rait0nous $1rions0vous $1riez0ils $1raient0elles $1raient0je $1sse0tu $1sses0il $1sse0elle $1sse0nous $1ssions0vous $1ssiez0ils $1ssent0elles $1ssent0je $1sse0tu $1sses0il avoît0elle avoît0nous $1ssions0vous $1ssiez0ils $1ssent0elles $1ssent

```

Handle all words ending with `re`, with `0` as line separator:

```
(.+)re$
je $1s0tu $1s0il fai0elle fai0nous $1ons0vous $1ez0ils $1ent0elles $1ent0je $1ais0tu $1ais0il $1ait0elle $1ait0nous $1ions0vous $1iez0ils $1aient0elles $1aient0je $1is0tu $1is0il $1it0elle $1it0nous $1îmes0vous $1îtes0ils $1irent0elles $1irent0je $1rai0tu $1ras0il $1ra0elle $1ra0nous $1rons0vous $1rez0ils $1ront0elles $1ront0je $1rais0tu $1rais0il $1rait0elle $1rait0nous $1rions0vous $1riez0ils $1raient0elles $1raient0je $1e0tu $1es0il $1e0elle $1e0nous $1ions0vous $1iez0ils $1ent0elles $1ent0je $1isse0tu $1isses0il $1ît0elle $1ît0nous $1issions0vous $1issiez0ils $1issent0elles $1issent

```

Replace all `je`  followed by a vowel or 'h' with `j'`:

```
je ([aeiouh].+)
j'$1

```

And finally split on zeroes, which basically replaces all `0`s with newlines:

```
S`0

```

After which the result is output implicitly.

---
Tags: code-golf, natural-language
---


title: Sum the unique numbers in a list

text:
# Question
Title: Sum the unique numbers in a list
For this challenge, the objective is to take a list of integers, and output the sum of every unique integer in that list, i.e. count multiples of the same integer only once.
Your input will be a string in the format `"{1,2,3,4}"` with any amount of elements. The string will never have whitespace or be in a format that does not match the example above. **A list with 0 elements should return `0`.**

## Examples

```
"{1,2,3,4}" -> 10
"{5,2,5}" -> 7
"{13,13,13}" -> 13
"{-5,5,5}" -> 0
"{12,12,13,13,14,14}" -> 39
"{}" -> 0
"{3}" -> 3

```

This is , so the shortest answer in bytes wins.

Good luck!

# Answer
# Jelly, 1 byte

```
S

```

**TryItOnline**

Since command line arguments are passed as a string to Python, it evaluates as a set\*.
`S` then sums the resulting list Jelly will receive.

* except in the empty case (as pointed out by @Dennis) when `"{}"` evaluates to an empty dictionary, but this gets cast to a list of it's keys, which is an empty list.
> 7 votes

# Answer
## Python 2, ~~21~~ 18 bytes:

```
print sum(input())

```
> 6 votes

# Answer
# MATL, 4 bytes

```
Ugus

```

String delimiter in MATL is `'`.

Try it online!

### Explanation

```
U    % Implicitly input string and evaluate it. Gives a cell array
g    % Convert to vector
u    % Unique
s    % Sum. Implicitly display

```
> 4 votes

# Answer
## JavaScript (ES6), 61 bytes

```
s=>[...new Set(s.slice(1,-1).split`,`)].reduce((s,n)=>+n+s,0)

```

Without the unreasonable input format it's only 39 bytes:

```
f=a=>[...new Set(a)].reduce((s,n)=>s+n,0)

```

The `,0` is necessary to work with an empty array.
> 2 votes

# Answer
## Actually, 2 bytes

```
≡Σ

```

Try it online!

(`eval`) evaluates the input, which is thankfully specified in Python's set literal syntax. `Σ` then sums the set elements.
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
0E¦¨',¡ÙO

```

Try it online!

**Explanation**

```
0          # push 0
 E         # push evaluated input
  ¦¨       # remove brackets
    ',¡    # split on ","
       Ù   # remove duplicates
        O  # sum

```

`0E` is needed as sum doesn't work on an empty list.
> 2 votes

# Answer
## Pyke, ~~9~~ 4 bytes

```
F )s

```

Try it here!

Yes, I have to spend 3 bytes converting a set to a list because Pyke's sum function errors out on sets.

The space is required because the default behavior for a for-loop in Pyke is to print out the arguments
> 2 votes

# Answer
# PHP, 34 Bytes

```
<?=array_sum(array_unique($argv));

```
> 1 votes

# Answer
# Octave, 29 bytes

```
@(x)sum(unique([eval(x){:}]))

```

This creates an anonymous function named `ans` can be called using `ans('{1, 2, 3}')`.

Online demo

**Explanation**

The `eval(x)` converts the input string into a cell array of numbers. The `[x{:}]` converts the cell array of numbers into a normal array of numbers. Then we compute the `unique` elements and `sum` the result.
> 1 votes

# Answer
# Ruby, 36 bytes

```
$><<eval(gets.scan(/-?\d+/).uniq*?+)

```

Search for all unique "integer-looking" strings in the input and join this list on the string `+`, then evaluate the resulting string and print the result.
> 1 votes

# Answer
# BASH + CoreUtils + sed + bc 75 68 50 bytes

Saved a bunch thanks to Digital Trauma and seshoumara

```
sed '/{}/c0
s:[}{,]:\n:g'|sort -u|xargs|tr \  +|bc

```
> 1 votes

# Answer
# Mathematica, ~~8~~ 9 bytes

```
Tr@*Union

```

`Union` deletes duplicates (and sorts), and `Tr` totals a list. A rare case when Mathematica can actually compete with golfing languages!
> 1 votes

# Answer
# Perl, 28 bytes

Includes +1 for `-p`

Give input on STDIN

```
#!/usr/bin/perl -p
s%-?\d*%$a{$&}//=$_+=$&%reg

```

Surprisingly hard to support the empty set and go below 29 bytes
> 1 votes

# Answer
## Bash + coreutils, 38 bytes

```
bc<<<0$(tr ,}{ \\n|sort -u|paste -sd+)

```

**Try it on ideone.com!**

**Explanation:** using `{1,2,1,4}` as test case

```
        tr ,}{ \\n       # replace commas and braces with newlines (\n1\n2\n1\n4\n)
        |sort -u         # sort and print unique lines (\n1\n2\n4)
        |paste -sd+      # merge lines with '+' as delimiter (+1+2+4)
bc<<<0$(           )     # prepend '0' and calculate sum (7)

```

Note how prepending a '0' will also help to give a correct answer when the input list is empty (`{}`).

**Run examples:**

```
me@LCARS:/PPCG$ ./sum_unique.sh <<< "{}"
0
me@LCARS:/PPCG$ ./sum_unique.sh <<< "{3}"
3
me@LCARS:/PPCG$ ./sum_unique.sh <<< "{-5,5,5}"
0
me@LCARS:/PPCG$ ./sum_unique.sh <<< "{12,12,13,13,14,14}"
39

```
> 1 votes

# Answer
# Zsh, ~~41~~ 34 bytes

```
<<<$[${${(us:,:)${1/\{}/\}}// /+}]

```

~~Try it online!~~ Try it online!

`${ / / }` is replacement, `${ // / }` is global replacement, `(s:,:)` splits the string on commas, `(u)` keeps the unique elements.
> 1 votes

# Answer
# Groovy (81 Bytes)

```
z={x->Eval.me(x.replaceAll("\\{","\\[").replaceAll("\\}","\\]")).unique().sum()}

```

Try it online: https://groovyconsole.appspot.com/edit/5074458091978752

*28 Bytes if you Use \[\] as brackets...* `z={Eval.me(it).unique().sum()}`
> 0 votes

# Answer
## R, 51 bytes

```
s=scan;sum(unique(s(t=gsub("\\{|}|,"," ",s(,"")))))

```
> 0 votes

# Answer
# Bash + GNU utilities, 54

```
eval printf '0%s\\n' $1|tr -d {}|sort -u|paste -sd+|bc

```

Input is given as a command-line parameter. Note that the input must be quoted to prevent expansion by the calling shell (this would be handy, and save some bytes, but I feel like that would be cheating a bit).

The input format is mostly a bash brace expansion, but it doesn't expand as we want it to for a 0 or 1 element list, so a bit more preprocessing is required before piping to `sort -u`.

Ideone.
> 0 votes

# Answer
# Pyth, 3 bytes

Unfortunately, the sum builtin doesn't work in Pyth with sets. I have to convert to a list first...

```
s[F

```

Explanation:

```
 [   Construct list
  F  By splatting in the elements of the input
s    Sum up

```

Taking input as a list-type form would actually be a byte shorter:

```
s{

```

Which is the `s`um of the `{`de-duplicated input.
> 0 votes

# Answer
# Perl 6, 29 bytes

```
*.comb(/<[-\d]>+/).unique.sum

```

## Example:

```
# give the Whatever lambda a name for clarity
my &code = *.comb(/<[-\d]>+/).unique.sum;

say code '{1,2,3,4}'; # 10
say code '{5,-5,5}';  # 0
say code '{}';        # 0

```
> 0 votes

# Answer
## C#, 103 bytes

```
(i)=>i[1]=='}'?0:Regex.Match(i,"{(.*)}").Groups[1].Value.Split(',').Select(int.Parse).Distinct().Sum();

```

this challange its pretty pointless really
> 0 votes

# Answer
## ListSharp, 134 bytes

```
STRG s=INPUT[""] AS STRG
SHOW=ROWSPLIT STRG["0"+GETRANGE s FROM [2] TO [s LENGTH-1]] BY [","]<c#.Select(int.Parse).Distinct().Sum()c#>

```
> 0 votes

---
Tags: code-golf, math, arithmetic
---


title: Finding Local Extremes

text:
# Question
Title: Finding Local Extremes
Write a function or program that takes in a list and produces a list of the local extremes.

In a list `[x_0, x_1, x_2...]` a local extreme is an `x_i` such that `x_(i-1) < x_i` and `x_(i+1) < x_i` or `x_(i-1) > x_i` and `x_(i+1) > x_i`. Notice that the first and last elements of the list can never be local extremes.

So for some examples

```
local_extremes([1, 2, 1]) = [2]
local_extremes([0, 1, 0, 1, 0]) = [1, 0, 1]
local_extremems([]) = []

```

This is code golf so the shortest code wins!

# Answer
> 5 votes
# Mathematica ~~66 58~~ 51

## Current Solution

Shortened thanks to a contribution by Calle.

```
Cases[Partition[#,3,1],{a_,b_,c_}/;(a-b) (b-c)<0⧴b]&

```

`Partition[#,3,1]` finds the triples.

`(a-b) (b-c)<0` is true if and only if `b` is below `a`, `c`, or above `a`,`c`. and looks at takes the signs of the differences. A local extreme will return either `{-1,1}` or `{1,-1}`.

---

**Examples**

```
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{1, 2, 1}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{0, 1, 0, 1, 0}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]

```

> {2}
> {1, 0, 1}
> {}
> {10, 6, 9, 0, 1}

---

## Earlier Solution

This looks examples all triples (generated by `Partition`) and determines whether the middle element is less than both extremes or greater than the extremes.

```
Cases[Partition[#,3,1],{a_,b_,c_}/;(b<a∧b<c)∨(b>a∧b>c)⧴b]& ;

```

---

## First Solution

This finds the triples, and looks at takes the signs of the differences. A local extreme will return either `{-1,1}` or `{1,-1}`.

```
Cases[Partition[#,3,1],x_/;Sort@Sign@Differences@x=={-1,1}⧴x[[2]]]&

```

**Example**

```
Cases[Partition[#,3,1],x_/;Sort@Sign@Differences@x=={-1,1}:>x[[2]]]&[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]

```

> {10, 6, 9, 0, 1}

---

**Analysis**:

```
Partition[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]

```

> {{9, 10, 7}, {10, 7, 6}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {0, 3, 3}, {3, 3, 1}, {3, 1, 10}}

`%` refers to the result from the respective preceding line.

```
Differences/@ %

```

> {{1, -3}, {-3, -1}, {-1, 3}, {3, -9}, {-9, 3}, {3, 0}, {0, -2}, {-2, 9}}

`Sort@Sign@Differences@x=={-1,1}` identifies the triples from {{9, 10, 7}, {10, 7, 6}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {0, 3, 3}, {3, 3, 1}, {3, 1, 10}} such that the sign (-, 0, +) of the differences consists of a `-1` and a `1`. In the present case those are:

> {{9, 10, 7}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {3, 1, 10}}

For each of these cases, x, `x[[2]]` refers to the second term. Those will be all of the local maxima and minima.

> {10, 6, 9, 0, 1}

# Answer
> 6 votes
# J - 19 char

Couldn't help it ;)

```
(}:#~0,0>2*/\2-/\])

```

Explanation follows:

* `2-/\]` \- Over each pair of elements in the argument (each 2-item long infix), take the difference.
* `2*/\` \- Now over each pair of the new list, take the product.
* `0>` \- Test whether each result is less than 0. This only happens if the multiplicands had alternating signs, i.e. it doesn't happen if they had the same sign or either was zero.
* `0,` \- Declare that the first element isn't an extreme element.
* `}:` \- Cut off the last element, because that can't possibly be an extreme either.
* `#~` \- Use the true values on the right side to pick items from the list on the left side.

Usage:

```
   (}:#~0,0>2*/\2-/\]) 1 2 1
2
   (}:#~0,0>2*/\2-/\]) 0 1 0 1 0
1 0 1
   (}:#~0,0>2*/\2-/\]) i.0   NB. i.0 is the empty list (empty result also)

   (}:#~0,0>2*/\2-/\]) 3 4 4 4 2 5
2

```

# Answer
> 5 votes
# Javascript - ~~62~~ 45 Characters

```
f=a=>a.filter((x,i)=>i&&i<a.length-1&&(a[i-1]-x)*(a[i+1]-x)>0)

```

**Edit**

```
f=a=>a.filter((x,i)=>(a[i-1]-x)*(a[i+1]-x)>0)

```

# Answer
> 4 votes
# Ruby, ~~83~~ ~~70~~ ~~60~~ ~~55~~ 49 characters

```
f=->a{a.each_cons(3){|x,y,z|p y if(x-y)*(z-y)>0}}

```

Prints all local extremes to STDOUT.

~~Uses the `<=>` "spaceship" operator, which I really like. (It returns 1 if the first thing is greater than the second, -1 if it's less, and 0 if equal. Therefore, if they add to -2 or 2, that means the middle is an extreme.)~~

~~Not anymore, as @daniero pointed out that the "obvious" way is actually shorter!~~

Changed yet again! Now it uses the awesome algorithm found in MT0's answer (+1 to him!).

Also, I like `each_cons` which selects each `n` groups of consecutive elements in an array. And trailing `if` is interesting too.

Overall, I just like how elegant it looks.

Some sample runs:

```
irb(main):044:0> f[[1,2,1]]
2
=> nil
irb(main):045:0> f[[1,0,1,0,1]]
0
1
0
=> nil
irb(main):046:0> f[[]]
=> nil
irb(main):047:0> f[[1,2,3,4,5,4,3,2,1]]
5
=> nil
irb(main):048:0> f[[1,1,1,1,1]]
=> nil
irb(main):049:0> f[[10,0,999,-45,3,4]]
0
999
-45
=> nil

```

# Answer
> 3 votes
# C++ - 208 chars

Longest solution again:

```
#include<iostream>
#include<deque>
using namespace std;
int main(){deque<int>v;int i;while(cin){cin>>i;v.push_back(i);}for(i=0;i<v.size()-2;)if(v[++i]>v[i-1]&v[i]>v[i+1]|v[i]<v[i-1]&v[i]<v[i+1])cout<<v[i]<<' ';}

```

To use, enter your integers, then any character that will crash the input stream - any non-number characters should work.

Input: `0 1 0 x`

Output: `1`

# Answer
> 3 votes
# Jelly, 8 bytes

```
IṠIỊ¬T‘ị

```

Try it online!

## Explanation

```
IṠIỊ¬T‘ị
I          Differences between adjacent elements {of the input}
 Ṡ         Take the sign of each difference
  I        Differences between adjacent difference signs
   Ị       Mark the elements that are     in the range -1..1 inclusive
    ¬                                 not
     T     Take the indexes of the marked elements
      ‘      with an offset of 1
       ị   Index back into the original list

```

An element is only a local extreme if its difference with its left neighbour has an opposite sign to its difference with its right neighbour, i.e. the signs of the differences differ by 2 or -2. Jelly has a number of useful primitives for dealing with "find elements with certain properties" (in particular, we can find elements with certain properties in one list and use that to extract elements from a different list), meaning that we can translate back to the original list more or less directly (we just need to offset by 1 because the first and last elements of the original list got lost in the difference-taking).

# Answer
> 2 votes
# Python 2.7 - 73 bytes

```
e=lambda l:[l[i]for i in range(1,len(l)-1)if(l[i]-l[i-1])*(l[i]-l[i+1])]

```

Not too impressive (Look at every element of the list except the first and last, see if it's larger or smaller than its neighbours). I'm mostly only posting it because not everyone knows you can do `x<y>z` and have it work. I think that's kind of neat.

Yes, `x<y>z` is a cool feature of python, but it's not actually optimal in this case. Thanks to V-X for the multiplication trick, that didn't occur to me at all. Wrzlprmft reminded me that declaring an anonymous function is less keystrokes than `def x(y):`.

# Answer
> 2 votes
# Matlab - 45 bytes

```
x=input('');y=diff(x);x(find([0 y].*[y 0]<0))

```

# Answer
> 2 votes
**Haskell 50**

```
f a=[x|(p,x,n)<-zip3 a(tail a)(drop 2 a),x>p&&x>n]

```

# Answer
> 2 votes
# 05AB1E, ~~11~~ 10 bytes

```
¥.±¥Ä2Q0šÏ

```

Try it online or verify a few more test cases.

**Explanation:**

```
¥           # Get the forward differences (deltas) of the (implicit) input-list
            #  i.e. [9,10,7,6,9,0,3,3,1,10] → [1,-3,-1,3,-9,3,0,-2,9]
 .±         # Get the signum of each delta (-1 if neg.; 0 if 0; 1 if pos.)
            #  → [1,-1,-1,1,-1,1,0,-1,1]
   ¥        # Get the forward differences of that list again
            #  → [-2,0,2,-2,2,-1,-1,2]
    Ä       # Convert each integer to its absolute value
            #  → [2,0,2,2,2,1,1,2]
     2Q     # And now check which ones are equal to 2 (1 if truthy; 0 if falsey)
            #  → [1,0,1,1,1,0,0,1]
       0š   # Prepend a 0
            #  → [0,1,0,1,1,1,0,0,1]
         Ï  # And only leave the values in the (implicit) input-list at the truthy indices
            #  → [10,6,9,0,1]
            # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Python with Numpy – ~~81 74~~ 67 bytes (~~61~~ 54 without the `import` line)

```
import numpy
e=lambda a:a[1:-1][(a[2:]-a[1:-1])*(a[1:-1]-a[:-2])<0]

```

The input needs to be a Numpy array.

# Answer
> 1 votes
# C, 83

```
x,y,z;main(){y=z=0;while(scanf("%d",&x)){(y-z)*(y-x)>0?printf("%d ",y):1;z=y,y=x;}}

```

# Answer
> 1 votes
# awk - 32 chars

```
{c=b;b=a;a=$0;$0=b}(b-c)*(a-b)<0

```

No hope of beating a language like J or APL on brevity, but I thought I'd throw my hat into the ring anyway. Explanation:

* At any given time, `a`, `b`, and `c` hold `x_i`, `x_(i-1)`, and `x_(i-2)`
* `b-c` and `a-b` approximate the derivative before and after `x_(i-1)`
* If their product is negative, then one is negative and the other is positive, therfore `x_(i-1)` is a local extreme, so print

# Answer
> 1 votes
# Brachylog, 17 bytes

```
s₃{b≠h.&k≠&{⌉|⌋}}

```

Try it online!

Takes input through the input variable and generates the output through the output variable.

```
s₃{             }    For a length-3 substring of the input:
  {b                 its last two elements
    ≠                are distinct,
     h               and the first of those elements is
      .              the output variable;
       &k            its first two elements
         ≠           are also distinct;
          &{⌉| }     either its largest element
          &{ |⌋}     or its smallest element
                }    is also the output variable.

```

If runs of values could be guaranteed to be absent, `s₃{{⌉|⌋}.&bh}` would save four bytes.

# Answer
> 1 votes
# Perl 5 `-p`, 49 bytes

```
s/\d+ (?=(\d+) (\d+))/say$1if($1-$&)*($1-$2)>0/ge

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~43~~ ~~42~~ 41 bytes

```
BlockMap[#2&@@#/.Median@#->Set@$&,#,3,1]&

```

Try it online!

```
BlockMap[                       &,#,3,1]&   (* for every consecutive triple of elements *)
         #2&@@#                             (* take the second (middle) element, *)
               /.Median@#->Set@$            (* discarding it if it is not a local extreme *)

```

# Answer
> 0 votes
# Javascript: 102 characters

```
function h(a){for(u=i=[];++i<a.length-1;)if(x=a[i-1],y=a[i],z=a[i+1],(x-y)*(y-z)<0)u.push(y);return u}

```

# Answer
> 0 votes
## PHP, ~~116 114~~ 113

```
function _($a){for(;$a[++$i+1];)if(($b=$a[$i])<($c=$a[$i-1])&$b<($d=$a[$i+1])or$b>$c&$b>$d)$r[]=$a[$i];return$r;}

```

Example usage:

```
print_r(_(array(2, 1, 2, 3, 4, 3, 2, 3, 4)));

Array
(
    [0] => 1
    [1] => 4
    [2] => 2
)

```

# Answer
> 0 votes
# APL, 19 bytes

```
{⍵/⍨0,⍨0,0>2×/2-/⍵}

```

I converted the 20 char J version to APL. But I add a zero to the beginning and the end instead of removing the first and last digit. Otherwise it works just like the J version.

\- formal parameter omega. This is the input to the function.

# Answer
> 0 votes
# Haskell, 70C

Golfed version

```
e(a:b:c:r)
 |a<b&&b>c||a>b&&b<c=b:s
 |True=s
 where s=e(b:c:r)
e _=[]

```

Ungolfed version

```
-- if it's possible to get three elements from the list, take this one
extrema (a:b:c:rest)
    | a<b && b>c = b:rec
    | a>b && b<c = b:rec
    | otherwise = rec
    where rec = extrema (b:c:rest)
-- if there are fewer than three elements in the list, there are no extrema
extrema _ = []

```

# Answer
> 0 votes
# Python 2, 59 bytes

```
f=lambda l=0,c=0,*r:r and(c,)*(l<c>r[0]or l>c<r[0])+f(c,*r)

```

Try it online!

This function mostly avoids the costly business of indexing, by taking the elements of the list as arguments, instead of the list itself. While there is more than one element left in the list, we recursively build up the list, checking for a maximum at each step.

---
Tags: code-golf
---


title: Binary Numbers Magic Trick

text:
# Question
Title: Binary Numbers Magic Trick
The challenge is simply; output the following six 2D integer arrays:

```
[[ 1, 11, 21, 31, 41, 51],
 [ 3, 13, 23, 33, 43, 53],
 [ 5, 15, 25, 35, 45, 55],
 [ 7, 17, 27, 37, 47, 57],
 [ 9, 19, 29, 39, 49, 59]]

[[ 2, 11, 22, 31, 42, 51],
 [ 3, 14, 23, 34, 43, 54],
 [ 6, 15, 26, 35, 46, 55],
 [ 7, 18, 27, 38, 47, 58],
 [10, 19, 30, 39, 50, 59]]

[[ 4, 13, 22, 31, 44, 53],
 [ 5, 14, 23, 36, 45, 54],
 [ 6, 15, 28, 37, 46, 55],
 [ 7, 20, 29, 38, 47, 60],
 [12, 21, 30, 39, 52]]

[[ 8, 13, 26, 31, 44, 57],
 [ 9, 14, 27, 40, 45, 58],
 [10, 15, 28, 41, 46, 59],
 [11, 24, 29, 42, 47, 60],
 [12, 25, 30, 43, 56]]

[[16, 21, 26, 31, 52, 57],
 [17, 22, 27, 48, 53, 58],
 [18, 23, 28, 49, 54, 59],
 [19, 24, 29, 50, 55, 60],
 [20, 25, 30, 51, 56]]

[[32, 37, 42, 47, 52, 57],
 [33, 38, 43, 48, 53, 58],
 [34, 39, 44, 49, 54, 59],
 [35, 40, 45, 50, 55, 60],
 [36, 41, 46, 51, 56]]

```

What are these 2D integer arrays? These are the numbers used in a magic trick with cards containing these numbers:

The magic trick asks someone to think of a number in the range \[1, 60\], and give the one performing the magic trick all the cards which contain this number. The one performing the magic trick can then sum the top-left numbers (all a power of 2) of the given cards to get to the number the person was thinking of. Some additional explanation of why this works can be found here.

## Challenge rules:

* You can output the six 2D integer arrays in any reasonable format. Can be printed with delimiters; can be a 3D integer array containing the six 2D integer arrays; can be a string-list of lines; etc.
* You are allowed to fill the bottom right position of the last four cards with a negative value in the range `[-60, -1]` or character `'*'` instead of leaving it out to make the 2D integer arrays rectangular matrices (no, you are not allowed to fill them with `0` or a non-integer like `null`/`undefined` as alternative, with the exception of `*` since a star is also used in the actual cards).
* The order of the numbers in the matrices is mandatory. Although it doesn't matter for the physical magic trick, I see this challenge mainly as a - one, hence the restriction on order.
The order of the matrices themselves in the output list can be in any order, since it's clear from the top-left card which matrix is which.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

# Answer
> 6 votes
# MATL, ~~12~~ 11 bytes

-1 byte thanks to the master himself:)

```
60:B"@fQ6eq

```

Explanation:

```
60:           % create a vector [1,2,3,...,60]
   B          % convert to binary matrix (each row corresponds to one number)
    "         % loop over the columns and execute following commands:
     @f       % "find" all the nonzero entries and list their indices
       Q      % increment everything
        6e    % reshape and pad with a zero at the end
          q   % decrement (reverts the increment and makes a -1 out of the zero
              % close loop (]) implicitly
              % display the entries implicitly

```

Try it online!

# Answer
> 8 votes
# Perl 6, ~~63~~ 46 bytes

```
say grep(*+&2**$_,^61)[$_,*+5...*for ^5]for ^6

```

Try it online!

Outputs as 2D arrays on multiple lines, with the last array of each one cut off if necessary.

# Answer
> 7 votes
# Python 2, 76 bytes

```
r=range;print[[[i for i in r(61)if i&2**k][j::5]for j in r(5)]for k in r(6)]

```

Try it online!

The method here is to create a list of all possible numbers `r(61)` and then whittle that down to the list of numbers for a card `i&2**k`.

Then, by using list slicing, that 1D list of numbers is rearranged to the correct 6x5 card size `[card nums][j::5]for j in r(5)`.

Then, this generator is just repeated for 6 cards `for k in r(6)`.

---

While I could not find any solutions less than 76 bytes, here are two others that are also 76 bytes:

```
r=range;print[[[i for i in r(61)if i&1<<k][j::5]for j in r(5)]for k in r(6)]

```

Try it online!

This next one is inspired by Jonathan Allan.

```
k=32
while k:print[[i for i in range(61)if i&k][j::5]for j in range(5)];k/=2

```

Try it online!

Any comments are greatly appreciated.

# Answer
> 6 votes
# Charcoal, 26 bytes

```
Ｅ⁶Ｅ⁵⪫Ｅ⁶§⁺§⪪Φ⁶¹＆πＸ²ι⁵ν⟦*⟧λ

```

Try it online! Link is to verbose version of code. I tried calculating the entries directly but this was already 27 bytes before adjusting for the `*` in the bottom right. Outputs each row joined with spaces and a blank line between cards. Explanation:

```
Ｅ⁶                          Loop over 6 cards
  Ｅ⁵                        Loop over 5 rows
     Ｅ⁶                     Loop over 6 columns
           Φ⁶¹              Filter over 0..60 where
               π            Current value
              ＆             Bitwise And
                 ²          Literal 2
                Ｘ           Raised to power
                  ι         Card index
          ⪪        ⁵        Split into groups of 5
         §          ν       Indexed by column
        ⁺                   Concatenated with
                      *     Literal string `*`
                     ⟦ ⟧    Wrapped in an array
       §                λ   Indexed by row
    ⪫                       Joined with spaces
                            Implicitly print

```

# Answer
> 6 votes
# 05AB1E, 16 bytes

```
60L2вíƶ0ζε0K5ô®ζ

```

Try it online!

**Explanation**

```
60L                 # push [1 ... 60]
   2в               # convert each to a list of binary digits
     í              # reverse each
      ƶ             # multiply each by its 1-based index
       0ζ           # transpose with 0 as filler
         ε          # apply to each list
          0K        # remove zeroes
            5ô      # split into groups of 5
              ®ζ    # zip using -1 as filler

```

# 05AB1E, 17 bytes

```
6F60ÝNoôāÈÏ˜5ô®ζ,

```

Try it online!

**Explanation**

```
6F                  # for N in [0 ... 5] do
  60Ý               # push [0 ... 60]
     Noô            # split into groups of 2^N numbers
        āÈÏ         # keep every other group
           ˜        # flatten
            5ô      # split into groups of 5
              ®ζ    # transpose with -1 as filler
                ,   # print

```

# Answer
> 5 votes
# Python 2, ~~82~~ ~~80~~ ~~78~~ 74 bytes

```
i=1
exec"print zip(*zip(*[(n for n in range(61)+[-1]if n&i)]*5));i*=2;"*6

```

Try it online!

<sub>-4 bytes, thanks to Jonathan Allan</sub>

# Answer
> 5 votes
# Husk, 13 bytes

```
ṠMöTC5Wnünḣ60

```

Try it online!

## Explanation

```
          ḣ60  Range [1..60]
        ü      Uniquify using equality predicate
         n     bitwise AND: [1,2,4,8,16,32]
 M             For each number x in this list,
Ṡ     W        take the indices of elements of [1..60]
       n       that have nonzero bitwise AND with x,
    C5         cut that list into chunks of length 5
  öT           and transpose it.

```

# Answer
> 5 votes
# Japt, 14 bytes

```
6Æ60õ f&2pX)ó5

```

Try it

```
6Æ              Create a range from 0 to 5 (inclusive) and map each X into
  60õ             Elements in the range [1..60]
      f             Where
       &2pX)          The number bitwise AND with X is not 0
  ó5              Split into 5 arrays, where each array contains every 5th element

-Q flag is just for formatting purposes

```

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

```
i,j,k;f(int o[][5][6]){for(i=6;i;)for(o[--i][4][5]=j=k=-1;j<60;)++j&1<<i?o[i][++k%5][k/5]=j:0;}

```

Try it online!

Returns the matrices as a 3D int array in o.

The last 4 matrices have -1 as their last value.

Saved 2 bytes thanks to Kevin Cruijssen.

Saved ~~7~~ 8 bytes thanks to Arnauld.

# Answer
> 4 votes
# JavaScript (ES6),  ~~90~~  88 bytes

```
_=>[1,2,4,8,16,32].map(n=>(g=i=>i<60?g(++i,i&n?m[y%5]=[...m[y++%5]||[],i]:0):m)(y=m=[]))

```

Try it online!

### Commented

```
_ =>                        // anonymous function taking no argument
  [1, 2, 4, 8, 16, 32]      // list of powers of 2, from 2**0 to 2**5
  .map(n =>                 // for each entry n in this list:
    ( g = i =>              //   g = recursive function taking a counter i
      i < 60 ?              //     if i is less than 60:
        g(                  //       recursive call:
          ++i,              //         increment i
          i & n ?           //         if a bitwise AND between i and n is non-zero:
            m[y % 5] =      //           update m[y % 5]:
            [ ...m[y++ % 5] //             prepend all previous values; increment y
              || [],        //             or prepend nothing if it was undefined so far
              i             //             append i
            ]               //           end of update
          :                 //         else:
            0               //           do nothing
        )                   //       end of recursive call
      :                     //     else:
        m                   //       return m[]
    )(y = m = [])           //   initial call to g with i = y = m = []
                            //   (i and y being coerced to 0)
  )                         // end of map()

```

# Answer
> 4 votes
# Python 2, 73 bytes

Inspiration taken from both TFeld's and The Matt's.

```
k=32
while k:print zip(*zip(*[(i for i in range(61)+[-1]if i&k)]*5));k/=2

```

**Try it online!**

# Answer
> 3 votes
# Wolfram Language (Mathematica), 88 bytes

```
Transpose@Partition[#~Append~-1,5]&/@Last@Reap[Sow[,NumberExpand[,2]]~Do~{,60},Except@0]

```

# Answer
> 3 votes
# Jelly, 13 bytes

```
60&ƇⱮs€5LÐṂZ€

```

A niladic Link which yields a list of (6) lists of lists of integers. (It outputs the using the default option of having no `*` or negative filler.)

**Try it online!**

### How?

Each matrix contains, in column-major order, the numbers up to \\$60\\$ which share the single set-bit with the top-left (minimal) number.

This program first makes ***all*** \\$60\\$ possible ordered lists of numbers in \\$\[1,60\]\\$ which share ***any*** set-bit(s) with their index number. It then splits each into chunks of \\$5\\$ and keeps only those with minimal length - which will be the ones where the index has only a single set-bit (and hence also being its minimal value). Finally it transposes each to put them into column-major order.

```
60&ƇⱮs€5LÐṂZ€ - Link: no arguments
60            - set the left argument to 60
    Ɱ         - map across ([1..60]) with:  (i.e. [f(60,x) for x in [1..60]])
   Ƈ          -   filter keep if:  (N.B. 0 is falsey, while non-zeros are truthy)
  &           -     bitwise AND
      €       - for each:
     s 5      -   split into chunks of five
         ÐṂ   - keep those with minimal:
        L     -   length
           Z€ - transpose each

```

---

Lots of 15s without realising the "minimal by length when split into fives" trick:

```
5Ż2*Ɱ60&ƇⱮs€5Z€
6µ’2*60&Ƈ)s€5Z€
60&ƇⱮ`LÞḣ6s€5Z€

```

...and, while attempting to find shorter, I got another 13 without needing the trick at all:

```
60B€Uz0Ts5ZƊ€

```

# Answer
> 3 votes
## CJam (18 bytes)

```
6{61{2A#&},5/zp}fA

```

Online demo. This is a full program which outputs to stdout.

### Dissection

```
6{             }fA    # for A = 0 to 5
  61{2A#&},           #   filter [0,61) by whether bit 2^A is set
           5/z        #   break into chunks of 5 and transpose to get 5 lists
              p       #   print

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 99 bytes

```
Transpose@Partition[#~FromDigits~2&/@Last@GatherBy[{0,1}~Tuples~6,#[[-k]]&],5]~Table~{k,6}/. 61->-1

```

Try it online!

# Answer
> 2 votes
# Jelly, 13 bytes

```
60B€Uz0µTs5Z)

```

Try it online!

Loosely based on flawr’s MATL answer. A niladic link which outputs a list of lists as required.

# Answer
> 2 votes
# , 73 bytes

```
`!`=as.raw;lapply(0:5,function(i)matrix(c((a=1:60)[(!a&!2^i)>0],-1),5,6))

```

I am not entirely sure if I have met the requirement for order, since R by default fills matrices by column, so the order such that it appears physically on the cards is the same as the way matrices are allocated in R.

Try it online!

# Answer
> 2 votes
# T-SQL, (1,168 1,139 bytes)

I just wanted to know I could do it.

**Optimised version**

```
 WITH g AS(SELECT 1 AS n UNION ALL SELECT n+1 FROM g WHERE n+1<61),B as(SELECT cast(cast(n&32 as bit)as CHAR(1))+cast(cast(n&16 as bit)as CHAR(1))+cast(cast(n&8 as bit)as CHAR(1))+cast(cast(n&4 as bit)as CHAR(1))+cast(cast(n&2 as bit)as CHAR(1))+cast(cast(n&1 as bit)as CHAR(1))as b FROM g),P as(SELECT * from (values(1), (2), (4), (8), (16), (32)) as Q(p)),S as(select distinct p,p+(substring(b,6,1)*1)*(case when p=1 then 0 else 1 end)+(substring(b,5,1)*2)*(case when p=2 then 0 else 1 end)+(substring(b,4,1)*4)*(case when p=4 then 0 else 1 end)+(substring(b,3,1)*8)*(case when p=8 then 0 else 1 end)+(substring(b,2,1)*16)*(case when p=16 then 0 else 1 end)+(substring(b,1,1)*32)*(case when p=32 then 0 else 1 end)as e from P cross apply B),D as(select * from S where e>=p and e<61),R as(select p,(row_number()over(partition by p order by cast(e as int)))%5 as r,e from D),H as(select k.p,'['+stuff((select','+cast(l.e as varchar)from R l where l.p=k.p and l.r=k.r for xml path('')),1,1,'')+']'as s from R k group by k.p,k.r)select stuff((select','+cast(x.s as varchar)from H x where x.p=z.p for xml path('')),1,1,'')from H z group by z.p

```

**Online demo**

Try it online!

**Verbose version - with notes as SQL comments**

```
WITH gen -- numbers 1 to 60
AS (
    SELECT 1 AS num
    UNION ALL
    SELECT num+1 FROM gen WHERE num+1<=60
),
BINARIES -- string representations of binaries 000001 through 111111
as (
SELECT
    +cast( cast(num & 32 as bit) as CHAR(1))
    +cast( cast(num & 16 as bit)  as CHAR(1))
    +cast( cast(num & 8 as bit)  as CHAR(1))
    +cast( cast(num & 4 as bit)  as CHAR(1))
    +cast( cast(num & 2 as bit)   as CHAR(1))
    +cast(cast(num & 1 as bit)  as CHAR(1)) as binry FROM gen
),
POWERS -- first 6 powers of 2
as (
SELECT * from (values(1), (2), (4), (8), (16), (32)) as Q(powr)
),
SETELEMENTS -- cross apply the six powers of 2 against the binaries
-- returns 2 cols. col 1 = the power of 2 in question.
-- col 2 is calculated as that power of 2 plus the sum of each power of 2 other than the current row's power value,
-- but only where a given power of 2 is switched "on" in the binary string,
-- ie. where the first digit in the string represents 32, the second represents 16 and so on.
-- That is, if the binary is 100100 then the number will be
-- the sum of (32 x 1) + (16 x 0) + (8 x 0) + (4 x 1) + (2 x 0) + (1 x 0)
-- but if the current row's power is 32 or 4, then just that number (32 or 4) is excluded from the sum.
-- rows are distinct.
as (
select distinct powr,
powr+
 (substring(binry,6,1) * 1) * (case when powr = 1 then 0 else 1 end)
 +(substring(binry,5,1) * 2) * (case when powr = 2 then 0 else 1 end)
 +(substring(binry,4,1) * 4) * (case when powr = 4 then 0 else 1 end)
 +(substring(binry,3,1) * 8) * (case when powr = 8 then 0 else 1 end)
 +(substring(binry,2,1) * 16) * (case when powr = 16 then 0 else 1 end)
 +(substring(binry,1,1) * 32) * (case when powr = 32 then 0 else 1 end) as elt
from POWERS cross apply BINARIES
),
DISTINCTELEMENTS -- purge calculated numbers smaller than the power of 2 or greater than 60
as (
select * from SETELEMENTS where elt >= powr and elt < 61
)--,
,
ROWNUMBERED -- for each power, number the rows repeatedly from 0 through 5, then back to 0 through 5 again, etc
as (
select powr, (row_number() over (partition by powr order by cast(elt as int)))%5 as r, elt  from DISTINCTELEMENTS
),
GROUPEDSETS -- for each row number, within each power, aggregate the numbers as a comma-delimited list and wrap in square brackets - the inner arrays
as (
select r1.powr, '['+stuff((select ',' + cast(r2.elt as varchar) from ROWNUMBERED r2 where r2.powr = r1.powr and r2.r = r1.r for xml path('')),1,1,'')+']' as s
from ROWNUMBERED r1
group by r1.powr,r1.r
)
select -- now aggregate all the inner arrays per power
stuff((select ',' + cast(g2.s as varchar) from GROUPEDSETS g2 where g2.powr = g1.powr for xml path('')),1,1,'')
from GROUPEDSETS g1
group by g1.powr

```

**Voila!**

Note 1: Some of the logic pertains to rendering square brackets and commas.

Note 2: Newer versions of SQLServer have more compact approaches to creating comma-delimited lists. (This was created on SQL Server 2016.)

Note 3: Arrays for a given card are not sorted (which is ok per the spec). Numbers within an array are correctly sorted. In this case, each "card" of the question, renders its arrays on a separate row in the results.

**Shorter to hard-code arrays?**

Yes.

Byte me.

# Answer
> 1 votes
# APL+WIN, ~~65~~ 62 bytes

```
v←∊+\¨n,¨29⍴¨1↓¨(n⍴¨1),¨1+n←2*0,⍳5⋄((v=61)/v)←¯1⋄1 3 2⍉6 6 5⍴v

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 112 bytes

```
_=>" ".Select(x=>Enumerable.Range(1,60).Where(l=>(l&x)>0).Select((a,b)=>new{a,b}).GroupBy(i=>i.b%5,i=>i.a))

```

Try it online!

# Answer
> 1 votes
# Red, ~~108~~ 107 bytes

```
n: 32 until[b: collect[repeat k 60[if n and k = n[keep k]]]loop 5[print
extract b 5 b: next b]1 > n: n / 2]

```

Try it online!

# Answer
> 1 votes
**MATLAB, 155 bytes**

```
cellfun(@disp,cellfun(@(x)x-repmat(62,5,6).*(x>60),cellfun(@(x)reshape(find(x,30),[5 6]),mat2cell(dec2bin(1:62)-48,62,ones(1,6)),'Uniform',0),'Uniform',0))

```

This could be shorter as multiple lines but I wanted to do it in one line of code.

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
žOε60LDNo&ĀÏ5ι

```

Try it online!

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


# Question
Title: Output the ŋarâþ crîþ alphabet song without using (m)any letters
Your goal is to write a program that takes no input and outputs the following text:

```
ca e na ŋa va o sa;
þa ša ra la ła.
ma a pa fa ga ta ča;
în ja i da ða.
ar ħo ên ôn ân uħo;
carþ taŋ neŋ es nem.
elo cenvos.

```

But there's a catch: for each letter (any character whose general category in Unicode starts with `L`) in your source, you get a penalty of 20 characters! (For reference, the text to be printed has 81 letters.)

The Perl 6 code below has 145 bytes and 84 letters, so it gets a score of 1,845:

```
say "ca e na ŋa va o sa;
þa ša ra la ła.
ma a pa fa ga ta ča;
în ja i da ða.
ar ħo ên ôn ân uħo;
carþ taŋ neŋ es nem.
elo cenvos."

```

The code below has 152 bytes and 70 letters, so it gets a score of 1,552:

```
$_="C e N ŋa V o S;
Þ Š R L Ł.
M a P F G T Č;
în J i D Ð.
ar ħo ên ôn ân uħo;
Crþ Tŋ neŋ es nem.
elo cenvos.";s:g/<:Lu>/{$/.lc~'a'}/;.say

```

Standard loopholes are forbidden.

*Originally, I thought of forbidding letters altogether, but I don't think there are many languages that make this possible. You're more than welcome to try.*

*(ŋarâþ crîþ \[ˈŋaɹa̰θ kɹḭθ\] is one of my conlangs. I wanted to capitalise its name here, but I get the ugly big eng here. Oh well, the language doesn't use capital letters in its romanisation anyway.)*

*Edit: realised that one of the lines is wrong, but I'll keep it since there are already answers. The correct version of the third line is `ma a fa ga pa ta ča`; at your choice, you may choose to produce the corrected text instead.*

# Answer
# , 410 characters, 154 bytes in 7's encoding, 0 letters = score 154

```
55104010504200144434451510201304004220120504005434473340353241135014335450302052254241052253052244241052335452241114014241310052340435303052335442302052335500302052335430302052313340435303135014243241310335514052312241341351052302245341351525755102440304030434030421030442030424030455733413512410523142410523030523112411350143355142410523414252410523102410523002410523413342411145257551220304010420030455741403

```

Try it online!

In a challenge that dislikes using letters, what better language to use than one consisting only of digits?

This is a full program that exits via crashing, so there's extraneous output to stderr, but stdout is correct.

## Explanation

A 7 program, on its first iteration, simply pushes a number of elements to the stack (because out of the 12 commands that exist in 7, only 8 of them can be represented in a source program, and those 8 are specialised for writing code to push particular data structures to the stack). This program does not use the **`6`** command (which is the simplest way to create nested structures, but otherwise tends not to appear literally in a source program), so it's only the **`7`** commands that determine the structure; **`7`** pushes a new empty element to the top of stack (whereas the `0``5` commands just append to the top of stack). We can thus add whitespace to the program to show its structure:

```
551040105042001444344515102013040042201205040054344 **7**

33403532411350143354503020522542410522530522442410523354522411140142413100523
40435303052335442302052335500302052335430302052313340435303135014243241310335
514052312241341351052302245341351525 **7**

55102440304030434030421030442030424030455 **7**

33413512410523142410523030523112411350143355142410523414252410523102410523002
41052341334241114525 **7**

551220304010420030455 **7**

41403
```

The elements near the end of the program are pushed last, so are on top of the stack at the start of the second iteration. On this iteration, and all future iterations, the 7 interpreter automatically makes a copy of the top of the stack and interprets it as a program. The literal `41403` pushes the (non-literal, live code) **`47463`** (7 has 12 commands but only 8 of them have names; as such, I use bold to show the code, and non-bold to show the literal that generates that code, meaning that, e.g. `4` is the command that appends **`4`** to the top stack element). So the program that runs on the second iteration is **`47463`**. Here's what that does:

```
**47463**
**4**       Swap top two stack elements, add an empty element in between
 **7**      Add an empty stack element to the top of stack
  **4**     Swap top two stack elements, add an empty element in between
   **6**    Work out which commands would generate the top stack element;
        append that to the element below (and pop the old top of stack)
    **3**   Output the top stack element, pop the element below

```

This is easier to understand if we look at what happens to the stack:

* *d* *c* *b* *a* **`47463`** (code to run: **`47463`**)
* *d* *c* *b* **`47463`** *empty* *a* (code to run: **`7463`**)
* *d* *c* *b* **`47463`** *empty* *a* *empty* (code to run: **`463`**)
* *d* *c* *b* **`47463`** *empty* *empty* *empty* *a* (code to run: **`63`**)
* *d* *c* *b* **`47463`** *empty* *empty* "*a*" (code to run: **`3`**)
* *d* *c* *b* **`47463`** *empty* (code to run: *empty*)

In other words, we take the top of stack *a*, work out what code is most likely to have produced it, and output that code. The 7 interpreter automatically pops empty elements from the top of stack at the end of an iteration, so we end up with the **`47463`** back on top of the stack, just as in the original program. It should be easy to see what happens next: we end up churning through every stack element one after another, outputting them all, until the stack underflows and the program crashes. So we've basically created a simple output loop that looks at the program's *source code* to determine what to output (we're not outputting the data structures that were pushes to the stack by our `0``5` commands, we're instead recreating what commands were used by looking at what structures were created, and outputting those). Thus, the first piece of data output is `551220304010420030455` (the source code that generates the second-from-top stack element), the second is `3341351…114525` (the source code that generates the third-from-top stack element), and so on.

Obviously, though, these pieces of source code aren't being output unencoded. 7 contains several different domain-specific languages for encoding output; once a domain-specific language is chosen, it remains in use until explicitly cleared, but if none of the languages have been chosen yet, the first digit of the code being output determines which of the languages to use. In this program, only two languages are used: `551` and `3`.

`551` is pretty simple: it's basically the old Baudot/teletype code used to transmit letters over teletypes, as a 5-bit character set, but modified to make all the letters lowercase. So the first chunk of code to be output decodes like this:

```
551  22 03 04 01 04 20 03 04  55
     c  a  SP e  SP n  a  SP  reset output format

```

As can be seen, we're fitting each character into two octal digits, which is a pretty decent compression ratio. Pairs of digits in the 0-5 range give us 36 possibilities, as opposed to the 32 possibilities that Baudot needs, so the remaining four are used for special commands; in this case, the `55` at the end clears the remembered output format, letting us use a different format for the next piece of output we produce.

`3` is conceptually even simpler, but with a twist. The basic idea is to take groups of three digits (again, in the 0-5 range, as those are the digits for which we can guarantee that we can recreate the original source code from its output), interpret them as a three-digit number in base 6, and just output it as a byte in binary (thus letting us output the multibyte characters in the desired output simply by outputting multiple bytes). The twist, though, comes from the fact that there are only 216 three-digit numbers (with possible leading zeroes) in base 6, but 256 possible bytes. 7 gets round this by linking numbers from 332₆ = 128₁₀ upwards to two different bytes; `332` can output either byte 128 or 192, `333` either byte 129 or 193, and so on, up to `515` which outputs either byte 191 or 255.

How does the program know which of the two possibilities to output? It's possible to use triplets of digits from `520` upwards to control this explicitly, but in this program we don't have to: 7's default is to pick all the ambiguous bytes in such a way that the output is valid UTF-8! It turns out that there's always at most one way to do this, so as long as it's UTF-8 we want (and we do in this case), we can just leave it ambiguous and the program works anyway.

The end of each of the `3…` sections is `525`, which resets the output format, letting us go back to `551` for the next section.
> 22 votes

# Answer
## Haskell, 0 letters, 423 bytes = score 423

```
(['\10'..]!!)<$>[89,87,22,91,22,100,87,22,321,87,22,108,87,22,101,22,105,87,49,0,244,87,22,343,87,22,104,87,22,98,87,22,312,87,36,0,99,87,22,87,22,102,87,22,92,87,22,93,87,22,106,87,22,259,87,49,0,228,100,22,96,87,22,95,22,90,87,22,230,87,36,0,87,104,22,285,101,22,224,100,22,234,100,22,216,100,22,107,285,101,49,0,89,87,104,244,22,106,87,321,22,100,91,321,22,91,105,22,100,91,99,36,0,91,98,101,22,89,91,100,108,101,105,36]

```

Try it online!
> 10 votes

# Answer
# Jelly,  ~~274 260~~  212 bytes \+ 2 letters =  ~~314 300~~  252

-48 bytes thanks to Nick Kennedy

```
“19×‘+49;7883,8220,8216,7884Ọ“19937801,1169680277365253“38“68112“;107¤+1+\“@“&%"("/%"@%"6%"0"3%$!<%" %"2%"-%"?%#!.%"%"1%")%"*%"4%"=%$!9/",%"+"'%":%#!%2">0"8/";/"7/"5>0$!&%2<"4%@"/(@"(3"/(.#!(-0"&(/603#“_32¤”;";/V

```

(Uses `!"#$%&'()*+,-./0123456789:;<=>?@V\_¤×Ọ‘“”` of which `V` and  are Unicode letters and are used once each)

**Try it online!**
> 6 votes

# Answer
# PowerShell, scores ~~601~~ 546

```
-join(67,65,0,69,0,78,65,0,299,65,0,86,65,0,79,0,83,65,27,-22,222,65,0,321,65,0,82,65,0,76,65,0,290,65,14,-22,77,65,0,65,0,80,65,0,70,65,0,71,65,0,84,65,0,237,65,27,-22,206,78,0,74,65,0,73,0,68,65,0,208,65,14,-22,65,82,0,263,79,0,202,78,0,212,78,0,194,78,0,85,263,79,27,-22,67,65,82,222,0,84,65,299,0,78,69,299,0,69,83,0,78,69,77,14,-22,69,76,79,0,67,69,78,86,79,83,14|%{[char]($_+32)})

```

Try it online!

Naive approach; I just took the code points and converted them to decimal, subtracted 32, then this code treats them as a `char` before `-join`ing it back together into a single string.
> 3 votes

# Answer
# Jelly, 321 bytes + 2 letters = score 361

```
3343781777797791350694255572961968519437585132057650209974147122192542459108221624793330048943528237823681411832154316740173721249435700067706302064570847610741421342406380917446310820012503592770000532190167243585300911078873144513786923305473352724133578818457026824110152529235136461572588027747840738399150398304b354Ọ

```

Try it online!

This is hideous and someone can definitely do better.

Verify score.
> 3 votes

# Answer
# 05AB1E, score ~~209~~ 207 (187 bytes + 20 penalty for 1 letter)

```
•£?;\:'%¢;.'¡£/':¢?'¢°':¢°#@¢«>#%¡¤;®[¢:¥¢:©¢:¦¢;®¢>#¡£#¨¢#&¢+¢#,¢:§¡¤#¬¢#@¢#)¢#(¢#<¢#¢#/¡£#¯¢#.¢#>¢#±¢#«¡¤#?¢;¢#\¢#°¢#:¢'¢#%•[₅‰`©®_#∞158+9022014013016708040204090101502501027¾¡17∍.¥>:ç?

```

Try it online!

The only letter is `ç`. The currency symbols `€£¢` are not considered letters in Unicode.
> 3 votes

# Answer
# Python 3, 380 bytes + 5 letters = 480

```
print("""\143\141 \145 \156\141 \513\141 \166\141 \157 \163\141;
\376\141 \541\141 \162\141 \154\141 \502\141.
\155\141 \141 \160\141 \146\141 \147\141 \164\141 \415\141;
\356\156 \152\141 \151 \144\141 \360\141.
\141\162 \447\157 \352\156 \364\156 \342\156 \165\447\157;
\143\141\162\376 \164\141\513 \156\145\513 \145\163 \156\145\155.
\145\154\157 \143\145\156\166\157\163.""")

```

Try it online!
> 2 votes

# Answer
# Retina, 140 characters, 159 bytes, 14 letters = score 439

```

%# ' 1# !# 9# 2 6#;¶þ# š# 5# /# ł#.¶0# # 3# (# )# 7# č#;¶î1 ,# + &# ð#.¶#5 ħ2 ê1 ô1 â1 8ħ2;¶%#5þ 7#! 1'! '6 1'0.¶'/2 %'1926.
T`!--/-9`ŋ\`-{

```

Try it online! Edit: Saved 1 letter by switching from `K`` to a newline. Now also works in Retina 0.8.2 (but the title would be too long).
> 1 votes

# Answer
# Japt `-S`, ~~304~~ 286 bytes + ~~2~~ 1 letter~~s~~ = ~~344~~ 306

Well, this is just god-awful!

```
"3 1
5
14 1
235 1
22 1
15
19 1 -37 -86 158 1
257 1
18 1
12 1
226 1 -50 -86 13 1
1
16 1
6 1
7 1
20 1
173 1 -37 -86 142 14
10 1
9
4 1
144 1 -50 -86 1 18
199 15
138 14
148 14
130 14
21 199 15 -37 -86 3 1 18 158
20 1 235
14 5 235
5 19
14 5 13 -50 -86 5 12 15
3 5 14 22 15 19 -50"·®¸®°d96} ¬

```

Try it
> 1 votes

# Answer
# PHP -a, 402 bytes + 200 penalty = 602 score

```
foreach([67,65,0,69,0,78,65,0,299,65,0,86,65,0,79,0,83,65,27,-22,222,65,0,321,65,0,82,65,0,76,65,0,290,65,14,-22,77,65,0,65,0,80,65,0,70,65,0,71,65,0,84,65,0,237,65,27,-22,206,78,0,74,65,0,73,0,68,65,0,208,65,14,-22,65,82,0,263,79,0,202,78,0,212,78,0,194,8,0,85,263,79,27,-22,67,65,82,222,0,84,65,299,0,78,69,299,0,69,83,0,78,69,77,14,-22,69,76,79,0,67,69,78,86,79,83,14] as $i){echo ''.mb_chr($i+32);}

```

Port of Artermis Fowl's answer, and my first codegolf entry!

Leaves me wishing that `chr()` could just support UTF-8; those extra 3 bytes + 40 characters hurts!
> 1 votes

# Answer
# Python 3, 397 bytes + 19 letters = 777 score

```
print(''.join(chr(i+32)for i in[67,65,0,69,0,78,65,0,299,65,0,86,65,0,79,0,83,65,27,-22,222,65,0,321,65,0,82,65,0,76,65,0,290,65,14,-22,77,65,0,65,0,80,65,0,70,65,0,71,65,0,84,65,0,237,65,27,-22,206,78,0,74,65,0,73,0,68,65,0,208,65,14,-22,65,82,0,263,79,0,202,78,0,212,78,0,194,78,0,85,263,79,27,-22,67,65,82,222,0,84,65,299,0,78,69,299,0,69,83,0,78,69,77,14,-22,69,76,79,0,67,69,78,86,79,83,14]))

```

Try it online!

Port of AdmBorkBork's answer.
> 0 votes

# Answer
# 05AB1E, score ~~383~~ 365 (325 bytes \+ 2 letters * 20 penalty)

```
3343781777797791350694255572961968519437585132057650209974147122192542459108221624793330048943528237823681411832154316740173721249435700067706302064570847610741421342406380917446310820012503592770000532190167243585300911078873144513786923305473352724133578818457026824110152529235136461572588027747840738399150398304 354вç.««

```

Port of *@HyperNeutrino*'s Jelly answer.

Will try to improve here on. The number is divisible by a bunch of numbers, but none of them would save any bytes unfortunately, and the larger divisors compressed contain at least 1 letter..

-18 (+2 bytes and -20 penalty) thanks to *@Grimy*, replacing the letter `J` (join) with `.««` (reduce by concatenating).

Try it online.
> 0 votes

# Answer
# , 384 bytes + 12 letters * 20 points = *684 score*

Not terribly original.

```
cat(intToUtf8(c(67,65,0,69,0,78,65,0,299,65,0,86,65,0,79,0,83,65,27,-22,222,65,0,321,65,0,82,65,0,76,65,0,290,65,14,-22,77,65,0,65,0,80,65,0,70,65,0,71,65,0,84,65,0,237,65,27,-22,206,78,0,74,65,0,73,0,68,65,0,208,65,14,-22,65,82,0,263,79,0,202,78,0,212,78,0,194,78,0,85,263,79,27,-22,67,65,82,222,0,84,65,299,0,78,69,299,0,69,83,0,78,69,77,14,-22,69,76,79,0,67,69,78,86,79,83,14)+32))

```

Try it online!
> 0 votes

---
Tags: code-challenge, kolmogorov-complexity, restricted-source
---


title: Write a radiation-hardened irradiator

text:
# Question
Title: Write a radiation-hardened irradiator
The task is to write a radiation-hardened irradiator. What do I mean by that, exactly?

An irradiator is a program that, when given a string as input, will output all possible versions of the string with one character removed. For example, given the input `Hello, world!`, the program should output:

```
ello, world!
Hllo, world!
Helo, world!
Helo, world!
Hell, world!
Hello world!
Hello,world!
Hello, orld!
Hello, wrld!
Hello, wold!
Hello, word!
Hello, worl!
Hello, world

```

An irradiator, however, must be protected from its radiation, so the irradiator you write must also survive when put through itself. That is, when any single byte of your program is removed, the program must still function properly.

## Test cases

```
abc -> bc; ac; ab
foo bar -> oo bar:fo bar:fo bar:foobar:foo ar:foo br:foo ba
source -> ource;surce;sorce;souce;soure;sourc;

```

## Specifications

* You may take input by any acceptable method by our Standard I/O rules
* The output may be either a list of strings or a printed list delimited by a character or group of characters. A trailing delimiter is acceptable
* The output may be in any order as long as it contains all of the possible versions
* Duplicate entries (such as the two `Helo, world!`s in the first example) may be filtered out, but this is not necessary
* As this is , the smallest program, in bytes, wins

# Answer
> 14 votes
# 05AB1E, ~~29~~ 26 bytes

```
æIg<ùˆ\æIg<ùˆ\æIg<ùˆ¯¯{Å`s

```

Try it online!, or try all irradiated versions.

The shortest irradiator I could find is 5 bytes:

```
æ        # powerset of the input
 Ig      # length of the input
   <     # - 1
    ù    # elements of a with length b

```

The idea is to repeat that 3 times, then do majority voting:

```
æIg<ù         # irradiate
     ˆ        # add the result to the global array
      \       # pop (in case the above instruction gets irradiated)
æIg<ùˆ\       # idem
æIg<ùˆ        # no pop, it's okay to dirty the stack at this point
¯             # push global array
 ¯            # and again, so at least one goes through
  {           # sort
   Å          # conveniently ignored by the parser
    `         # dump
     s        # swap
              # and implicitly output

```

`Å` is a prefix for 2-byte commands, but there's no `Å`` command, which is why the `Å` gets ignored. We'll need it later, though.

Sorting makes sure the majority vote is in the middle of the array. Dumping then swapping gets that value to the top of the stack.

Any irradiation in the initial part only results in an error in the global array, which gets solved by the majority vote. Irradiations in the final `{Å`s` bit are much trickier to reason about:

* `Å` is ignored anyway, so it's okay to irradiate it
* If the backtick is irradiated, `Å`s` becomes `Ås`, which is the "get middle of the array" extended command.
* If `{` or `s` are irradiated, that means nothing else is, so the global array is the same value three times. In that case we don't need sorting/swapping, any value will work.

# Answer
> 5 votes
# 8086 machine code (MS-DOS .COM), 83 bytes

Runnable in DOSBox or your favourite steam-powered computing engine. The string to irradiate is given as a command line argument.

Binary:

```
00000000 : EB 28 28 8A 0E 80 00 49 BD 83 00 B4 02 51 8A 0E : .((....I.....Q..
00000010 : 80 00 BE 82 00 AC 39 EE 74 04 88 C2 CD 21 E2 F5 : ......9.t....!..
00000020 : 59 45 B2 0A CD 21 E2 E5 C3 90 EB D7 D7 8A 0E 80 : YE...!..........
00000030 : 00 49 BD 83 00 B4 02 51 8A 0E 80 00 BE 82 00 AC : .I.....Q........
00000040 : 39 EE 74 04 88 C2 CD 21 E2 F5 59 45 B2 0A CD 21 : 9.t....!..YE...!
00000050 : E2 E5 C3                                        : ...

```

Readable:

```
cpu 8086
org 0x100
    jmp part2
    db 0x28

part1:
    mov cl, [0x80]
    dec cx
    mov bp, 0x83
    mov ah, 0x02

.l:
    push cx
    mov cl, [0x80]
    mov si, 0x82
.k:
    lodsb
    cmp si, bp
    je .skip
    mov dl, al
    int 0x21
.skip:
    loop .k
    pop cx
    inc bp
    mov dl, 10
    int 0x21
    loop .l
    ret

    nop
part2:
    jmp part1
    db 0xd7
    mov cl, [0x80]
    dec cx
    mov bp, 0x83
    mov ah, 0x02

.l:
    push cx
    mov cl, [0x80]
    mov si, 0x82
.k:
    lodsb
    cmp si, bp
    je .skip
    mov dl, al
    int 0x21
.skip:
    loop .k
    pop cx
    inc bp
    mov dl, 10
    int 0x21
    loop .l
    ret

```

# Rundown

The active part is duplicated so that there is always one untouched by radiation. We select the healthy version by way of jumps. Each jump is a short jump, and so is only two bytes long, where the second byte is the displacement (i.e. distance to jump, with sign determining direction).

We can divide the code into four parts which could be irradiated: jump 1, code 1, jump 2, and code 2. The idea is to make sure a clean code part is always used. If one of the code parts is irradiated, the other must be chosen, but if one of the jumps is irradiated, both code parts will be clean, so it will not matter which one is chosen.

The reason for having two jump parts is to detect irradiation in the first part by jumping over it. If the first code part is irradiated, it means we will arrive one byte off the mark. If we make sure that such a botched landing selects code 2, and a proper landing selects code 1, we're golden.

For both jumps, we duplicate the displacement byte, making each jump part 3 bytes long. This ensures that irradiation in one of the two last bytes will still make the jump valid. Irradiation in the first byte will stop the jump from happening at all, since the last two bytes will form a completely different instruction.

Take the first jump:

```
EB 28 28        jmp +0x28 / db 0x28

```

If either of the `0x28` bytes are removed, it will still jump to the same place. If the `0xEB` byte is removed, we will instead end up with

```
28 28           sub [bx + si], ch

```

which is a benign instruction on MS-DOS (other flavours might disagree), and then we fall through to code 1, which must be clean, since the damage was in jump 1.

If the jump is taken, we land at the second jump:

```
EB D7 D7        jmp -0x29 / db 0xd7

```

If this byte sequence is intact, and we land right on the mark, that means that code 1 was clean, and this instruction jumps back to that part. The duplicated displacement byte guarantees this, even if it is one of these displacement bytes that were damaged. If we either land one byte off (because of a damaged code 1 or jump 1) or the `0xEB` byte is the damaged one, the two remaining bytes will also here be benign:

```
D7 D7           xlatb / xlatb

```

Whichever the case, if we end up executing those two instructions, we know that either jump 1, code 1, or jump 2 were irradiated, which makes a fall-through to code 2 safe.

## Testing

The following program was used to automatically create all versions of the .COM file. It also creates a BAT file that can be run in the target environment, which runs each irradiated binary, and pipes their outputs to separate text files. Comparing the output files to validate is easy enough, but DOSBox does not have `fc`, so it was not added to the BAT file.

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

int main(int argc, char **argv)
{
    FILE *fin, *fout, *fbat;
    int fsize;
    char *data;

    if (!(fin = fopen(argv[1], "rb")))
    {
        fprintf(stderr, "Could not open input file \"%s\".\n", argv[1]);
        exit(1);
    }

    if (!(fbat = fopen("tester.bat", "w")))
    {
        fprintf(stderr, "Could not create BAT test file.\n");
        exit(2);
    }

    fseek(fin, 0L, SEEK_END);
    fsize = ftell(fin);
    fseek(fin, 0L, SEEK_SET);

    if (!(data = malloc(fsize)))
    {
        fprintf(stderr, "Could not allocate memory.\n");
        exit(3);
    }

    fread(data, 1, fsize, fin);

    fprintf(fbat, "@echo off\n");

    for (int i = 0; i < fsize; i++)
    {
        char fname[512];

        sprintf(fname, "%03d.com", i);
        fprintf(fbat, "%s Hello, world! > %03d.txt\n", fname, i);

        fout = fopen(fname, "wb");

        fwrite(data, 1, i, fout);
        fwrite(data + i + 1, 1, fsize - i - 1, fout);

        fclose(fout);
    }

    free(data);
    fclose(fin);
    fclose(fbat);
}

```

---
Tags: code-golf, radiation-hardening
---


title: Find the nth decimal of pi

text:
# Question
Title: Find the nth decimal of pi
There are already 30 challenges dedicated to pi but not a single one asks you to find the nth decimal, so...

# Challenge

For any integer in the range of `0 <= n <= 10000` display the nth decimal of pi.

# Rules

* Decimals are every number after `3.`
* Your program may be a function, or a full program
* You must output the result in base 10
* You may get `n` from any suitable input method (stdin, input(), function parameters, ...), but not hardcoded
* You may use 1-based indexing if that's native to your language of choice
* You don't have to deal with invalid input (`n == -1`, `n == 'a'` or `n == 1.5`)
* Builtins are allowed, if they support up to **at least** 10k decimals
* Runtime doesn't matter, since this is about the shortest code and not the fastest code
* This is , shortest code in bytes wins

# Test cases

```
f(0)     == 1
f(1)     == 4 // for 1-indexed languages f(1) == 1
f(2)     == 1 // for 1-indexed languages f(2) == 4
f(3)     == 5
f(10)    == 8
f(100)   == 8
f(599)   == 2
f(760)   == 4
f(1000)  == 3
f(10000) == 5

```

For reference, here are the first 100k digits of pi.

# Answer
> 22 votes
## 05AB1E, 3 bytes

```
žs¤

```

**Explained**

```
žs   # push pi to N digits
  ¤  # get last digit

```

Try it online

Uses 1-based indexing.
Supports up to 100k digits.

# Answer
> 18 votes
## Python 2, 66 bytes

```
n=input()+9
x=p=5L**7
while~-p:x=p/2*x/p+10**n;p-=2
print`x/5`[-9]

```

Input is taken from stdin.

---

**Sample Usage**

```
$ echo 10 | python pi-nth.py
8

$ echo 100 | python pi-nth.py
8

$ echo 1000 | python pi-nth.py
3

$ echo 10000 | python pi-nth.py
5

```

# Answer
> 11 votes
# Bash + coreutils, ~~60~~ 49 bytes

~~`echo "scale=10100;4*a(1)"|bc -l|tr -d '\\\n'|cut -c$(($1+2))`~~

```
bc -l<<<"scale=$1+9;4*a(1)-3"|tr -dc 0-9|cut -c$1

```

Improved by Dennis. Thanks!

The index is one-based.

# Answer
> 11 votes
# Python 2, ~~73~~ ~~71~~ 73 bytes

thanks to @aditsu for increasing my score by 2 bytes

Finally an algorithm that can complete under 2 seconds.

```
n=10**10010
a=p=2*n
i=1
while a:a=a*i/(2*i+1);p+=a;i+=1
lambda n:`p`[n+1]

```

Ideone it!

Uses the formula `pi = 4*arctan(1)` while computing `arctan(1)` using its taylor series.

# Answer
> 7 votes
# MATL, ~~11~~ 10 bytes

*1 byte saved thanks to @Luis*

```
YPiEY$GH+)

```

This solution utilizes 1-based indexing

**Try it Online**

All test cases

**Explanation**

```
YP  % Pre-defined literal for pi
iE  % Grab the input and multiply by 2 (to ensure we have enough digits to work with)
Y$  % Compute the first (iE) digits of pi and return as a string
G   % Grab the input again
H+  % Add 2 (to account for '3.') in the string
)   % And get the digit at that location
    % Implicitly display the result

```

# Answer
> 6 votes
# Mathematica 30 bytes

```
RealDigits[Pi,10,1,-#][[1,1]]&

```

---

```
f=%

f@0
f@1
f@2
f@3
f@10
f@100
f@599
f@760
f@1000
f@10000

```

1
4
1
5
8
8
2
4
3
5

# Answer
> 4 votes
# CJam, 32

```
7e4,-2%{2+_2/@*\/2e10005+}*sq~)=

```

Try it online (it's a bit slow)

# Answer
> 4 votes
# Sage, ~~32~~ 25 bytes

```
lambda d:`n(pi,9^5)`[d+2]

```

My first answer in a language of this kind.

`n` rounds `pi` to 17775 digits.

# Answer
> 3 votes
# , ~~19~~ 15 bytes

```
10([|<.@o.@^)>:

```

Takes an integer *n* and outputs the *n**th* digit of pi. Uses zero-based indexing. To get the *n**th* digit, compute pi times 10*n*+1, take the floor of that value, and then take it modulo 10.

## Usage

The input is an extended integer.

```
   f =: 10([|<.@o.@^)>:
   (,.f"0) x: 0 1 2 3 10 100 599 760 1000
   0 1
   1 4
   2 1
   3 5
  10 8
 100 8
 599 2
 760 4
1000 3
   timex 'r =: f 10000x'
1100.73
   r
5

```

On my machine, it takes about 18 minutes to compute the 10000*th* digit.

## Explanation

```
10([|<.@o.@^)>:  Input: n
             >:  Increment n
10               The constant n
           ^     Compute 10^(n+1)
        o.@      Multiply by pi
     <.@         Floor it
   [             Get 10
    |            Take the floor modulo 10 and return

```

# Answer
> 3 votes
# Mathematica, ~~23~~ 21 bytes

```
⌊10^# Pi⌋~Mod~10&

```

# SageMath, 24 bytes

```
lambda n:int(10^n*pi)%10

```

# Answer
> 3 votes
# Clojure, 312 bytes

```
(fn[n](let[b bigdec d #(.divide(b %)%2(+ n 4)BigDecimal/ROUND_HALF_UP)m #(.multiply(b %)%2)a #(.add(b %)%2)s #(.subtract % %2)](-(int(nth(str(reduce(fn[z k](a z(m(d 1(.pow(b 16)k))(s(s(s(d 4(a 1(m 8 k)))(d 2(a 4(m 8 k))))(d 1(a 5(m 8 k))))(d 1(a 6(m 8 k)))))))(bigdec 0)(map bigdec(range(inc n)))))(+ n 2)))48)))48)))

```

So, as you can probably tell, I have no idea what I'm doing. This ended up being more comical than anything. I Google'd "pi to n digits", and ended up on the Wikipedia page for the Bailey–Borwein–Plouffe formula. Knowing just barely enough Calculus(?) to read the formula, I managed to translate it into Clojure.

The translation itself wasn't that difficult. The difficulty came from handling precision up to n-digits, since the formula requires `(Math/pow 16 precision)`; which gets huge really fast. I needed to use `BigDecimal` everywhere for this to work, which *really* bloated things up.

Ungolfed:

```
(defn nth-pi-digit [n]
  ; Create some aliases to make it more compact
  (let [b bigdec
        d #(.divide (b %) %2 (+ n 4) BigDecimal/ROUND_HALF_UP)
        m #(.multiply (b %) %2)
        a #(.add (b %) %2)
        s #(.subtract % %2)]
    (- ; Convert the character representation to a number...
      (int ; by casting it using `int` and subtracting 48
         (nth ; Grab the nth character, which is the answer
           (str ; Convert the BigDecimal to a string
             (reduce ; Sum using a reduction
               (fn [sum k]
                 (a sum ; The rest is just the formula
                       (m
                         (d 1 (.pow (b 16) k))
                         (s
                           (s
                             (s
                               (d 4 (a 1 (m 8 k)))
                               (d 2 (a 4 (m 8 k))))
                             (d 1 (a 5 (m 8 k))))
                           (d 1 (a 6 (m 8 k)))))))
               (bigdec 0)
               (map bigdec (range (inc n))))) ; Create an list of BigDecimals to act as k
           (+ n 2)))
      48)))

```

Needless to say, I'm sure there's an easier way to go about this if you know any math.

```
(for [t [0 1 2 3 10 100 599 760 1000 10000]]
  [t (nth-pi-digit t)])

([0 1] [1 4] [2 1] [3 5] [10 8] [100 8] [599 2] [760 4] [1000 3] [10000 5])

```

# Answer
> 2 votes
# Clojure, 253 bytes

```
(defmacro q[& a] `(with-precision ~@a))(defn h[n](nth(str(reduce +(map #(let[p(+(* n 2)1)a(q p(/ 1M(.pow 16M %)))b(q p(/ 4M(+(* 8 %)1)))c(q p(/ 2M(+(* 8 %)4)))d(q p(/ 1M(+(* 8 %)5)))e(q p(/ 1M(+(* 8 %)6)))](* a(-(-(- b c)d)e)))(range(+ n 9)))))(+ n 2)))

```

Calculate number pi using this formula. Have to redefine macro `with-precision` as it's used too frequently.

You can see the output here: https://ideone.com/AzumC3 1000 and 10000 takes exceeds time limit used on ideone, *shrugs*

# Answer
> 2 votes
# Smalltalk – 270 bytes

Relies on the identity `tan⁻¹(x) = x − x³/3 + x⁵/5 − x⁷/7 ...`, and that `π = 16⋅tan⁻¹(1/5) − 4⋅tan⁻¹(1/239)`. SmallTalk uses unlimited precision integer arithmetic so it will work for large inputs, if you're willing to wait!

```
|l a b c d e f g h p t|l:=stdin nextLine asInteger+1. a:=1/5. b:=1/239. c:=a. d:=b. e:=a. f:=b. g:=3. h:=-1. l timesRepeat:[c:=c*a*a. d:=d*b*b. e:=h*c/g+e. f:=h*d/g+f. g:=g+2. h:=0-h]. p:=4*e-f*4. l timesRepeat:[t:=p floor. p:=(p-t)*10]. Transcript show:t printString;cr

```

Save as `pi.st` and run as in the following test cases. Indexing is one based.

```
$ gst -q pi.st <<< 1
1
$ gst -q pi.st <<< 2
4
$ gst -q pi.st <<< 3
1
$ gst -q pi.st <<< 4
5
$ gst -q pi.st <<< 11
8
$ gst -q pi.st <<< 101
8
$ gst -q pi.st <<< 600
2
$ gst -q pi.st <<< 761
4
$ gst -q pi.st <<< 1001
3
$ gst -q pi.st <<< 10001 -- wait a long time!
5

```

# Answer
> 2 votes
# Python 3, 338 bytes

This implementation is based on the Chudnovsky algorithm, one of the fastest algorithms to estimate pi. For each iteration, roughly 14 digits are estimated (take a look here for further details).

```
f=lambda n,k=6,m=1,l=13591409,x=1,i=0:not i and(exec('global d;import decimal as d;d.getcontext().prec=%d'%(n+7))or str(426880*d.Decimal(10005).sqrt()/f(n//14+1,k,m,l,x,1))[n+2])or i<n and d.Decimal(((k**3-16*k)*m//i**3)*(l+545140134))/(x*-262537412640768000)+f(n,k+12,(k**3-16*k)*m

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js) (Chrome 67+), ~~75~~ ~~73~~ ~~67~~ 63 bytes

```
n=>`${eval(`for(a=c=100n**++n*20n,d=1n;a*=d;)c+=a/=d+++d`)}`[n]

```

Try it online!

Using \\$\pi/2=\sum\_{k=0}^{\infty}k!/(2k+1)!!\\$ (same logic used by Leaky Nun's Python answer, but thanks to the syntax of JS that makes this shorter). Input is passed to the function as a BigInt. 2 bytes can be removed if 1-based indexing is used:

```
n=>`${eval(`for(a=c=100n**n*20n,d=1n;a*=d;)c+=a/=d+++d`)}`[n]

```

# JavaScript (Node.js) (Chrome 67+), ~~90~~ 89 bytes

```
n=>`${eval(`for(a=100n**++n*2n,b=a-a/3n,c=0n,d=1n;w=a+b;a/=-4n,b/=-9n,d+=2n)c+=w/d`)}`[n]

```

Try it online!

Using \\$\pi/4=\arctan(1/2)+\arctan(1/3)\\$. Input is passed to the function as a BigInt. 2 bytes can be removed if 1-based indexing is used:

```
n=>`${eval(`for(a=100n**n*2n,b=a-a/3n,c=0n,d=1n;w=a+b;a/=-4n,b/=-9n,d+=2n)c+=w/d`)}`[n]

```

# Answer
> 1 votes
# Java 7, ~~262~~ 260 bytes

```
import java.math.*;int c(int n){BigInteger p,a=p=BigInteger.TEN.pow(10010).multiply(new BigInteger("2"));for(int i=1;a.compareTo(BigInteger.ZERO)>0;p=p.add(a))a=a.multiply(new BigInteger(i+"")).divide(new BigInteger((2*i+++1)+""));return(p+"").charAt(n+1)-48;}

```

Used *@LeakyNun's* Python 2 algorithm.

**Ungolfed & test code:**

Try it here.

```
import java.math.*;
class M{
  static int c(int n){
    BigInteger p, a = p = BigInteger.TEN.pow(10010).multiply(new BigInteger("2"));
    for(int i = 1; a.compareTo(BigInteger.ZERO) > 0; p = p.add(a)){
      a = a.multiply(new BigInteger(i+"")).divide(new BigInteger((2 * i++ + 1)+""));
    }
    return (p+"").charAt(n+1) - 48;
  }

  public static void main(String[] a){
    System.out.print(c(0)+", ");
    System.out.print(c(1)+", ");
    System.out.print(c(2)+", ");
    System.out.print(c(3)+", ");
    System.out.print(c(10)+", ");
    System.out.print(c(100)+", ");
    System.out.print(c(599)+", ");
    System.out.print(c(760)+", ");
    System.out.print(c(1000)+", ");
    System.out.print(c(10000));
  }
}

```

**Output:**

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

```

# Answer
> 0 votes
# Maple, 24 bytes

```
 trunc(10^(n+1)*Pi)mod 10

```

Test cases:

```
> f:=n->trunc(10^(n+1)*Pi)mod 10;
> f(0);
  1
> f(1);
  4
> f(2);
  1
> f(3);
  5
> f(10);
  8
> f(100);
  8
> f(599);
  2
> f(760);
  4
> f(1000);
  3
> f(10000);
  5

```

---
Tags: code-golf, math, pi
---


title: Compress my Malbolge!

text:
# Question
Title: Compress my Malbolge!
## Background

Malbolge is truly intriguing language. But programs written in it are also extraordinairly huge (and in some cases, unpostable on PPCG).

Your challenge (shall you accept it) is, to compress and decompress given normalized Malbolge program. Devise your own lossless algorithm. You may compress your data further using an existing algorithm afterwards, but you must cite the algorithm used. You may use dictionaries.

## Input

On the input, there will be given (in most cases very long) string, containing only following characters: `i</*jpov`. Example data:

```
iooooooooooooooooooooovoooioooipooooo<ooooooooooivojo<<<<<oio*ioooooooooooooooopiooooooooooooooooooo/jpooooooooooo

```

Example bigger chunk of data, 86 kilobytes big.

## Output

Well, not very much to say about it, output depends on the algorithm.

## Rules:

* Input taken by your program, compressed, and then decompressed, shall be identical.
* Submissions are scored by the following formula: \\$ \frac{Compressed}{Original} \times 100\\% \\$, applied to the example 86 kilobytes big chunk.
* If a submission abuses the fact that only one example chunk is provided (eg. by hardcoding it), I reserve right to add more example chunks.
* Standard loopholes are forbidden, I/O rules apply.

Note: 7zip with PPMd algorithm manages to compress the code with 2,95% score.

# Answer
# Score with test 1: 38.6%, Score with test 2: 4.9%

# Compressor

## Jelly, 97 bytes

```
ṡ2ṢŒɠżQƊ1ị>ɗƇ3NÞḣ8Ṫ€,‘ɼ$€Ẏœṣ;@W}ɗjƭƒ
7©ṛ⁸“i</*jpov”iⱮ’Ç31¡
“i</*jpov”iⱮḅ8b256,ÇĖF€LÞḢL;L};÷/$ʋ,ḷɗ

```

Try it online!

# Decompressor

## Jelly, 44 bytes

```
ḅ256ḃ8
ḣ3s2ṚṣḢ}©¥jƭƒṫ5µṛ®n8Ɗ¿‘
ḢĿị“i</*jpov”

```

Try it online!

## Explanation

Uses two different methods and picks the one with the shortest output.

Method 1: Convert the input from base 8 to base 256 Method 2: Repeatedly finds the 8 most common sublists of length 2 and replaces them with an integer between 8 and 255. The dictionary is stored at the beginning of the output.

The first byte of the output indicates the method used.

Input to compressor is a string of Malbolge. Output is a list of integers between 0 and 255. This could easily be encoded in Jelly’s code page if preferred. Input and output to/from decompressor mirror the compressor.
> 2 votes

# Answer
## Retina, 47.25%

**I know this is currently uninteresting, but this is still a WIP.**

Cheap algorithm to compress Malbolge programs.

```
ooooooooo
a
oooooooo
b
ooooooo
c
oooooo
d
ooooo
e
oooo
f
ooo
g
j\*
h
jah
k

```

Decompressor:

```
a
ooooooooo
b
oooooooo
c
ooooooo
d
oooooo
e
ooooo
f
oooo
g
ooo
h
j\*
k
jah

```

## Explanation

This simply shortens the source by replacing the o's, after noticing that there are too many o's in the Malbolge program. Try compressor online!
> 1 votes

# Answer
This code using standard Python libraries serves as a baseline for other advanced approaches.

Here is the outcomes for common compression algorithms.

```
Test case 0
Library   Score
gzip      50.000%
bz2       64.912%
lzma      87.719%

Test case 1
Library   Score
gzip      3.908%
bz2       2.968%
lzma      3.826%

PPMd      3.161%

```

NOTE: The PPMd algorithm score is obtained manually using 7zip to compress Test Case 1 into a zip file using a dictionary size of 16M and word size of 16 on Windows.
> 1 votes

# Answer
# ///, 0.00116%

Compressor (large test case)

Decompressor (large test case)

Compressor (small test case)

Decompressor (small test case)

Explanation: simple dictionary-based approach. The decompressor performs the same substitions as the compressor, but in reverse order. Note that both these programs take input by concatenating it into the source, as is usual for ///.
> 1 votes

---
Tags: code-challenge, compression
---