title: Whole-number powers

text:
# Question
Title: Whole-number powers
Some numbers like `64` can be expressed as a whole-number power in multiple ways:

```
64 ^ 1
 8 ^ 2
 4 ^ 3
 2 ^ 6

```

Output a sorted array of all possible such powers (here, `[1,2,3,6]`) in as few bytes as possible.

---

# Input

A positive whole number that's greater than 1 and less than 10000.

---

# Output

An array of whole-number powers `p` (including `1`) for which the input can be expressed as `a^p` with whole-number `a`. The outputs may have decimals, as long as they are in order.

Any floating point issues must be handled by the program.

---

# Examples

```
Input: 3
Output: [1]

Input: 9
Output: [1, 2]

Input: 81
Output: [1, 2, 4]

Input: 729
Output: [1, 2, 3, 6]

```

---

# Scoreboard

For your score to appear on the board, it should be in this format:

```
# Language, Bytes

```

Strikethroughs shouldn't cause a problem.

```
function getURL(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:getURL(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58047,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```

```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```

# Answer
# Pyth, 10 bytes

```
f}Q^RTSQSQ

```

Demonstration

For each power, it generates the list of all numbers up to the input taken to that power, and then checks if the input is in the list.
> 10 votes

# Answer
## Haskell, 38

```
f n=[b|b<-[1..n],n`elem`map(^b)[1..n]]

```

Pretty straightforward. The list comprehension finds values of `b` for which the input `n` appears among `[1^b, 2^b, ..., n^b]`. It suffices to check `b` in the range `[1..n]`.
> 10 votes

# Answer
# Python 2, 53

```
lambda n:[i/n for i in range(n*n)if(i%n+1)**(i/n)==n]

```

Brute forces all combinations of bases in exponents in \[0, n-1\] and bases in \[1, n\].
> 9 votes

# Answer
## Python 3, 56 bytes

```
lambda n:[i for i in range(1,n)if round(n**(1/i))**i==n]

```

This is really clumsy. Tests if each potential `i`-th root gives an integer by rounding it, taking it the power of `i`, and checking that it equals to original.

Directly checking that the root is a whole number is tricky because floating points give things like `64**(1/3) == 3.9999999999999996`. Rounding it to an integer let us check if taking the power returns to the original value. Thanks to ypercube for suggesting this, saving 1 byte.

feersum has a shorter and more clever solution. You all should really upvote that.
> 8 votes

# Answer
# Pyth, 11 10 12 bytes

```
fsmqQ^dTSQSQ

```

Checks all possible combinations of powers. Very slow.
> 7 votes

# Answer
# APL, 17 bytes

```
(X=⌊X←N*÷⍳N)/⍳N←⎕

```

My first APL program; golfing suggestions are appreciated.

```
              N←⎕  ⍝ Store input into N
             ⍳     ⍝ The list [1 2 ... N]
            /      ⍝ Select the elements A for which
      N*÷⍳N)       ⍝ N^(1/A)
(X=⌊X←             ⍝ equals its floor (that is, is an integer)

```
> 5 votes

# Answer
# CJam, 23 bytes

```
rimF{1=:E){E\d%!},}%:&p

```

This works by taking the prime factorization of **n** and computing the intersection of the divisors of all exponents.

It is a bit longer than my other solution, but I expect it to work (and finish instantly) for all integers between **2** and **263 \- 1**.

Try it online in the CJam interpreter.

### How it works

```
ri                       Read an integer from STDIN.
  mF                     Push its prime factorization.
    {             }%     For each [prime exponent]:
     1=:E                  Retrieve the exponent and save it in E.
         ){     },         Filter; for each I in [0 ... E]:
           E\d%              Compute E % Double(I).
                             (Casting to Double is required to divide by 0.)
               !             Push the logical NOT of the modulus.
                           Keep I if the result is truhty, i.e., if I divides E.
                    :&   Intersect all resulting arrays of integers.
                      p  Print the resulting array.

```
> 5 votes

# Answer
# Jelly, 6 bytes

```
ÆEg/ÆD

```

Try it online!

```
    ÆD    The list of divisors of
ÆE        the exponents in the prime factorization of the input
   /      reduced by
  g       greatest common divisor.

```
> 4 votes

# Answer
# JavaScript (ES5), ~~73 bytes~~ ~~81 bytes~~ ~~79 bytes~~ 75 bytes

```
for(n=+prompt(),p=Math.pow,i=0;i++<n;)p(.5+p(n,1/i)|0,i)==n&&console.log(i)

```

Checks to see if closest integer power of possible root equals `n`. `~~(.5+...)` is equivalent to `Math.round(...)` for expressions within integer range (0 to 2^31 - 1).

**Edit:** Used lazy `&&` logic instead of `if` to shave 2 bytes and added prompt for input since question added a clarification. Was previously assuming input was stored in `n`.

**Edit 2:** Changed `~~(.5+...)` to `.5+...|0` to save two bytes by avoiding grouping.

**Edit 3:** Removed `var`  to save 4 bytes. In non-strict mode, this is acceptable.
> 3 votes

# Answer
# Brachylog, 8 bytes

```
≥^↙.?≥ℕ≜

```

Try it online!

Takes input through its input variable and generates each power through its output variable, in ascending order as required, unlike the old solution `≥ℕ≜^↙.?∧` which just so happens to have the exact same length.

```
≥           Some number which is less than or equal to
            the input,
 ^          when raised to the power of
  ↙.        the output,
    ?       is the input.
       ≜    Label
            the output
      ℕ     as a whole number
     ≥      which is less than or equal to
    ?       the input.

```

I don't have any rigorous justification for asserting that every exponent is no greater than the input, but in order for the program to actually terminate it needs to be bounded.

`ḋḅlᵛf` is a far shorter (non-generator) solution for all of the given test cases, but it fails if the input isn't a power of a product of distinct primes. (Come to think of it, since all of the test cases are powers of primes, `ḋlf` also works...) The best I've come up with to salvage the idea, `ḋḅlᵐḋˢ⊇ᵛ×f`, comes out to 10 bytes.
> 3 votes

# Answer
# 05AB1E, 3 bytes

```
Ó¿Ñ

```

Try it online!

Port of Unrelated String’s Jelly answer.

```
Ó       # exponents in the prime factorization
 ¿      # gcd
  Ñ     # divisors

```
> 3 votes

# Answer
# CJam, 20 bytes

```
ri_,1df+\1$fmL9fmO&p

```

For input **n**, this computes **logb n** for all **b** less or equal to **n** and keeps the results that are integers.

This should work for all integers between **2** and **9,999**. Run time is roughly **O(n)**.

Try it online in the CJam interpreter.

### How it works

```
ri                   e# Read an integer N from STDIN.
  _,                 e# Copy N and transform it into [0 ... N-1].
    1df+             e# Add 1.0 to each, resulting in [1.0 ... Nd].
        \1$          e# Swap the array with N and copy the array.
           fmL       e# Mapped log base N: N [1.0 ... Nd] -> [log1(N) ... logN(N)]
              9fmO   e# Round each logarithm to 9 decimals.
                  &  e# Intersect this array with [1.0 ... Nd].
                   p e# Print the result.

```
> 2 votes

# Answer
# JavaScript ES7, 66 bytes

Takes advantage of experimental array comprehensions. Only works on Firefox.

```
n=>[for(i of Array(n).keys(m=Math.pow))if(m(0|.5+m(n,1/i),i)==n)i]

```

Possible golfing. I'll probably try to squish the expressions a little shorter and hopefully find an alternative to the long `Array(n).keys()` syntax.

Could be shorter but JavaScript has horribly floating point accuracy.
> 2 votes

# Answer
# Ruby, 50

```
->n{(1..n).map{|i|(n**(1.0/i)+1e-9)%1>1e-8||p(i)}}

```

Prints to screen.

# Ruby, 57

```
->n{a=[]
(1..n).map{|i|(n**(1.0/i)+1e-9)%1>1e-8||a<<i}
a}

```

Returns an array.

In test program:

```
f=->n{(1..n).map{|i|(n**(1.0/i)+1e-9)%1>1e-8||puts(i)}}

g=->n{a=[]
(1..n).map{|i|(n**(1.0/i)+1e-9)%1>1e-8||a<<i}
a}

f.call(4096)
puts g.call(4096)

```

Calculates each root and tests them modulo 1 to see if the remainder is less than 1e-8. Due to limited precision some valid integer roots are calculated to be the form 0.9999.., hence the need to add 1e-9 to them.

Up to the nth root of n is calculated, which is total overkill, but seemed the shortest way to write a non-infinite loop.
> 2 votes

# Answer
# Stax, 6 bytes

```
£ÅeÉåC

```

Run and debug it

All divisors of the gcd of exponents in the prime factorization. It's the same as the jelly algorithm.
> 2 votes

# Answer
# **DC, 104 bytes**

Input is taken from terminal, output is printed and also on the stack.

Because this uses the ? operator, you need to use `dc -e "<solution>"` or `dc <file with solution in it>`.

Nobody ever sees my answers, let alone vote on them, but I really just enjoy solving problems in DC. It's the least efficient solution in this thread so far, but I thought I'd post it anyways.

```
1sb?sn[lesi]ss[lble1+dse^dln=sln>c]sc[liSflq1+sq]sm[Lfplq1-dsq0<p]dsp[lb1+sb0si0selcxli0!=mlbln!=h]dshxx

```

starter stuff

```
1sb           Store 1 in register b
?sn           Store user input in register n
[lesi]ss      A macro to copy the e to the i register, stored in the s register

```

Macro to raise a base to all powers until the result is larger than the target or equal to the target

```
[lble1+dse^dln=sln>c]sc
[lb                 ]   load our base num (register b)
[  le               ]   load our exponent (register e)
[    1+dse          ]   add 1 to the exponent, copy and store in the e register
[         ^d        ]   raise the base to the exponent and copy it
[           ln=s    ]   load the user input, if that is equal to the power result run the macro in register s
[               ln>c]   load the user input, if it's greater than the power result run the macro in register c (this one)
[                   ]sc save this macro in register c

```

Macro to save a valid exponent value as found from the above exponent macros to another stack

```
[liSflq1+sq]sm
[liSf      ]     copy the i register to the top of the stack in register f
[    lq1+sq]     add 1 to the q register
[          ]sm   save this macro in the m register

```

Macro to run the 2x above macro (macro c) through all bases from 2 to our target number

```
[lb1+sb0si0selcxli0!=mlbln!=h]dsh
[lb1+sb                      ]     add 1 to the base number
[      0si0se                ]     reset the i and e registers (previously found value and exponent
[            lcx             ]     load and run the c macro
[               li0!=m       ]     load the result of the c macro and if it's not 0, run m to save it to the f stack
[                     lbln!=h]     if our base number is not equal to our target number, run macro h (this macro)
[                            ]dsh  duplicate this macro and save one copy, so that one is left on the stack to run later

```

Macro to print the values from the f stack

```
[Lfplq1-dsq0<p]dsp
[Lfp          ]      load the top value from the f register and print it
[   lq1-dsq   ]      load the q register and subtract one from it and save it
[          0<p]      if the q register is greater than 0, run macro p (this macro) again
[             ]dsp   duplicate this macro and save one copy, so that one is left on the stack to run later

xx finally run the two macros on the stack (h and then p)

```
> 2 votes

# Answer
# Ruby, 46 bytes

Brute force solution. Self-explanatory; for input \\$n\\$, find all numbers \\$e\\$ where for some \\$b\\$, \\$b^e=n\\$.

```
->n{(0..n).select{|e|(1..n).find{|b|b**e==n}}}

```

Try it online!
> 1 votes

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

```
g=n=>Enumerable.Range(1,n);
f=n=>g(n).SelectMany(x=>g(n).Where(y=>(Math.Pow(x,y)==n))).Reverse()

```

Try it online!
> 0 votes

# Answer
# Japt, 10 bytes

```
õ
f@mpX øN

```

Try it

```
õ            :Implicit input of integer U
õ            :Range [1,U]
f@mpX øN     :Reassign to U
f            :Filter
 @           :By passing each X through the following function
  m          :  Map U
   pX        :    Raise to the power of X
      ø      :  Contains
       N     :    Any element of the (singelton) array of inputs

```
> 0 votes

---
Tags: code-golf, math, number
---


title: Create a simple line editor

text:
# Question
Title: Create a simple line editor
**In:** a string without line breaks\*
**Allow the user to edit and submit the line**
**Out:** the modified string (optionally with a trailing linebreak)

The line editor must at minimum allow the user to:

1. move a visible cursor left and right
2. insert and/or overwrite characters at the cursor position
3. remove characters at the cursor position
4. submit the new string, i.e. cease editing cause the modified string to be returned/printed/displayed/saved… (with no other text)

Appreciated, but not required:

* explanation of your code.
* link to an online testing site that can demonstrate your program/function
* an animated image demonstrating usage (TIO, for instance, does not allow interactivity)

Note:

* key-bindings are suggestions only
* GUI or visual styling is not required

### Examples

In the following, the cursor is illustrated with `_`.

**In:** `Just some text`
**Allow the user to edit:**
``Just some text_``  User presses  (left arrow key) nine times
``Just ̲some text``  User presses **`Del`** four times
``Just ̲ text``  User presses **`a``n``y`**
``Just any_text``  User presses **`Enter`**
**Out:** `Just any text`

**In:** `Remove me`
**Allow the user to edit:**
``Remove me_``  User presses **`Backspace`** nine times
``_``  User presses **`Enter`**
**Out:**  (empty string)

---

* To prevent trivial editor solutions, this must either be supplied via a different input method than the editing commands, or must be separated from them by a newline or similar.

# Answer
# APL (Dyalog), 5 bytes

```
⍞←⍞⋄⍞

```

This is a tradfn, so to use it, do

```
∇a
⍞←⍞⋄⍞
∇

```

And then call it by using `a`, after which you supply the starting string, and then you can edit the string.
> 4 votes

# Answer
# JavaScript (ES6), ~~15~~ 14 bytes

I don't understand why this is getting so many upvotes!

```
s=>prompt(s,s)

```

Saved a byte thanks to Adám's suggestion that I display the original input in the `prompt`.

---

## Try It

```
f=
s=>prompt(s,s)
console.log(f("Edit this ..."))
```
> 10 votes

# Answer
# Bash 4.x, 25 characters

```
read -ei "$*" t
echo "$t"

```

Sample run:

```
bash-4.3$ bash interactive.sh hello world
hello golfing world
hello golfing world

```

(Line 2 above was the interactive editing, line 3 the output of resulted text.)
> 5 votes

# Answer
# C + NCURSES, 573 bytes

```
#include <curses.h>
i;j;k;s;c;p;int main(a,b)char**b;{char*q;char t[999];if(a&&(q=b[1]))while(*q)t[s++]=*q++;i=s;initscr();noecho();keypad(stdscr,1);do{for(j=0;j<i;j++)addch(t[j]);addch('|');for(j=i;t[j];j++)addch(t[j]);c=getch();switch(c){case KEY_LEFT:if(i)i--;break;case KEY_RIGHT:if(i<s)i++;break;case 8:case 127:case KEY_BACKSPACE:if(i){for(k=i-1;k<s;k++)t[k]=t[k+1];i--;s--;}break;case KEY_DC:if(i<s){for(k=i;k<s;k++)t[k]=t[k+1];s--;}break;default:if(c>31&c<127){for(k=s;k>i;k--)t[k]=t[k-1];t[i]=c;i++;s++;}}clear();}while(c!=10);printw(t);getch();endwin();return 0;}

```

**Test**

* Compile & Run with input `Just some text`.

* Press Left-Arrow button nine times.

* Press Delete button four times.

* Press `a` then `n` then `y`.

* Press `Enter` to terminate.

**Detailed**

```
#include <curses.h>

int main(int argc, char ** argv)
{
    char*q = 0;
    char t[999] = {0};
    int j = 0, k = 0;
    int i = 0; // cursor before first char
    int s = 0; // current size
    int c = 0; // current input
    int p = 0;

    // copy first command-line argument
    if(argc>0 && (q=argv[1]))while(*q)t[s++]=*q++; i=s;

    initscr(); // initiate NCURSES
    noecho(); // input does not echo on entry
    keypad(stdscr,TRUE); // handle all input

    do
    {
        // print current content with cursor
        for(j=0;j<i;j++) addch(t[j]);
        addch('|'); for(j=i;t[j];j++) addch(t[j]);

//      printw("\n\n> key %d pressed",c); // debug

        c = getch(); // read next char

        switch(c)
        {
            case KEY_LEFT: // left arrow; cursor left
            if(i > 0) i--;
            break;

            case KEY_RIGHT: // right arrow; cursor right
            if(i < s) i++;
            break;

            case 8: // backspace; remove previous char
            case 127:
            case KEY_BACKSPACE:
            if(i > 0)
            {
                for(k=i-1; k<s; k++) t[k]=t[k+1];
                i--;s--;
            }
            break;

            case KEY_DC: // delete; remove next char
            if(i < s)
            {
                for(k=i; k<s; k++) t[k]=t[k+1];
                s--;
            }
            break;

            default: // none of the above

            if(c > 31 && c < 127) // printable char
            {
                for(k=s; k>i; k--) t[k]=t[k-1];
                t[i] = c;i++;s++;
            }
        }

        clear(); // clear screen
        if(c == 10) break;
    }
    while(c);

    addch('\n');
    printw(t); // print final result
    getch(); // wait for any input
    endwin();
    return 0;
}

```
> 4 votes

# Answer
# HTML + JavaScript (ES6), 77 66 64 bytes

**HTML**

```
<input id=t

```

**JavaScript**

```
onkeyup=e=>e.which-13||alert(t.value);f=a=>t.value=a;

```

Saved 10 bytes thanks to Jörg Hülsermann and 2 bytes thanks to Luke.

```
onkeyup=e=>e.which-13||alert(t.value);f=a=>t.value=a;

f("Remove Me");
```

```
<input id=t>
```
> 3 votes

# Answer
# Bash + Vi/Vim, 14 bytes

```
echo $1>a;vi a

```

`vi` is aliased to `vim` on macOS, I don't know about other OSes.
> 3 votes

# Answer
# Python 2, ~~275~~ 200 bytes

Not a winner, but here it is:

```
from msvcrt import*
s=list(input())[::-1]
c=i=0
def p(a):print''.join(a)[::-1]
while'\r'!=c:p(s[:i]+['<']+s[i:]);c=getch();x=c!='\b';exec["s[i:i+1-x]=c*x","i=(i-1+2*(c<'\\t'))%-~len(s)"][x*' '>c]
p(s)

```

## Explanation:

It works by reversing the input (with `[::-1]`), and excluding and inserting characters in that reversed input so that the cursor does not have to move. Reverses it again when printing.

## Usage:

\[Tab\] key to move Right
\[Ctrl+C\] to move Left
\[Backspace\] to erase
\[Return\] to finish editing
Any other key, will be inserted into text

## Example:

Using OP's example

**In:** `Just some text`
``Just some text>``
``Just some> text`` User presses **`Ctrl+C`** five times
``Just > text``  User presses **`Backspace`** four times
``Just any> text``  User presses **`a``n``y`**
``Just any> text``  User presses **`Enter`**
**Out:** `Just any text`

## Inline editor version:

If you want the text to be editted inline, append `,'\r',` at the end of the `print` statement:

```
def p(a):print''.join(a)[::-1],'\r',

```
> 3 votes

# Answer
## VBScript, ~~23~~ 40 bytes

```
MsgBox InputBox("",,Wscript.Arguments(0))

```
> 2 votes

# Answer
## Ruby, ~~9~~ ~~19~~ ~~22~~ 84 bytes

```
->s{r=Readline;r.pre_input_hook=->{r.insert_text s;r.redisplay};r.readline}

```

This creates a Readline pre input hook that inserts the text s and then redisplays. After this, irb gets messed up so make sure to run this from a file. Run as a lambda, it takes the input string as an argument and returns the output string.

~~```
puts Readline.readline

```
This uses the Readline library to perform line editing. My previous answer only allowed backspaces.
```
puts gets

```
This is really, *really* self explanatory.
~~

~~Edit: I have been asked for an explanation. This is equivalent to `puts(gets)`. `gets` inputs a string with a line editor. `puts` outputs it.~~
> 2 votes

# Answer
# C#, 53 bytes

```
s=>{SendKeys.SendWait(s);return Console.ReadLine();};

```

Where `s` is a string to modify and the output is the new value.

SendKeys.SendWait: Sends the given keys to the active application, and then waits for the messages to be processed.

or 74 bytes if we are not in a Windows Forms context:

```
s=>{System.Windows.Forms.SendKeys.SendWait(s);return Console.ReadLine();};

```
> 2 votes

# Answer
# PHP + HTML, 26 Bytes

```
<input value=<?=$_GET[0]?>

```

The Browser adds automatically the closing tag

$\_GET Using a url like `http://example.com?0=input` as Input Creates in a HTML `<input value=input`

And this is the output for the string input

```
<input value=input
```
> 1 votes

# Answer
# Tcl, 17

```
puts [gets stdin]

```

Online interpreters just suck to demonstrate it, then I showcase some images from a Windows command shell:

# Test case 1

# Test case 2
> 1 votes

# Answer
# AHK, 32 bytes

```
InputBox,s,,,,,,,,,,%1%
Send,%s%

```

`InputBox` stores whatever is typed as the variable `s` and gives a starting prompt of the variable `1` which is the first passed parameter.
`Send` sends keystrokes to the current window. In this case, it'll be the contents of `s`.
`MsgBox` was an option but, for golfing, `Send` is 2 bytes shorter.
> 1 votes

# Answer
## Excel VBA Immediate Window Command - 22 bytes

```
[a1]=inputbox(0,,[a1])

```
> 1 votes

# Answer
# SmileBASIC, 138 bytes

```
DEF E S@L
WAIT
B=BUTTON(1)C=C-(B==4&&C)+(B>7&&C<LEN(S))I$=INKEY$()IF"\u0008"<I$THEN B=I$<"\u000E"S=SUBST$(S,C,B,I$*!B)?S?" "*C;1IF"\u0008"!=I$GOTO@L
END

```

Creates a function `E` with 1 argument and 0 outputs. (Output is displayed in the console)

The escaped characters should be the actual symbols, but they wouldn't show up here.

Controls:

```
Normal keys: Insert a character before the cursor.
Enter: Delete the character at the cursor.
Backspace: Submit.
D-pad left: Move cursor left.
All buttons except up, down, and left on the d-pad: Move cursor right.

```

Inserting/deleting characters is backwards so it's very annoying to use (but should still fulfill the requirements).

```
Just some text
1
'(press right 5 times)
Just some text
     1
'(press enter 4 times)
Just  text
     1
'(press a)
Just a text
     1
'(press right)
Just a text
      1
'(...)
Just any text
       1
'(press backspace)

```
> 1 votes

# Answer
# ZX Spectrum BASIC, 7 bytes

Trivial, included for completeness (`INPUT` and `PRINT` are one byte tokens each).

```
INPUT a$: PRINT a$

```
> 0 votes

# Answer
## Windows command interpreter, 16 bytes

```
set/pa=
echo %a%

```

This is very trivial; the command interpreter is trivially a "line editor".
> 0 votes

# Answer
# Commodore BASIC (C64Mini, C64/128, VIC-20 etc...) 179 tokenized BASIC bytes

This should be typed in business mode (upper/lower case characters)

```
 0a$="Just some text":?"{SHIFT+CLR/HOME}"a$"_":fOi=0to1step0:getk$:on-(k$<>"")goS2:goS1:nE
 1?"{CTRL+N}{CLR/HOME}"a$"_  ";:return
 2ifasc(k$)<>20thena$=a$+k$:on-(asc(k$)=13)goS4:return
 3if-(len(a$))thena$=leF(a$,len(a$)-1):goS4:return
 4?"{ARROW LEFT}{ARROW LEFT}{ARROW LEFT}  ":return

```

Allows basic text editing + delete + new line. Maximum size of `a$` like all strings in Commodore BASIC is 255 characters, so any more than that will crash the program. I will find a way to do \> 255 characters if that is necessary.
> 0 votes

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


title: Alex is sometimes right

text:
# Question
Title: Alex is sometimes right
This challenge is to lift the spirits of our mod Alex A., who is usually wrong.

---

Suppose you have a friend named Alex who needs help with basic logic and math, specifically mathematical equivalence.

He gives you a list of equations of the form `[variable] = [variable]` where a `[variable]` is always a single uppercase letter A to Z (not a lowercase letter, not a number, nor anything else). There's one equation per line in the list except for a single line that only says `therefore`.

All the equations above the `therefore` are premises, facts that are assumed to be true. All the equations below the `therefore` are unverified propositions, facts that Alex is attempting to infer from the premises, and they may or may not be true.

For example, in this equation list the single conclusionary proposition `A = C` happens to be true:

```
A = B
B = C
therefore
A = C

```

