title: GO OUT AND VOTE

text:
# Question
Title: GO OUT AND VOTE
Today is November 8th, 2016, Election Day in the United States of America.

If you are a U.S. citizen eligible to vote, then go out and vote if you haven't already before answering this challenge. **Do not discuss who you voted for.** It only matters that you voted.

If you are not a U.S. citizen or not eligible to vote, then, before answering this challenge, do the U.S. a favor by telling anyone you know who is an eligible citizen to go out and vote if they haven't already.

# Challenge

Write a program that indicates that you voted, like a digital "I Voted" sticker.

It should take no input and must output in a reasonable way the phrase `I Voted` where the `I`, `o`, and `e` are red (`#FF0000`) and the `V`, `t`, and `d` are blue (`#0000FF`). The background must be white (`#FFFFFF`).

For example:

>

These colors are of course representative of the American flag (though not the official colors). Red comes first simply because it comes first in the common idiom "red white and blue".

To be valid, an answer must:

* Use the colors specified in the arrangement specified.
* Use a single legible font and font size. The example uses 72pt Times New Roman bold but any common font above 6pt is probably fine.
* Have just the phrase `I Voted` on a **single line**, capitalized correctly, with a clear space between the two words. It shouldn't look like `IVoted`.
* Not indicate who the answerer voted for or supports for president or any down-ballot races. Let's not start any internet debates. This is about celebrating voting, not candidates.

Any reasonable way of displaying or producing the output is valid, such as:

* Drawing the text to an image that is then displayed, saved, or output raw.
* Writing the text to a console using color formatting. In this case you may approximate pure red and blue if necessary, and it's ok if only the area directly behind the text can be made white.
* Displaying the text on a WPF/Windows form.
* Outputting an HTML/RTF/PDF file with the text.

Please post an image of your output.

**The shortest answer in bytes wins.**

# Answer
> 121 votes
## Minecraft Chat (vanilla 1.10 client, spigot 1.10 server): 19 bytes

```
&4I &1V&4o&1t&4e&1d

```

or from the clientside:

```
§4I §1V§4o§1t§4e§1d

```

Minecraft uses a color coding system with these colors programmed in.

Mind the rules:

> * Writing the text to a console using color formatting. In this case you may approximate pure red and blue if necessary, and it's ok if only the area directly behind the text can be made white.

All of these are true, as:
the red and blue ARE approximations (though still very similar).
The background in Minecraft chat is transparent, meaning that it's possible to put this on a white background (such as an empty world or a world which is still generating).

# Answer
> 106 votes
# C, ~~82~~ ~~80~~ ~~78~~ ~~74~~ 54 bytes

*Thanks to @WillihamTotland and @criptych for saving 2 bytes each!*

```
f(){puts("␛[47;31mI␛[34m V␛[31mo␛[34mt␛[31me␛[34md");}

```

Where the ␛s represent 0x1B bytes (escape key). As this code contains unprintable control characters, here is a reversible hexdump:

```
00000000: 6628 297b 7075 7473 2822 1b5b 3437 3b33  f(){puts(".[47;3
00000010: 316d 491b 5b33 346d 2056 1b5b 3331 6d6f  1mI.[34m V.[31mo
00000020: 1b5b 3334 6d74 1b5b 3331 6d65 1b5b 3334  .[34mt.[31me.[34
00000030: 6d64 2229 3b7d                           md");}

```

Output on my phone:

# Answer
> 75 votes
# Google Blockly, ~~10~~ 14 blocks, ~~28~~ ~~41~~ 35 blytes

### Code

### Output

Try it here

Not counting the `hide turtle` block because it's just aesthetics.

A blyte is a combination of a block and a byte, there's no meta post yet as how to count this, but I'll create one later. As for now, this is how I count:

* `I o e`, 8 blytes
* `V t d`, 10 blytes (2 leading spaces here)
* Colours, 1 blyte each, 2 total
* 90, 2 blytes
* 999, 3 blytes
* 0, 1 blyte
* turn right, 2 blytes
* move forward, 2 blytes
* normal blocks, 1 blyte each, 5 total

Since Google Blockly is rarely used for golfing and I'm thinking waaay outside of the box for this challenge, I hope this is a valid submission.

# Answer
> 49 votes
# HTML, 52 bytes

```
I <c>V<e>o<c>t<e>e<c>d<style>*{color:red}c{color:0ff

```

# Answer
> 40 votes
# LaTeX, ~~147~~ 126 bytes

```
\documentclass{proc}\input color\begin{document}\def\z{\color{red}}\def\y{\color{blue}}\z I \y V\z o\y t\z e\y d\end{document}

```

*Saved 21 bytes and got better kerning thanks to @AndreïKostyrka.*

This prints an a4 page with this on the first line (note that this also prints page 1 on the bottom):

# Answer
> 34 votes
## Windows 10 Batch, ~~51~~ 50 bytes

```
@color fc&echo I ␛[94mV␛[91mo␛[94mt␛[91me␛[94md␛[m

```

Where ␛ represents the ANSI Escape 0x1B character. Outputs using colour formatting. Edit: Saved 1 byte thanks to @brianush1. I tried writing the code to generate this but it took 97 bytes. Output:

# Answer
> 28 votes
# JavaScript, 71 bytes

```
console.log('%cI %cV%co%ct%ce%cd',r='color:red',b='color:blue',r,b,r,b)

```

Makes use of `console.log`'s ability to print in color. Doesn't work in a stack snippet so you should paste this answer to the console to test it.

Picture credits to @Mast

# Answer
> 23 votes
# R, 113 85 81 74 73 55 bytes

Edit: Saved a bunch of bytes thanks to @rturnbull and @JDL

```
plot(8:1,0:7*0,pc=el(strsplit("detoV  I","")),co=2:1*2)

```

The size of the output (and spacing etc) depends on the resolution of the currently open graphics device. Tested in RGui and RStudio on my monitor and produces:

# Answer
> 22 votes
## LÖVE, ~~152 142~~ 136 bytes

Let's show some löve for a fun little prototyping language! It's not perfect for the task of golfing (c'mon, it's LUA based), but it's easy to write.

```
function love.draw()l=love.graphics
a=255
l.setBackgroundColor(a,a,a)s=l.setColor
p=l.print
s(a,0,0)p('I   o e')s(0,0,a)p('  V  t d')end

```

---

Screenshot:

---

Fully ungolfed version:

```
function love.draw()
    love.graphics.setBackgroundColor(255,255,255)
    love.graphics.setColor(255,0,0)
    love.graphics.print('I   o e')
    love.graphics.setColor(0,0,255)
    love.graphics.print('  V  t d')
end

```

# Answer
> 19 votes
## Hot Soup Processor, 48 bytes

```
color 255
mes"I  o e
pos,0
color,,-1
mes"  V t d

```

The ungolfed version is:

```
color 255,0,0
mes "I  o e"
pos 0,0
color 0,0,255
mes "  V t d"

```

If you bear in mind that `mes` (message) is HSP's `echo`, I think this is fairly readable.

Weirdly, if you try to do `pos` or `pos,`, the blue line doesn't overwrite the red line and appears beneath it. Even weirder, `color` is only meant to take values in `0-255`, but `0,0,-1` works for blue, `0,-1,0` works for green and `-1,0,0` works for... black? (`-257,0,0` and `511,0,0` work for red though, so something's funky about the mod 256 going on)

# Answer
> 18 votes
## MATLAB, 74 bytes

We create a white 50x50 (one column for each state) background using `imshow` of an array of `ones`. We then display a text, using my trick of shortening property names to get the colours. Since the default font is not fixed width, the text is padded with spaces.

```
imshow(ones(50))
text(2,9,'I   o e','Co','r')
text(8,9,'V  t  d','Co','b')

```

### MATLAB, 99 bytes, fixed width font

The first version uses fiddling with spaces and coordinates to get a proper kerning on the default font, and might not display properly on your computer. Instead, we can use a fixed width font, like `Courier` (or, for some more bytes, `FixedWidth` which works on any system that has a fixed width font installed). This does come at the cost of quite a few extra bytes. We can mitigate this slightly by using a `for` loop to print the text. The text and corresponding colours are stored in a cell array. The background needs to be a little bit larger.

```
imshow(ones(80))
for y={'I  o e ','  V t d';'r','b'}
text(9,9,y{1},'Co',y{2},'FontN','Courier')
end

```

### Matlab, 80 bytes bonus edition

Sadly, underlined blue text is not allowed. Otherwise, this answer would have highlighted some interesting behaviour in MATLAB. You can print red text using `fprintf(2,txt)`, and you can print blue underlined text with `fprintf('<a href="">txt</a>')`. Combining this works... sometimes. **Completely at random**, it may also create red underlined text. You can issue `drawnow` between consecutive `f` calls if this is the case on your system.

```
f=@(p)fprintf(2,'%s<a href>%s</a>',p(1:end-1),p(end));f('I V');f('ot');f('ed');fprintf('\n')

```

# Answer
> 18 votes
# ImageMagick, 102 bytes

```
magick xc:[x60] -fill red -draw 'text 5,30 "I     o  e"' -fill blue -draw 'text 15,30 "V   t   d"' x:

```

Ungolfed:

```
magick convert canvas:white[60x60!] \
       -fill red  -draw 'text 5,30   "I     o  e"' \
       -fill blue -draw 'text 15,30      "V   t   d"' \
       show:

```

Golfing the full ImageMagick command consisted of

* not explicitly calling the default `convert` utility
* using `xc:` instead of `canvas:` (`xc:` is an old synonym for `canvas:`; I don't foresee ImageMagick ever eliminating it)
* not specifying the canvas color but relying on ImageMagick's default, which happens to be white
* removing the width `60` from the geometry (when it's omitted, width==height)
* removing the "!" from the geometry which is only needed to produce a non-square canvas, like `canvas:white[60x30!]`
* using the older `x:` instead of `show:` as the output file (assumes that ImageMagick was built with `X` support)
* removing some whitespace that I had used to line up the text strings
* joining the multiple lines of the command (removed the backslash-CR between lines)

If you are so inclined after the election, add 12 bytes `-rotate 180` preceding the `show:` directive:

# Answer
> 15 votes
# Mathematica (REPL image output), ~~65~~ 49 bytes

```
Overlay@{"I  o e"~Style~Red,"  V t d"~Style~Blue}

```

Graphical REPL expression.

# Answer
> 15 votes
# Bash, 35 bytes

My script looks like this

```
echo "^[[47;31mI hope^[[34md^H^H^Ht^H^H^Hv"

```

xxd of script file:

```
0000000: 6563 686f 2022 1b5b 3437 3b33 316d 4920  echo ".[47;31mI
0000010: 686f 7065 1b5b 3334 6d64 0808 0874 0808  hope.[34md...t..
0000020: 0876 22                                  .v"
```

Typing it: ctrl-v-esc and ctrl-v-h will insert the escapes and backspaces (^\[ and ^H).

# Answer
> 14 votes
# Java, ~~322~~ ~~319~~ ~~318~~ ~~309~~ ~~304~~ ~~229~~ 217 bytes

-9 Bytes thanks to kevin.
-75 Bytes thanks to Angzuril, nice callout on the old awt classes, always forget those exist.
-12 Bytes thanks to user902383.

```
import java.awt.*;
void n(){new Frame(){{add(new Panel(){public void paint(Graphics g){int i=0;for(String c:"IVoted".split("")){g.setColor(i%2<1?Color.RED:Color.BLUE);g.drawString(c,i++*8,10);}}});setVisible(0<1);}};}

```

Output:

# Answer
> 13 votes
## PowerShell v2+, ~~71~~ ~~59~~ ~~57~~ 55 bytes

```
"I Voted"[0..6]|%{Write-Host -b w -n -f (9,12)[$_%2]$_}

```

*Saved two bytes thanks to @flashbang ... saved two more thanks to @ConnorLSW*

Takes `"I Voted"` and turns it into a `char`-array, then loops `|%{...}`. Each letter, we execute `Write-Host` with the `-b`ackground color to `White`, `-n`oNewLine, and the `-f`oreground color to be the appropriate index. This leverages the fact that odd ASCII values are Red, while even ASCII values are Blue via `$_%2` as the index.

Console colors in PowerShell are *very* limited, so this is the closest approximation I could get. It would be golfier to use `4` (`DarkRed`) for the red, but it doesn't look right, so I'm sacrificing a couple bytes for the sake of color accuracy.

Below is the output, followed by the 16 available colors the console can display. Note that the background isn't *truly* white, since Microsoft in their wisdom opted to have the background colors ever-so-slightly-off from the foreground colors.

# Answer
> 13 votes
# Bubblegum, 28 bytes

```
0000000: 938e 3636 ccf5 0492 e6b9 0a40 d224 370c  ..66.......@.$7.
0000010: 2c92 0f66 9780 d9a9 6076 0a00            ,..f....`v..

```

Does not work online since it uses ANSI color codes for coloring.

# Answer
> 11 votes
# Python, 91 bytes + `termcolor`

Not gonna win, but posted it for fun.

```
from termcolor import*
for c in'I Voted':cprint(c,'brleude'[ord(c)%2::2],'on_white',end='')

```

Half the credit goes to Sp3000.

# Answer
> 9 votes
# Python IDLE, ~~97~~ ~~96~~ ~~78~~ 69 bytes

*Thanks to DrMcMoylex for shaving off some bytes!*

*EDIT: Figured out that a direct `.write()` was 9 bytes shorter*

Not really a proper answer, more abuse of a standard theme. IDLE is Python's IDE, and unless it's customized, `STDOUT` is blue, `STDERR` is red, and the background is white. So, the following code:

```
from sys import*
for i in'I Voted':[stdout,stderr][ord(i)%2].write(i)

```

Prints this:

This works because `ord(i)%2` checks the parity of the letter's code point and prints it to `ERR`/`OUT` accordingly.

# Answer
> 8 votes
# Jolf, 53 bytes

```
"<z>I <w>V<z>o<w>t<z>e<w>d<style>w{ΞΩ4blue}z{ΞΩ4red

```

There are unprintables. Try it here!

Jolf's output is HTML capable. I tried doing something clever like modulus 2 to decide color, but that only wound up longer (around 69 bytes). So, the output is in HTML.

Output:

(larger version)

# Answer
> 8 votes
# sh, ~~61~~ 49 bytes

```
echo "[47;31;1mI [34mV[31mo[34mt[31me[34md"

```

Because this contains unprintables, here is a reversible xxd hexdump:

```
00000000: 6563 686f 2022 1b5b 3437 3b33 313b 316d  echo ".[47;31;1m
00000010: 4920 1b5b 3334 6d56 1b5b 3331 6d6f 1b5b  I .[34mV.[31mo.[
00000020: 3334 6d74 1b5b 3331 6d65 1b5b 3334 6d64  34mt.[31me.[34md
00000030: 22                                       "
```

*Xterm(322)*

Thanks to 4198 (manatwork) for -12 bytes.

# Answer
> 8 votes
# Python, ~~99~~ 87 bytes

```
from turtle import*
up()
for c in"I Voted":color("brleude"[ord(c)%2::2]);write(c);fd(7)

```

**Try it online**

# Answer
> 8 votes
## REBOL, ~~100~~ ~~90~~ 95 bytes (-7 bytes with REPL for 88)

```
REBOL[]view layout[style b tt blue white space 0 across b"I"red b b"V"b"o"red b"t"b"e"red b"d"]

```

In REPL, the initial *REBOL\[\]* is not required. That's 7 bytes.

The ungolfed version is:

```
REBOL[]
view layout[
  ; by default, tt (text) has a grey background and a 2x2 padding
  style b tt blue white space 0
  ; this one doesn't appear in the golfed version as it's slightly shorter to just manually set red everywhere needed
  style r b red

  ; by default, vertical stack panel
  across
  r "I"
  r
  b "V"
  r "o"
  b "t"
  r "e"
  b "d"
]

```

On the left, with "space 0x0" added to each text block, on the right, with the default 2x2 padding.

(source: canardpc.com)

# Answer
> 8 votes
# SVG + `bzip2`, 1807 bytes

A vectorized version of the example image, then compressed with bzip2 to about half (4385 -\> 1807 bytes). You can download it here. (direct GitHub Pages link)

```
BZh91AY&SY!�l�ß�x��>�ߠ/���`    0����Ҁ�D�5��ޠII�T�O!45J??��i�@JzH���
.�M�&�Q�vا����bB���� �쾾�4AV�8�8���)Z�ޣ�j�q}�����?�t�/
�±%��"A����B�X�(␌�[⎺;Z/┐├*��%�␤�       I���Uƒ�Y�9ǝK���B��┤�=���±?�W���
            ��ڰj�?�H��\����^��m�=X�d���>�!C�@�.���9�" DZ+��V1+�;�����58Q���-:�5,HDQŧ`A>����W�+h��>m��G�m�uWv�&�U�|mq�u���?=S�\{(��Z�a�I��G{Cd��;Bz���qX7��?P�@�Jt[w�]����%W���37f���-�iԳ]c��|�;i�k�H��
    sHz��Y�$�.�*�?�ڐ��Us=\뫅6%�Ud�9w���D
                                          ��H��^�Q��P��%n�O����l��+*q�U�"F%��*�     *b��
                                         @mP���Z�(ZL`
  bIv⦳�~�F=��>H�Ti����0@≠R≥��T�E��┴��D����␍│��2*◆=└6&⎽M�◆␊?�/�U�����r�.�`gƅ���E'��^��ILPz@���zR&u$��l^�U�n�'O\�Xj+چ�o�*�O�w��JP8���]���r��k=��N�b�ƵpM�8|���=7���N��W�M(����*�E�DݐT��Zi�v"���49�J�0}�F�*x�K���P��⎼*�������6[G,4� ү)UUT␍��%4D��Թ␉��⎻�8�CZ_3ɷwW�9��-&�Ov�a՜
�'ӥtߢ�>��^�m-������c�]:��*��2��촄Ujr�?"�J�"���DE�f?┴⎻��␍3·└���Ԉ��? ׌�5|ᫎ���|DO���%�4Ư`W�ƐV/=�]V`gˇ��^Z��cP������.{������6   o.*�sɽ���U?E.3�,�H$�{�?
             �%�0��2    ��n�C!%�>��]��
#߽v�E��K��?X|���5�ΰ@>A;#J���,��Q��$���ݨ��^����7�g�Xn�k����d욒�`fQ/7��vh|�ȥ*^M
                            �[����׈���i�I��    $��4��
  Y��`V.��ح��?�eT����5K˱~�瞯r�fL^I �#b�@�pBƞ���V`5��a��qH���Ş�t�V3��┌���T���1␉�␍$5��@T␤$�>$����π���S�[۸£�[ȟ␋CO≥�ގ^��>��]E�A��┘���I(�㴨Z�J'��:�-_┤±�K␌�ۓ#:�?m��^�Z�+�����G
�k�t�O��SD�4����^o��Z�n���6M�)!��r��w�3\�R����
�X6<#����.��p� Cj"�2�ĭ�*h�S�`}�L���C?�� �چZc'kG��

```

Not gonna win, but posted it for fun.

# Answer
> 8 votes
## C, 65 bytes

```
i;main(c){for(;c="I Voted"[i++];printf("\33[3%dm%c",c&1?1:4,c));}

```

or, more accurately:

```
i;main(c){for(i=90;c="\0.noitcele ym saw ti fi enod evah dluow I sseug I tuB .hsitirB ma I esuaceb ,etov ton did I"[i--];printf("\33[3%dm%c",c&1?1:4,c));}

```

Uses the same bash colour technique used by betseg, but with the octal escape sequence instead of hex, and with Sp3000's observation that all odd codepoints are red.

Leaves the terminal in blue. Reset with:

```
printf "\33[0m";

```

# Answer
> 8 votes
# Node, ~~57~~ ~~55~~ 41 bytes

```
console.log("q47;91mI  o eHHHHq94mV t d")

```

Replace each `q` with the literal byte `1B` and `H` with byte `08` before running.

Here's how it looks in the ConEmu terminal emulator on my Windows computer (zoomed in):

# Answer
> 7 votes
# Perl, 57 + 17 = 74 bytes

Run with `-MTerm::ANSIColor`

```
sub c{color$a++%2?blue:red}say c,"I ",c,V,c,o,c,t,c,e,c,d

```

Your terminal may be blue at the end (append `,c("reset")` at the end of the code to restore it to normal).

By default, terminals are *usually* black background, but they can be optionally changed to white, which I personally don't think is cheating.

With picture:

# Answer
> 7 votes
# PHP, ~~199~~ ~~201~~ 151 bytes

This script outputs image to standard output. **Updated thanks to manatwork**

```
imagefill($i=imagecreatetruecolor(99,99),0,0,2**24-1);foreach([I,' ',V,o,t,e,d]as$k=>$e)imagestring($i,2,$k*9,0,$e,!$k|$k&1?0xFF0000:255);imagepng($i);

```

Run it in the command line like this:

```
php -d error_reporting=0 -r "imagefill($i=imagecreatetruecolor(99,99),0,0,2**24-1);foreach([I,' ',V,o,t,e,d]as$k=>$e)imagestring($i,2,$k*9,0,$e,!$k|$k&1?0xFF0000:255);imagepng($i);" > output.png

```

Output:

# Answer
> 7 votes
# Xamarin.Forms C#, ~~317~~ 313 bytes

```
using Xamarin.Forms;public class A:Application{public A(){var s=new StackLayout{BackgroundColor=Color.White,Orientation=(StackOrientation)1,VerticalOptions=LayoutOptions.End};foreach(var c in"I Voted")s.Children.Add(new Label{Text=c+"",TextColor=c%2<1?Color.Blue:Color.Red});MainPage=new ContentPage{Content=s};}}

```

`VerticalOptions=LayoutOptions.End` is needed for iOS, otherwise the text will be overlayed by status bar. No problem on Android so can save 34 bytes including comma.

*Edit: 2016-11-14: -4 bytes*

Ungolfed

```
using Xamarin.Forms;
public class A : Application
{
    public A()
    {
        // Make a horizontal StackLayout for labels
        var s = new StackLayout
        {
            BackgroundColor = Color.White,
            Orientation = (StackOrientation)1,   // StackOrientation.Horizontal
            VerticalOptions = LayoutOptions.End
        };
        foreach(var c in "I Voted")
            // Make a new label for each letter, then add to StackLayout
            s.Children.Add(new Label
                {
                    // Cast char to string
                    Text = c + "",
                    // Happens that 'I', 'o', and 'e' are all odd in ASCII, and 'V', 't', and 'd' are all even :)
                    TextColor = c%2<1 ? Color.Blue : Color.Red
                }
            );
        // Set app MainPage to be a new ContentPage, where the content is the StackLayout above
        MainPage = new ContentPage { Content = s };
    }
}

```

# Answer
> 7 votes
# x86 machine code + DOS + BIOS, 25 bytes

Hexdump:

```
b8 02 13 b1 07 bd 0b 01 cd 10 c3 49 74 20 74 56
71 6f 74 74 71 65 74 64 71

```

Assembly code (suitable as input to `debug.com`, so all numbers are hexadecimal):

```
mov ax, 1302
mov cl, 7
mov bp, 10b
int 10
ret
db 'It tVqottqetdq'

```

It uses a BIOS routine to output the string to the display memory. The string will appear at a "random" position on screen (see below), like this:

The string contains the letters `I V o t e d`, interleaved with "attributes"

```
74 74 71 74 71 74 71

```

that specify the colour of the letters. Here 7 as the most significant digit means "white background", and the least significant digit specifies the foreground (1=blue; 4=red).

The display position of the string is specified by the `dx` register. As mentioned here, the initial value of this register is equal to the value of the `cs` register. And the value of that one is the first available address in memory, after DOS is loaded.

The size of DOS is typically less than 64K, that is, the segment address of the loaded user's program is less than hexadecimal `1000`. So the output will appear somewhere around the first 16 lines of text on the display. In my example, it appeared at line 8 (the upper half of `dx`, called `dh`, is equal to 8).

The low half of `dx`, called `dl`, contains the column at which the text is output. Experiments show that BIOS doesn't check overflow, so it doesn't matter if `dx` asks for output at e.g. column 100.

# Answer
> 6 votes
# Qbasic, ~~137~~, ~~126~~, ~~124~~, ~~122~~, ~~115~~, ~~114~~, 113 bytes

```
a$="I m C n d a ":b$=" '   a a i n"
FOR i=1TO 12
c$=MID$(a$,i,1)
IF c$<>" "THEN
COLOR 4,7:?c$;
ELSE
COLOR 7,4:?MID$(b$,i,1);
ENDIF
NEXT

```

:) And the real program

```
a$="I  o e":b$="  V t d"
FOR i=1TO 7
c$=MID$(b$,i,1)
IF c$=" "THEN COLOR 4,7:?MID$(a$,i,1);ELSE COLOR 1:?c$;
NEXT

```

Output:

# Answer
> 6 votes
# BASIC (zx spectrum), 24 bytes

```
1 PRINT "{BRIGHT 1}{INK 2}I {INK 1}V{INK 2}o{INK 1}t{INK 2}e{INK 1}d"

```

But it’s not a real spectrum code, it is just a text that should be feed to BAS2TAP compiler.

70 ASCII-chars (including the end of line).

Actually, it produces a .TAP file. To easily run it, I give you the encoded version:

```
data:text/cmd;base64,EwAAAFZPVEUgICAgICAdAAAAHQAIHwD/AAEZAPUiEwEQAkkgEAFWEAJvEAF0EAJlEAFkIg0r

```

This URI is 93 characters in Base64, but the real TAP file size is 54 bytes.

Visit this online emulator and press “Open file” (4-th button, «folder»), flip “Spectrum 128K” to “Spectrum 48K”, paste that "data:text…" to “Load from web:” field and finally hit “Open URL”!

But my program is even smaller. You see, Spectrum uses one byte for language keywords and control codes.

So `PRINT` (and spaces around it) is just one “char” from ZX’s point of view. If I will not count line number “1” (piece of code could be executed directly) and final ENTER, then program dump looks like this:

```
Offset   |  0  1  2  3  4  5  6  7   8  9 10 11 12 13 14 15 |
---------+--------------------------------------------------+-----------------
00000000 | F5 22 13 01 10 02 49 20  10 01 56 10 02 6F 10 01 | х"....I ..V..o..
00000016 | 74 10 02 65 10 01 64 22                          | t..e..d"

```

**24 bytes**

Color codes are represented as two byte sequences. But they could be written as one logical character from the keyboard!

Since we don’t need to restore colors after line, my logical length is this: “1” as line number; keyword “PRINT” (typed with only one keypress); quote char. Then comes BRIGHT mode (to make background pure white) and BLUE ink. Then type all letters with according color (can switch to RED directly). And a final quote. That way, I got 18.

Also we can count actual keystrokes that are needed to write this program to Spectrum! Go here.

`Ctrl` key stand for SYMBOL SHIFT and `Shift` stand for CAPS SHIFT. The combination “Ctrl+Shift” will put the cursor in "E" mode and back, so don’t hold it for long.

To type my golfing, press this key sequence:

`1` `P` `CTRL+P` `CTRL+SHIFT` `9` `CTRL+SHIFT` `SHIFT+2` `SHIFT+I` `SPACE` `CTRL+SHIFT` `SHIFT+1` `SHIFT+V` `CTRL+SHIFT` `SHIFT+2` `O` `CTRL+SHIFT` `SHIFT+1` `T` `CTRL+SHIFT` `SHIFT+2` `E` `CTRL+SHIFT` `SHIFT+1` `D` `CTRL+P` `ENTER` `R` `ENTER`

We have as much as 28 keystrokes!

---

**Moderator Note**: for anyone interested in seeing the remaining part of this answer (the polyglot code which is not a serious competitive contender), it is now in a gist here to save space.

# Answer
> 5 votes
# Processing, ~~83~~ ~~85~~ 83 bytes

Had to increase byte count to include spaces to avoid overlapping letters

Then I reduced byte count by changing the positions and removing spaces

Processing is basically Java, but more artistic and **less verbose** (emphasis on less verbose).

```
background(255);fill(#ff0000);text("I   o e",2,9);fill(#0000ff);text("V  t d",9,9);

```

Explanation:

```
background(255); //sets background colour to white
fill(#ff0000); //setting the text colour to red
text("I   o e",2,9); //Display text "I   o e" (in red) at position (2,9) [Origin is top left]
fill(#0000ff); //set the text colour to blue
text("V  t d"); //Display text "  V  t d" (in blue) at position (9,9)

```

# Answer
> 5 votes
# Bash, 61 bytes

```
b="\e[34m";r=${b/4/1};echo -e ${r}I ${b}V${r}o${b}t${r}e${b}d

```

with white background 61 + 9 byte:

```
b="\e[34m";r=${b/4/1};echo -e "\e[107m"${r}I ${b}V${r}o${b}t${r}e${b}d

```

# Answer
> 5 votes
## Quake 3/Live Colour Codes (19 characters)

```
^1I ^4V^1o^4t^1e^4d

```

# Answer
> 4 votes
# Emmet, 49 62 61 68 bytes

`a{I}+r{V}+a{o}+r{t}+a{e}+r{d}+style{r{color:red}}`
`r{I }+w{V}+r{o}+w{t}+r{e}+w{d}+style{r{color:red}w{color:#00f}}`

Running this will generate the following HTML code:

`<w>I</w>
<r>V</r>
<w>o</w>
<r>t</r>
<w>e</w>
<r>d</r>
`

And it looks like this:

It's using the blue of links, so the only color that needs to be set is red, saving us some bytes.

# Answer
> 4 votes
# Encapsulated Postscript, 103 bytes

Copy-paste and save as .eps to display it:

```
%!PS
/run{100 500 moveto setrgbcolor show}def/Courier 60 selectfont(I  o e)1 0 0 run(  V t d)0 0 1 run

```

**Explanation:**

```
/run{100 500 moveto setrgbcolor show}def

```

Declares a procedure "run" that expects to have in the stack a string and 3 rgb values. The procedure moves the cursor to 100 500, takes the 3 rgb values from the stack to set the color, then takes the string from the stack and displays it,

```
/Courier 60 selectfont

```

Sets the Courier font with size 60

```
(I  o e)1 0 0 run

```

Puts the string and the 3 rgb componets in the stack and calls "run"

# Answer
> 4 votes
# Printf (in sh), ~~49~~ 44 bytes

Sad to see no one has used `printf`, only `echo`. (See Why is printf better than echo?)

:)

```
printf '\e[47;1;31m%s\e[34m%s' I\  V o t e d

```

Thanks to matatwork for helping shave off five bytes. :)

---

As noted in the comments, two more bytes could be shaved off by using literal escape characters rather than `\e` in both places where that appears.

(I've chosen not to update the screenshot, and of course can't include literal escape characters in the code anyway. I don't know if I should reduce the byte count to 42 bytes, since I didn't make those updates.)

# Answer
> 4 votes
# IRC - 19 bytes

```
4I 2V4o2t4e2d

```

Here it is with the nonprintables escaped, UNIX style:

```
^C4I ^C2V^C4o^C2t^C4e^C2d

```

xxd output:

```
00000000: 0334 4920 0332 5603 346f 0332 7403 3465  .4I .2V.4o.2t.4e
00000010: 0332 64                                  .2d

```

This makes use of IRC coloring, which uses ASCII character 03 and a colour palette.

# Answer
> 3 votes
# Mouse2002, 84 bytes

```
"[47;31;1mI "#B,86;#R,111;#B,116;#R,101;#B,100;$B1%c:"[34m"c.!'@$R1%c:"[31m"c.!'@

```

Ungolfed:

```
"[47;31;1mI " #B,86; #R,111; #B,116; #R,101; #B,100;

$B 1% c: "[34m" c. !' @
$R 1% c: "[31m" c. !' @

```

A hexdump of the golfed code (note the unprintables), reversible with `xxd -r`:

```
00000000: 221b 5b34 373b 3331 3b31 6d49 2223 422c  ".[47;31;1mI"#B,
00000010: 3836 3b23 522c 3131 313b 2342 2c31 3136  86;#R,111;#B,116
00000020: 3b23 522c 3130 313b 2342 2c31 3030 3b0a  ;#R,101;#B,100;.
00000030: 0a0a 2442 3125 633a 221b 5b33 346d 2263  ..$B1%c:".[34m"c
00000040: 2e21 2740 0a24 5231 2563 3a22 1b5b 3331  .!'@.$R1%c:".[31
00000050: 6d22 632e 2127 40                        m"c.!'@

```

# Answer
> 3 votes
# SVG, 71 bytes

This may not parse as an .svg file, but it works if you save it as html.

```
<svg letter-spacing=8><text y=20 fill=red>I oe<tspan x=16 fill=blue>Vtd
```

# Answer
> 3 votes
# Python 2 (or 3), (75 bytes)

##

```
a="\033[3%sm"
r,b=a%"1;47",a%4
print(r+"I "+b+"V"+r+"o"+b+"t"+r+"e"+b+"d")

```

Resized my terminal font size to 72 for a bigger picture, outputs in colour in most terminals.

# Answer
> 3 votes
## C#, ~~262~~ ~~201~~ ~~180~~ ~~170~~ 166 bytes

```
using c=System.Console;using o=System.ConsoleColor;static void M(){c.BackgroundColor=(o)15;foreach(var a in "I Voted"){c.ForegroundColor=(o)(a%2<1?9:12);c.Write(a);}}

```

*Saved 46 bytes thanks to Link Ng*

Outputs the following to console:

# Answer
> 3 votes
# Befunge, 47 bytes

```
41+:+"detoV I":v:,,,\<
93"[47;3m"g0%2:_@>,,,^#*

```

**Try it online** \- you'll need to *Compile* then *Execute*

# Answer
> 3 votes
## Bash, 51 bytes

```
GREP_COLORS='sl=34;47' grep [Ioe] --col<<<I\ Voted

```

Without the white background (who says terminals have to be black??), it is even shorter: 46 bytes.

```
GREP_COLORS=sl=34 grep [Ioe] --col<<<I\ Voted

```

But it looks like OP wouldn't accept the latter.

`grep` highlights any of letters `I`, `o` or `e` red (default coloring). I don't think there is a regex for *vowels* in general which could shorten the syntax. For blue color and white background, instead of stating the complicated bash color codes, you can let `grep` do that when defining `GREP_COLORS`:

> grep takes care of assembling the result into a complete SGR sequence (\33\[...m).

Looks like the syntax highlighting on Codegolf is a bit based though.

# Answer
> 3 votes
# Geometry Dash, 2 objects/276 bytes

Raw text that the level is stored as:

```
H4sIAAAAAAAAE6WPzQrCMBCEX2iFnc1PU8RDexGPUvC66EWkvoDgw5tkKyJYtHjIDJlhPpJxcImgEoJKVVcVFsEyWOh1BY0KZtZGoQhFkrImxR3ZJZfyGwL_I9qPiIVfES37TyDIC8TfMGEWw0teE2cwNHZwxMWCWTTzlDVSLseusWiyVGxwbb1JVSPUovNVrQWbgXgNajNUCDGQI3CgNuPJo0gGHHEsB-RAw9CdT7f--hqlZhoJ8vU5WkHedodLz7vtfrN-APfUD_t-AgAA

```

Level editor

Object count in the top-left

This is made by converting RGB to Geometry Dash's version of HSL (in Geometry Dash its hue, saturation, and brightness), and coloring "V t d" blue (hue -120, saturation 1, and brightness 0) and "I o e" red (hue 0, saturation 1, and brightness 0).

# Answer
> 3 votes
# Trackmania Nations Forever, 31 bytes

Uses colour codes for in-game nickname. When selecting profile on startup, the background is white.

**Code**

```
$f00I $00fV$f00o$00ft$f00e$00fd

```

**Output**

# Answer
> 2 votes
# Python 2, 77 bytes

```
r='\033[91m'
b='\033[94m'
print r+'\033[47mI '+b+'V'+r+'o'+b+'t'+r+'e'+b+'d'

```

I don't know about other platforms, and it does not work online but on Windows 10 this works just fine with the command line, it looks like this:

I tried this:

```
e='\033[9
r=e+'1m'
b=e+'4m'
print r+'\033[47mI '+b+'V'+r+'o'+b+'t'+r+'e'+b+'d'

```

And this:

```
r='\033[91m'
b='\033[94m'
v,o,t,e,d='Voted'
print r+'\033[47mI '+b+v+r+o+b+t+r+e+b+d

```

But they did not actually help (but they are much cooler!)

# Answer
> 2 votes
# Ruby - 46 45 bytes

`puts"1I 4V1o4t1e4d".gsub(/\d/){"\e[47;3#$&m"}`

The digits are placeholders for colors. They are injected into escape sequences via '#$&' (interpolation of the last match).

# Answer
> 2 votes
# PHP, 132 bytes

```
imagefill($i=imagecreatetruecolor(62,13),0,0,~0);($s=imageString)($i,6,0,0,"I Vote",255<<16);$s($i,6,18,0,"V t d",255);imagepng($i);

```

Based on Kodos Johnson´s answer (prints image data to stdout)

create image with full alpha background, add `I Vote` in red, add `V t d` in blue, output image.

# Answer
> 2 votes
# SVG - 205 bytes

### (167 bytes bzip2, for comparison's sake)

Yes, I know this is old and been over for a while, but I finally had time to do what I said in my comment on the SVG + bzip2 example.

Here's just plain SVG, golfed down by hand as much as I can. UTF-8 is the default, which means this each character is one byte:

`<svg xmlns="http://www.w3.org/2000/svg"><rect fill="#fff" width="99" height="99"/><text fill="blue" y="99"><tspan fill="red">I</tspan> V<tspan fill="red">o</tspan>t<tspan fill="red">e</tspan>d</text></svg>`

Problem is, there is no default font or text size for SVG, so I had to just guess a reasonable number for other elements. The background white rectangle is 99x99 (and the text bottom at y=99) just because that's the largest 2 digit number, and every default font I've seen is at most 2 digits high.

And, while SVG is already an image format, here's a PNG from Wikimedia Commons:

# Answer
> 1 votes
# Ruby, 85 Bytes

UPDATE: Forgot the white background

```
require"colorize";puts ("I".red+"V".blue+"o".red+"t".blue+"e".red+"d".blue).on_white

```

Output:

# Answer
> 1 votes
# OCL 2, 96 bytes

```
ShowCanvas
setFillColor 255 0 0
DrawText 0 9 "I  o e"
setFillColor 0 0 255
DrawText 4 9 "V t  d"

```

I'm a bit late for this, but I think I did alright. I've tried optimizing it, but I literally can not find any way of making it shorter, despite it looking very optimizable.

# Answer
> 0 votes
# Decimal, ~~108~~ 88 bytes

Saved 20 bytes by reusing resources (manipulating stack instead of pushing ANSI colors repeatedly)

```
13027091051049109D13027091051052109D00D301I12032D301201D301V00D301o01D301t00D301e01D301d

```

Try it online! Be warned that the online version displays raw ANSI escape sequences and not the actual colors. Ungolfed and commented:

```
13027091051049109D     ; push STRING "ESC[31m" (idx 0)
13027091051052109D     ; push STRING "ESC[34m" (idx 1)
00D301I                ; set DSI to 0, print, print I
12032D3012             ; push CHAR ' ', print, pop
01D301V                ; set DSI to 1, print, print V
00D301o                ; set DSI to 0, print, print o
01D301t                ; set DSI to 1, print, print t
00D301e                ; set DSI to 0, print, print e
01D301d                ; set DSI to 1, print, print d

```

How it works:

* `ESC[31m` is the ANSI color code to set the foreground output color to red.
* `ESC[34m` is the ANSI color code to set the foreground output color to blue.
* Decimal automatically prints every non-`D`ecimal character in the source (`I`,`V`,`o`,`t`,`e`,`d`)

# Answer
> 0 votes
# SmileBASIC 3, 57 bytes

```
GCLS-1GPUTCHR.,.,"I  o e",#RED
GPUTCHR.,.,"  V t d",#BLUE

```

In recognition of the upcoming US midterm elections.

# Answer
> 0 votes
# Rust, 61 bytes

```
fn main(){print!("[47;31mI[34m V[31mo[34mt[31me[34md")}

```

Since the code above contains unprintable bytes, here's a reversible hexdump:

```
00000000: 666e 206d 6169 6e28 297b 7072 696e 7421  fn main(){print!
00000010: 2822 1b5b 3437 3b33 316d 491b 5b33 346d  (".[47;31mI.[34m
00000020: 2056 1b5b 3331 6d6f 1b5b 3334 6d74 1b5b   V.[31mo.[34mt.[
00000030: 3331 6d65 1b5b 3334 6d64 2229 7d         31me.[34md")}

```

# Answer
> 0 votes
# CodingLang, 136 bytes

```
(I )>b(color:red)@style(V)>b(color:blue)@style(o)>b(color:red)@style(t)>b(color:blue)@style(e)>b(color:red)@style(d)>b(color:blue)@style

```

Try it!(code needs to be pasted)

I'm not sure how classes and stuff work in this. If someone else knows how to use predefined classes repeatedly, it would save a lot of bytes.

Please do vote this year!

# Answer
> 0 votes
# SmallBasic, 244 bytes

```
s="IVoted"
For i=1 To 7
x=Text.GetSubText(s,i,1)
If Math.Remainder(i,2)=0 then
If i=2 then
TextWindow.Write(" ")
EndIf
TextWindow.ForegroundColor="Blue"
TextWindow.Write(x)
Else
TextWindow.ForegroundColor="Red"
TextWindow.Write(x)
EndIf
EndFor

```

This is also self explanatory. It changes console colors at even and odd character in the string, plus insert a space after first char.

I wish I could use `With` here....

# Answer
> 0 votes
# PostScript, 157 bytes

Code (compressed):

```
0 0 moveto/Courier 72 selectfont 1 0 0 setrgbcolor/i true def{pop 73 eq{30 0 rmoveto}if i{0 0 1}{1 0 0}ifelse setrgbcolor/i i not def}(IVoted) kshow showpage

```

Code (uncompressed, with comments):

```
0 0 moveto
/Courier 72 selectfont
1 0 0 setrgbcolor     % red
/i true def
{
    pop
    73 eq {           % 'I' ?
        30 0 rmoveto  % insert space
    } if
    i {
        0 0 1         % blue
    }{
        1 0 0         % red
    } ifelse
    setrgbcolor
    /i i not def      % toggle i
} (IVoted) kshow
showpage

```

Result:

# Answer
> 0 votes
# Julia, 50 bytes

```
print.("\e[47;$(34-3Int(c)%6)m"*c for c="I Voted")

```

(Don't) Try it online!

# Answer
> 0 votes
# 05AB1E, 32 bytes

```
"25I 6V5o6t5e6d"₁Ƶsç•7η/•2ô«'m«‡

```

Try it online!

```
"..."₁Ƶsç•7η/•2ô«'m«‡  # full program
"..."                  # literal...
                    ‡  # with each character of...
     ₁                 # 256...
                    ‡  # replaced by corresponding element in...
                       # (implicit) list of length of...
         •7η/•         # 473134...
               ô       # split into pieces of length...
              2        # literal...
        ç              # character with codepoint...
      Ƶs               # 155...
                       # (implicit) s with each element...
                «      # concatenated with...
                       # (implicit) corresponding element in...
         •7η/•         # 473134...
               ô       # split into pieces of length...
              2        # literal...
                       # (implicit) with each element...
                   «   # concatenated with...
                 'm    # literal
                       # implicit output

```

`«'m«` can also be `'m««` with no change in functionality: Try it online!

# Answer
> 0 votes
# QBasic, 76 bytes

```
SCREEN 7
FOR i=1TO 6
COLOR(i MOD 2)*3+1,15
?MID$("IVoted",i,1)SPC(1\i);
NEXT

```

### Explanation

Observing that the colors alternate between red and blue, we run a FOR loop for six iterations, one for each letter. On odd values of `i`, we want color 4 (red), and on even values we want color 1 (blue). The formula `(i MOD 2)*3+1` achieves this. We use color 15 (bright white) for the background.

We pull the correct letter out of the string `IVoted` using `MID$`. Now, we need to put a space after the `I`, which is to say we want to print an extra space on just the first iteration. Conveniently, `1\i` is 1 when `i` is 1 and 0 when `i` is greater than 1, so after the letter, we use `SPC` to print `1\i` spaces. A trailing `;` suppresses the newline, and we go on to the next iteration.

Running at Archive.org gives this output:

---
Tags: code-golf, string, graphical-output, color
---


title: Construct a polynomial with given roots

text:
# Question
Title: Construct a polynomial with given roots
The challenge is to write the shortest function/program to find a polynomial given the roots. The function or program should take valid input; that is, a list of integers representing the roots of the polynomial, and return valid output.

Output should return a sequence of numbers representing the polynomial. For example:

`2, 3` represents `2x^1 - 3x^0 = 0`

`1, 6, 1, 8, 0, 3, 3` represents `1x^6 + 6x^5 + 1x^4 + 8x^3 + 0x^2 + 3x^1 + 3x^0 = 0`

`-1 0 5, -3` represents `-1x^3 + 0x^2 + 5x^1 + -3x^0 = 0`

I hope you get the idea.

**Example Usage**

For an input of `1, 2`, the output should be `1, -3, 2`, which represents the equation `1x^2 + -3x^1 + 2x^0 = 0`, or `x^2 - 3x + 2 = 0`.

For an input of `1, -1, 0`, the output should be `1, 0, -1, 0`.

For the input, duplicate values should be removed and order does not matter. For example, the result with input `3, 3, 6` should be the same as the result with input `6, 3`.

Float arguments are optional.

As this is code golf, the shortest entry in *characters* wins. Good luck!

# Answer
# J, 8 bytes

A series of verbs:

```
|.p.1;~.

```

Call it like this:

```
   |.p.1;~. 1 2
1 _3 2

```

J has a built-in verb `p. (Roots)`. It converts between polynomials like `2 _3 1` (reverse order from the problem) and a multiplier/root pair like `(1; 1 2)`.

From right-to-left, `~.` takes the unique elements, `1;` pairs the list with 1, meaning we want the *smallest* integer polynomial, `p.` does the actual work, and `|.` reverses the resulting list.
> 10 votes

# Answer
## Python 2, 71

```
P=[1]
for r in set(input()):P=map(lambda a,b:a-r*b,P+[0],[0]+P)
print P

```

Iteratively updates the polynomial `P` to add one root at a time. Adding the root `r` multiplies the polynomial as `P*(x-r)`. This requires shifting the polynomial list `P` by one index to represent multiplication by `x`, the subtracting `r` times the original list. This is handled by shifting a copy of the list, padding with zeroes, and mapping the function `a,b -> a-r*b`.

To remove duplicate roots, the input is made into a `set`.

Using `reduce` turned out one char longer (72):

```
lambda R:reduce(lambda P,r:map(lambda a,b:a-r*b,P+[0],[0]+P),set(R),[1])

```

Three lambdas though!
> 6 votes

# Answer
## Haskell, 70

Basically a port of the `reduce` version of my Python solution.

```
import Data.List
foldr(\x p->zipWith(\a b->a-b*x)(p++[0])(0:p))[1].nub

```

I tried to shorten the lambda expression `\a b->a-b*x` by making it point-free, but best I have is `(+).(*(-x))` on switched inputs (thanks to @isaacg), which is the same length.

The lengthy import for `nub` is for the requirement to ignore duplicate roots. Without it, we'd have 49:

```
foldr(\x p->zipWith(\a b->a-b*x)(p++[0])(0:p))[1]

```
> 3 votes

# Answer
## Matlab, 56 bytes

Polynomial multiplication is convolution of their coefficients:

```
function y=f(R)
y=1;for r=unique(R);y=conv(y,[1 -r]);end

```

Floating-point roots are supported.

Example:

```
>> f([1 2])
ans =
     1    -3     2
>> f([1 2 1])
ans =
     1    -3     2
>> f([1 2.1 -3.2])
ans =
    1.0000    0.1000   -7.8200    6.7200

```
> 3 votes

# Answer
# Ruby 2.7+, 60 58 57 50 bytes

```
->i{p=*1;(i&i).map{|x|p<<z=0;p.map!{-x*z+z=_1}};p}

```

Requires ruby 2.7+ for numbered arguments to work. Based on xnor's python answer

Takes input as an array of roots, and returns an array of coefficients.

Thanks to @Martin Ender for -2 bytes!

Thanks to Lydxn for -1 byte

Thanks to JoKing for -7 bytes.
> 3 votes

# Answer
# Julia, 41 bytes

Note: this is assuming the list is what matters, not the input/output format.

```
s->foldl((i,j)->[0,i]j+[i,0],1,unique(s))

```
> 2 votes

# Answer
# Pyth, 17 bytes

```
u-V+G0*LH+0GS{Q]1

```

17 bytes. A reduce over the input set. `+G0` is essentially `*x`, and `*LH+0G` is essentially `*r`, and `-V` performs element by element subtraction to perform `*(x-r)`.

Demonstration.
> 2 votes

# Answer
# Jelly, 3 bytes

```
QÆṛ

```

Try it online!

Outputs them in order from the zero coefficient first. +1 byte to go the other way

It would just be a builtin (`Æṛ`) aside from the fact that duplicates shouldn't matter. Therefore we deduplicate the input first with `Q`, then use the builtin
> 2 votes

# Answer
# CJam, ~~24~~ 21 bytes

```
1al~_&{W*1$f*0\+.+}/`

```

Input format is a list in square brackets (e.g. `[1 2]`). Output format is the same. This is a full program. It might get slightly shorter if I package it as an anonymous function.

The approach is fairly straightforward: It starts out with `1` for the polynom, which is described by a coefficient array of `[1]`. It then multiplies it with `x - a` for each root `a`. This results in two arrays of coefficients:

* One from the multiplication with `-a`, which simply multiplies each previous coefficient by this value.
* One from the multiplication with `x`, which shifts the array of coefficients by 1, padding the open position with 0.

The two are then combined with a vector addition. I actually don't have to do anything for the second array, since CJam uses remaining array elements of the longer array unchanged if the other array is shorter, so padding the second array with a 0 is redundant.

Try it online

Explanation:

```
1a      Put starting coefficient array [1] on stack.
l~      Get and interpret input.
_&      Uniquify input array, using setwise and with itself.
{       Loop over roots given in input.
  W*      Negate value.
  1$      Get a copy of current coefficient array to top.
  f*      Multiply all values with root.
  0\+     Add a leading zero to align it for vector addition.
  .+      Vector add for the two coefficient array.
}/      End loop over roots.
`       Convert array to string for output.

```
> 1 votes

# Answer
# Javascript, 121 bytes

```
r=>{o=[...r,0].fill(0);for(i=2**r.length;i--;)e=r.length,a=r.reduce((a,q,j)=>a*(i&1<<j?q:(e--,-1)),1),o[e]+=a;return o;}

```

## Explantation

Similar to other answers, we imagine a polynomial of the form:

```
 (r_1 - x) * (r_2 - x) * ... * (r_n - x)

```

And we want to multiply it out to get the polynomial:

```
 a_0 * x^n + ... + a_n * x^0

```

This program does that by looping over every permutation of the input brackets. We can do this by counting in binary from 0 to 2^n. The i-th bit of that count tells us whether to multiply by r\_i, or by -x.

## Ungolfed:

```
function make_poly(roots) {
  o = [...roots, 0].fill(0);
  for (i = 0; i < 2 ** roots.length; i++) {
    a = 1;
    t_index = roots.length;
    for (j = 0; j < roots.length; j++) {
      if (i & (1 << j)) {
        a *= roots[j];
      } else {
        a *= -1;
        t_index--;
      }
    }
    o[t_index] += a;
  }
  return o;
}

```
> 1 votes

# Answer
# Husk, 13 bytes

```
FȯmΣ∂Ṫ*moe1_u

```

Try it online!

### Explanation

The idea is to generate the polynomials `(x-r0),…,(x-rN)` for the roots `r0,…,rN` and simply multiply them out:

```
F(mΣ∂Ṫ*)m(e1_)u  -- accepts a list of roots, example: [-1,1,-1]
              u  -- remove duplicates: [-1,1]
        m(   )   -- map the following (eg. on 1):
            _    --   negate: -1
          e1     --   create list together with 1: [1,-1]
F(     )         -- fold the following function (which does polynomial multiplication),
                 -- one step with [1,-1] and [1,1]:
     Ṫ*          --   compute outer product: [[1,1],[-1,-1]]
    ∂            --   diagonals: [[1],[1,-1],[-1]]
  mΣ             --   map sum: [1,0,1]

```
> 0 votes

---
Tags: code-golf, polynomials
---


title: Set the sum and product

text:
# Question
Title: Set the sum and product
Given two positive reals \\$a\\$ and \\$b\\$, output some positive reals \\$r\_i\\$, such that \\$\sum r\_i=a\\$ and \\$\prod\left(r\_i+1\right)=b\\$. You can assume that it's possible. You can also assume that your float type have infinite precision.

Test cases:

```
2,3 => 2
2,4 => 1,1 or 1/2,(sqrt(57)+9)/12,(9-sqrt(57))/12 or etc.
2,5 => 1/3,1/2,2/3,1/2 or etc.
2,8 => (undefined behavior)
2,2 => (undefined behavior)
e,2e => 1,e-1 or etc. (e is natural base, though any number>1 work)
3,e^3 => (undefined behavior) (It's possible to get as close as you want to e^3, but not reaching)

```

Shortest code wins.

# Notes

* Given the assumption with infinite precision, you can't solve arbitrary equation if your language doesn't have such functions(you can still use functions like `Solve` in Mathematica to solve such). In this case, some forms may have solution mathematically but you can't work it out, e.g. \\$p,p,p,...,p,q\\$ where \\$p\\$ and \\$q\\$ are reals. (At least software don't provide exact solution for `x*x*x*y=5,3*x+y=7`)

# Answer
> 15 votes
# Haskell, 67 bytes

```
a#b|h<-a/2,c<-sqrt$(1+h)^2-b,c>0=h+c:[h-c|h>c]|l<-(a/2)#sqrt b=l++l

```

Try it online!

Based on this solution of Delfad0r, who also saved 1 byte off this

We first try to find a two-element solution with \\$r\_1+r\_2=a\\$ and \\$(r\_1+1)(r\_2+1)=b\\$, which we do by solving a quadratic equation. If we get real solutions, we're done. (If one solution is zero, we remove it and output a singleton.)

If this quadratic isn't solvable in the reals, we replace \\$a \to a/2\\$ and \\$b \to \sqrt{b}\\$ and solve from there. If we find a solution to this, then duplicating the list (that is, repeating each element a second time) gives a solution to the original problem, since this doubles the sum and squares the product of numbers-plus-one. We recursively make these substitutions until we simplify \\$(a,b)\\$ to ones that give a two-element solution.

We show that this process always reaches a solution. For the problem to be solvable, we must have \\$b \< e^a\\$, which follows directly from \\$\sum r\_i=a\\$ and \\$\prod\left(r\_i+1\right)=b\\$ along with \\$e^{r\_i}\>r\_i+1\\$. Since \\$e^a\\$ is the increasing limit of \\$(1+a/N)^N\\$ as \\$N \to \infty\\$, the bound \\$b \< e^a\\$ implies that \\$b \< (1+a/N)^N\\$, or equivalently that \\$b^{1/N} \< 1+a/N\\$, for sufficiently large \\$N\\$. By choosing \\$N=2^n\\$ as a large power of \\$2\\$, doing \\$n-1\\$ steps of the substitution \\$a \to a/2\\$ and \\$b \to \sqrt{b}\\$ gives us \\$a' = 2a/N\\$ and \\$b' = b^{2/N}\\$, which we've shown satisfy \\$\sqrt{b'} \< 1 + a'/2\\$.

This is exactly what we need to have real solutions for \\$r\_1+r\_2=a\\$ and \\$(r\_1+1)(r\_2+1)=b\\$, which gives a quadratic with discriminant \\$(1+a/2)^2-b\\$. It solutions are $$r = a/2 \pm \sqrt{(1+a/2)^2-b}$$

# Answer
> 8 votes
# Haskell, <sup>~~102~~</sup> 95 bytes

```
a#b|m<-until(\m->(1+a/m)**m>=b)(+2)2=filter(>0)[a/m+sqrt((1+a/m)^2-b**(2/m))*(-1)**i|i<-[1..m]]

```

Try it online!

The relevant function is `(#)` which takes as input `a` and `b` as described in the statement.

# Answer
> 2 votes
# Jelly, ~~32~~ 31 bytes

```
ḷ‘ɼ_’;N};1Ær½ßH}¥/}x®$ÆiṪṪƊ?,ḟ0

```

Try it online!

A full program taking two arguments, `b` and `a` in that order. Implements @xnor’s algorithm, so be sure to upvote that one too! Uses recursion to find real roots to a quadratic equation of the form \\$x^2 - w x + (y - w - 1) = 0\\$ where \\$w = \frac{a}{2 ^ n}\\$ and \\$y = b ^ \frac{1}{2n} \\$ for some non-negative integer \\$n\\$.

## Explanation

```
ḷ‘ɼ                              | Increment the register, then revert to the original left argument (i.e. b)
   _                             | b - a
    ’                            | Subtract 1
     ;N}                         | Concatenate to -a
        ;1                       | Concatenate to 1
          Ær                     | Roots of polynomial with terms (b - a - 1, -a, 1)
                      ÆiṪṪƊ?     | Does the last root havecan imaginary component?
                ¥/}         ,    | - If yes, do the following using the original arguments to this link:
            ½ßH}                 |   - Call the current link recursively with the square root of the left argument and half the right argument
                   x®$           | - If not, repeat each term the number of times indicated by the register
                             ḟ0  | Filter out zeros

```

# Answer
> 2 votes
# Charcoal, 52 bytes

```
ＮθＮη≔¹ζＷ›ηＸ⊕∕θ⊗ζ⊗ζ≦⊕ζＦζＩΦＥ²⁺∕θ⊗ζ×∨λ±¹₂⁻Ｘ⊕∕θ⊗ζ²Ｘη∕¹ζκ

```

Try it online! Link is to verbose version of code. Explanation: Basically another port of @xnor's answer.

```
ＮθＮη≔¹ζ

```

Input \\$ a \\$ and \\$ b \\$ and start counting the number of repetitions of the output that we need.

```
Ｗ›ηＸ⊕∕θ⊗ζ⊗ζ≦⊕ζ

```

Keep incrementing (doubling also works of course, but it's not strictly necessary) the number of repetitions while \\$ b \> (1 + \frac a {2n}) ^ {2n} \\$. (This explains why \\$ b \< e^a \\$.)

```
Ｆζ

```

Repeat the output the appropriate number of times...

```
ＩΦＥ²⁺∕θ⊗ζ×∨λ±¹₂⁻Ｘ⊕∕θ⊗ζ²Ｘη∕¹ζκ

```

... output up to two non-zero solutions to the quadratic.

# Answer
> 0 votes
# JavaScript (ES10), 93 bytes

This is really just a port of @xnor's answer.

Expects `(a)(b)`.

```
a=>g=(b,r=1,x=(q=a/=2)+(d=(++q*q-b)**.5))=>x?Array(r).fill(a-d?[x,a-d]:x).flat():g(b**.5,r*2)

```

Try it online!

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


title: Shortest Konami Code

text:
# Question
Title: Shortest Konami Code
# The Problem

You must write a program that, when the Konami Code is typed in during runtime, prints the string "`+30 lives`" and sounds a noise of your choice from the computer's speaker.

### Definition

The "Konami Code" is defined as `UUDDLRLRBA` followed by pressing the enter key.

### The Rules

* You may choose to use the up arrow for `U`, down for `D`, left for `L`, and right for `R`, as long as your code is consistent with either arrows or letters.
* Your input may be accepted from a controller or a keyboard, but does not need to support both.
* Existing answers may continue to use `BABA` instead of `BA`, but may also shorten it if they wish to do so. Future answers should all use `BA` for consistency.
* Empty input doesn't need to be supported.

# Answer
# 05AB1E, 33 bytes (Fine on Empty Input)

```
Dg0Qiq}•ï“ë™µyê!•36BQi7ç“+30™‹“J,

```

Try it online!

# 05AB1E, ~~30~~ 26 bytes (Fails on Empty Input)

-4 thanks to Adnan

```
•ï“ë™µyê!•36BQi7ç,“+30™‹“,

```

Try it online!

```
•ï“ë™µyê!•36B                  # UUDDLRLRBABA in base-214, converted back to base-36.
             Qi                # If implicit input is equal to...
               7ç,             # Print 7 converted to a character to the console (bell sound)...
                  “+30™‹“, # Print +30 lives.

```

Disclaimer: Bell sound does not play on TryItOnline, maybe ask Dennis if one of his servers somewhere is pinging when you run it.
> 13 votes

# Answer
## JavaScript (ES6), ~~202~~ ~~200~~ 198 bytes

Tested only on Chrome and Firefox. Uses `UDLR` rather than the arrow keys. Please make sure that CapsLock is off.

```
(o=(A=new AudioContext()).createOscillator()).connect(A.destination);s='';document.onkeyup=e=>{(s+=e.key[0]).slice(-11)=='uuddlrlrbaE'&&setTimeout('o.stop()',500,console.log('+30 lives'),o.start())}
```

```
Please click inside this area to make sure it gets focus.
```
> 9 votes

# Answer
# Python 3,  ~~55~~  53 bytes

-1 byte thanks to isaacg (use bitwise not to replace `-10` with `~9`).
-1 byte thanks to CalculatorFeline (it is possible to use a literal `BEL` byte).

```
while'UUDDLRLRBA'!=input()[~9:]:1
print('+30 lives7')

```

where the `7` shown above is a literal byte `0x07` (an unprintable in a code block).

Once enter is pressed the `while` loop condition is checked. If the last `~9` = 10 characters (at most) do not match the Contra command code then the no-op `1` is executed (replacement of `pass` for brevity); if they *do* match then the while loop ends and the `print` statement is executed, which writes the required text along with an ASCII bell character ("alarm"), `0x07`, which produces a sound unless it has been explicitly disabled (or the terminal has no speaker!).
> 8 votes

# Answer
# Processing, ~~161~~ ~~157~~ 155 bytes

```
String k="";void keyTyped(){if(match(k+=key,"uuddlrlrba\\n$")!=null){print("+30 lives");new processing.sound.SoundFile(this,"a.mp3").play();}}void draw(){}

```

The audio file must be saved as `sketchName/data/a.mp3`. Note: I have only tested this program without the audio file because I am too lazy to download an `mp3` file (since only limited extensions are supported from `processing.sound.SoundFile`).

The `draw()` function is needed to be there in order for `keyTyped` to work.

The reason we are using `keyTyped` is because Processing does not have STDIN, it can only listen for keys being pressed via the sketch being run.

### Explanation

```
String k="";
void keyTyped(){
  if(match(k+=key,"uuddlrlrba\\n$")!=null){
    print("+30 lives");
    new processing.sound.SoundFile(this,"a.mp3").play();
  }
}
void draw(){
}

```

All of the user's keystrokes are stored as chars inside the String `k`. The `keyTyped` is an inbuilt function that is called whenever the user types a key. Simultaneously, we are checking if this String ends with the keystrokes. Then we print `+30 lives` and play the sound file. And the `draw` function is there to continuously update `keyTyped`. After the Konami code is entered, then nothing else will be outputted and no audio will be played.
> 5 votes

# Answer
## Jelly, ~~33~~ ~~30~~ ~~29~~ 27 bytes

```
ɠ⁻“UUDDLRLRBA”$¿ṛ7Ọ“¡}ʠƈ[ỵ»

```

Turns out, the append () is not needed, strings are automatically ~~joined together~~ both printed.

```
ɠ⁻“UUDDLRLRBABA”$¿ṛ7Ọṭ“¡}ʠƈ[ỵ»

```

---

**Uncompressed**

```
ɠ⁻“UUDDLRLRBABA”$¿ṛ7Ọṭ“+30 lives”

```

Try it online
If you remove everything after `¿`, you can mess with the input and see that it only returns when the input string is correct.

```
ɠ⁻“UUDDLRLRBABA”$¿ṛ7Ọṭ“+30 lives” - main link
ɠ                                 - takes a line of input
 ⁻“UUDDLRLRBABA”$                 - $ groups it into a monadic !="UUDDLRLRLRBABA"
                 ¿                - while (the inequality, which takes from the getline)
                  ṛ               - take the right argument (to ignore the input string)
                   7Ọ             - chr(7), the bell character
                     ṭ“+30 lives” - append that bell character to the output

```

Thanks @JonathanAllan for helping me figure out string compression :)
> 5 votes

# Answer
## \>\<\>, ~~132~~ ~~69~~ ~~64~~ 62 bytes ~~\*\>\<\>, 84 bytes~~

```
i:1+?\0[
:1+?!\i
BA"a~/"UUDDLRLR
{v!?l/!?=
7/"+30 lives"
o<;!?l

```

Try it here!

This relys on the bell chime (ascii `7`) for the noise at the end (not heard on the online interpreter).

Thanks to @TealPelican for saving another 15 bytes!

Saved two bytes checking for `BA` instead of `BABA`.
> 4 votes

# Answer
# C 119 -1 - 2 = 116 bytes

### Golfed

```
i;f(){char a[14];a[13]=0;while(strcmp(a,"UUDDLRLRBA"))for(i=0;i<12;a[i]=a[i+++1]);a[i]=getch();puts("+30 Lives\a");}

```

### Ungolfed

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

i;
f()
{
    char a[14];
    a[13]=0;
    while(strcmp(a,"UUDDLRLRBA"))
    {
        for(i=0;i<12;a[i]=a[i+++1]);
        a[i]=getch();
        puts(a); //This is to print every step in the runtime
    }
    puts("+30 Lives\a"); // '\a' is the acsii char that makes sound when passed to STDOUT
}

main()
{
    f();
}

```
> 3 votes

# Answer
# GNU sed, ~~32~~ 25 + 1 = ~~33~~ 26 bytes

+1 byte for `-n` flag.

```
/UUDDLRLRBA$/a+30 Lives\a

```

Try it online!

# Explanation

Every time enter is pressed (`$`), the program checks if the preceding 10 keystrokes were the code. If they were, the `a` command queues the text `+30 Lives` and the bell sound (`\a`) to be printed at the end of the current cycle (which, in this case, is immediately).
> 3 votes

# Answer
## Mathematica, 50 bytes

```
While[x=!=UUDDLRLRBA,x=Input[]];Beep[];"+30 lives"

```

Initially, `x` is just a symbol and is thus not identical (`=!=`) to the symbol `UUDDLRLRBA`, so `x=Input[]` is evaluated. This will open a dialog box with the cursor already in the input field, so the user can immediately start typing on the keyboard.

If `Enter` is pressed or `OK` is clicked without typing anything, then `InputField[]` will return `Null`, which is not identical to `UUDDLRLRBA`, so the loop continues and another dialog box will be opened.

If the user clicks `Cancel` or otherwise exits the dialog box, then `InputField` will return `$Canceled`, which is also not identical to `UUDDLRLRBA`, so the loop will continue.

The user can type in the dialog box to their heart's desire. When they hit `Enter`, their input is interpreted as a Wolfram language expression (possibly just boxes). If that expression is anything other than the symbol `UUDDLRLRBA`, the loop will continue.

"Must loop until the Konami code is entered" is a little vague, but I believe this satisfies it. Once the `While` loop is completed, `Beep[]``;"+30 lives"`.
> 3 votes

# Answer
# Stacked, 41 bytes

```
['+30 lives'BEL+out]prompt'UUDDLRLRBA'=if

```

Reads input from keyboard.

```
['+30 lives'BEL+out]prompt'UUDDLRLRBA'=if
[                  ]prompt'UUDDLRLRBA'=if  if the input is the desired string,
 '+30 lives'BEL+out                           output '+30 lives' and the BEL character.

```
> 3 votes

# Answer
# Petit Computer BASIC, 91 bytes

```
@L
WAIT 1S$=S$+CHR$(B)*!!B
B=BTRIG()IF B<1024GOTO@L
IF"xxxxxxxxxx"==S$THEN BEEP?"+30 lives

```

Finally a solution that actually uses controller input!

I used Petit Computer rather than the newer version (SmileBASIC) because it has access to the Start button, and `BTRIG()` is shorter than `BUTTON()`.

I've replaced the data string with `x`'s, it should contain characters with ascii codes 1,1,2,2,4,8,4,8,32,16

### Boring version, 46 bytes

```
INPUT S$IF"UUDDLRLRBA"==S$THEN BEEP?"+30 lives

```
> 3 votes

# Answer
## AutoHotkey, 63 bytes

```
Input,K,L10
if(K="UUDDLRLRBA"){
MsgBox,"+30 lives"
SoundBeep
}

```

After running this script, it will check if the next 10 keys are the Konami code and if it is, it will show a message box saying "+30 lives" and it *should* play a beep (I don't have speakers now to test).
> 3 votes

# Answer
# Vyxal, 21 bytes

```
«_sa}]∷«⇧=`+30 æ§\7`*

```

Based on @Makonede's 05AB1E answer.

Try it Online!

Explained:

```
«_sa}]∷«⇧=`+30 æ§\7`*
                    *    # Repeat...
          `+30 æ§\7`     # the string '+30 lives␇'... (escape code \7 is BEL)
                         # once if ...
         =               # the (implicit) input equals...
«_sa}]∷«                 # the compressed code...
        ⇧                # in uppercase...
                         # otherwise repeat zero times

```
> 3 votes

# Answer
## Powershell, ~~89~~ 86 Bytes

```
if((Read-Host)-eq"UUDDLRLRBABA"){"+30 Lives";[System.Media.SystemSounds]::Beep.Play()}

```

enter submits the string to the `Read-Host`, so it should.. work?
> 2 votes

# Answer
# Wonder, 50 bytes

```
ol"•";f\@[="UUDDLRLRBA"rl0?ol"+30 lives•"?f0];f0

```

Replace  with the character of code `\x07` (the BEL control char). Takes input through STDIN.
> 2 votes

# Answer
# C# (the boring version), 80 bytes

```
void n(){while(Console.ReadLine()!="UUDDLRLRBA"){}Console.Write("+30 Lives\a");}

```

# C# (The interesting one), 202 bytes

```
void n(){t();Console.Write("+30 Lives\a");}void t(){var k="UUDDLRLRBA";var s="";while(s!=k){s+=Console.ReadKey().Key.ToString();s=k.StartsWith(s)?s:"";}if(Console.ReadKey().Key!=ConsoleKey.Enter){t();}}

```

I **think** this works, sadly online testers do not support the existence of a console input, as such I will have to go on the tests I have done

Can most likely be golfed hugely - I'm not great at this! :)

Ungolfed:

```
void n()
{
    t();
    Console.WriteLine("+30 Lives\a");
}

void t()
{
    var k = "UUDDLRLRBA";
    var s = "";
    while(s != k)
    {
        s += Console.ReadKey().Key.ToString();
        s = k.StartsWith(s) ? s : "";
    }
    if(Console.ReadKey().Key != ConsoleKey.Enter)
    {
        t();
    }
}

```
> 2 votes

# Answer
## flex, 37 + 5 = 42 bytes

```
%%
UUDDLRLRBA puts("+30 lives\a");

```

The code itself is 37 bytes, compile it with the "-main" option which adds 5 bytes. Naturally, you have to compile the resulting C file with your favorite C compiler, but I don't think that step should count toward the byte count.

I could save a byte by using a literal BEL character instead of `\a`, but I'd rather be able to read my own code.
> 1 votes

# Answer
# C, ~~87~~ ~~85~~ 81 bytes

```
s[13];f(){for(;strcmp(s,"UUDDLRLRBA\n");fgets(s,12,stdin));puts("+30 Lives!\a");}

```
> 1 votes

# Answer
# shortC, 52 bytes

```
s[13];AO;Ms,"UUDDLRLRBA\n");Ys,12,N));J"+30 Lives!\a

```

Explanation:

```
s[13];                                                // declare array with 13 members
      A                                               // main function
       O;Ms,"UUDDLRLRBA\n");                          // for loop while input is not equal to the Konami Code
                            Ys,12,N));                // read 12 characters of input into array
                                      J"+30 Lives!\a  // print the string

```

Try it online!
> 1 votes

# Answer
# C, 114 bytes

```
#define X "UUDDLRLRBA"
main(i,j){for(i=j=0;!j;)(getchar()==X[i++])&&((j=1?!X[i]|puts("+30 lives\a"):0)|1)||(i=0);}

```
> 1 votes

# Answer
# 05AB1E, 22 bytes

```
.•›Gβ…Ýò•uQ7ç“+30™‹ÿ“×

```

Try it online!

```
.•...•uQ7ç“...“×  # trimmed program
          “...“   # push "+30 livesÿ"...
                  # (implicit) with ÿ replaced by...
         ç        # unicode character with codepoint...
        7         # literal...
               ×  # repeated...
       Q          # is...
                  # implicit input...
       Q          # equal to...
.•...•            # "uuddlrlrba"...
      u           # in uppercase...
               ×  # times
                  # implicit output

```
> 0 votes

# Answer
# Stax, 21 bytes

```
é>Δ┼3Σöîc9qz╔°→cz╣╖↑└

```

Run and debug it

## Explanation

```
`!j.o6F>"`=D"+30 lives"7+
`!j.o6F>"`=               input equals sequence?
           D              if so,
            "+30 lives"   push +30 lives
                       7+ add a bell to it

```
> 0 votes

---
Tags: code-golf, parsing, keyboard, audio
---


title: Floor of complex number

text:
# Question
Title: Floor of complex number
## Background

**Complex floor** is a domain extension of the mathematical floor function for complex numbers. This is used in some APL languages to implement floor , ceiling , residue `|`, GCD , and LCM  on complex numbers.

For the rest of this challenge, an *integer* refers to a Gaussian integer, i.e. a complex number whose real and imaginary parts are integers.

Eugene McDonnell defined seven requirements of a complex floor function (copied from the wiki page, with APL code fragments translated into plain math notation):

1. *Existence.* Every number has a floor.
2. *Uniqueness.* Every number has only one floor.
3. *Fractionality.* The magnitude of the difference of a number and its floor shall be less than one. This property must be satisfied to guarantee that remainders are less in magnitude than divisors. It may be called the fundamental property of the floor function.
4. *Integrity.* The floor of a number is an integer.
5. *Convexity.* If \\$g\\$ is the floor of the numbers \\$z\\$ and \\$w\\$, then it is also the floor of all numbers on the line segment between \\$z\\$ and \\$w\\$.
6. *Integer Translation.* For \\$c\\$ a complex integer, \\$c+ \lfloor z \rfloor = \lfloor c+z \rfloor\\$.
7. *Compatibility.* The complex floor function is compatible with the real floor function. Furthermore, its action on purely imaginary numbers is similar to the action of the real floor function on real numbers. In particular, \\$\operatorname{re}(\lfloor z \rfloor) ≤ \operatorname{re}(\lceil z \rceil)\\$ and \\$\operatorname{im}(\lfloor z \rfloor) ≤ \operatorname{im}(\lceil z \rceil)\\$. (Ceiling for complex numbers is defined as \\$\lceil z \rceil = -\lfloor -z \rfloor \\$.)

One shape that satisfies these conditions is a rectangle \\$\sqrt{1\over2}\\$ units high and \\$\sqrt2\\$ units wide, rotated 45 degrees, as in the following image.

One interesting consequence of *fractionality* is that the magnitude of the residue is always smaller than that of the divisor, and the Euclidean algorithm always terminates on arbitrary complex number inputs.

## Task

Define your own complex floor that satisfies the requirements listed above, and implement it. It is OK if you simply use McDonnell's function. If you use a different function, please include an explanation of how it satisfies the requirements.

Please note that simply flooring the two components is NOT a valid answer since it violates Fractionality: when \\$z = 3.9 + 2.9i\\$,

$$ \lfloor z \rfloor = 3 + 2i \\ z-\lfloor z \rfloor = 0.9 + 0.9i \\ |z-\lfloor z \rfloor| = |0.9 + 0.9i| = 0.9 \sqrt2 \> 1 $$

You may represent a complex number as a built-in complex number or a pair of real numbers. You don't need to care too much about boundary conditions, since floating-point imprecision will impact its correctness anyway.

It is known to be implemented in Dyalog APL, J, and NARS2000. You are not allowed to use floor/ceiling/residue/GCD/LCM functions with non-real complex arguments for these languages.

Standard rules apply. Shortest code in bytes wins.

# Answer
# **BQN**, 14 bytesSBCS

```
⌊+·(⍋×1<+´)1⊸|

```

Try it here.

```
⌊+·(⍋×1<+´)1⊸| # Tacit function which takes input as an array of 2 numbers
⌊              # floor
 +             # plus
   (      )    # the parenthesized train:
    ⍋          #   grade
     ×         #   times
      1<+´     #   comparison 1 less than the sum
  ·            #   applied monadically to
           1⊸| # the fractional part

```

Replicating the image in the challenge description.
> 10 votes

# Answer
# , 32 31 26 bytes

```
j.&<.+((1<:+)*0j1^<)&(1|])

```

Try it online!

-5 thanks to Razetime for pointing out I could take real and imag parts as left and right args.

Obligatory J answer.

For reference, per the link in the OP, Eugene McDonnell's algorithm is:

> The algorithm for the determination of g , the floor of a complex number z , may be explained informally as follows:
>
> 1. Let b be the point at the lower left corner of the unit square containing z . Let x and y be the fractional parts of the real and imaginary parts of z .
> 2. Then:
>
> * Let g = b if 1 \> (x + y) ,
> * Let g = (b + 1) if (1 ≤ x + y) and x ≥ y ,
> * Let g = (b + 0i1) if (1 ≤ x + y) and x \< y .

We take the real and imaginary parts as left and right args.

We note that the answer is:

```
b + (0 or 1 or i)

```

depending on the case.

* `j.&<.+` Floors both parts and converts back to complex `j.&<./`, then adds everything to the right `+`. This gives us the `b +` part.
* `(...)&(1|])` Get fractional parts of real/imag pieces, and feed those as left and right args to everything in parens. This gives us x and y.
* `(1<:+)` Is x + y greater than or equal to 1? Returns 0 or 1. Multiply that by...
* `0j1^<` \\$i\\$ raised to "is x \< y?" -- gives us \\$i\\$ if true, 1 otherwise.
> 8 votes

# Answer
# MMIX, 56 bytes (14 instrs)

```
00000000: e0043ff0 17020300 17030301 06000002  ṭ¥?ṅç£¤¡ç¤¤¢©¡¡£
00000010: 06010103 04ff0001 01ffff04 6104ff00  ©¢¢¤¥”¡¢¢””¥a¥”¡
00000020: 01ff0001 7005ff04 26040405 04000305  ¢”¡¢p¦”¥&¥¥¦¥¡¤¦
00000030: 04010204 f8020000                    ¥¢£¥ẏ£¡¡

```

```
cfloor  SETH $4,#3FF0           // readj = 1.
        FINT $2,ROUND_DOWN,$0   // xf = floor(x)
        FINT $3,ROUND_DOWN,$1   // yf = floor(y)
        FSUB $0,$0,$2           // x -.= xf
        FSUB $1,$1,$3           // y -.= yf
        FADD $255,$0,$1
        FCMP $255,$255,$4
        CSN  $4,$255,0          // if(x +. y <. 1) readj = 0
        FCMP $255,$0,$1
        ZSN  $5,$255,$4         // imadj = x <. y? readj : 0
        SUBU $4,$4,$5           // readj -= imadj
        FADD $0,$3,$5
        FADD $1,$2,$4           // add in adjustments and swap (MMIX shuffle)
        POP  2,0

```
> 7 votes

# Answer
# , 55 bytes

```
function(x,y=x%%1)(x+(sum(y)>1)*c(z<-diff(y)<0,!z))%/%1

```

Try it online!

Straightforward implementation of McDonnell's function.

---

# , 71 bytes

```
function(x,y=x%%1,w=c(z<-diff(y)<0,!z))(x+(sum(y/(1+2^.5*!w))>1)*w)%/%1

```

Try it online!

16 bytes longer, but minimizes the amount of rounding-up required\*, while still satsifying the convexity requirement, for all complex numbers.

McDonnell's function unsatisfyingly rounds-up either the `r`eal or `i`maginary part of a complex number whenever their fractional parts sum to greater than `1`, even though the fractionality requirement (condition #3) would still be satisfied by rounding down until `r^2+i^2>1`.
The convexity requirement (condition #5) prevents us from rounding down for all `r^2+i^2<=1`, but we can minimize the amount of rounding-up needed by using a 'quarter-octagon' shape, instead of a triangle, for fractional `r` and `i` between `0` and `1`.
The rounding 'domains' are shown in different colours here:

* I think.
> 7 votes

# Answer
# Jelly, 12 bytes

```
Ḟɓ_Ụ’×S>1ƊƲ+

```

Try it online!

-3 bytes by using the `grade up` idea from frasiyav's BQN answer. Go upvote that too.
-1 byte by fixing a bug pointed out by tsh
-1 byte thanks to caird coinheringaahing

This is just a golf of Eugene McDonnell's algorithm. Using the same concept for golfing the 3-way conditional as Jonah's J answer.
> 6 votes

# Answer
# JavaScript (Node.js), ~~57~~ 74 bytes

```
(a,b,x=a%1,y=b%1,s=Math.abs)=>1>x+y?[a-s(x),b-s(y)]:[a-x+(x>=y),b-y+(x<y)]

```

Try it online!

## Explanation

Uses a similar algorithm as @Jonah's answer.

> The algorithm for the determination of g , the floor of a complex number z , may be explained informally as follows
>
> Let b be the point at the lower left corner of the unit square containing z . Let x and y be the fractional parts of the real and imaginary parts of z . Then: Let g = b if 1 \> (x + y) , Let g = (b + 1) if (1 ≤ x + y) and x ≥ y , Let g = (b + 0i1) if (1 ≤ x + y) and x \< y .

Needed to add 17 bytes in order to sort out a bug.
> 6 votes

# Answer
# Python 3.8 (pre-release), 58 bytes

```
lambda a,b:[a//1+(w:=a%1>=b%1)*(q:=1<=a%1+b%1),b//1+(q>w)]

```

Try it online!

thanks to @ovs for -12
> 3 votes

# Answer
# Ruby, ~~55~~ 47 bytes

```
->a,b{(a-a%=1)+1i*(b-b%=1)+(a+b<1?0:a>b ?1:1i)}

```

Try it online!

Thanks Eric Duminil for the idea of using 2 arguments.
> 3 votes

# Answer
# Charcoal, ~~26~~ 23 bytes

```
ＮθＮηＩＥ²⌊⊘⁺⊕⁺θη×⌊⁻θη∨±ι¹

```

Try it online! Explanation: Calculates \\$ \lfloor a + bi \rfloor \\$ using the following formula which is the complex conjugate of the rectangular tiling suggested in the question, and therefore trivially still satisfies all the requirements:

$$ \lfloor a + bi \rfloor = \left \lfloor \frac { 1 + a + b + \lfloor a - b \rfloor } 2 \right \rfloor + \left \lfloor \frac { 1 + a + b - \lfloor a - b \rfloor } 2 \right \rfloor i $$

In particular when \\$ b = 0 \\$, \\$ \lfloor a + bi \rfloor = \left \lfloor \frac { 1 + a - \lfloor a \rfloor + 2 \lfloor a \rfloor } 2 \right \rfloor + \left \lfloor \frac { 1 + a - \lfloor a \rfloor } 2 \right \rfloor i = \lfloor a \rfloor \\$ and when \\$ a = 0 \\$, \\$ \lfloor a + bi \rfloor = \lceil b \rceil i \\$.
> 2 votes

# Answer
# Excel, 61 bytes

```
=LET(a,INT(A1:B1),a+(SUM(A1:B1-a)>=1)*({1,0}+(A1<B1)*{-1,1}))

```

Uses McDonnell's definition. Real coefficient in A1; imaginary in B1. Output is an array of real and imaginary coefficients.

## Without LET, also 61 bytes

```
=INT(A1:B1)+(SUM(A1:B1-INT(A1:B1))>=1)*({1,0}+(A1<B1)*{-1,1})

```

## Alternate, 35 bytes

```
=INT((1+A3+B3+INT(A3-B3)*{1,-1})/2)

```

This is a port of Neil's answer
> 2 votes

---
Tags: code-golf, math, complex-numbers, open-ended-function, apl
---


title: Backspace-and-retype a list of words

text:
# Question
Title: Backspace-and-retype a list of words
Here’s how to **backspace-and-retype** from one string to another:

1. Start from the first string.
2. Remove characters at the end until the result is a **prefix** of the second string. (This may take 0 steps.)
3. Add characters at the end until the result equals the second string. (This may take 0 steps, too.)

For example, the path from `fooabc` to `fooxyz` looks like:

```
fooabc
fooab
fooa
foo
foox
fooxy
fooxyz

```

## Task

Given a list of words, write a program that **backspace-and-retypes** its way from the empty string, to all of the words in the list in succession, back to the empty string. Output all intermediate strings.

For example, given the input list `["abc", "abd", "aefg", "h"]`, the output should be:

```
a
ab
abc
ab
abd
ab
a
ae
aef
aefg
aef
ae
a

h

```

## Rules

You may return or print a list of strings, or a single string with some delimiter of choice. You may **optionally** include the initial and final empty strings. The input is guaranteed to contain at least one word, and each word is guaranteed to contain only lowercase ASCII letters (`a``z`). *Edit:* consecutive strings in the input are guaranteed not to equal each other.

This is ; shortest code in bytes wins.

A reference implementation in Python 3: Try it online!

# Answer
> 5 votes
# Pyth, ~~25~~ 23 bytes

```
V+QkWxNk
=Pk)
M>._Nl~kN

```

Try it online.

# Answer
> 9 votes
## Perl, 43 bytes

42 bytes of code + `-n` flags.

```
chop$@,say$@while!s/^$@//;s/./say$@.=$&/ge

```

To run it:

```
perl -nE 'chop$@,say$@while!s/^$@//;s/./say$@.=$&/ge' <<< "abc
abd
aefg
h"

```

# Answer
> 5 votes
# Java 8, 144 bytes

This one is similar to the reference implementation but combines the two `while` loops. It's a lambda expression accepting a `String[]` parameter.

```
a->{String c="";int l=0,i;for(String w:a)while((i=w.indexOf(c))!=0||!c.equals(w))System.out.println(c=i!=0?c.substring(0,--l):c+w.charAt(l++));}

```

## Ungolfed

```
a -> {
    String c = "";
    int l = 0, i;
    for (String w : a)
        while ((i = w.indexOf(c)) != 0 || !c.equals(w))
            System.out.println(c = i != 0 ? c.substring(0, --l) : c + w.charAt(l++));
}

```

## Acknowledgments

* -38 bytes thanks to CAD97's lambda suggestion

# Answer
> 4 votes
# Mathematica, 149 bytes

```
Reap[Fold[n=NestWhile;s=StringMatchQ;r=StringReplace;n[k=#2;Sow@r[k,#~~a_~~___:>#<>a]&,n[Sow@r[#,a___~~_:>a]&,#,!s[k,#~~___]&],k!=#&]&,"",#]][[2,1]]&

```

# Answer
> 3 votes
## Retina, 39 bytes

Byte count assumes ISO 8859-1 encoding.

```
M!&r`.+
%)`\G.
¶$`$&
+`((.*).¶)\2¶\1
$1

```

Try it online!

Input and output are linefeed-separated lists. Output does include the leading and trailing empty string.

# Answer
> 3 votes
# Jelly, ~~31~~ ~~29~~ 26 bytes

```
⁷œ|;\
ÇṚðfḢṭḟ;ḟ@ḊðÇ}
⁷;ç2\

```

Try it online!

### How it works

```
⁷;ç2\           Main link. Argument: A (string array)

⁷;              Prepend a linefeed to A.
                This is cheaper than prepending an empty string.
  ç2\           Reduce all overlapping pairs by the second helper link.

ÇṚðfḢṭḟ;ḟ@ḊðÇ}  Second helper link. Arguments: s, t (strings)

Ç               Call the first helper link with argument s.
 Ṛ              Reverse the results.
            Ç}  Call the first helper link with argument t.
  ð        ð    Combine everything in between into a dyadic chain, and call it
                with the results to both sides as arguments.
                Let's call the arguments S and T.
   f            Filter; get the common strings of S and T.
    Ḣ           Head; select the first one.
      ḟ         Filterfalse; get the strings in S that do not appear in T.
     ṭ          Tack; append the left result to the right one.
        ḟ@      Filterfalse swap; get the strings in T that do not appear in S.
       ;        Concatenate the results to both sides.
          Ḋ     Dequeue; remove the first string.

⁷œ|;\           First helper link. Argument: s (string)

⁷œ|             Linefeed multiset union; prepend a linefeed to s unless it already
                has a linefeed in it (the first string does).
   ;\           Concatenate cumulative reduce; generate all prefixes of the result.

```

# Answer
> 2 votes
## Haskell, ~~102 93 91~~ 90 bytes

```
(?)=take.length
a!x@(b:c)|a==b=b!c|a/=a?b=a:init a!x|d<-'?':a=a:d?b!x
_!x=x
(""!).(++[""])

```

The last line is an anonymous function, which takes and returns a list of strings. Try it online!

## Explanation

My solution is recursive. First, `?` is a helper infix function: `a?b` gives the first `length a` characters of `b`, or the whole of `b` if `a` is longer. Next I define an infix function `!`. The idea is that `a!x`, where `a` is a string and `x` a list of strings, produces the path from `a` to the first string in `x` and recurses to the tail of `x`. On the final line I define an anonymous function that appends the empty string, then applies `!` to the empty string and the input.

Explanation of `!`:

```
a!x@(b:c)        -- a!x, where x has head b and tail c:
  |a==b          -- If a equals b,
    =b!c         -- recurse to x.
  |a/=a?b        -- If a is not a prefix of b,
    =a:          -- produce a and
    init a!x     -- continue with one shorter prefix of a.
  |              -- Otherwise a is a proper prefix of b.
   d<-'?':a      -- Let d be a with an extra dummy element,
    =a:          -- produce a and
    d?b!x        -- continue with one longer prefix of b.
_!x=x            -- If x is empty, return x.

```

# Answer
> 2 votes
# Python 2, ~~118~~ ~~107~~ ~~103~~ ~~97~~ ~~93~~ 92 bytes

```
s=''
for i in input()+[s]:
 while i.find(s):s=s[:-1];print s
 while i>s:s+=i[len(s)];print s

```

Input is given as `['abc', 'abcdef', 'abcfed']`, or as \[`"abc", "abcdef", "abcfed"]`.

Revision 1: -11 bytes. Credit goes to @xnor for his post on Python golfing tips, and to @Lynn for finding the tip for me, and to me for being smart. Two changes were made: Instead of `not s.startswith(i)`, I used `s.find(i)`, and instead of `i!=s` I used `i>s`.

Revision 2: -4 bytes. Credit goes to me realizing I made a really dumb mistake. Instead of using single-tab and double-tab indentation, I used single-space and single-tab indentation.

Revision 3: -6 bytes. Credit goes to @mbomb007 for suggesting to put the whiles on a single line. I also fixed a bug by changing `s.find(i)` to `i.find(s)`.

Revision 4: -4 bytes. Credit goes to @xnor for realizing that I didn't need to store the input in a variable.

Revision 5: -1 byte. Credit goes to me for realizing that `['']` is the same thing as `[s]` when adding it to the input.

# Answer
> 2 votes
# GNU M4, 228 or 232 bytes¹

(¹ depending on whether to end the file with `dnl\n` or not—I'm still new to both golfing and M4)

```
define(E,`ifelse(index($2,$1),0,`T($1,$2)',`$1
E(substr($1,0,decr(len($1))),$2)')')define(T,`ifelse($1,$2,,`$1
T(substr($2,0,incr(len($1))),$2)')')define(K,`ifelse($2,,$1,`E($1,$2)K(shift($@))')')define(M,`K(substr($1,0,1),$@)')

```

Additionally, 3 bytes could be saved by replacing the second argument for `substr` from `0` to the empty string, but that would produce a lot of warnings on stderr.

Ungolfed:

```
define(erase_til_prefix, `dnl arguments: src dst; prints src and chops one char off of it until src == dst, at which point it calls type_til_complete instead
ifelse(dnl
index($2, $1), 0, `type_til_complete($1, $2)',dnl
`$1
erase_til_prefix(substr($1, 0, decr(len($1))), $2)dnl
')')dnl
define(type_til_complete, `dnl arguments: src dst; types src, does not type `dst' itself
ifelse(dnl
$1, $2, ,dnl
`$1
type_til_complete(substr($2, 0, incr(len($1))), $2)'dnl
)')dnl
define(main_, `dnl
ifelse(dnl
$2, , $1, dnl no arguments left
`erase_til_prefix($1, $2)main_(shift($@))'dnl
)')dnl
define(main, `main_(substr($1, 0, 1), $@)')dnl

```

Usage:

```
$ m4 <<<"include(\`backspace-golfed.m4')M(abc, abd, aefg, abcdefg, h)"

```

# Answer
> 1 votes
## Batch, ~~296~~ 291 bytes

```
@echo off
set f=
set t=%1
:t
set f=%f%%t:~,1%
set t=%t:~1%
echo(%f%
if not "%t%"=="" goto t
shift
set t=%1
set s=%f%
set p=
:h
if %s:~,1%==%t:~,1% set p=%p%%t:~,1%&set s=%s:~1%&set t=%t:~1%&goto h
:b
set f=%f:~,-1%
echo(%f%
if not "%f%"=="%p%" goto b
if not "%1"=="" goto t

```

Computing the common prefix was cumbersome.

# Answer
> 1 votes
# PHP, ~~116~~ ~~111~~ ~~101~~ 83 bytes

Note: uses Windows-1252 encoding.

```
for(;$w=$argv[++$i];)for(;$c!=$w;)echo$c=($c^$c^$w)==$c?$c.ÿ&$w:substr($c,0,-1),~õ;

```

Run like this:

```
php -r 'for(;$w=$argv[++$i];)for(;$c!=$w;)echo$c=($c^$c^$w)==$c?$c.ÿ&$w:substr($c,0,-1),~õ;' -- abc abd aefg h 2>/dev/null
> a
> ab
> abc
> ab
> abd
> ab
> a
> ae
> aef
> aefg
> aef
> ae
> a
>
> h

```

# Explanation

```
for(                       # Outer loop.
  ;
  $w=$argv[++$i];          # Loops over the input words.
)
  for(                     # Second inner loop.
    ;
    $c!=$w;                # Loop until the word was output.
  )
    echo $c=
      ($c^$c^$w)==$c?      # Check if last output string is a substring
                           # match with the next word to output.
        $c.ÿ&$w:           # ... If yes, suffix the string with the next
                           # char of the word, and output the result.
        substr($c,0,-1),   # ... If not, remove a char and output.
      ~õ;                  # Output newline.

```

# Tweaks

* Saved 5 bytes by using `trim($c^$w,"\0")` to check for substring match instead of `$c&&strpos($w,$c)!==0`.
* Saved 2 bytes by using `~ÿ` to yield a string with a NUL byte instead of `"\0"`
* Saved 8 bytes by using `$c=$c.ÿ&$w` to suffix `$c` with the next char of `$w`
* Saved a massive 18 bytes by combining the logic of the 2 inner loops in a single loop
* Fixed a bug with a testcase from the comments, no change in byte count

# Answer
> 1 votes
# Pip, ~~33~~ 30 bytes

```
FsgAExTyQsYPyQs@<#y?y.s@#y;@<y

```

Try it online!

### Explanation

```
                                g is list of cmdline args; x & y are "" (implicit)
Fs                              For each s in
  gAEx                          g with an empty string appended:
      TyQs                       Do this till y equals s:
              s@<                 Get the prefix of s
                 #y               having the same length as y
            yQ                    and check if it equals y
                   ?              If so (y is a prefix of s), calculate:
                    y.             y, concatenated with
                      s@           the character in s at index
                        #y         len(y)
                          ;       If not, calculate:
                           @<y     y without its last character
          YP                      Print that quantity and yank it back into y

```

# Answer
> 0 votes
# PHP, 153 bytes

awfully long :(

```
for($s=$argv[$k=1];$t=$argv[++$k];){for(;$s>""&&strstr($t,$s)!=$t;$s=substr($s,0,-1))echo"$s
";for($i=strlen($s);$s<$t;$s.=$t[$i++])echo"$s
";echo"$s
";}

```

Run with `php -nr '<ode>' <text1> <text2> ...`.

# Answer
> 0 votes
# JavaScript (ES6), 135 bytes

Interesting challenge! Usage: `g(["abc", "abd", "aefg", "h"])`. I couldn't seem to save any bytes by writing this as one function, so it's two. Newlines not included in byte count.

```
f=a=>console.log(([,...z]=[x,y]=a)[0])||
y?f(a=(x==y.slice(0,-1))?z:([y.match(x)
?x+y[x.length]:x.slice(0,-1),...z])):1;
g=a=>f(['',...a])

```

I'm sure this can be reduced a lot more. Will add ungolfed version later.

# Answer
> 0 votes
# Javascript, 98 bytes

```
a=>{c="",l=0;for(w of a)while((i=w.indexOf(c))!=0||c!=w)alert(c=i!=0?c.substring(0,--l):c+w[l++])}

```

Port of Jakob's Java answer

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


title: Where should I put my mirror?

text:
# Question
Title: Where should I put my mirror?
This is a mirror: `|`. I just found out that you can stick a mirror in the middle of a string if the string can be mirrored on itself! For example, the string `abccba`. If you cut it in half the two halves are mirror images of each other:

```
abc  <-->  cba

```

So, we can stick a mirror in the middle of the string, and our new string is `abc|cba`. Sometimes, only part of the string can be mirrored on itself. For example, the string "mirror". The two r's are mirrored, but the rest of the string isn't. That's OK, we'll just remove the parts of the string that don't mirror each other, and we get the following string:

```
r|r

```

Some strings could be mirrored in multiple places. For example, "Hello World, xyzzyx". I like having a lot of text reflected in my mirror, so you need to find the best place to put my mirror. In this case, you should output the longer mirrored string and just like our last example, remove everything else. This string becomes:

```
xyz|zyx

```

Some strings *look* like they can be mirrored, but actually can not. If a string cannot be mirrored anywhere, you should output nothing.

# The challenge:

Given a string containing only printable-ascii, find the best place to put my mirror. In other words,

> Find the largest even-length palindromic substring, then output it with a pipe character '|' in the middle of it.

The input will be 1-50 characters long.

You can assume that the input will not contain mirrors `|` or newlines. Beyond that, all printable-ascii characters are fair game. If the longest mirrored substring is tied between two substrings, you can choose which one to output. For example, for the string "abba ollo", you must output "ab|ba" or "ol|lo", but it doesn't matter which one you output. Strings are case-sensitive, e.g. "ABba" should *not* output "AB|ba", it should output the empty string.

# Sample IO:

```
"Hello World"     --> "l|l"
"Programming Puzzles and Code-Golf"     --> Either "m|m" or "z|z"
"abcba"           --> ""
"Hulluh"          --> "ul|lu"
"abcdefggfedcba"  --> "abcdefg|gfedcba"
"abcdefggfabc"    --> "fg|gf"
"AbbA"            --> "Ab|bA"
"This input is a lot like the last one, but with more characters that don't change the output. AbbA" --> "Ab|bA"

```

As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!

# Answer
# Pyth - ~~19~~ ~~17~~ ~~15~~ 13 bytes

*Thanks to @FryAmTheEggman for saving me two bytes.*

~~ARRGH the special case for no answer.~~ Solved that!

```
e_I#jL\|cL2.:

```

Test Suite.

```
e                Last element in list, this works out to longest one
  _I             Invariance under reverse, this detect palindrome
   #             Filter
   jL            Map join
    \|           By "|"
    cL2          Map chop in two pieces
     .:Q)        Substrings. Implicit Q). ) makes it do all substrings.

```
> 9 votes

# Answer
# 05AB1E, ~~19~~ ~~17~~ 14 bytes

Code:

```
Œévy2ä'|ý©ÂQi®

```

Explanation:

```
Œ                # Get all substrings of the input
 é               # Sort by length (shortest first)
  vy             # For each element...
    2ä           # Split into two pieces
      '|ý        # Join by "|"
         ©       # Copy this into the register
          Â      # Bifurcate, pushing a and reversed a
           Q     # Check if it's a palindrome
            i®   # If so, push that string again
                 # Implicit, the top element is outputted

```

Uses the **CP-1252** encoding. Try it online!.
> 8 votes

# Answer
# Python 2, ~~102~~ 97 bytes

```
def f(s):h=len(s)/2;r=s[:h]+'|'+s[h:];return s and max(r*(r==r[::-1]),f(s[1:]),f(s[:-1]),key=len)

```

Rather slow and inefficient... Verify the smaller test cases on Ideone.
> 5 votes

# Answer
# JavaScript, ~~100~~ 99 bytes

```
s=>eval('for(O=i=0;s[i++];O=O[j+j]?O:o)for(o="|",j=0;(S=s[i-1-j])&&S==s[i+j++];o=S+o+S);O[1]?O:""')

```

**or**

```
s=>eval('for(O="",i=0;s[i++];O=O[j+j]||j<2?O:o)for(o="|",j=0;(S=s[i-1-j])&&S==s[i+j++];o=S+o+S);O')

```
> 4 votes

# Answer
# Lua, 133 bytes

```
s=...for i=#s,1,-1 do for j=1,#s-i do m=j+i/2-i%2/2t=s:sub(j,m).."|"..s:sub(m+1,i+j)if t==t.reverse(t)then print(t)return end end end

```

Verify all testcases on Ideone.com.
> 3 votes

# Answer
## Retina, 66 bytes

Byte count assumes ISO 8859-1 encoding.

```
M!&`(.)+(?<-1>\1)+(?(1)¶)
O$#`.+
$.&
A-2`
^(.)+?(?=(?<-1>.)+$)
$&|

```

Try it online! (The first line enables testing of several linefeed-separated test cases at once.)

Hmmm, much longer than I would like...
> 2 votes

# Answer
# JavaScript (ES6), 91

```
s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r

```

*Less golfed*

```
f=s=>
  [...s].map(
    (d,i) => {
    for(a='|', j=0; d=s[i-j], d&&d==s[i-~j]; r = r[j++ +j]? r : a)
      a = d+a+d
    }, r=''
  ) && r

```

**Test**

```
F=
s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r

;[["Hello World", "l|l"]
,["Programming Puzzles and Code-Golf", "m|m"]
,["abcba", ""]
,["Hulluh", "ul|lu"]
,["abcdefggfedcba", "abcdefg|gfedcba"]
,["abcdefggfabc", "fg|gf"]
,["AbbA", "Ab|bA"]
,["This input is a lot like the last one, but with more characters that don't change the output. AbbA", "Ab|bA"]]
.forEach(t=>{
  var i=t[0],k=t[1],r=F(i)
  console.log(k==r?'OK ':'KO ',i+' -> '+r,k!=r?'(check '+k+')':'')
})
```
> 2 votes

# Answer
## Perl 5, ~~105~~ ~~100~~ 98 + 1 = ~~106~~ ~~101~~ 99 bytes

```
/(?=((.)(?1)?\2)(?{[push@_,$1})(?!))/;($_)=sort{length$b<=>length$a}@_;substr($_,length>>1,0)='|'if$_

```

I just wanted to give recursive regexes a go. Needs the `-p` option. Edit: Saved (crossed out 4) 7 bytes thanks to @msh210. (The missing byte is due to a saving that was superseded by @msh210's latest saving.)
> 2 votes

# Answer
## Python 2, 91 bytes

```
f=lambda s,p='':s and max((''<p<=s<p+'\x7f')*(p[::-1]+'|'+p),f(s[1:]),f(s[1:],s[0]+p),key=len)

```

Replace `\x7f` with the actual character DEL, which is ASCII 127 (credit to Dennis).

This follows a similar strategy to Dennis's answer of using `max` and recursively branching to find the longest palindrome interval. But, instead, it finds the left half, checking that the corresponding mirrored right half comes right after it with a self-made startswith.

The function guesses whether the first character is in the mirrored left half. If not, it just drops it and recurses on the remainder. If it is, it's added to to the stack `p` of reversed characters. If the string ever starts with the stack, the mirror string is generated and considered as a possible longest mirror. To avoid `|` as an output, only non-empty stacks are considered.
> 2 votes

# Answer
# TSQL ~~227~~ 223 bytes

I hardcoded the length to max 99 bytes, this saved bytes but made it slower. It still have a decent performance though.

**Golfed:**

```
DECLARE @t varchar(99)='AbccbA'

,@z char(99)='',@a INT=0,@ INT=0WHILE @a<LEN(@t)SELECT
@z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE
Thai_bin,x+'|'+REVERSE(x),@z),@=IIF(@=50,1,@+1),@a+=IIF(@=1,1,0)FROM(SELECT
SUBSTRING(@t,@a,@)x)x PRINT @z

```

**Ungolfed:**

```
DECLARE @t varchar(99)='AbccbA'

,@z char(99)='',
@a INT=0,
@ INT=0
WHILE @a<LEN(@t)
  SELECT
    @z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE Thai_bin,x+'|'
       +REVERSE(x),@z),
    @=IIF(@=99,1,@+1),
    @a+=IIF(@=1,1,0)
  FROM
    (SELECT SUBSTRING(@t,@a,@)x)x

PRINT @z

```

**Fiddle**
> 1 votes

# Answer
# Haskell, ~~126~~ 111 bytes

```
(!)=drop
f s|n<-length s=last$"":[a++'|':b|k<-[1..n],t<-map(!s)[1..n-k],let[a,b]=take k<$>[t,k!t],a==reverse b]

```
> 1 votes

# Answer
# Husk, 12 bytes

```
►S=↔ΘmoJ'|½Q

```

Try it online!

-1 from Leo.
> 1 votes

# Answer
## Python 2, 149 bytes

```
R,L,s=range,len,input()
t=max([s[i:j/2+i/2]for i in R(L(s))for j in R(L(s)+1)if s[i:j]==s[i:j][::-1]and(j-i)%2<1],key=L)
print t+'|'*(L(t)>0)+t[::-1]

```

Try it online

This program finds the first half of the largest palindromic substring of even length, and prints that string, followed by a `|`, followed by that string reversed. If there is no suitable string, `t` will be the empty string, and `'|'*(L(t)>0)` will evaluate to the empty string.
> 0 votes

# Answer
# Java 8, ~~294~~ ~~283~~ 232 bytes

```
s->{int l=s.length(),i=0,j,z,y=0;String a,b="";for(;i<l;i++)for(j=0;j<=l-i;)if((a=s.substring(i,i+j++)).equals(new StringBuffer(a).reverse()+"")&(z=a.length())%2<1&z>y){y=z;b=a;}return y>0?b.substring(0,y/=2)+"|"+b.substring(y):"";}

```

**Explanation:**

Try it here.

```
s->{                               // Method with String as both parameter and return-type
  int l=s.length(),                //  Length of the input-String
      i=0,j,                       //  Index-integers
      z,y=0;                       //  Temp-integers
  String a,b="";                   //  Temp-Strings
  for(;i<l;i++)                    //  Loop (1) from 0 to `l` (exclusive)
    for(j=0;j<=l-i;                //   Inner loop (2) from 0 to `l-i` (inclusive)
      if((a=s.substring(i,i+j++))  //    Set the current substring to `a`
          .equals(new StringBuffer(a).reverse()+"")
                                   //    If `a` is a palindrome
         &(z=a.length())%2<1       //    And the length of `a` is even
         &z>y){                    //    And the length of `a` is larger than `y`
        y=z;                       //     Change `y` to `z`
        b=a;}                      //     Change `b` to `a`
                                   //   End of inner loop (2) (implicit / single-line body)
                                   //  End of loop (1) (implicit / single-line body)
  return y>0?                      //  If the result-length is not 0:
    b.substring(0,y/=2)+"|"+b.substring(y)
                                   //   Return the result
   :                               //  Else:
    "";                            //   Return an empty String
}                                  // End of method

```
> 0 votes

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