It's your job to tell Alex if **all** of his propositions logically follow from the given premises. That is, you need to tell Alex if he is wrong or right in his conclusions.

Write a program/function that takes in a string of a list of equations as described and prints/returns

```
Alex is right

```

if all the conclusions follow logically from the premises, and otherwise outputs

```
Alex is wrong

```

if any conclusion does not logically follow from the premises.

**The shortest code in bytes wins.**

Be sure to watch out for these cases:

* Variable always equals themselves. e.g.

```
B = A
therefore
A = A
X = X

```

results in `Alex is right`.
* Variables with unknown relationships cannot be assumed to be equal. e.g.

```
P = Q
therefore
E = R

```

results in `Alex is wrong`.
* When there are no equations after the `therefore` then the conclusions are vacuously true. e.g.

```
D = C
therefore
```

and

```
therefore
```

both result in `Alex is right`.
* When there are no equations before the `therefore` then only self-equality can be inferred. e.g.

```
therefore
R = R

```

results in `Alex is right`, but

```
therefore
R = W

```

results in `Alex is wrong`.

## More Examples

**Alex is wrong cases:** (separated by empty lines)

```
A = B
C = D
therefore
A = C

A = L
E = X
A = I
S = W
R = O
N = G
therefore
G = N
L = I
R = O
S = A
X = X
X = E

D = K
D = Q
L = P
O = L
M = O
therefore
K = L

A = B
therefore
B = C

Z = A
S = S
therefore
A = Z
A = A
S = A
A = S
Z = A
Z = A

K = L
K = X
therefore
X = P
L = X
L = P

therefore
A = B
B = C
A = C

therefore
A = A
B = B
C = C
D = D
E = E
F = F
G = G
H = H
I = I
J = J
K = K
T = I
L = L
M = M
N = N
O = O
P = P
Q = Q
R = R
S = S
T = T
U = U
V = V
W = W
X = X
Y = Y
Z = Z

A = B
B = C
C = D
D = E
E = F
F = G
G = H
H = I
I = J
J = K
K = L
L = M
M = N
N = O
O = P
P = O
Q = R
R = S
S = T
T = U
U = V
V = W
W = X
X = Y
Y = Z
therefore
A = Z

therefore
C = D
T = Y
A = Z

P = Q
therefore
E = R

therefore
R = W
```

**Alex is right cases:**

```
H = J
therefore
J = H

K = L
K = X
therefore
L = X

C = B
B = A
therefore
A = B

K = L
K = X
K = P
therefore
L = X
L = P
X = P

A = Y
Y = Q
Q = O
therefore
O = Y
O = A

C = C
therefore
C = C

A = B
B = A
therefore
A = B
B = A

A = B
B = C
C = D
therefore
A = A
A = B
A = C
A = D
B = A
B = B
B = C
B = D
C = A
C = B
C = C
C = D
D = A
D = B
D = C
D = D

therefore
A = A
B = B
C = C
D = D
E = E
F = F
G = G
H = H
I = I
J = J
K = K
L = L
M = M
N = N
O = O
P = P
Q = Q
R = R
S = S
T = T
U = U
V = V
W = W
X = X
Y = Y
Z = Z

D = I
F = H
J = M
therefore
M = J
D = I
H = F

A = B
B = C
C = D
D = E
E = F
F = G
G = H
H = I
I = J
J = K
K = L
L = M
M = N
N = O
O = P
P = Q
Q = R
R = S
S = T
T = U
U = V
V = W
W = X
X = Y
Y = Z
therefore
Z = A
F = R
G = I
W = L

A = B
B = C
therefore
A = C

B = A
therefore
A = A
X = X

P = P
C = G
M = C
therefore

D = C
therefore

therefore

therefore
R = R
```

# Answer
> 18 votes
# CJam, 49

```
"Alex is "qN%S{f{)er}(_el-}h;{)#},"wrong""right"?

```

Inspired from histocrat's Ruby solution. Try it online
3 bytes obliterated thanks to jimmy23013 :)

**Explanation:**

For each premise, the program replaces the first variable with the 2nd variable in the rest of the text. It then checks if there's any conclusion with different variables.

```
"Alex is "    first push the part we know
qN%           read the input and split into lines
S             push a space (initial no-op replacement string, see below)
{…}h          do-while
  f{…}        for each line and the replacement string
    )         take out the last character
    er        replace the remaining character(s) with that character
  (           afterwards, take out the first line
  _el         duplicate and convert to lowercase
  -           remove all the resulting characters from the line
               this removes all lowercase letters and non-letters
               "X = Y" becomes "XY" (new replacement string)
               and "therefore" becomes "" (ending the loop)
              this is the loop condition and is left on the stack every time
;             after the loop, pop the empty string (from "therefore")
{…},          filter the remaining (conclusion) lines using the condition block
  )           take out the last character
  #           find its index in the remaining string
               this is 0 (false) iff the first character is the same as the last
              afterwards, we have an array of lines with non-equal variables
"wrong"       push "wrong"
"right"       push "right"
?             choose "wrong" if the array was not empty, else choose "right"

```

**Old version, 85**

```
"Alex is "26,:A;{:i{{_A=_@-}g}%$~}:F;0q"= "-'t/Nf%~\{A\Ft:A;}/1>{F=}%-"right""wrong"?

```

This uses a union-find algorithm. Try it online

# Answer
> 31 votes
# Ruby, ~~80~~ 76 + 2 = 78

With command-line flags `p0`, run

```
gsub$1,$2%p=$`[/e/]while~/(.) = (?!\1)(.)/
$_="Alex is #{p ?:wrong: :right}"

```

Explanation:

This uses pure string manipulation. `p0` reads the full input as a single string into the variable `$_`. Then, we repeatedly match that string against the regular expression `/(.) = (?!\1)(.)/`, which finds all strings of the form "X = Y" where X and Y aren't the same letter, and assigns X to $1 and Y to $2. When such a match is found, `gsub$1,$2` replaces all instances of X with Y in the string. We also check whether this match occurred before or after the "therefore" with

```
$`[/e/]

```

If it occurred after, it's an unjustified claim and Alex is wrong. We track whether any such occurrences have happened using `p=`. The use of `p` as a tracking variable prevents things from breaking if the loop never hits even once, since `p` will return nil if it's never been assigned to.

As of this post, the CJam solution is longer. A proud, if no doubt fleeting moment.

Edit: Yup, quickly dethroned. Also, to finish the explanation, with the `p` flag the final value of `$_` is output at the end of execution, so the last line is the output.

# Answer
> 12 votes
# CJam, ~~83~~ ~~75~~ ~~68~~ ~~67~~ 64 bytes

*Thanks to Dennis for saving 1 byte.*

```
"Alex is "q_elN--N/:$La/~{)-},\{__m*{:&},::^|}5*-"wrong""right"?

```

Test suite. The test cases are too long for a permalink, so simply copy them in from the question. Note that this is fairly slow - it takes a minute or two in the online interpreter. You can make it much faster by changing `5*` to `2*` in which case it will finish almost instantly and solve all but one test case.

## Explanation

*(Slightly outdated.)*

The idea is to do a sort of "flood fill" of possible equalities and then remove all the equalities we obtained from the conclusion list. It can be shown that we need no more than 5 steps of the flood fill, because those would cover a distance (in the initial graph of inequalities) of `2<sup>5</sup> = 32` but the maximum distance is 25.

```
"Alex is " e# Push the string.
q          e# Read the input.
_elN-      e# Make a copy, convert to lower case, remove linefeeds. This gives us a string
           e# with all the characters we don't want from the input.
-          e# Remove them from the input. This leaves two upper-case letters on each line
           e# and an empty line between premises and conclusions.
N/         e# Split into lines.
La/        e# Split around the empty line.
~          e# Dump both halves on the stack.
{)-},      e# Remove any "A = A"-type equalities from the conclusions.
\          e# Swap with the premises.
{          e# Extend the premises 5 times...
  _Wf%     e#   Duplicate the premises and reverse each one, because = is symmetric.
  |        e#   Set union with the original premises.
  __m*     e#   Make two copies and get an array of every possible pair of premises.
  {:&},    e#   Select those which have at least one character in common.
  ::^      e#   For each such pair, take the mutual set difference, i.e. those characters
           e#   that are in only one of the strings.
  |        e#   Set union with the original premises.
}5*
-          e# Remove all the equalities we've obtained from the conclusions. If all
           e# conclusions were valid, the result will now be a empty array, which is falsy.
!          e# Logical not.
"wrong""right"?
           e# Select "wrong" or "right", respectively.

```

# Answer
> 6 votes
## R, 183 192 bytes

*I have modified my answer to address a limitation pointed out by user2357112. There is still an extremely small probability of calling Alex out when he is in fact right (which itself does not seem to happen very often if I understand the context of the challenge :-). I hope he won't mind.*

```
i=grep("t",z<-scan(,"",,,"\n"))
cat("Alex is",if(eval(parse(t=c(paste(LETTERS,"=",1:26),sample(rep(head(z,i-1),1e3)),paste(c(TRUE,sub("=","==",tail(z,-i))),collapse="&")))))"right"else"wrong")

```

I need to de-golf this a bit:

```
lines = scan(, what = "", sep = "\n")
therefore_idx = grep("therefore", lines)
setup = paste(LETTERS, "=", 1:26)
premises = sample(rep(head(lines, therefore_idx - 1), 1000))
propositions = paste(c(TRUE, sub("=", "==", tail(lines, -therefore_idx))), collapse = "&")
things_to_evaluate = c(setup, premises, propositions)
boolean_result = eval(parse(text = things_to_evaluate))
cat("Alex is", if (boolean_result) "right" else "wrong")

```

For example, if the input is

```
A = B
B = C
therefore
A = C
B = C

```

it will first evaluate the `setup`:

```
A = 1
B = 2
...
Z = 26

```

then the `premises`

```
A = B
B = C

```

will be run 1,000 times each in a random order. This is to make sure ("almost sure") that all equalities are propagated. Finally, it will evaluate the `propositions`:

```
TRUE & A == B & B == C

```

# Answer
> 5 votes
# Haskell, 208 bytes

```
import Data.Equivalence.Persistent
c l=equate(l!!0)$last l
r=foldr(c)$emptyEquivalence('A','Z')
l#r=equiv r(l!!0)$last l
f x|(h,_:t)<-span((<'t').head)$lines x="Alex is "++if all(#r h)t then"right"else"wrong"

```

I'm offloading the work to the `Data.Equivalence.Persistent` module, which provides functions for manipulating equivalence classes. All left to do is parsing the input and calling functions which sometimes have too long names for proper golfing.

Usage example:

```
*Main> f "A = B\nB = C\ntherefore\nA = C"
"Alex is right"

*Main> f "A = B\nB = D\ntherefore\nA = C"
"Alex is wrong"

```

# Answer
> 4 votes
# Python 2, 264 bytes

There's already a remarkable Python 3 answer by mbomb007. This answer steals flagrantly from that one (in particular the "Alex is wrriognhgt" trick).

And this answer is also significantly longer than that one...

Well, anyway, the idea in this answer is to maintain a dictionary of key-value pairs, where the keys are the 26 capital letter characters, and each key's corresponding value is the set of letters that are equivalent to the key. (If all 26 letters were equivalent, then each key would have a set of 26 letters for its corresponding value.)

```
def a(s):
 d={C:set(C)for C in map(chr,range(65,91))};p,c=s.split('t');c,p=[x.split('\n')for x in[c[9:],p]]
 for u in p[:-1]:
    g,h=u[::4];y=d[g]|d[h]
    for v in y:
     for w in y:d[v]|=d[w];d[w]|=d[v]
 print'Alex is','wrriognhgt'[all(u[0]in d[u[4]]for u in c if u)::2]

```

(To save bytes, this answer mixes spaces and tabs, which is legal in Python 2.)

This code is really pretty efficient, because the dictionary is limited to a maximum possible size (26 by 26 as described above) which doesn't depend on the number of lines of input.

Now, as I was golfing this solution, I realized that I could **save four bytes** by using strings instead of sets for the dictionary values, by replacing

```
d={C:set(C)for C in map(

```

with

```
d={C:C for C in map(

```

Of course then you also have to replace (NOTE: DON'T DO THIS) the three instances of the set union operation `|` with string concatenation `+`, but that doesn't change the code length. The result is that everything should still work just the same, except it won't eliminate duplicates like you do with sets (it'll just keep adding onto the end of the string). Sounds OK--a little less efficient, sure, but 260 bytes instead of 264.

Well, it turns out that **the 260-byte version is so inefficient** that it caused a `MemoryError` when I tested it with

```
A = B
A = B
therefore
B = A

```

This was surprising to me. **Let's investigate the 260-byte "string concatenation" version!**

Of course it would start out with the key-value pairs `A:A` and `B:B` (plus 24 others that don't matter). We'll write `d[A]` to mean the dictionary value corresponding to the key `A`, so at the beginning we'd have `d[A] = A`. Now, given the premise `A = B`, it would start by concatenating the values `d[A]=A` and `d[B]=B` to get `y = AB`. Then it'd loop over this string twice: `for v in AB: for w in AB:`...

So, the first time through the loop, we have `v=A` and `w=A`. Applying `d[v] += d[w]` and `d[w] += d[v]` results in the following sequence of dictionaries:

```
{A:A, B:B}      (start)
{A:AA, B:B}     (d[A] += d[A])
{A:AAAA, B:B}     (d[A] += d[A])

```

Next, with `v=A` and `w=B`:

```
{A:AAAA, B:B}     (start)
{A:AAAAB, B:B}    (d[A] += d[B])
{A:AAAAB, B:BAAAAB}   (d[B] += d[A])

```

Next, `v=B, w=A`:

```
{A:AAAAB, B:BAAAAB}   (start)
{A:AAAAB, B:BAAAABAAAAB}     (d[B] += d[A])
{A:AAAABBAAAABAAAAB, B:BAAAABAAAAB}     (d[A] += d[B])

```

And `v=B, w=B`:

```
{A:AAAABBAAAABAAAAB, B:BAAAABAAAAB}     (start)
{A:AAAABBAAAABAAAAB, B:BAAAABAAAABBAAAABAAAAB}     (d[B] += d[B])
{A:AAAABBAAAABAAAAB, B:BAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB}     (d[B] += d[B])

```

The above sequence of steps would implement the single premise `A = B`, with the conclusion that `A` is equal to every letter in the string `AAAABBAAAABAAAAB`, while `B` is equal to every letter in `BAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB`.

Now, suppose that the next premise is `A = B` **again**. You first calculate `y = d[A] + d[B] = AAAABBAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAABBAAAABAAAAB`.

Next, you loop over this string twice: `for v in y: for w in y:`...

Yeah. Maybe that wouldn't be a very efficient implementation.

# Answer
> 3 votes
# Mathematica, 182

```
f[s_]:="Alex is "<>If[True===And@@Simplify[#2,#1]&@@(StringSplit[s,"\n"]/.{a___,"therefore",b___}:>StringSplit/@{{a},{b}}/.{x_,_,y_}:>Symbol[x<>"$"]==Symbol[y<>"$"]),"right","wrong"]

```

Works on string input, as per the challenge.

```
In[]:= f["A = B
B = C
therefore
A = C"]
Out[]= Alex is right

In[]:= f["D = K
D = Q
L = P
O = L
M = O
therefore
K = L"]
Out[]= Alex is wrong

```

# Answer
> 3 votes
# Retina, 90 bytes

To run, place the following 12 lines of code in 12 separate files (+11 bytes counted for each file beyond the first). `<empty>` designates an empty file; `\n` designates a literal newline. Alternately, keep the `\n`s as they are, put all lines in a single file, and use the `-s` option. Make sure that all files use literal newlines, not Windows `\r\n`, and note the space at the end of the last line.

```
s+`^(.) = (.)(.*)\1
$1 = $2$3$2
)`^. .+\n
<empty>
^.+|(.) = \1
<empty>
^\n*$
right
^[^r]+
wrong
^
Alex is

```

**How it works**

The first replacement matches the first premise in the input, whenever the lhs of the premise occurs later on in the file. It replaces that later occurrence with the rhs of the premise. The `+` modifier ensures that the replacement is repeated until it doesn't match any more. Thus, if the first premise is `A = B`, all subsequent `A`s in the file get transmuted into `B`s.

The second replacement removes the first premise from the input, since we're done with it now. Then the `)` modifier loops back to the first replacement, and repeats until there were no changes in a whole pass through the loop. This happens when all the premises have been substituted and removed, and the input starts with `therefore`.

The third replacement matches the first line of input (which is `therefore`) or anything of the form `A = A`, and deletes it. If all propositions are supported by the premises, all of them will match this form, so what remains should consist solely of newlines. The fourth replacement changes this into `right`. Otherwise, the fifth replacement changes everything remaining (which doesn't contain `r` since `therefore` was deleted) into `wrong`. Finally, the last replacement adds `Alex is`  at the beginning.

# Answer
> 2 votes
# ES6, 128 bytes

Loosely based on the Ruby version.

```
r=s=>(m=/^[^e]*(.) = (?!\1)(.)/.exec(s))?r(s.replace(RegExp(m[1],'g'),m[2])):'Alex is '+(/(.) = (?!\1)/.test(s)?'wrong':'right')

```

Looks for any non-self-equality before the "therefore" and recurisvely replaces the variable throughout the string each time (this saves bytes over a while loop).

# Answer
> 1 votes
# C, 240 bytes

```
#define V[v-65]
v[26];char*r[]={"wrong","right"};i=65;j;g(a){return a V^a?g(a V):a;}main(){char b[16];for(;i<91;++i)i V=i;while(gets(b)&&*b<99)b[0]V=b[4]V=b[0]V<b[4]V?b[0]V:b[4]V;while(gets(b))j|=g(*b)^g(b[4]);printf("Alex is %s\n",r[!j]);}

```

This works by combining values into set trees, so any equivalent values lead to the same set root. Ungolfed, with implicit types made explicit.

```
// Anything before `V` becomes an index into `v`, offset by -'A'.
#define V [v-65]
int v[26];
char* r[] = {"wrong", "right"};
int i=65;
int j;
// Finds a set identifier for a by recursing until some index points to itself.
int g(int a) {
    return a V ^ a
           ? g(a V)
           : a;
}
int main() {
    char b[16];
    // Initialize all entries to point to themselves.
    for(; i < 91; ++i)
        i V = i;
    // For each premise "A = B", set the entries for A and B to point to the
    // smaller of their current values. This exits after reading "therefore"
    // as 't' > 99.
    while (gets(b) && *b < 99)
        b[0]V = b[4]V = b[0]V < b[4]V
                        ? b[0]V
                        : b[4]V;
    // For each conclusion "A = B", OR j with non-zero if the set identifiers
    // for A and B are different.
    while (gets(b))
        j |= g(*b) ^ g(b[4]);
    printf("Alex is %s\n", r[!j]);
}

```

# 180 bytes

This shorter version works for all cases from the OP, but for some other inputs incorrectly claims Alex is wrong. It uses a similar approach, but for each premise simply sets the second entry to the current value of the first entry. When comparing, it looks only at exact values instead of searching up a tree.

```
v[26];*V=v-65;char*r[]={"wrong","right"};i;j;main(){char b[16];for(;i<26;++i)v[i]=i;while(gets(b)&&*b<99)V[b[4]]=V[*b];while(gets(b))j|=V[*b]^V[b[4]];printf("Alex is %s\n",r[!j]);}

```

An example input for which this fails:

> A = B
> C = B
> therefore
> A = C

# Answer
> 1 votes
# 05AB1E, 32 bytes

```
…±º€ˆ „–Ñƒ©#|€á[ćD.l#`:}\€ËPè«.ª

```

Inspired by *@aditsu*'s CJam answer.

Try it online or verify all test cases.

**Explanation:**

```
…±º€ˆ      # Push dictionary string "alex is "
„–Ñƒ©      # Push dictionary string "wrong right"
     #     # Split by spaces: ["wrong","right"]
|          # Push all input-lines as list
 €à        # Only leave the letters of each line
   [       # Start an infinite loop:
    ć      #  Extract the head of the list; pop and push remainder-list and head separately
     D     #  Duplicate the head
      .l   #  If it's a lowercase string:
        #  #   Stop the infinite loop
    `      #  Push both letters in the string to the stack
     :     #  Replace all these letters in the remainder-list
 }\        # After the infinite loop: discard the duplicated "therefore"
   €       # For each letter-pair in the remainder list of condition-lines:
    Ë      #  Check if both letters are equal (1 if truhy; 0 if falsey)
   P       # Check if everything was truthy by taking the product
    è      # Use this to index into the earlier ["wrong","right"]-list
     «     # Append it to the "alex is " string
      .ª   # Sentence capitalize it
           # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `…±º€ˆ`  is `"alex is "` and `„–Ñƒ©` is `"wrong right"`.

# Answer
> 0 votes
# bash \+ awk \+ SWI-Prolog, 167 bytes

```
head -n1 <(awk '/therefore/{s=1;next};{if(s)print"?=("$1","$3")";else print};END{print"write(\"Alex is right\");write(\"Alex is wrong\"). halt."}' -|paste -sd ,|swipl)

```

Try it online!

Originally, this was just going to be a Prolog answer, but the tools I could find to actually transform the input format into something usable were limited enough that I decided to do that part of it in bash, even though I had next to no experience doing anything in bash, and had never even touched awk. I ended up spending enough hours on it to want to post it even after it grew into this 167-byte, barely golfed at all monster.

Essentially, what the awk program does is take the input from stdin, erase the line with `therefore`, replace every `A = B` after it with `?=(A,B)`, and append `write(\"Alex is right\");write(\"Alex is wrong\"). halt.`. Then, `paste -sd ,` replaces every newline but the last with a comma, transforming it into a valid two queries to the SWI-Prolog shell, which are then run with the printed result being truncated to one line by `head -n1`, which requires `<(...)` instead of a pipe for reasons beyond my understanding. All this, just to use a builtin!

---
Tags: code-golf, math, logic
---


title: The 21 Hairstyles of the Apocalypse

text:
# Question
Title: The 21 Hairstyles of the Apocalypse
# The 21 Hairstyles of the Apocalypse

Given a a list of numbers between 1 and 21 (or 0 and 20) output a "stitched together" drawing of the following faces (***see rules for stitching information***):

```
     ___           ,,,           ooo           ===           +++           ###          -*~*-
    (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-

     ***           |||           _/7           )))           (((           xxx           @__
    (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-

     ((_           >X<           '*`           ^^^           )|(           \|/           &&&
    (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-

```

Each, unique face listed on a new-line (the # is the integer ID for the face):

```
     ___
    (o o)
ooO--(_)--Ooo #1

     ,,,
    (o o)
ooO--(_)--Ooo #2

     ooo
    (o o)
ooO--(_)--Ooo #3

     ===
    (o o)
ooO--(_)--Ooo #4

     +++
    (o o)
ooO--(_)--Ooo #5

     ###
    (o o)
ooO--(_)--Ooo #6

    -*~*-
    (o o)
ooO--(_)--Ooo #7

     ***
    (o o)
ooO--(_)--Ooo #8

     |||
    (o o)
ooO--(_)--Ooo #9

     _/7
    (o o)
ooO--(_)--Ooo #10

     )))
    (o o)
ooO--(_)--Ooo #11

     (((
    (o o)
ooO--(_)--Ooo #12

     xxx
    (o o)
ooO--(_)--Ooo #13

     @__
    (o o)
ooO--(_)--Ooo #14

     ((_
    (o o)
ooO--(_)--Ooo #15

     >X<
    (o o)
ooO--(_)--Ooo #16

     '*`
    (o o)
ooO--(_)--Ooo #17

     ^^^
    (o o)
ooO--(_)--Ooo #18

     )|(
    (o o)
ooO--(_)--Ooo #19

     \|/
    (o o)
ooO--(_)--Ooo #20

     &&&
    (o o)
ooO--(_)--Ooo #21

```

The face is as follows:

```
    hhhhh
    (o o)
ooO--(_)--OooS

```

Where `h` is the dynamic apocalyptic hairstyle and `S` is the potential stitching hyphen.

---

# Examples

**Input:** `[1,2,3,4,5]`

**Output:**

```
     ___           ,,,           ooo           ===           +++
    (o o)         (o o)         (o o)         (o o)         (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-

```

---

**Input:** `[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]`

**Output:**

```
     ___           ,,,           ooo           ===           +++           ###          -*~*-          ***           |||           _/7           )))           (((           xxx           @__           ((_           >X<           '*`           ^^^           )|(           \|/           &&&
    (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)         (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-

```

---

**Input:** `["Fraggle Rock"]` / `[22]` / `[-21041024]` / `[22,23,24,25,26]`

**Output:** `Nobody cares.`

---

**Input:** `[1,1,1,1]`

**Output:**

```
     ___           ___           ___           ___
    (o o)         (o o)         (o o)         (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-

```

---

# Rules

* Preceeding and trailing newlines/spaces/hyphen are fine.
* Faces can occur more than once in the input.
* If there is an invalid number in the input you may have undefined behavior.
* The stitching:
    + The stitched faces will be concatenated by a single hyphen on the bottom (3rd) line.
    + The faces will all be on a single line (unlike the first drawing).
* Input can be 0 or 1 indexed, with 20 being the max for 0, 21 for 1.
* This is , lowest byte-count wins.

# Answer
# Japt `-R`, ~~122~~ ~~117~~ ~~113~~ ~~110~~ ~~109~~ ~~107~~ ~~105~~ ~~104~~ ~~103~~ ~~102~~ ~~100~~ 99 bytes

1-indexed, with index wrapping. I've followed the spec here, which requires a hyphen *between* the last line of each face, rather than the test cases, which include a hyphen *after* the last line of each face.

```
[Umg"@__((_>X<'*`^^^)|(\\|/"i"&_,o=+#*|)(x"m³ ò3 i7"-*~"ê)iA"_/7")¡"(o o)"Ã¡"O--(_)--O"ûoDÃq-]ûD m¸

```

Try it

```
[                                             :Construct an array of 3 elements
Umg"@.../"i"&...x"m³ ò3 i7"-*~"ê)iA"_/7")     :FIRST ELEMENT (F)
U                                             :  Input array
 m                                            :  Map
  g                                           :    Index into
   "@.../"                                    :      Literal string
          i                                   :      Prepend
           "&...x"                            :        Literal string
                  m                           :        Map
                   ³                          :          Repeat 3 times
                     ò3                       :      Split into chunks of 3
                        i7                    :      Insert at 0-based index 7
                          "-*~"ê              :        "-*~" palindromised
                                )             :      End insert
                                 iA"_/7"      :      Insert "_/7" at index 10
                                        )     :  End map
¡"(o o)"Ã                                     :SECOND ELEMENT (S)
¡                                             :  Map input array
 "(o o)"                                      :    Literal string
        Ã                                     :  End map
¡"O...O"ûoDÃq-                                :THIRD ELEMENT (T)
¡                                             :  Map input array
 "O...O"                                      :    Literal string
        ûo                                    :    Centre pad with "o"
          D                                   :      To length 13
           Ã                                  :  End map
            q-                                :  Join with "-"
]                                             :End array
 ûD                                           :Centre pad each to length 13 with spaces (T will always be at least 13 characters long)
    m                                         :Map
     ¸                                        :  Join F & S with spaces. Split T on spaces, creating a singleton array which gets cast back to a string on output
                                              :Implicit output, joined with newlines

```
> 9 votes

# Answer
# Charcoal, ~~103~~ 102 bytes

```
Ｅ²⪫Ｅθ⎇ι(o o)⪫×²§ -⁼λ⁶§⪪”|″:αuxkτT↷K[ï�↔ς↨?◧BZ@C←↑⊞Ａ⧴M✂↶ºKf÷H#S⦃J&≔⁰∧5À³≕r‹▷”³λ× ⁹Ｍ⁴←⪫ＥθooO--(_)--Ooo¦-

```

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

```
Ｅ²⪫Ｅθ

```

Loop over the input twice. Each result is then implicitly printed on its own line.

```
⎇ι(o o)

```

On the second loop, just generate the eyes.

```
⪫×²§ -⁼λ⁶

```

Wrap hairstyle 6 in `-`s, other hairstyles in spaces.

```
§⪪”|″:αuxkτT↷K[ï�↔ς↨?◧BZ@C←↑⊞Ａ⧴M✂↶ºKf÷H#S⦃J&≔⁰∧5À³≕r‹▷”³λ

```

Extract the three hairstyle characters from a compressed string.

```
× ⁹

```

Insert nine spaces between each hair or eyes.

```
Ｍ⁴←

```

Move 4 spaces left.

```
⪫ＥθooO--(_)--Ooo¦-

```

Print the rest of the faces, joined with a `-`.
> 6 votes

# Answer
# , ~~413~~ 391 bytes

Thanks Giuseppe for 22 less bytes and getting this under 400 bytes.

```
function(s,n=length(s)){I=intToUtf8
U=utf8ToInt
R=rep
K=cat
a=U("_,o=+#^*|&)(x")
b=c("@__","((_",">X<","'*`","",")|(","\\|/","","-*~*-","_/7")
s[s==7]=22;s[s==10]=23;s[s==18]=7;s[s==21]=10
for(i in s)K(I(c(rep(32,4+(i!=22)),"if"(i<14,R(a[i],3),U(b[i-13])),R(32,5+(i!=22)))))
K("
",I(R(c(R(32,3),40,111,32,111,41,R(32,6)),n)),"
")
K(I(40+R(c(x<-c(71,71,39,5,5),0,55,1,rev(x),5),n)[-(14*n)]))}

```

Try it online!
> 6 votes

# Answer
# Python 2, 209 bytes

```
def f(a):s=t=u='\n';i=0;exec"s+=(\"_,o=+#-*|_)(x@(>'^)\\&_,o=+#**|/)(x_(X*^||&_,o=+#~*|7)(x__<`^(/&\"[a[i]::21]+'*-'*(a[i]==6)).center(14);t+='    (o o)     ';u+='ooO--(_)--Ooo-';i+=1;"*len(a);print s+t+u[:-1]

```

Try it online!

0-based indexing; nothing especially clever here, just data accessed via slicing and using exec instead of a loop.
> 6 votes

# Answer
# JavaScript (ES6), ~~200~~ 199 bytes

Expects 1-indexed input.

```
a=>[1,0,2].map(y=>a.map(n=>s=y&2?'ooO--(_)--Ooo':`    ${p='( -'[y*n-7?y:2]}${"o o___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&".substr(y*n*3,3)}${y?p:')'}    `).join(s[3])).join`
`

```

Try it online!

### Commented

```
a =>                              // given the input array a[]
  [1, 0, 2].map(y =>              // for each row y:
    a.map(n =>                    //   for each integer n in a[]:
      s =                         //     let s be the content of this row
        y & 2 ?                   //     if this is the 3rd row:
          'ooO--(_)--Ooo'         //       use a hardcoded string
        :                         //     else:
          `    ${                 //       append 4 spaces
            p = '( -'[            //       append and save in p:
              y * n - 7 ? y : 2   //         '(' if y = 0 (2nd row)
            ]                     //         ' ' if y = 1 and n != 7
          }${                     //         '-' if y = 1 and n = 7
            "o o___,,,ooo(...)"   //       append the middle pattern (NB: truncated string)
            .substr(y * n * 3, 3) //       which is always the eyes if y = 0
          }${                     //
            y ? p : ')'           //       append p for the 1st row or ')' for the 2nd row
          }    `                  //       append 4 spaces
    ).join(s[3])                  //   join with the 4th character of s (space or hyphen)
  ).join`\n`                      // join with line-feeds

```
> 5 votes

# Answer
# Ruby, 164 bytes

```
->a{puts a.map{|i|j="_,o=+# *| )(x    ^  &"[i];(j<?!?%w{@__ ((_ >X< '*` -*~*- )|( \|/ _/7}[i%11-2]:j*3).center(14)}*"","    (o o)     "*k=a.size,"ooO--(_)--Ooo-"*k}

```

Zero indexed. Try it online!

All the difficult stuff happens on the top line.

`"_,o=+# *| )(x ^ &"` contains all the hairstyles with 3 identical characters, from which we select the `i`th character, `j`.

if `j` is not a space, the following expression returns 3 copies of the character. If it is a space, we select the correct hairstyle from between the `%w{}`. The "odd" hairstyles are numbers 6,9,13,14,15,16,18,19 and `i%11-2` gives a perfect hash to `0..7`

```
j<?!?%w{@__ ((_ >X< '*` -*~*- )|( \|/ _/7}[i%11-2]:j*3

```

All that remains is to pad to 14 spaces (centred) and print an appropriate number of middles/bottoms.
> 4 votes

# Answer
# Java 8, ~~273~~ ~~263~~ ~~254~~ 247 bytes

```
a->{String p="",q=p,r=p,s="    ",t="ooO--(_)--Ooo",u="(o o)",z;for(int i:a){z=i==7?"-":" ";p+=s+z+"___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&".split("(?<=\\G...)")[i]+z+s+" ";q+=s+u+s+" ";r+=t+"-";}return t.join("\n",p,q,r);}

```

-16 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
a->{                       // Method with integer-array parameter and String return-type
  String p="",q=p,r=p,     //  The three rows, starting all as empty Strings
         s="    ",         //  Temp-String of four spaces for the first and second rows
         t="ooO--(_)--Ooo",//  Temp-String for the third row
         u="(o o)",        //  Temp-String for the second row
         z;                //  Temp-String, uninitialized
  for(int i:a){            //  Loop over the input-array
    z=i==7?                //   If the number is 7 (edge-case):
       "-"                 //    Set temp-String `z` to "-"
      :                    //   Else:
       " ";                //    Set temp-String `z` to a space " "
    p+=                    //   Append to the first row:
          s                //    Four spaces
          +z               //    Append the temp-String `z`
          +"___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&"
             .split("(?<=\\G...)")[i]
                           //    Append the correct hat based on `i`
          +z               //    Append temp-String `z` again
          +s+" ";          //    And append five spaces
    q+=                    //   Append to the second row:
          s                //    Four spaces
          +u               //    The head
          +s+" ";          //    Five spaces
    r+=                    //   Append to the third row:
          t                //    The hands and bodies
          +"-";}           //    And the stitch "-"
  return t.join("\n",      //  Return a newline-joined String, of
                p,q,r);}   //  the three rows

```
> 3 votes

# Answer
# Python 2, 204 bytes

```
i=input();l=len(i)
for l in[' '*4+' -'[x==6]+"_,o=+#**|_)(x@(>'^)\\&_,o=+#~*|/)(x_(X*^||&_,o=+#**|7)(x__<`^(/&"[x::21]+' -'[x==6]+' '*5for x in i],['    (o o)     ']*l,['ooO--(_)--Ooo-']*l:print''.join(l)

```

Try it online!
> 2 votes

# Answer
# , ~~247~~ 242 bytes

```
function(a,n=length(a)){for(i in a)cat(format(h[i],,,,"c",14+!20-i))
cat("
","   (o o)     "*n,"
")
cat("ooO--(_)--Ooo"*n,sep="-")}
"*"=rep
h=readLines(,21)
___
,,,
ooo
===
+++
###
-*~*-
***
|||
_/7
)))
(((
xxx
@__
((_
>X<
'*`
^^^
)|(
\|/
&&&

```

Try it online!

Now, trying to bring R to a more manageable byte count...

Since doing character manipulations in R is so hopelessly verbose, I settled on listing all face and hairstyle patterns completely as is. For pretty-printing the hairstyles I use `format` function with `justify="centre"`. Unfortunately, we need to use an extra padding character for `i==20` because `format` calculates padding as if the backslash was escaped, like `\\|/`.

The current version does *not* use trailing hyphen.

Edit: Credit to JayCe for -2 and Giuseppe for -3 bytes.
> 2 votes

# Answer
# Red, 333 319 bytes

```
func[x][h: copy[]i: 0
foreach[k l m]{___,,,ooo===+++###   ***|||_/7)))(((xxx@__((_>X<'*`^^^^^^)|(\|/&&&}[alter h
pad pad/left either 7 = i: i + 1["-*~*-"][rejoin[" "k l m" "]]9
14]foreach y x[prin h/(y)]print append/dup copy"^/"{    (o o)     }l: length? x
print take/part append/dup copy""{ooO--(_)--Ooo-}l 14 * l - 1]

```

Try it online!
> 1 votes

# Answer
# Ruby, 163 bytes

```
->a{puts a.map{|i|(i==6?"-*~*-":i<9?"_,o=+#~*|"[i]*3:"_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&"[3*i-27,3]).center 14}*"","    (o o)     "*k=a.size,"ooO--(_)--Ooo-"*k}

```

Try it online!

0-indexed. I fiddled with Level River St's answer and found another approach to encode the hairstyles, apparently of similar golfiness. Here, we treat the "longest" 5-char haircut as a special case, trivial patterns in the first part of the list are encoded by 1 char each, and in the second part all 3-char patterns are listed literally, no matter - are those chars distinct or not. Finally comes the monkey-face boilerplate.
> 1 votes

# Answer
# C (gcc), ~~210~~ 212 bytes

-4 bytes thanks to ceilingcat. (It grew again when I fixed a bug that the original code had.)

Pretty straight-forward.

```
#define r(s)for(i=!puts("");i<n;printf(s,c,"___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&"+x*3,c=x^6?32:45,x=l[i++]));
x,c,i;f(l,n)int*l;{r("%5c%.3s%-6c")r("    (o o)     ")r("ooO--(_)--Ooo-")}

```

Try it online!
> 1 votes

# Answer
# PowerShell, ~~187~~ 171 bytes

<sup>-16 bytes thanks to mazzy</sup>

```
''+($args|%{($x=' '*4)+($y=' -'[$_-eq6])+("___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*``^^^)|(\|/&&&"|% s*g($_*3)3)+$y+$x;$z++})
"$x(o o)$x "*$z
"ooO--(_)--Ooo-"*$z

```

Try it online!

0-indexed, has a trailing hyphen.

Unrolled:

```
''+($args|%{
    ($x=' '*4) + ($y=' -'[$_-eq6]) +
    ("___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*``^^^)|(\|/&&&"|% substring ($_*3) 3) +
    "$y$x ";
    $z++
    })
"$x(o o) $x"*$z
"ooO--(_)--Ooo-"*$z

```

Nothing too fancy. Only the first line has some decent logic in it. It indexes into the hair string by using the `$current_entry_value*3` and scoops out that chunk by using `s`ubstrin`g`, before joining all the chunks into one big line. Ran into the issue of \` escaping the next caret, leaving me wondering why I was getting an IndexOutOfBounds error but that's fixed. Now using a much better way to combine the first line.

195 Bytes to follow the spec of no leading/trailing hyphens
> 1 votes

# Answer
# Runic Enchantments, 313 bytes

```
B6?>8b2*B0il2)?\B" "9a2*
{" ___ "D
{" ,,, "D
{" ooo "D
{" === "D
{" +++ "D
{" ### "D
{"-*~*-"D
{" *** "D
{" ||| "D
{" _/7 "D
{" ))) "D
{" ((( "D
{" xxx "D
{" @__ "D
{" ((_ "D
{" >X< "D
{" '*` "D
{" ^^^ "D
{" )|( "D
{" \|/ "D\
{" &&& "D{
{"    " LLRB͍!{
"-(_)--Ooo-"{*@\~4-:l͍e,:{$ak$"    (o o)     "{*$ak$"ooO-"

```

Try it online!

Reasonably compact in terms of compressing the strings and re-using segments where possible as well as using the input values as direct jump offsets when `B`ranching.

If excess trailing space is allowed, this can be shortened by 2 bytes by omitting the `4-` on the last line. +2 bytes for a `1-` if the final `-` is intended to not be there (matching spec, violating examples).

The chunk, `" (o o) "` is annoying impossible to compress, as constructing it using things like `" "4*` ends up being exactly the same number of bytes.

Passing inputs \>21 do fun things. E.g. a single 22 gives a close shave.
> 1 votes

# Answer
# Python 3, 240 bytes

```
h=[x*3for x in"_,o=+#*|)(x^&"]
for i,*l in(6,"-*~*-"),(9,"_/7"),(13,"@__","((_",">X<","'*`"),(18,")|(","\|/"):h[:i]+=l
*x,=map(int,input().split())
l=len(x)
p=print
p(*(h[i].center(13)for i in x))
p("    (o o)     "*l)
p("ooO--(_)--Ooo-"*l)

```

Try it online!
> 1 votes

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


title: Find the C-factor of a vote

text:
# Question
Title: Find the C-factor of a vote
In this challenge you will be determining how controversial a vote is, given an array of other votes, by figuring out a number called the C-factor. What is the C-factor, you ask?

Well, imagine you've got multiple votes on an election. We'll use `1` and `0` for the sake of the challenge to represent two different candidates in an election. Here's the ten votes in our sample election:

```
0110111011

```

Now, say we want to find the C-factor of any vote for candidate `0`. We can do that with the following function:

$$ f(o,v) = abs(o-mean(v)) $$

In \\$f\\$, `o` is the vote we want to determine the C-factor for, and `v` is an array of votes. So, using our function, to get the C-factor of any vote for candidate `0`:

$$ f(0, \[0,1,1,0,1,1,1,0,1,1\]) = 0.7 $$

A lower C-factor shows that the vote was less controversial in comparison to the other votes. So, a vote for candidate `0` is more different from the other votes than a vote for candidate `1`. In comparison, the C-factor for a candidate `1` vote is \\$0.3\\$, so it is less controversial because it is more like the other votes.

## The Challenge

Write a function \\$f(o,v)\\$ to determine the C-factor of a vote `o` given results of a vote `v`.

* `o` must be an integer, either `0` or `1`.
* `v` must be an array (or similar container type depending on language specifications) of arbitrary length containing zeroes and ones.
* The function should return or print to the console the resulting C-factor given the function parameters, using the formula above or a modified method.

Good luck! The least bytes wins (winner chosen in five days).

# Answer
# Jelly, 3 bytes

```
ạÆm

```

Try it online!

Literally just "absolute difference to mean".

```
ạÆm  Main link
ạ    Absolute difference
 Æm  Arithmetic Mean

```

If you invert the arguments you can invert the atoms.
> 6 votes

# Answer
# , 23 bytes

```
function(o,v)mean(o!=v)

```

Try it online!

The challenge boils down to computing the proportion of values in `v` different from `o` (i.e. `mean(xor(o,v))`). We can therefore avoid using `abs`.
> 10 votes

# Answer
# APL (Dyalog Unicode), ~~9 8~~ 5 bytes

```
≠⌹⊢=⊢

```

Try it online!

Anonymous train. Thanks to @Adám for a byte saved, and thanks to @ngn for 3 bytes!

### How:

```
≠⌹⊢=⊢ ⍝ Anonymous Train
    ⊢ ⍝ The right argument (⍵)
  ⊢=  ⍝ Equals itself. Generates an array of 1s
≠     ⍝ XOR left (⍺) and right args; generates ⍵ or (not ⍵), depending on ⍺.
 ⌹    ⍝ Divide these matrices.

```
> 6 votes

# Answer
# Actually, 3 bytes

```
♀^æ

```

Try it online!

Explanation:

```
♀^æ
♀^   XOR each vote with candidate (0 if matches, 1 if not)
  æ  mean of the list

```
> 4 votes

# Answer
# 05AB1E, 3 bytes

```
ÅAα

```

Try it online!
> 3 votes

# Answer
# Octave, 16 bytes

```
@(a,b)mean(a!=b)

```

Try it online!
> 3 votes

# Answer
# Attache, ~~11~~ 8 bytes

```
Mean@`/=

```

Try it online! Takes arguments as `f[o, v]`.

Nothing terribly original.

## Alternative approaches

**11 bytes:** `Average@`/=`

**11 bytes:** `${1-x~y/#y}` Counts the occurrences of `x` in `y` divided by the length of `y`, then subtracts that from `1`.

**11 bytes:** `{1-_2~_/#_}` (Arguments are reversed for this one)

**15 bytes:** `${Sum[x/=y]/#y}` A more explicit version of the above, without `Average`.
> 2 votes

# Answer
# Elm 0.19, 48 bytes

```
f a v=abs(v-(List.sum a/toFloat(List.length a)))

```

Online demo here.
> 2 votes

# Answer
# Proton, 26 bytes

```
(o,v)=>1-v.count(o)/len(v)

```

Try it online!

The output is a fraction because Proton uses sympy instead of regular Python numbers for better precision.

(-7 bytes; abs-diff to mean is shorter than mean of abs-diff; I'm actually dumb)

-1 byte thanks to Rod
> 1 votes

# Answer
# Enlist, 3 bytes

```
nÆm

```

Try it online!

```
nÆm  Main Link
n    Not Equals (returns a list of whether or not each element is unequal to to the value)
 Æm  Arithmetic Mean

```

The language is very heavily inspired by Jelly to the point that it's probably more like me experimenting to try to recreate the structure of how Jelly is parsed with my own code.

-1 byte thanks to Mr. Xcoder
> 1 votes

# Answer
# JavaScript, 38 bytes

```
n=>a=>a.map(x=>n-=x/a.length)|n<0?-n:n

```

Try it
> 1 votes

# Answer
# Perl 6, 20 bytes

```
{@_.sum/@_}o(*X!= *)

```

Try it online!

`* X!= *` is an anonymous function which takes the not-equals cross product of its two arguments. It produces a sequence of Booleans; for example, `1 X!= (1, 0, 1)` evaluates to `(False, True, False)`.

`{ @_.sum / @_ }` is another anonymous function that returns the average of its arguments. Boolean `True` evaluates to `1` numerically, and `False` to `0`.

The `o` operator composes those two functions into one.
> 1 votes

# Answer
# Retina 0.8.2, 27 bytes

```
(.),((?(\1)|()).)*$
$#3/$#2

```

Try it online! Outputs a fraction. Explanation: The first group captures `o` and the second group captures each entry of `v`, while the conditional ensures that the third group only makes a capture when the vote is dissimilar. The `$#` construction then returns the count of the relevant captures as desired.
> 1 votes

# Answer
# Perl 5 `-MList::Util=sum`, 30 bytes

```
sub f{abs((shift)-sum(@_)/@_)}

```

Try it online!
> 1 votes

# Answer
# K (Kona), 17 bytes

```
{_abs+/y-x%.0+#x}

```

Try it online!
> 1 votes

# Answer
# C (gcc), 62 bytes

```
float f(o,v,l,k)int*v;{float r=0;for(k=l;k;)r+=v[--k]^o;r/=l;}

```

Try it online!

Call as `f(int o, int *v, int length_of_v)`.
> 1 votes

# Answer
# JavaScript (Node.js), ~~47~~ 42 bytes

*-5 bytes from @arnauld*

```
a=>b=>Math.abs(a-eval(b.join`+`)/b.length)

```

Try it online!
> 0 votes

# Answer
# Japt v2.0a0, 6 bytes

```
aVx÷Vl

```

Try it
> 0 votes

# Answer
# Java 8, 47 bytes

```
v->o->(o-=v.get().sum()/v.get().count())<0?-o:o

```

Try it online.

or alternatively:

```
v->o->Math.abs(o-v.get().sum()/v.get().count())

```

Try it online.

For both the inputs are a `Supplier<DoubleStream>` for the list of votes `v` and `double` for the vote `o`.

**Explanation:**

```
v->o->                 // Method with DoubleStream-Supplier & double parameters and double return
  (o-=v.get().sum()    //  Get the sum of the DoubleStream-Supplier
      /v.get().count() //  Divide it by the amount of items in the DoubleStream-Supplier
      )                //  Subtract this from `o`
       <0?-o:o         //  And get the absolute value of this updated value `o`

```
> 0 votes

# Answer
# Common Lisp 49 bytes

**Solution:**

```
(defun c(o v)(abs(- o(/(reduce'+ v)(length v)))))

```

Try it online

**Explanation:**

```
(defun c(o v)
  (abs (- o (/ (reduce '+ v) (length v)))))

```
* reduce applies an function over all list elements (+ in this case)
* rest is just the base function, abs(o - mean(v))
> 0 votes

# Answer
# Ruby, 31 bytes

```
->o,v{v.count(1-o)/v.size.to_f}

```

Try it online!
> 0 votes

# Answer
# Pyth, 4 bytes

```
aE.O

```

Explanation:

```
       ( implicitly set Q = eval(input()) )
a      Absolute difference between
 E     eval(input()) (this is the second line of input taken)
  .O   and the average of
    Q  (implicit) Q (the first line of input)

```

Input is in the format of:

```
[0,1,1,0,1,1,1,0,1,1]
0

```

with the array of votes first, and the candidate second.

Try it online!
> 0 votes

---
Tags: code-golf, math, function
---


title: Find the diameter of a word graph

text:
# Question
Title: Find the diameter of a word graph
**Introduction**

A popular word puzzle is to convert one word into another via a series of steps which replace only one letter and which always result in a valid word. For example, BAG can be converted to DOG via a path of five steps:

BAG -\> BAT -\> CAT -\> COT -\> COG -\> DOG

Shorter paths also exist in this case; for example:

BAG -\> BOG -\> DOG

If one drew a graph whose vertices were labelled by words, with an edge between any pair of words that differ by one letter, then the shortest path from "BAG" to "DOG" would consist of two edges.

**Challenge**

You are to write a program which receives as input a "dictionary" of words which all have the same length, representing all allowable words that can appear as steps along a path. It should output at least one "longest shortest path", that is, a path between two of the words which is:

* no longer than any other path between those two words;
* at least as long as the shortest possible path between any other pair of words in the list.

In the context of the graph described above, the length of such a path is the *diameter* of the graph.

In the degenerate case where none of the input words can be transformed into any of the others, output at least one path of length zero, that is, a single word.

**Examples**

* The input \["bag", "bat", "cat", "cot", "dot", "dog"\] should yield a path traversing all six words in that order (or reverse order), since the shortest path from "bag" to "dog" within this dictionary is the longest achievable, five steps.
* The input \["bag", "bat", "bot" , "cat", "cot", "dot", "dog"\] should yield the path "bag, bat, bot, dot, dog" and/or its reversal.
* The input \["code","golf","male","buzz","mole","role","mold","cold","gold","mode"\] should yield a path between "code and "golf".
* The input \["one", "two", "six", "ten"\] corresponds to a graph with no edges, so output one or more single-word (zero-length) paths.
* If the input contains any two words of unequal length, the output is undefined.

**Rules**

* Standard code golf rules apply
* There will be multiple "shortest" paths. You must output at least one, but are free to output as many as you wish.
* You are free to decide how the input dictionary is passed into your program.
* Shortest code in bytes wins.

# Answer
# Jelly, 20 bytes

```
ŒPŒ!€ẎnƝ§ỊẠƲƇ.ịⱮḢƙƊṪ

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Classic), ~~84 80 77 76 74 66~~ 61 bytes

```
{⍵⌷⍨{⍵,⍨⊃⍋(1≠a⌷⍨⊃⍵),⍪⍺⌷a}⍣d/⊃⍸a=d←⌈/512|,a←⌊.+⍨⍣≡9*⍨2⌊⍵+.≠⍉⍵}

```

Try it online!

input and output are character matrices

`⍵+.≠⍉⍵` matrix of hamming-like distances between words

`9*⍨2⌊` leave 0s and 1s intact, turn 2+ into some large number (512=29, used as "∞")

`⌊.+⍨⍣≡` floyd&warshall's shortest path algorithm

* `⌊.+` like matrix multiplication but using `min` () and `+` instead of `+` and `×` respectively
* use the same matrix on the left and right
* `⍣≡` repeat until convergence

`d←⌈/512|,` length of longest (not "∞") path, assigned to `d`

`⊃⍸a=` which two nodes does it connect, let's call them *i* and *j*

`{⍵,⍨⊃⍋(1≠a⌷⍨⊃⍵),⍪⍺⌷a}⍣d/` reconstruct the path

* `{` `}⍣d/` evaluate the `{` `}` function `d` times. the left arg  is always *i*. the right arg  starts as *j* and gradually accumulates the internal nodes of the path
* `(1≠a⌷⍨⊃⍵),⍪⍺⌷a` build a 2-column matrix of these two vectors:

+ `1≠a⌷⍨⊃⍵` booleans (0 or 1) indicating which nodes are at distance 1 to the first of
    + `⍺⌷a` distances of all graph nodes to
* `⊃⍋` index of the lexicographically smallest row
* `⍵,⍨` prepend to

`⍵⌷⍨` index the original words with the path
> 3 votes

# Answer
# Python 3, 225 bytes

```
from itertools import*
def f(a):b=[((p[0],p[-1]),(len(p),p))for i in range(len(a))for p in permutations(a,i+1)if all(sum(q!=r for q,r in zip(*x))<2for x in zip(p,p[1:]))];return max(min(r for q,r in b if x==q)for x,y in b)[1]

```

Try it online!

Basically, take all possible paths, only keep the ones that are valid, then go through each start-end combination, find the minimum path distance, and find the maximum of that.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 105 bytes

```
f@x_:=MaximalBy[AdjacencyGraph[x,UnitStep[1-DistanceMatrix@x]]~FindShortestPath~##&@@@Tuples[x,2],Length]

```

Try it online!
> 2 votes

# Answer
# Python 3, 228 bytes.

```
def G(w):
    D={A+B:[A,B]if sum(a!=b for a,b in zip(A,B))<2else[0,0]*len(w)for A in w for B in w}
    for k in w:
        for i in w:
            for j in w:
                p=D[i+k]+D[k+j][1:]
                if len(p)<len(D[i+j]):D[i+j]=p
    return max(D.values(),key=len)

```

Implements the Floyd-Warshall algorithm for all-pairs shortest-paths, then takes the maximum over the found paths.

16 of the characters in this implementation are tabs, which is unfortunate :(
> 2 votes

# Answer
# JavaScript (ES6),  ~~195~~  194 bytes

Returns `[optimal_length, [optimal_path]]`.

```
f=(a,p=[],w=o=[],l=0)=>Object.values(o,o[k=[w,p[0]]]=(o[k]||0)[0]<l?o[k]:[l,p],a.map((v,i)=>w+w&&[...v].map((c,i)=>s-=c!=w[i],s=1)|s||f(a.filter(_=>i--),[...p,v],v,l+1))).sort(([a],[b])=>b-a)[0]

```

Try it online!

### How?

We use a recursive function \\$f\\$ which builds an object \\$o\\$ whose keys consist of a pair of words \\$w\_0\\$ and \\$w\_1\\$ separated by a comma and whose values are defined as \\$\[l, p\]\\$, where \\$p\\$ is the shortest path between \\$w\_0\\$ and \\$w\_1\\$ and \\$l\\$ is the length of this path.

Given a path \\$p\\$ of length \\$l\\$ and the last word \\$w\\$ added to \\$p\\$, \\$o\\$ is updated with:

```
o[k = [w, p[0]]] = (o[k] || 0)[0] < l ? o[k] : [l, p]

```

We eventually return the longest path stored in \\$o\\$:

```
Object.values(o).sort(([a], [b]) => b - a)[0]

```

(this code is executed at each recursion depth, but only the root level really matters)

We use the following test to know whether a word \\$v\\$ differs by exactly one letter with the last word \\$w\\$:

```
[...v].map((c, i) => s -= c != w[i], s = 1) | s

```

For each word \\$v\\$ that can be added to the path, we process a recursive call as follows:

```
f(                    //
  a.filter(_ => i--), // remove the i-th word from a[]
  [...p, v],          // append v to p[]
  v,                  // pass v as the last word
  l + 1               // increment the length of the path
)                     //

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 92 bytes

```
MaximalBy[Select[Rule@@@a,EditDistance@@#<2&]~FindShortestPath~##&@@@(a=#~Tuples~2),Length]&

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Big base, small digits

text:
# Question
Title: Big base, small digits
The J language has a very silly syntax for specifying constants. I want to focus on one cool feature in particular: the ability to write in arbitrary bases.

If you write `XbY` for `X` any number and `Y` any string of alphanumerics, then J will interpret `Y` as a base `X` number, where `0` through `9` have their usual meaning and `a` through `z` represent 10 through 35.

And when I say `X` any number, I mean *any* number. For the purposes of this question, I'll constrain `X` to be a positive integer, but in J you can use anything: negative numbers, fractions, complex numbers, whatever.

The thing that's weird is that **you can only use the numbers from 0 to 35** as your base-whatever digits, because your collection of usable symbols consists *only* of 0-9 and a-z.

## The problem

I want a program to help me golf magic numbers like 2,933,774,030,998 using this method. Well, okay, maybe not that big, I'll go easy on you. So...

> Your task is to write a program or function which takes a (usually large) decimal number `N` between 1 and 4,294,967,295 (= 232-1) as input, and outputs/returns the shortest representation of the form `XbY`, where `X` is a positive integer, `Y` is a string consisting of alphanumerics (0-9 and a-z, case insensitive), and `Y` interpreted in base `X` equals `N`.
>
> If the length of every representation `XbY` representation is greater than or equal to the number of digits of `N`, then output `N` instead. In all other ties, you may output any nonempty subset of the shortest representations.

This is code golf, so shorter is better.

## Test cases

```
      Input | Acceptable outputs (case-insensitive)
------------+-------------------------------------------------------
          5 | 5
            |
   10000000 | 79bkmom  82bibhi  85bgo75  99bauua  577buld
            | 620bq9k  999baka
            |
   10000030 | 85bgo7z
            |
   10000031 | 10000031
            |
   12345678 | 76bs9va  79bp3cw  82bmw54  86bjzky  641buui
            |
   34307000 | 99bzzzz
            |
   34307001 | 34307001
            |
 1557626714 | 84bvo07e  87brgzpt  99bglush  420blaze
            |
 1892332260 | 35bzzzzzz  36bvan8x0  37brapre5  38bnxkbfe  40bij7rqk
            | 41bgdrm7f  42bek5su0  45bablf30  49b6ycriz  56b3onmfs
            | 57b38f9gx  62b244244  69b1expkf  71b13xbj3
            |
 2147483647 | 36bzik0zj  38br3y91l  39bnvabca  42bgi5of1  48b8kq3qv
 (= 2^31-1) | 53b578t6k  63b2akka1  1022b2cof  1023b2661  10922bio7
            | 16382b8wv  16383b8g7  32764b2gv  32765b2ch  32766b287
            | 32767b241
            |
 2147483648 | 512bg000  8192bw00
            |
 4294967295 | 45bnchvmu  60b5vo6sf  71b2r1708  84b12mxf3  112brx8iv
 (= 2^32-1) | 126bh5aa3  254b18owf  255b14640  1023b4cc3  13107bpa0
            | 16383bgwf  21844b9of  21845b960  32765b4oz  32766b4gf
            | 32767b483  65530b1cz  65531b1ao  65532b18f  65533b168
            | 65534b143  65535b120

```

If you're ever unsure about whether some representation is equal to some number, you can use any J interpreter, like the one on Try It Online. Just type in `stdout 0":87brgzpt` and J will spit back out `1557626714`. Note that J only accepts lowercase, even though this problem is case-insensitive.

## Some possibly helpful theory

* For all `N` less than 10,000,000, the decimal representation is as short as any other and hence is the only acceptable output. To save anything you would need to be at least four digits shorter in the new base, and even more if the base is greater than 99.
* It suffices to check bases up to the ceiling of the square root of `N`. For any larger base *B*, `N` will be at most two digits in base *B*, so the first time you'll get something with a valid first digit is at around *B*`N`/35. But at that size you will always be at least as large as the decimal representation, so there's no point in trying. That in mind, ceil(sqrt(largest number I'll ask you to solve this problem for)) = 65536.
* If you have any representation in a base less than 36, then the base 36 representation will be at least as short. So you don't have to worry about accidentally short solutions in bases less than 36. For example, the representation `35bzzzzzz` for 1,892,332,260 uses an unusual digit for that base, but `36bvan8x0` has the same length.

# Answer
## JavaScript (ES6), ~~103~~ 101 bytes

Takes input as a string.

```
n=>[...Array(7e4)].reduce(p=>p[(r=++b+(g=x=>x?g(x/b|0)+(x%b).toString(36):'b')(n)).length]?r:p,n,b=2)

```

### Test cases

*NB: The number of iterations in the snippet function is limited to 600 so that the test cases complete faster. (It would take a few seconds otherwise.)*

```
let f =

n=>[...Array(6e2)].reduce(p=>p[(r=++b+(g=x=>x?g(x/b|0)+(x%b).toString(36):'b')(n)).length]?r:p,n,b=2)

console.log(f("5"))
console.log(f("10000000"))
console.log(f("10000030"))
console.log(f("10000031"))
console.log(f("12345678"))
console.log(f("34307000"))
console.log(f("34307001"))
console.log(f("1557626714"))
console.log(f("1892332260"))
console.log(f("2147483647"))
console.log(f("2147483648"))
console.log(f("4294967295"))
```
> 9 votes

# Answer
# Ruby, 118 bytes

This was linked in another question and I noticed there aren't many answers here, so I decided to give it a shot.

Walk through *all bases* up to and including the input to construct all valid J number constructions. It skips 1-8 though, because there's no way those will be shorter than the base-10 representation anyways. It's a pretty naive solution, all things considered, since it calls the `digits` builtin to get the digits, but since that starts with the least significant digit first we have to `reverse` it to get the actual number, so it could possibly be improved.

It's slow. So, soooooo incredibly slow. TIO times out on 34307000, for example. We *could* go with the square root or even Arnauld's choice of `7e4` to save time, but that costs extra bytes, so why bother?

```
->n{([n.to_s]+(9..n).map{|b|d=n.digits b;"#{b}b"+d.reverse.map{|i|i.to_s 36}*''if d.all?{|i|i<36}}-[p]).min_by &:size}

```

Try it online!

Try it online w/ sqrt so everything finishes on time
> 3 votes

# Answer
# 05AB1E, 37 bytes

```
[¼35Ý¾ãvtîEyNβQižhA«yèJ'bìNìDgIg@i\}q

```

Should work in theory, but times out for all non-trivial test cases, even `10000000`. The cartesian product builtin `ã` is extremely slow for \\$\geq4\\$..

Without the final if-statement `DgIg@i\}` it can still be tested for lower values, to verify that it does in fact work: **Try it online.**

Will see if I can come up with a (probably much longer but) more efficient solution later on.

**Explanation:**

```
[              # Start an infinite loop:
 ¼             #  Increase the counter variable by 1 (0 by default)
 35Ý           #  Push a list in the range [0, 35]
 ¾ã            #  Take the cartesian product of this list with itself,
               #  with chunks-sizes equal to the counter variable
 v             #  Loop `y` over each of these lists:
  t            #   Take the square-root of the (implicit) input-integer
   î           #   Ceil it
  E            #   Loop `N` in the range [1, ceil(square(input))]:
   yNβ         #    Convert list `y` to base-`N`
   Qi          #    If it's equal to the (implicit) input-integer:
     žh        #     Push string "0123456789"
       A«      #     Append the lowercase alphabet
     yè        #     Index each value in list `y` into this string
     J         #     Join the characters to a single string
     'bì      '#     Prepend a "b"
        Nì     #     Prepend the number `N`
     D         #     Duplicate it
      g        #     And pop and push the length of this string
       Ig      #     Also push the length of the input
         @i }  #     If the length of the string is >= the input-length:
           \   #      Discard the duplicated string
     q         #     Stop the program
               #     (after which the result is output implicitly;
               #      or if the string was discarded and the stack is empty, it will
               #      implicitly output the implicit input as result instead)

```
> 1 votes

---
Tags: code-golf, base-conversion
---


title: Distributing parliament seats

text:
# Question
Title: Distributing parliament seats
# Introduction

In a general election, one would like to calculate a constant price per parliament seat. This means that for `N >= 0` seats to be distributed and a list `ns` of votes per party, we would like to find a number `d` such that

```
sum(floor(n/d) for n in ns) == N

```

To make things interesting (and more like the real world), we add two more facts:

1. Two parties can gather in a 'coalition', so that the seats are given to the 'coalition' by the sum of votes for all parties in it. Then the seats the 'coalition' got are split between parties in a similar fashion (find divisor, etc.)
2. A party that didn't pass a certain percentage of the votes (e.g. 3.25%) automatically gets 0 seats, and its votes don't count for a 'coalition'.

# Challenge

You are given :

1. A list of lists, each of the nested lists contains integers (number of votes), and is of length 1 for a single party, or length 2 for a 'coalition'.
2. Minimal percentage of votes (a.k.a "bar" for "barrage") to get seats, as a fraction (so 3.25% is given as 0.0325)
3. Total number of seats to be distributed between all parties (integer)

You are to print out the same nested list structure, with the number of votes substituted with parliament seats.

Winner is the code with the smallest amount of bytes.

Corner cases:

* There might (and usually will be) more than one possible divisor. Since it is not in the output, it doesn't really matter.
* Imagine `N=10` and `ns = [[1]]`, so the divisor may be 0.1 (not an integer)
* Some cases can't be solved, for example `ns=[[30],[30],[100]]`, `bar=0`, `N=20`. There's a boundary with `d=7.5` where the sum of floored values jumps from 19 to 21. You are not expected to solve these cases. (thanks to community member Arnauld for pointing this case out)

# Example Input and Output

A very not-optimized Python3 example:

```
from math import floor

def main(_l, bar, N):
    # sum all votes to calculate bar in votes
    votes = sum(sum(_) for _ in _l)

    # nullify all parties that didn't pass the bar
    _l = [[__ if __ >= bar * votes else 0 for __ in _] for _ in _l]

    # find divisor for all parliament seats
    divisor = find_divisor([sum(_) for _ in _l], N)

    # find divisor for each 'coalition'
    divisors = [find_divisor(_, floor(sum(_)/divisor)) for _ in _l]

    # return final results
    return [[floor(___/_) for ___ in __] for _, __ in zip(divisors, _l)]

def find_divisor(_l, N, _min=0, _max=1):
    s = sum(floor(_ / _max) for _ in _l)
    if s == N:
            return _max
    elif s < N:
            return find_divisor(_l, N, _min, (_max + _min) / 2)
    else:
            return find_divisor(_l, N, _max, _max * 2)

print(main(l, bar, N))

```

Example input:

```
l = [[190970, 156473],
    [138598, 173004],
    [143666, 193442],
    [1140370, 159468],
    [258275, 249049],
    [624, 819],
    [1125881],
    [152756],
    [118031],
    [74701]]
bar = 0.0325
N = 120

```

And its output:

```
[[6, 4], [0, 5], [4, 6], [35, 5], [8, 8], [0, 0], [35], [4], [0], [0]]

```

Some more example outputs:

If `bar=0.1` we get an interesting stand-off between two parties as none of the smaller parties are counted in:

```
[[0, 0], [0, 0], [0, 0], [60, 0], [0, 0], [0, 0], [60], [0], [0], [0]]

```

And if `N=0` (corner case) then of course no one gets anything:

```
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0], [0], [0], [0]]

```

# Answer
# 05AB1E, ~~42~~ 39 bytes

```
ÐOOI*@*DO¸I¸¸2Fнζε`sDO/*Ð©±/D{®1%Oòè‹+ï

```

Try it online!

05AB1E lacks good recursion, so implementing a binary search as in the reference code would be painful. Thankfully, we don’t need to find the divisor at all!

Let’s use a simple example: \[600, 379, 12, 9\] votes, 100 seats, no coalitions, no bar. First, we compute how many *fractional seats* each party gets, defining fractional seats as `party_votes * seats / sum_of_votes`. In our example, that yields \[60, 37.9, 1.2, 0.9\].

The interesting bit is that if a party gets `f` fractional seats, it will get either `int(f)` or `int(f) + 1` real seats. This means we already know how 60+37+1 = 98 of the seats will be allocated, and we’re left with 2 “bonus seats” to distribute among the 4 parties (no party can get more than 1 bonus seat). Who do these bonus seats go to? The parties with the highest ratio of `f / (int(f) + 1)` (proof left as an exercise to the reader). In our examples, the ratios are `[0.98, 0.997, 0.6, 0.9]`, so the first two parties get a bonus seat each.

---

Let’s take a look at the code. First, we replace the vote count of all parties that didn’t meet the bar with 0:

```
Ð          # triplicate the first input (list of votes)
 OO        # flattened sum
   I*      # multiply by the second input (bar)
     @     # greater than? (returns 0 or 1)
      *    # multiply

```

Now, to work around the lack of recursion, we use an awkard `2F` to repeat the main code twice. On the first pass it’ll distribute the total seats between coalition, and on the second pass it’ll distribute each coalition’s seats between its parties. Since the first pass runs only once, but the second pass runs for each coalition, this involves rather a lot of busy work.

```
DO¸I¸¸2Fнζε`s    # i don’t want to detail this tbh

```

Okay, after this obscure bit, the top of the stack is now a list of votes (coalition votes on the first pass, party votes on the second), and below that is the number of seats to allocate. We use this to compute the list of fractional seats:

```
D        # duplicate
 O       # sum
  /      # divide each vote count by the sum
   *     # multiply by the number of seats
    ©    # save the fractional seats in variable r

```

Now, we compute the ratios:

```
Ð            # triplicate
 ±           # bitwise not
  /          # divide

```

Bitwise not works beautifully, here. It truncates to integer, adds 1, and negates, all in a single byte. Why negate? In 05AB1E, division by 0 returns 0, and we need these to sort last.

D{ # sorted copy of the ratios ®1% # fractional votes mod 1 (aka the decimal parts) O # sum of the above (this is the number of bonus seats) ò # round to nearest (required due to floating point bs) è # index into the sorted ratios

This gives us the (n+1)th best ratio, where n is the number of bonus seats (+1 because indexing is 0 based). Thus, the parties that get a bonus seat are those that have a ratio strictly less than this.

```
‹      # less than
 +     # add to the fractional seats
  ï    # truncate to integer

```
> 2 votes

# Answer
# Python 2, 220 bytes

```
def d(l,n,a=0,b=1.):s=sum(x//b for x in l);return s-n and d(l,n,*[a,b,(a+b)/2,b*2][s>n::2])or b
def f(l,b,n):l=[[x*(x>=b*sum(sum(l,[])))for x in r]for r in l];return[[v//d(x,sum(x)//d(map(sum,l),n))for v in x]for x in l]

```

Try it online!

Basically just a golf of the reference implementation...
> 3 votes

# Answer
# Wolfram - no golf

Was just curious to solve it using LinearProgramming, not a golfing candidate, but maybe an interesting approach to a problem:

```
findDivisor[l_, n_] := Quiet@Module[{s, c, r, m, b, cons, sol},
   s = Length[l];
   c = Append[ConstantArray[0, s], 1];
   r = Thread[Append[IdentityMatrix[s], -l]];
   m = Append[Join[r, r], Append[ConstantArray[1, s], 0]];
   b = Append[Join[ConstantArray[{0, -1}, s], ConstantArray[{-1, 1}, s]], {n, 0}];
   cons = Append[ConstantArray[Integers, s], Reals];
   sol = LinearProgramming[c, m, b, 0, cons];
   {1/sol[[-1]], Most@sol}
   ]
solve[l_, bar_, n_] :=
 With[{t = l /. x_ /; x <= bar Total[l, 2] -> 0},
  With[{sol = findDivisor[Total /@ t, n]},
   {First@sol, MapThread[findDivisor, {t, Last@sol}]}]
  ]

```

Read some explanation and try it out!
> 2 votes

# Answer
# Jelly, ~~63~~ 36 bytes

```
F×S<ḷ×ḷµ§⁵:,1_×¥:@"§IṠʋ÷9ɗ¥ƬṪṪƲ¥¥@⁺"

```

Try it online!

A full program taking three arguments: the numbers of votes in the format described by the question, bar and N in that order. Returns a list of lists of seat counts. The footer on TIO is just to highlight the list structure of the output. (Otherwise Jelly hides `[]` for single-item lists.)

## Explanation

```
F×S<ḷ×ḷµ§⁵:,1_×¥:@"§IṠʋ÷9ɗ¥ƬṪṪƲ¥¥@⁺"

F                                   | Flatten vote counts
 ×                                  | Multiply by bar
  S                                 | Sum
   <ḷ                               | Less than original vote counts (vectorises and respects input list structure)
     ×ḷ                             | Multiply by original vote counts
       µ                            | Start a new monadic link with processed vote counts as input
        §                           | Vectorised sum

         ⁵                      ¥@  | Apply the following as a dyad with the number of seats as the right argument and the vectorised sum of votes as left

           ,                  Ʋ¥    |(*)- Pair vote counts with seat sum and find divisor using the following as a monad:
            1             ¥Ƭ        |     - Starting with 1 as a guess for divisor, and using the paired vote counts and seat sum as the right argument, apply the following as a dyad, collecting intermediate results, until the results repeat
                         ɗ          |       - Following as a dyad:
                      ʋ             |         - Following as a dyad:
                :@"                 |           - Integer divide with arguments zipped and reversed, i.e. divide cote counts by current divisor guess and leave total seats alone
                   §                |           -  Vectorised sum (will sum vote counts but leave seat number alone)
                    I               |           - Find differences i.e. desired total seats minus current calculation based on current divisor guess. Will return a list.
                     Ṡ              |           - Sign of this (-1, 0 or 1)
                       ÷9           |         - Divide by 9 (-0.111, 0 or 0.111)
             _×¥                    |     - Now multiply the current divisor guess by this and subtract it from that guess to generate the next guess. If the current guess is correct, the guess will be unchanged and so the Ƭ loop will terminate
                            ṪṪ      |     - Take the last item twice (first time to get the final
                               output of the Ƭ loop and second to remove the list introduced by I
         :                          | - Integer divide the vote counts by the output of the above

                                  ⁺"| Apply the above dyad from the step labelled (*) again, this time with the output of the previous step (total votes per coalition) as right argument and the vote counts as left argument, zipping the two together and running the link once for each pair

```

# Original Submission (larger but more efficient)

# Jelly, 63 bytes

```
:S_3ƭƒṠ©ḢḤ;$;ṪƲṖÆm;ḊƲ®‘¤?ß¥/}ṛ¹?,
1,0;çḢḢ
FS×Ċ’<ḷ×ḷµ:"§:⁵ç$$ç"Ɗ

```

Try it online!
> 1 votes

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