title: Draw the national flag of France

text:
# Question
Title: Draw the national flag of France
There have been many other flag challenges posted but not one for the national flag of France. This week seems like an appropriate time.

Produce this flag in the fewest bytes possible:

* The image must be in a ratio of 3:2, with size at least 78 pixels wide and 52 pixels tall.
* Each stripe takes up one third of the width.
* The stripe colors from left to right are RGB: `(0, 85, 164)`, `(255, 255, 255)`, `(239, 65, 53)`.
* The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed.
* Alternatively, output a block of text at least 78 characters wide made of non-whitespace characters that depicts the flag, using ANSI color codes to color it. (Use standard blue, white, and red.)
* Built-in flag images/libraries are not allowed.

The shortest code in bytes wins.

# Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 64140; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 42156; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 38 votes
# CJam, ~~23~~ 22 bytes

```
00000000: 27 9b 22 5c 22 25 1f 22 66 7b 69 27 6d 32 37 2a  '."\"%."f{i'm27*
00000010: 7d 4e 5d 32 36 2a                                }N]26*

```

The above is a hexdump that can be reversed with `xxd -r`.

At the cost of two extra bytes – for a total of **24 bytes** – we can use background colors instead, making the output a bit prettier.

```
00000000: 27 9b 22 2c 2f 29 00 22 66 7b 69 27 6d 53 32 36  '.",/)."f{i'mS26
00000010: 2a 7d 57 4e 74 32 36 2a                          *}WNt26*

```

### How it works

In both programs, we use the ANSI escape sequence `\x9bXYm` – where `X` is `3` for foreground color and `4` for background color, and `Y` specifies the color to use – to switch between the three colors of the flag.

```
'<CSI>       Push the '\x9b' character (Control Sequence Introducer).
"\"%<US>"    Push the string of the ISO 8859-1 characters with code
             points 34, 37, and 31.
f{           For each character in the string, push the CSI and that
             character; then:
  i            Cast the character to integer.
  'm27*        Push 27 m's. The first completes the control sequence,
               the remaining 26 will be printed.
}
N]           Wrap the generated array and "\n" in an array.
26*          Repeat it 26 times.

```

The other program is similar.

### Output

# Answer
> 77 votes
# Pure Bash (on OSX), 84

The default OSX terminal supports full colour emojis. Not sure if this counts as text or graphical output.

```
printf -vs %26s
for i in {1..26}
do echo ${s// /}${s// /⚪}${s// /}
done

```

### Output looks like:

---

Alternatively:

# Bash with OSX utilities, 56

```
yes `dc -e3do26^d1-dn2/*p|tr 201 ⚪`|sed 26q

```

The `dc` expression:

* calculates `3^26-1` and prints it in ternary `22222222222222222222222222`
* divides this by 2, then multiplies by `3^26`. Output in ternary this is `1111111111111111111111111100000000000000000000000000`

`tr` then translates the 210 characters to ⚪. `yes` outputs this line indefinitely. `sed 26q` halts output at 26 lines.

# Answer
> 54 votes
# Desmos, ~~30~~ 12 bytes

```
3x>10
3x<-10

```

Try it online.

I'm not entirely sure if this is valid, please let me know if there are any issues.

# Answer
> 51 votes
## Python 2, 47 bytes

```
s="[3%smF";print(s%4*26+s%7*26+s%1*26+"\n")*30

```

Contains unprintables - here's a hexdump (reversible with `xxd -r`):

```
00000000: 733d 221b 5b33 2573 3b31 6d46 223b 7072  s=".[3%s;1mF";pr
00000010: 696e 7428 7325 342a 3236 2b73 2537 2a32  int(s%4*26+s%7*2
00000020: 362b 7325 312a 3236 2b22 5c6e 2229 2a33  6+s%1*26+"\n")*3
00000030: 30                                       0

```

Uses ANSI escape codes to print colored characters to STDOUT - I chose "F" for France. No online link because ideone doesn't support ANSI escape codes in output.

Thanks to Dennis and xnor for some great tips.

Screenshot from xterm:

# Answer
> 43 votes
# HTML / SVG, 76 bytes ~~87 88 121 122 149~~

*Saved 27 bytes thanks to @insertusernamehere*

*Saves 9 bytes thanks to @Joey*

*Saved 1 bytes thanks to @sanchies*

*Saves 1 bytes thanks to @Neil*

```
<svg><path fill=#0055a4 d=m0,0h26v52H0 /><path fill=#ef4135 d=M52,0h26v52H52

```

Using lots of HTML syntax abuse, this can get pretty short.

---

Screenshot of output:

---

Or try it (make sure your browser supports SVG):

```
<svg><path fill=#0055a4 d=m0,0h26v52H0 /><path fill=#ef4135 d=M52,0h26v52H52
```

# Answer
> 29 votes
# Brainfuck$, 153 bytes

```
+++++++++++++[->>>++>+++++++>++++>>>>++++++++>+++<<<<<<<<<<]>>>+>>#->$#>$#+++++++>$--->+++++[<]<<+++++[->+++++>++++++<<]>+#>($#([-]>[.>]<[<])>>>>+++<<<<)

```

Outputs the image with ANSI color codes. I chose a height of 30 like Mego.

The reference implementation from 2009 linked on the esolangs page has gone missing. You can run it using this interpreter made by me, which supports everything from the esolangs page.

```
window.addEventListener("load",function(){document.querySelector("#r").addEventListener("click",function(){var  c=document.querySelector("#c").value,u=document.querySelector("#i").value,d=Array(30000).fill(0),p=0,i=0,q=0,s=[],o=document.querySelector("#o");o.value="";eval(c.replace(/[^]/g,function(e,i){return{"+":"d[p]=(-~d[p]+256)%256;","-":"d[p]=(~-d[p]+256)%256;",">":"p++;","<":"p--;",",":"d[p]=q-u.length?u[q++].charCodeAt()%256:0;",".":"o.value+=String.fromCharCode(d[p]);","[":"while(d[p]){","]":"}","#":"s.push(d[p]);","$":"d[p]=s.pop();",";":"d[p]=(parseInt(prompt())%256+256)%256;",":":"o.value+=d[p].toString();","(":"for(var i"+i+"=d[p];i"+i+">0;i"+i+"--){",")":"}","@":"o.value+=('D '+d.slice(0,20)+'\\nS '+s+'\\nIP '+i+' DP '+p);"}[e]||"";}));});});
```

```
<label for=c>Code:</label><br/><textarea style="width:100%;height:15em;white-space:pre" id=c>+++++++++++++[->>>++>+++++++>++++>>>>++++++++>+++<<<<<<<<<<]>>>+>>#->$#>$#+++++++>$--->+++++[<]<< init sequence to cells 3 to 10
+++++[->+++++>++++++<<] set cells 1~2 to 25 & 30
>+ set cell 1 to 26
# push 26 to stack
> go to cell 2
( do 30 times
    $# get 26 to this cell from stack
    ( do 26 times
        [-]>[.>]<[<] print sequence
    )
    >>>>+++<<<< change color to white
    $# get 26 to this cell from stack
    ( do 26 times
        [-]>[.>]<[<] print sequence
    )
    >>>>------<<<< change color to red
    $# get 26 to this cell from stack
    ( do 26 times
        [-]>[.>]<[<] print sequence
    )
    >>>>+++<<<< change color to blue
    ++++++++++. print newline
)</textarea><br/><button id=r>Run</button><br/><label for=i>Input:</label><br/><textarea id=i style="width:100%"></textarea><br/><label for=o>Output:</label><br/><textarea readonly id=o style="width:100%;height:15em;white-space:pre"></textarea>
```

# Brainfuck, 258 bytes

This is basically the same thing, but just in plain old Brainfuck.

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

```

Or, if you prefer this one in **oOo CODE** (984 bytes):

```
one day ThERe WIlL Be PEaCE iN ThIS wORlD
OnE DaY ThERe WiLl Be peaCe iN ThIS wOrld
one day theRe WIlL be pEaCE iN ThIS wORlD
OnE DaY theRe WIlL Be PEaCe in ThIS wORlD
OnE day ThERe WIlL Be PEaCe in ThIS wORlD
OnE day ThERe WIlL Be PEaCE iN ThIS wOrld
OnE DaY ThErE wilL bE PeaCe IN this woRlD
one day There will Be pEacE in ThiS woRld
one Day TheRe will Be PEaCE iN ThIS wOrLd
onE dAY thEre WilL Be PEaCE iN ThIs World
OnE DaY ThERe WIlL bE pEace in ThIS wORlD
OnE DaY thErE Will Be PeAce in this WoRLd
one dAY thErE wilL bE PeaCE in tHIs world
one day theRe WIlL Be PeAce iN tHIS wORlD
OnE DaY ThErE wIll be PEaCE iN ThIS wORlD
one dAY thERe WiLl be peace In THis worLD
onE dAy thErE WilL Be peACe in this world
one Day TheRe wIll Be pEace In thIs WORlD
OnE DaY ThERe WiLl Be peaCE iN ThIS wORlD
OnE day tHEre WIlL bE peace in tHiS World
oNE daY tHere WiLL be PEace IN this world
one day ThERe WIlL bE peaCe IN thIS wORlD
OnE DaY ThERe WIlL Be PEaCE iN THis WoRld
oNE daY thERe wiLL

```

# Answer
> 25 votes
# LaTeX, 139 bytes

Thanks to @WChargin for saving 21 bytes.

```
\documentclass{proc}\input color\begin{document}\def\z#1!{{\color[rgb]{#1}\rule{4cm}{8cm}}}\z0,.33,.64!\z1,1,1!\z.94,.25,.21!\end{document}

```

This prints the following 12cm\*8cm image on an A4 page:

*Note that "Page 1" is also printed at the bottom of the page*

# Answer
> 24 votes
## Bash + ImageMagick, ~~60~~ ~~77~~ 73 bytes

```
convert -sample 78x52\! - a<<<"P3 3 1 255 0 85 164 255 255 255 239 65 53"

```

(ugh, +17 chars due to color requirements I didn't notice earlier...)

Outputs to the file `a`, in netpbm format:

```
llama@llama:~$ convert -sample 78x52\! - a<<<"P3 3 1 255 0 85 164 255 255 255 239 65 53"
llama@llama:~$ file a
a: Netpbm image data, size = 78 x 52, rawbits, pixmap

```

Can also output in PNG, if you change the filename to `a.png` (+4 chars).

Output:

# Answer
> 24 votes
# Pyth, 27 bytes

```
 .w*52[smmdGc3CM"\0U¤ÿÿÿïA5

```

There are some unprintable chars, so here's a hexdump:

```
00000000   2E 77 2A 35  32 5B 73 6D  6D 64 47 63  33 43 4D 22  .w*52[smmdGc3CM"
00000010   5C 30 55 A4  FF FF FF EF  41 35                     \0U.....A5

```

This creates a file `o.png`, which is exactly 78 pixels wide and 52 pixels tall:

### Explanation:

```
.w*52[smmdGc3CM"........
               "........  a string containing the bytes
                          0, 85, 164, 255, 255, 255, 239, 65, 53
             CM           convert them to integers
           c3             split into 3 lists
      smmdG               duplicate each list 26 times
     [                    put them into a list
  *52                     and duplicate it 52 times
.w                        save it as an image o.png

```

# Answer
> 22 votes
# HTML (quirks mode), 68 bytes

This uses quirks mode to render the flag.

The HTML is **VERY** invalid, but works on a stock Android 4.4.2 browser and on Firefox 42.0 (on Windows 7 x64).

```
<table width=78 height=52><td bgcolor=0055a4><td><td bgcolor=ef4135>
```

The flag is rendered with the right size and the standard red and blue colors. All webpages start with a standard white background.

---

---

As an alternative:

A **perfectly valid** HTML5 version (141 bytes):

```
<!DOCTYPE html><title>x</title><table style=width:78px;height:52px><tr><td style=background:#0055a4><td><td style=background:#ef4135></table>
```

Check it's validity on: https://html5.validator.nu/

Print-screen of the result:

# Answer
> 20 votes
## ffmpeg, ~~110~~ ~~113~~ ~~116~~ ~~117~~ ~~119~~ ~~108~~ 100 bytes

Display, using ffplay, 100 bytes:

```
ffplay -f lavfi color=#0055a4:49x98[r];color=white:49x98[w];color=#ef4135:49x98[b];[r][w][b]hstack=3

```

Saved to file, using ffmpeg, 108 bytes:

```
ffmpeg -lavfi color=#0055a4:49x98[r];color=white:49x98[w];color=#ef4135:49x98[b];[r][w][b]hstack=3 -t 1 .png

```

The current version of the command will abort with an error BUT will output a single image ".png", same as shown below.

# Answer
> 17 votes
# CSS, 127 ~~128~~ ~~144~~ bytes

```
body:before,body:after{content:'';float:left;width:33%;height:100%;background:#0055a4}body:after{float:right;background:#ef4135}

```

No need for another tag, works solely with the `body`-element.

**Edits**

* *Saved* **16 bytes** by removing `display:block;` and some `;`.
* *Saved* **1 byte**, removed the trailing `}`.

# Answer
> 16 votes
# JavaScript, 140 ~~143~~ ~~147~~ ~~151~~ ~~153~~ bytes

```
   with(document)with(body.appendChild(createElement`canvas`).getContext`2d`)for(i=2;i--;fillRect(i*52,0,26,52))fillStyle=i?"#ef4135":"#0055a4"
```

---

**Edits**

* *Saved* **2 bytes** by replacing `2*i*26` with `i*52`. Thanks to Cᴏɴᴏʀ O'Bʀɪᴇɴ.
* *Saved* **4 bytes** by refactoring the `for`-loop. Thanks to ETHproductions.
* *Saved* **2 bytes** by using the `with`-statement. Thanks to Dendrobium.
* *Saved* **2 bytes** by turning increment into decrement. Thanks to Shaun H.
* *Saved* **3 bytes** by replacing `fillStyle=["#0055a4","#ef4135"][i]` with `i?"#ef4135":"#0055a4"`.

# Answer
> 16 votes
# TI-Basic, ~~52~~ ~~44~~ 42 bytes

```
GridOff
AxesOff
11
Shade(-Ans,Ans,Xmin,Xmin/3
Shade(-Ans,Ans,Xmax/3,Xmax,1,1,Ans

```

(assumes a default \[-10,10,1\] by \[-10,10,1\] graph area)

Would be 4 bytes shorter without the first 2 lines, but by default would have axes and would not look as nice.

Looks like this:

If the shading is invalid for the challenge, let me know!

Without the first 2 lines, it looks like this:

# Answer
> 12 votes
## R, 59 bytes

```
frame();rect(0:2/3,0,1:3/3,1,,,c("#0055a4",0,"#ef4135"),NA)

```

Output is displayed:

One can also do 49 bytes with

```
barplot(rep(1,3),,0,col=c("#0055a4",0,"#ef4135"))

```

if you do not mind the axes and borders:

# Answer
> 12 votes
# Mathematica, ~~63~~ ~~94~~ 103 bytes

When I first saw this challenge, I thought *Sweet! Mathematica would be perfect for this!* until I noticed that built-ins were banned :'(

But wait! I can use bar graphs!

```
r=RGBColor;BarChart[{1,1,1},ChartStyle->{r@"#0055a4",White,r@"#ef4135"},BarSpacing->0,AspectRatio->2/3]

```

(Thanks to Martin Büttner for shaving off 5 bytes but adding 16)

Looks like this:

If you add `,Axes->None` it looks like this:

If you don't care about the border, you can use this: (95 bytes)

```
r=RGBColor;BarChart[{1,1},ChartStyle->{r@"#0055a4",r@"#ef4135"},BarSpacing->1,AspectRatio->2/3,Axes->None]

```

Looks like this:

Without axes:

# Answer
> 11 votes
## Blitz 2D/3D, ~~154~~ 108 bytes

This produces exactly the same thing as the example given in the question (except for the anti-aliasing at the edges where colors meet).

```
Graphics 800,533
ClsColor 255,255,255
Cls
Color 0,35,149
Rect 0,0,267,533
Color 237,41,57
Rect 533,0,267,533

```

Output is displayed and it looks like this:

# Answer
> 11 votes
# Javascript (ES6) 117 bytes

Draws it in the console

```
for(i=c=s=[];i<156;c[i++]=`color:${[,'blue','#fff'][i%3]||(s+=`
`,'red')}`)s+='%c'+'+'.repeat(26);console.log(s,...c)
```

# Answer
> 11 votes
# pb, 68 bytes

```
cw[Y!52]{cccw[X!26]{b[77]>}ccccw[X!52]{b[77]>}cw[X!78]{b[77]>}<[X]v}

```

Wow, a challenge that pb is actually kinda good for! Those are few and far between.

When I was writing the spec for pb, I included coloured output mostly as a joke. The language was named after a "paintbrush", why would it *not* do colour? Other than example programs, this is the second time I've ever used it. It is implemented with ANSI codes as the question requires.

I used 'M' as the character to output with because it's fairly dense.

**Output:**

I resized that screenshot vertically to be two thirds of its height because letters aren't square. The output is 78 by 52, but the original screenshot looks really wrong.

**With comments and indentation and junk:**

```
c               # Increase output colour by 1
                # 0 (White) -> 1 (Red)
                # Loop ends with output colour == 1, this is cheaper than
                # setting it back to white every time.

w[Y!52]{        # While the brush's Y coordinate is not 52:
    ccc           # Increase output colour by 3
                    # 1 (Red) -> 4 (Blue)

    w[X!26]{      # While the brush's X coordinate is not 26:
        b[77]       # Write 'M' at the brush's coordinates
        >           # Increase X coordinate by 1
    }

    cccc          # Increase output colour by 4
                    # 4 (Blue) -> 8 mod 8 = 0 (White)

    w[X!52]{      # While the brush's X coordinate is not 52:
        b[77]       # (same as before)
        >
    }

    c             # Increase output colour by 1
                    # 0 (White) -> 1 (Red)

    w[X!78]{      # While the brush's X coordinate is not 78:
        b[77]       # (same as before)
        >
    }

    <[X]          # Set X back to 0
    v             # Increase Y by 1
}

```

# Answer
> 10 votes
# MATLAB, 82 79 78 bytes

```
x=[0 1 1 0];y(3:4)=2;fill(x,y,[0 85 164]/255,x+1,y,'w',x+2,y,[239 65 53]/255)

```

Output looks like:

# Answer
> 10 votes
# C, 115 bytes

```
#define c"[48;2;%d;%d;%dm%9c"
d=255;main(a){while(a++<9)printf(c c c c,0,85,164,0,d,d,d,0,239,65,53,0,0,0,0,10);}

```

Contains unprintables:

```
00000000: 2364 6566 696e 6520 6322 1b5b 3438 3b32  #define c".[48;2
00000010: 3b25 643b 2564 3b25 646d 2539 6322 0a64  ;%d;%d;%dm%9c".d
00000020: 3d32 3535 3b6d 6169 6e28 6129 7b77 6869  =255;main(a){whi
00000030: 6c65 2861 2b2b 3c39 2970 7269 6e74 6628  le(a++<9)printf(
00000040: 6320 6320 6320 632c 302c 3835 2c31 3634  c c c c,0,85,164
00000050: 2c30 2c64 2c64 2c64 2c30 2c32 3339 2c36  ,0,d,d,d,0,239,6
00000060: 352c 3533 2c30 2c30 2c30 2c30 2c31 3029  5,53,0,0,0,0,10)
00000070: 3b7d 0a                                  ;}.

```

For this program to work, a couple of things need to be true:

* The terminal supports the `ESC [48;2;<r>;<g>;<b>m` "truecolor" escape sequence.
* The terminal is not xterm, becase xterm's implementation of the above will produce slightly wrong colors.
* The terminal completely ignores NUL characters.

It also looks nicer if your terminal's background is black.

To change to height of the flag, pass command line arguments to the program. For every argument passed, the flag becomes one line shorter. *It's not a bug, it's a feature!*

Output:

# Answer
> 9 votes
## CSS, 102 ~~110~~ ~~111~~ ~~114~~ bytes

```
*{background:linear-gradient(90deg,#0055a4 33%,#fff 33%,#fff 66%,#ef4135 66%) 0 0/78px 52px no-repeat
```

# Answer
> 9 votes
## Visual Basic+Excel, 618 137 bytes

Just curious to see how this can be golfed.

**EDIT:** Curiosity sated, thanks to @Neil and @JimmyJazzx, 618 bytes dropped right down to 137 bytes

```
Sub a(): Columns("A:C").ColumnWidth = 26: Range("A1:A13").Interior.Color = RGB(0, 85, 164): Range("C1:C13").Interior.Color = RGB(239, 65, 53): End Sub

```

# Answer
> 8 votes
# iKe, 43 bytes

```
,(0 0;"|"\"#0055A4|#FFF|#EF4135";52#,&3#26)

```

This is an example of a "raw tuple" iKe program- it's just a description of an origin (`0 0`), a palette (`3 7#"#0055A4#FFFFFF#EF4135"`) and a bitmap (`+52#'&3#26`). You need to wrap a description like this in a function or use references to views if you want to animate it.

The palette is a very simple way of creating a series of CSS colors, hex equivalents of the spec.

```
  3 7#"#0055A4#FFFFFF#EF4135"
("#0055A4"
 "#FFFFFF"
 "#EF4135")

```

If the color requirements were less stringent we could use one of iKe's built-in palettes and save a considerable number of characters:

```
windows@7 0 4

```

Try it in your browser.

## Edit:

Saved one byte by using a short `#FFF` CSS color for the white stripe:

```
,(0 0;3 7#"#0055A4#FFFFFF#EF4135";+52#'&3#26)
,(0 0;"|"\"#0055A4|#FFF|#EF4135";+52#'&3#26)

```

If anyone else is interested in playing with iKe, there's a manual on the github repo. here's another problem I solved using iKe.

## Edit 2:

Saved one byte with a simpler way to construct the bitmap:

```
+52#'&3#26
52#,&3#26

```

My question in the OP hasn't been answered, but for the record if more flexible color requirements are permitted, this program would be 30 bytes by using the Windows 3.1 palette:

```
,(0 0;windows@7 0 4;52#,&3#26)

```

Since this problem was posted, iKe has gained a feature which automatically centers textures drawn without a position, which could save another 3 bytes, but this would be against the rules:

```
,(;windows@7 0 4;52#,&3#26)

```

# Answer
> 8 votes
# Dyalog APL (~~47~~ 44)

```
⎕SM←↑1 21 41{(''⍴⍨2/20)1⍺,⍵,⍨4↑0}¨2*8 11 10

```

Result:

# Answer
> 7 votes
# ShaderToy (GLSL), 147 bytes

```
void mainImage(out vec4 o,vec2 i){float x=i.x/iResolution.x*3.0;vec3 w=vec3(255,255,255);o=vec4((x<1.0?vec3(0,85,164):x<2.0?w:vec3(239,65,53))/w,1);}

```

See it here

Not particularly exciting. I'm sure there are ways to golf it more; I'll take a crack when I get home.

# Answer
> 7 votes
# Octave, ~~77~~ 76 bytes

```
s(98,49)=0;imshow(cat(3,[s w=s+255 w-18],[s+35 w s+41],[s+149 w s+57])/255);

```

Displays the image:

# Answer
> 7 votes
# Processing, 100 Bytes

```
size(78,52);background(255);noStroke();fill(#0055A4);rect(0,0,26,52);fill(#EF4135);rect(52,0,26,52);

```

Displays this:

(The naive solution is shorter than my first one.)

# Answer
> 7 votes
# PHP, 70 bytes

```
0000000: 424d 0000 0000 0000 0000 2300 0000 0c00  BM........#.....
0000010: 0000 2001 c000 0100 0800 a455 00ff ffff  .. ........U....
0000020: 3541 ef3c 3f66 6f72 283b 3665 343e 2469  5A.<?for(;6e4>$i
0000030: 3b29 6563 686f 2063 6872 2824 692b 2b2f  ;)echo chr($i++/
0000040: 3936 2533 293b                           96%3);

```

*The above is a hexdump which may be reversed with `xxd -r`. Alternatively, it may also be generated with the following PHP script:*

```
<?=hex2bin('424d0000000000000000230000000c0000002001c00001000800a45500ffffff3541ef3c3f666f72283b3665343e24693b296563686f206368722824692b2b2f39362533293b');

```

I assume default settings, as they are without an .ini (you may disable your local .ini with the `-n` option). Produces a .bmp image (288 x 192), which should be piped to a file. This is as large as I can make it without affecting the byte count.

---

**Sample Usage**

```
$ xxd -r in.hex > france.php
$ php -n france.php > out.bmp
$ out.bmp

```

---

**Output**

# Answer
> 7 votes
# Ruby, ~~56~~ ~~47~~ 45 bytes

ASCII

```
$><<"\e[34z\e[37z\e[31z\n".gsub(?z,?m*27)*52

```

# Answer
> 7 votes
# Googly Blockly, 45 blocks

Produces

Try it here

# Answer
> 7 votes
## ZX Spectrum BASIC, 10 bytes

(including the final end-of-line)

This does not fulfil the minimum flag size requirement, but I like this version, because it is so nice and compact. Please take it as a non-competing entry.

The hexadecimal dump is: F5 22 10 01 8A 10 02 8A 22 0D

Explanation:

PRINT is a keyword and takes one byte, 0xF5, its graphical representation includes the spaces around. The ZX Spectrum BASIC has one-byte colour codes, introduced by the 0x10 code for the foreground - 01 is for blue, 02 for red. 0x8A is a pseudographical character "▌", the left part of which is displayed in either blue or red.

The colours are of course from the standard ZX Spectrum palette - please adjust your PAL TV if the RGB values are not displayed quite correctly.

Despite the seemingly text mode of the program, the output is fully (bitmapped) graphical, as can be seen by looking into the VideoRAM. Thus there is no need to comply with the ANSI codes requirement, which the ZX does not support anyway (it has superior INK and PAPER commands).

# Answer
> 6 votes
## Powershell, ~~173 bytes~~, ~~170 bytes,~~ ~~155 bytes~~, 97 bytes!

~~```
$i=26;$y=0;function w($c){for($x=0;$x -le $i; $x++){write-host -noNewLine "F" -ForegroundColor $c}}for($x=0;$x -le $i; $x++){w("blue");w("white");w("red");write-host '';}

```~~ ~~```
sal q write-host;$i=26;$y=0;function w($c){for($x=0;$x -le $i; $x++){q -noNewLine F -ForegroundColor $c}}for($x=0;$x -le $i; $x++){w("blue");w("white");w("red");q '';}

```~~

(Thanks to Cole Johnson for saving me 15 bytes):

~~sal q write-host;$i=26;function w($c){for($x=0;$x -le $i; $x++){q -noNewLine F -ForegroundColor $c}}for($x=0;$x-le$i;$x++){w("blue");w("white");w("red");q}~~

(Thanks Steve for saving me 58 bytes!!!)

```
sal q write-host;function w($c){1..26|%{q -noNewLine F -Foreground $c}}1..26|%{w(9);w(7);w(12);q}

```

Output:

My first code golf, so I hope I didn't do something wrong.

# Answer
> 5 votes
## Unix Shell, 57 bytes.

```
for i in {a..z}
do printf ␛[4%-28s 4m 7m 1m
echo ␛[m
done

```

The escapes are in the script literally. On most color terminals you can change 47 to 107 to get a brighter white, but that's not ANSI standard. The script ends up being 61 bytes then. The 28 rather than 26 is because the color code 'steals' two characters from the field width.

Obligatory xxd dump:

```
0000000: 666f 7220 6920 696e 207b 612e 2e7a 7d0a  for i in {a..z}.
0000010: 646f 2070 7269 6e74 6620 1b5b 3425 2d32  do printf .[4%-2
0000020: 3873 2034 6d20 376d 2031 6d0a 6563 686f  8s 4m 7m 1m.echo
0000030: 201b 5b6d 0a64 6f6e 65                    .[m.done

```

On a terminal that supports 8-bit control codes it can be made slightly shorter, for 55 bytes.

```
0000000: 666f 7220 6920 696e 207b 612e 2e7a 7d0a  for i in {a..z}.
0000010: 646f 2070 7269 6e74 6620 9b34 252d 3238  do printf .4%-28
0000020: 7320 346d 2037 6d20 316d 0a65 6368 6f20  s 4m 7m 1m.echo
0000030: 9b6d 0a64 6f6e 65                        .m.done

```

**EDIT**: It has come to my attention that ANSI-based solutions are required to draw text in non-white space characters. I have a solution of 65 characters that does so, but I would like someone to explain the reason for the requirement before I post it.

# Answer
> 5 votes
## Perl, 90, 50 + 2 (-p flag) = 52 bytes 44 + 2 (-p flag) = 46 bytes

As nobody's done a Perl version yet, here we go:

$*=sprintf "%c\[44m%27s%c\[47m%27s%c\[41m%27s%c\[40m\n",27,' ',27,' ',27,' ',27;print $* x 26;

$x=' ' x 27;$\_="^\[\[44m$x^\[\[47m$x^\[\[41m$x^\[\[40m\n" x 26

```
$x=' 'x26;$_="^[[44m$x^[[47m$x^[[41m$x^[[0m\n"x26

```

Hexdump:

```
00000000: 2478 3d27 2027 7832 363b 245f 3d22 1b5b  $x=' 'x26;$_=".[
00000010: 3434 6d24 781b 5b34 376d 2478 1b5b 3431  44m$x.[47m$x.[41
00000020: 6d24 781b 5b30 6d5c 6e22 7832 360a       m$x.[0m\n"x26.

```

# Answer
> 5 votes
## Java, 156 bytes

```
enum F{;public static void main(String[]a){String b="[3";for(int i=0;i<'࿘';i++)System.out.print((i%78<26?b+4:(i%78>51?b+1:b+7))+(i%78>76?"m#\n":"m#"));}}

```

Used some old tricks like the unicode char used as an int in the loop and so earning a character (but not a byte), modulos (so there's only one loop) and some ternary expressions.

Nothing really special else.

# Answer
> 5 votes
# x86 machine code, 34 bytes

```
00000000  68 00 b8 07 bb 40 1f 31  ff 83 e7 f0 89 d8 25 00  |h....@.1......%.|
00000010  f1 c1 c3 04 f6 c4 f0 74  f0 b1 1b f3 ab 85 ff 7f  |.......t........|
00000020  eb c3                                             |..|
00000022

```

Link to the .COM file \- runs just fine in DOSBox:

Notice that it doesn't hang after drawing - it's just that the prompt is left in blue not to ruin the result; you can quit from DOSBox as usual with `exit`, it'll work even if you don't see it while typing.

Commented assembly:

```
    ; usual .COM boilerplate
    org 100h

section .text

start:
    ; point the ES segment to the graphics memory
    push 0x0b800
    pop es
    ; bx is used (mainly) as repository for the background colors
    ; 1 => blue; f => white; 4 => red; 0 => flag for new row
    mov bx,0x1f40
    ; reset the destination pointer
    xor di,di
newrow:
    ; === start of a new row ===
    ; round down DI to multiples of 16, to avoid overflowing the row by one
    ; character (27*3 = 81, while the row is 80 characters)
    and di,0xfff0
span:
    ; === start of a span ===
    ; build the pattern to write; start with BX
    mov ax,bx
    ; adjust the pattern in AX:
    ; - keep the upper byte (background color);
    ; - leave blue as foreground color at the very end (avoid the prompt
    ;   ruining the flag when we exit);
    ; - put NUL as character to display;
    and ax,0xf100
    ; rotate bx, to switch to the next color pattern
    rol bx,4
    ; check if we got to the sentinel value (=> we finished one row)
    test ah,0xf0
    ; in this case, go back to newrow; this will re-align DI and do a new
    ; rotation on BX
    jz newrow
    ; fill the video memory with 27 times the word built above in AX
    mov cl,27
    rep stosw
    ; continue as far as DI is positive; notice that this way we keep writing
    ; well past the 25 lines limit, but doesn't seem to impact anything
    test di,di
    jg span
    ; otherwise exit; the point of this thing is to avoid a wraparound, which
    ; ends up unaligned, thus breaking the drawing
    ret

```

# Answer
> 5 votes
# ZX Spectrum Z80 assembly, ~~32~~, 30 Bytes

```
    org 8000h

red:      equ 16
white:    equ 120
blue:     equ 8

start:
    ld    c,16     ;height
    ld    e,8      ; blue/offset/counter
    ld    hl,5800h
sheldon:
    ld    b,e      ;counter
fun:
    ld    (hl),e   ;blue
    inc   hl
    djnz  fun
    ld    b,e      ;counter
with:
    ld   (hl),white
    inc  hl
    djnz with
    ld   b,e       ;counter
flags:
    ld   (hl),red
    inc  hl
    djnz flags
    ld   d,b       ;e holds offset
    add  hl,de
    dec  c
    jr   nz,sheldon
    ret

    end

    30 bytes

```

output is 24\*8 pixels wide =192 pixels wide
and 16\*8 pixels high =128 pixels high

edit 1: removed preload of de with two colours,shorter to directly load (hl):saves 1 byte
By not using "de" it can now transfer values instead of "a":saves 1 byte

# Answer
> 4 votes
## Marbelous, 122 bytes

```
@0
--34
=0Ro
\/@0
:Ro
}0
..1B'['0'm0A
Bl1B'['4'1'm
Bl1B'['4'7'm
Bl1B'['4'4'm
{0
:Bl
@0
--1A
=0PS
&0@0
}0
&0
{0
:PS
}0
{0'F

```

Main board calls Ro 52 times. Ro prints one row including 3 color codes, 3 blocks of spaces, 1 color reset, 1 newline. Bl prints 26 ~~spaces~~Fs. PS prints one ~~space~~ F.

# Answer
> 4 votes
## Python, ~~223~~ 208 bytes

Thanks @Sp3000

```
from turtle import*
def D():fill(1);fd(100);rt(90);fd(200);rt(90);fd(100);rt(90);fd(200);rt(90);fill(0)
lt(180)
fillcolor("#0055a4")
D()
fillcolor("white")
goto(100,0)
D()
fillcolor("#ef4135")
goto(200,0)
D()

```

Try it here

# Answer
> 4 votes
# Befunge-98, 170 bytes

```
a"552"a"25 87"a"3P"ck,dd+20pv
_v#p02:-1g02,k8"0 85 164 "  <
v>d6*20p#4
<_v#p02:-1g02,k3"255 "
v >dd+20p
>" 35 56 932"9v>
_v#p02:-1g02,k<^
a<v_@#p29:-1g29,
v >"<"00pdd+20p

```

Outputs the image in PPM format. It's probably still not optimal.

# Answer
> 4 votes
## CBM BASIC 7.0, 76 bytes

```
1fOi=1to26:?"r←";:goS3:?"e";:goS3:?"£";:goS3:?:nE:end
3fOj=1to26:?" ";:nE:reT

```

Note that in line 1, the characters between the quotation marks are PETSCII control codes which actually appear in reverse video on a real Commodore computer:

* `r` enables reverse video
* changes the text colour to blue
* `e` changes the text colour to white
* `£` changes the text colour to red

It's not strictly ANSI, as specified in the question, but given the hardware limitations I think it's close enough. :)

Here is an excerpt of the output on a Commodore 128 80-column display:

# Answer
> 4 votes
# Javascript, 91 bytes

Not the most exciting one.

This one **only** works on Google Chrome. Current version is 46.0.2490.86m.

```
console.log((Z='%c▮')+Z+Z,(X='font-size:100px;color:#')+'0055a4','color:#fff',X+'ef4135')
```

This draws the flag in the console.

Google Chrome has a pure white background for the console, and the default font weight allows it to have 33% of it's width.

This uses the BLACK VERTICAL RECTANGLE character to produce the output.

---

---

If you don't have Google Chrome, here's the output:

---

---

As an alternative, with 84 bytes:

```
console.log((Z='%c█')+Z+Z,(X='font-size:9cm;color:#')+'0055a4',X+'fff',X+'ef4135')
```

This one uses the FULL BLOCK UTF8 character (`\xDC` in ASCII).

It produces a ~13x9cm flag on Chrome's console.

And this is the result:

# Answer
> 4 votes
## QBASIC, ~~88~~ 122 Bytes

```
SCREEN 13
h=200
a=100
PALETTE 2,856123
PALETTE 1,2626816
LINE(0,0)-(a,h),1,BF
LINE(a,0)-(h,h),15,BF
LINE(h,0)-(300,h),2,BF

```

Edit: As was correctly pointed out, the colors did not meet the requirements. The corrected version is basically as close as one can get in QB as far as I know, since RGB in mode 13 are represented by 18 bits instead of 24 bit. The colors are (0,85,162), (255,255,255), (239,65,52). So blue is ever so slightly off the mark, but close enough I would say.

Here is it in QB64 (it's getting autoformatted there, but it's the same code):

# Answer
> 4 votes
## CSS, ~~74~~ 72 bytes

*Note: every CSS code is also a valid Sass code: since Sass is a scripting language then this entry should be valid too :)*

http://codepen.io/anon/pen/xweEBX?editors=010

```
*{box-shadow:33.3vw 0 #0055a4 inset,-33.3vw 0 #ef4135 inset;height:66.6vw}

```

The correct ratio is ensured by the height, expressed as `2/3` of the viewport width (clearly this lacks precision when the viewport is larger than `999px`, but at least it is responsive :D )

---

**Edit 1:** (72 bytes) from the previous example, a space can be safely removed before each colour.

http://codepen.io/anon/pen/BoEXZP?editors=010

```
*{box-shadow:33.3vw 0#0055a4 inset,-33.3vw 0#ef4135 inset;height:66.6vw}

```

**Result**

Note that with less code (**68 bytes**, since decimals are not needed in the box-shadow) it is possible to draw the 1853 naval variant, in `30:33:37` proportions, as suggested in a comment above

```
*{box-shadow:30vw 0#0055a4 inset,-37vw 0#ef4135 inset;height:66.6vw}

```

# Answer
> 4 votes
# CSS, 86 bytes

This creates a simple border around the body element:

```
body{border-left:2cm solid #0055a4;width:2cm;height:4cm;border-right:2cm solid #ef4135
```

This renders a 6x4cm flag, and should work on any file.

To test on a clean page, paste this on your address bar:

`data:text/html,<style>body{border-left:2cm solid #0055a4;width:2cm;height:4cm;border-right:2cm solid #ef4135`

URL-encoded:

`data:text/html,%3Cstyle%3Ebody%7Bborder-left%3A2cm%20solid%20%230055a4%3Bwidth%3A2cm%3Bheight%3A4cm%3Bborder-right%3A2cm%20solid%20%23ef4135`

# Answer
> 3 votes
# Mathematica, 131 bytes

```
".png"~Export~ImageCrop@Graphics[{RGBColor@"#0055a4",{0,0}~Rectangle~{1,2},RGBColor@"#ef4135",{2,0}~Rectangle~{3,2}},ImageSize->82]

```

Saves to a file named `.png` in the current working directory.

# Answer
> 3 votes
## Javascript, ~~109~~ ~~98~~ ~~96~~ 91

Attempt 1 109

```
var i=0,a='%cFRANCE',b='color:#';for(;i<6;i++)console.log(new Array(4).join(a),b+'0055A4',b+'FFF',b+'EF4135')

```

Attempt 2 98

```
for(var i=0;i<6;i++)console.log('%cFRANCE'.repeat(3),'color:#0055A4','color:#FFF','color:#EF4135')

```

Attempt3 120

```
eval("console.log(('%cFRANCE'.repeat(3)+'\\n').repeat(6)"+",'color:#0055A4','color:#FFF','color:#EF4135'".repeat(6)+")")

```

Attempt 3 solves the issue with chrome forcing them together still attempt 2 works for me in ff.

**No longer and issue just enable time stamps in options for console logging.**

Attempt 4 96

```
var i=0,c='color:#';for(;i<6;i++)console.log('%cFRANCE'.repeat(3),c+'0055A4',c+'FFF',c+'EF4135')

```

Attempt 5 91

```
for(i=0,c='color:#';i<6;i++)console.log('%cFRANCE'.repeat(3),c+'0055A4',c+'FFF',c+'EF4135')

```

Moved var decs into for loop saved 5 bytes :D

Try it out here :).

```
for(i=0,c='color:#';i<6;i++)console.log('%cFRANCE'.repeat(3),c+'0055A4',c+'FFF',c+'EF4135')
```

# Answer
> 3 votes
## PostScript, 128 bytes.

```
%!PS
<</PageSize[78 52]>>setpagedevice
0 .333 .643 setrgbcolor
0 0 26 52 rectfill
.937 .255 .208 setrgbcolor
52 0 26 52 rectfill

```

## Questionable PS version, 84 bytes

```
0 .33 .64 setrgbcolor
0 0 26 52 rectfill
.94 .25 .21 setrgbcolor
52 0 26 52 rectfill

```

This may not have exact color matches (though they should be indistinguishable to the human eye), may render in the corner of a larger page, and some interpreters may not accept it without the magic line at the beginning.

I can't test right now, but it may be possible to save some bytes by using a subroutine:

```
/a{setrgbcolor rectfill}def
0 0 26 52 0 .33 .64 a
52 0 26 52 .94 .25 .21 a

%!PS
/a{setrgbcolor rectfill}def
0 0 26 52 0 .33 .64
52 0 26 52 .94 .25 .21<</PageSize[78 52]>>setpagedevice
a a

```

# Answer
> 3 votes
# Scala, 84 bytes

Using ANSI colors, Running on bash (Ubuntu)

```
val (p,b)=("\033[;3","\u2588"*26);(1 to 52).map(_=>println("471".mkString(p,"m"+b+p,"m"+b)))

```

# Answer
> 3 votes
## Octave, 58 bytes

The online Octave interpreter seems to scale up by default, so the Octave answer is rather short, especially since you can use inline assignment.

```
imshow([c=cat(3,[0 m=255 239],[85 m 65],[164 m 53]);c]/m);

```

# Answer
> 3 votes
## Ruby, 77 bytes

```
puts"P3\n78 52\n255","#{"0 85 164 "*26+"255 255 255 "*26+"239 65 53 "*26}"*52

```

**Output** (converted to png, since ppm doesn't seem to be supported):

Outputs in ppm format to STDOUT. Still working on plusgolfing. I know ppm can take bytes instead of ascii, but I haven't figured out a good way to do that yet.

# Answer
> 3 votes
# C-Sharp, ~~4608~~, ~~1312~~, ~~687~~, 606 bytes

Thanks for your comments and suggestions. This is actually my first "published" piece of code ever! have been learning for about two-and-a-half months.

```
class P { static void Main(string[] args) { int l = 0; while (l < 24) { int B = 0; int R = 0; int W = 0; while (B < 26) { Console.BackgroundColor = ConsoleColor.DarkBlue; Console.Write(" "); B++; } while (W < 26) { Console.BackgroundColor = ConsoleColor.White; Console.Write(" "); W++; } while (R < 26) { Console.BackgroundColor = ConsoleColor.Red; Console.Write(" "); R++; } Console.WriteLine(); l++; } Console.BackgroundColor = ConsoleColor.Black; Console.ReadKey();}}

```

# Answer
> 3 votes
# Ruby with Shoes, 119 bytes

```
Shoes.app(width:78,height:52){strokewidth 0
[rgb(0,85,164),white,rgb(239,65,53)].map{|c|
fill c
rect$.,0,26,52
$.+=26}}

```

Sample output:

# Answer
> 3 votes
## MATLAB, 70 bytes

Since I'm not entirely sure if it's just the online interpreter doing the scaling or whether that's an actual language feature in my Octave answer, here's my MATLAB version as well:

```
m=255;c=cat(3,[0 m 239],[85 m 65],[164 m 53]);imshow([c;c]/m,'I',6e3);

```

`I` stands for `InitialMagnification`.

# Answer
> 3 votes
# FLTK, ~~234~~ 199 bytes

```
Function{}{}{Fl_Window{}{xywh{9 9 78 52}}{Fl_Box{}{xywh{0 0 26 52}box FLAT_BOX color 0x0055a4ff}Fl_Box{}{xywh{26 0 26 52}box FLAT_BOX color 7}Fl_Box{}{xywh{52 0 26 52}box FLAT_BOX color 0xef4135ff}}}

```

Ungolfed:

```
Function {} {} {
    Fl_Window {} {
        xywh {9 9 78 52}
    } {
        Fl_Box {} {
            xywh {0 0 26 52}
            box FLAT_BOX
            color 0x0055a4ff
        }
        Fl_Box {} {
            xywh {26 0 26 52}
            box FLAT_BOX
            color 7
        }
        Fl_Box {} {
            xywh {52 0 26 52}
            box FLAT_BOX
            color 0xef4135ff
        }
    }
}

```

Sample output:

# Answer
> 3 votes
# JavaScript ~~206~~ 175

```
c=c.getContext('2d')
d=c.createImageData(w=78,h=52),a=Int32Array(d.data.buffer)
for(i=w*h;i--;)a[i]=-[6007552,1,13286929][i%w/26|0]
c.putImageData(d,0,0)
```

```
<canvas id=c></canvas>
```

Here's something just for fun. The code can be modified to make all images on a page the french flag.

```
function france(g){
  var c =document.createElement('canvas')
  var x = c.getContext('2d');
  var w = c.width = g.width;
  var h = c.height = g.height;
  var d = x.createImageData(w,h);
  var a = new Int32Array(d.data.buffer);
  var s = w / 3;
  for(var i=w*h;i--;)a[i]=-[6007552,1,13286929][i%w/s|0];
  x.putImageData(d,0,0);
  g.src = c.toDataURL();
}

function allFrance() {
  var g = document.getElementsByTagName("img");
  for(var i = g.length; i--;) france(g[i]);
}

allFrance()

```

# Answer
> 3 votes
## C#, 176 bytes as a Program

A program that outputs the Full Block character 219, 78 wide, 52 tall. If your font is square, this will have the correct ratio.

```
using System;class P{static void Main(){for(int x,y=52;y-->0;)for(x=4;x-->1;Console.Write(new string('█',26)+(x<2?"\n":"")))Console.ForegroundColor=(ConsoleColor)(x%3*3+9);}}

```

Indentation and new lines for clarity:

```
using System;
class P{
    static void Main(){
        for(int x,y=52;y-->0;)
            for(x=4;x-->1;Console.Write(new string('█',26)+(x<2?"\n":"")))
                Console.ForegroundColor=(ConsoleColor)(x%3*3+9);
    }
}

```

## C#, 157 bytes as a Function

I argue that the requirements did not require a program and that a function would suffice. In that case, I can drop the byte count substantially.

```
using System;void F(){for(int x,y=52;y-->0;)for(x=4;x-->1;Console.Write(new string('█',26)+(x<2?"\n":"")))Console.ForegroundColor=(ConsoleColor)(x%3*3+9);}

```

Indentation and new lines for clarity:

```
using System;
void F(){
    for(int x,y=52;y-->0;)
        for(x=4;x-->1;Console.Write(new string('█',26)+(x<2?"\n":"")))
            Console.ForegroundColor=(ConsoleColor)(x%3*3+9);
}

```

# Answer
> 3 votes
## Python 2, 46 bytes

```
s="[3%s;1m"+"#"*26;print(s%4+s%7+s%1+"\n")*30

```

There is a non-printable ESC character at the beginning of the format string:

```
$ hexdump -C f.py
00000000  73 3d 22 1b 5b 33 25 73  3b 31 6d 22 2b 22 23 22  |s=".[3%s;1m"+"#"|
00000010  2a 32 36 3b 70 72 69 6e  74 28 73 25 34 2b 73 25  |*26;print(s%4+s%|
00000020  37 2b 73 25 31 2b 22 5c  6e 22 29 2a 33 30        |7+s%1+"\n")*30|
0000002e

```

Coloured space character version:

```
s="[3%s;7m"+" "*26;print(s%4+s%7+s%1+"\n")*30

```

## Tiny version, 44 bytes

Doesn't fit for the "at least 78 chars wide" requirements.

```
s="[3%s;7m"+" "*9;print(s%4+s%7+s%1+"\n")*9

```

# Answer
> 3 votes
# CJam, 43

```
'P[Z"s<h8_.KUw'rFa"158b256b3/(\30f*60*]e_N*

```

Outputs an image in PPM format. Try it online

# Answer
> 3 votes
# PowerShell, 152 bytes

```
sal w write-host;$v=" "*26;foreach($u in 1..26){;w $v -backgroundcolor blue -NoNewLine;w $v -backgroundcolor white -NoNewLine;w $v -backgroundcolor red}

```

# Answer
> 3 votes
# LibreLogo, ~~88~~ 85 bytes

**Code:**

```
pc [24]lt 90 fd 26 fc 21924 rectangle[52,26]rt 180 fd 52 fc 0xef4135 rectangle[52,26]

```

**Result:**

**Explanation:**

```
pc [24]                     ; Pen Color = INVISIBLE
lt 90                       ; Left 90°
fd 26                       ; Forward 26 pt
fc 21924                    ; Fill Color = RGB(0, 85, 164)
rectangle [52, 26]          ; Rectangle 52x26 pt
rt 180                      ; Right 180°
fd 52                       ; Forward 52 pt
fc 0xef4135                 ; Fill Color = RGB(239, 65, 53)
rectangle [52, 26]          ; Rectangle 52x26 pt

```

**Previous Attempts:**

```
pc [24]lt 90 fd 26 fc 0x0055a4 rectangle[52,26]rt 180 fd 52 fc 0xef4135 rectangle[52,26]

```

# Answer
> 3 votes
# Excel VBA 62 bytes

VBE Immediate Window commands

```
[a1:d25].interior.colorindex=23:[i1:l25].interior.colorindex=3

```

# Answer
> 3 votes
Je préfère (en /bin/bash):

```
for i in {a..z}; do printf '\033[4%-28s' 4m 7m 1m; echo; done

```

Inspirée d'une autre contribution, mais les caractères ne fonctionnaient pas trop (escape)

Vive la République!

# Answer
> 3 votes
# Java (JDK 10), 86 bytes

```
v->{for(int i=0,x;i<4108;)System.out.printf((x=i++%79/26*3+4)<13?"[3%sm@":"\n",x%9);}

```

Try it online!

Notes:

* On TIO, it will print the characters, not the flag. To show the flag, run it in Bash.
* There is a `\u001b` character between `"` and `[3%sm@`.

Credits:

* steve for giving the idea of moving the `i++`to a more appropriate place, sparing one byte.

# Answer
> 3 votes
# Swift + SwiftUI, entire iOS App, 195 bytes

`project.pbxproj` and other supporting files not included.

```
import SwiftUI
@main struct A:App{let body=WindowGroup{HStack(spacing:0){Color(red:0,green:1/3,blue:0.643)
Color.white
Color(red:0.937,green:0.255,blue:0.208)}.aspectRatio(1.5,contentMode:.fit)}}

```

Works best in dark mode, where the background isn't white:

# Answer
> 3 votes
## Grasshopper JS, 21 bytes

`drawBoxes('bwr bwr');`

Outputs this image:

# Answer
> 2 votes
# Lua + LÖVE, ~~176~~ 174 bytes

```
l=love
g=l.graphics
l.window.setMode(78,52)
function l.draw()for k,v in next,{[0]={0,85,164},{255,255,255},{239,65,53}}do
g.setColor(v)g.rectangle("fill",k*26,0,26,52)end
end

```

Sample output:

# Answer
> 2 votes
## JavaScript, 141 bytes

```
a='';for(j=0;j<24;j++){for(i=1;i<80;i++){a+="<d style='color:"+(78/i<1.5?'blue':(78/i<3?'white':'red'))+"'>F</d>"}a+="<br>"}document.write(a)
```

(click "full page" to see the proper result)

# Answer
> 2 votes
## ActionScript, 90 bytes

`var g=graphics,f=g.beginFill,d=g.drawRect;f(21924);d(0,0,26,52);f(0xef4135);d(52,0,26,52);`

Ouput:

# Answer
> 2 votes
## Processing, 88 bytes

```
size(78,52);scale(26,52);stroke(-1);background(#EF4135);fill(#0055A4);rect(-2,-1,3.5,3);

```

# Answer
> 2 votes
## R, 57 bytes

```
barplot(c(1,1),,c(1),yaxt='n',col=c("#0055a4","#ef4135"))

```

# Answer
> 2 votes
# Postscript, 136 bytes

```
/r{rlineto}def /b{translate newpath 0 0 moveto 0 2 r 1 0 r 0 -2 r closepath setrgbcolor fill}def 90 90 scale 0 .33 .64 1 1 b 1 0 0 2 0 b

```

# Answer
> 2 votes
# FLIF, 37 bytes

FLIF is an excellent bitmap format for when you really want to squeeze some bytes away:

```
4c46 4649 3133 4e00 3400 1e27 2ce3 5d2f
ab15 8fdd c110 4117 8d25 5fa2 c8b6 d02d
fdfe af77 000a

```

Using `viewflif`:

# Answer
> 2 votes
# PaperScript, 83 bytes

```
R=Path.Rectangle
R(0,0,49,98).fillColor="#0055a4"
R(98,0,49,98).fillColor="#ef4135"

```

PaperScript is an extension of JavaScript based on the Paper.js vector graphics library. You can run PaperScript code directly, without having to mess with the HTML and CSS, at sketch.paperjs.org.

This code is very straightforward: it draws a rectangle and colors it blue; then it draws another rectangle and colors it red. (The arguments to `Path.Rectangle` are `x`, `y`, `width`, and `height`, respectively.) The background is assumed to be white. Try it at Paper.js Sketch!

### Output

Displayed at the top left of the canvas:

# Answer
> 1 votes
## HTML, 124 bytes

converted rob values mentioned in the question to the hex ones, that cuts off 13 bytes

```
<a><b><c><style>*{position:fixed;left:0;right:0;bottom:0;top:0}a{background:#0055A4;width:33%}c{background:#EF4135;left:66%;
```

Very invalid HTML. Unclosed and non-standard elements (fun fact: I can't remove the last semicolon, doesn't render). If your window isn't resized to the aspect ratio of 3:2, I'd advice you to do it ;)

# Answer
> 1 votes
## Tandy Color Computer 2 BASIC, 131 bytes

```
CLS:B$=CHR$(175):W$=CHR$(207):R$=CHR$(191):L$=B$+B$+B$+B$+B$+B$+W$+W$+W$+W$+W$+W$+R$+R$+R$+R$+R$+R$:?L$:?L$:?L$:?L$:?L$:?L$:?L$:?L$

```

Ungolfed (somewhat):

```
10 CLS
20 B$=CHR$(175)
30 W$=CHR$(207)
40 R$=CHR$(191)
50 L$=B$+B$+B$+B$+B$+B$+W$+W$+W$+W$+W$+W$+R$+R$+R$+R$+R$+R$
60 ?L$:?L$:?L$:?L$:?L$:?L$:?L$:?L$

```

I could save 4 bytes if I removed the clear screen code in the beginning (CLS) but it would like kinda gnarly seeing all the code listed on one line then the flag thereafter... otherwise, this clears the screen, assigns B$ the solid blue character, W$ the solid white character, and R$ the solid red character. Then creates a line (L$) with 6 each blue, white, red characters and writes 8 lines of that out to standard output.

This takes advantage of the upper ASCII codes in the Motorola 6847 VDG (Video Display Generator) chip that the CoCo 1 & 2 relied on; they were block graphic codes in any of 8 colors.

As the standard character size of the CoCo was 8 pixels wide by 12 pixels deep, the only way to get the correct ratio at the minimum size is to use 6 characters per color wide by 8 lines. 6\*3\*8=144 pixels wide, and 8\*12=96 pixels deep. 144/96=1.5x wider than tall, or 3:2 ratio.

This also takes advantage of the '?' character being shorthand for the PRINT statement. If you list the ungolfed version of the program you actually will see 8 instances of 'PRINTL$:' instead of '?L$:' due to the tokenization of the '?' being equal to 'PRINT'. However, to my knowledge you can't list a one-liner (a.k.a. 'immediate mode') BASIC program.

# Answer
> 1 votes
# Python 3, ~~54~~ 51 bytes

~~```
c="\033[0;4%sm ";print((c%4*30+c%7*30+c%1*30+"\n")*30)

```~~
```
c="\033[0;4%sm"+" "*30;print((c%4+c%7+c%1+"\n")*30)

```

Output:

# Answer
> 1 votes
# C++ (Windows), 398 bytes

```
#include <iostream>
#include <Windows.h>
using namespace std;int main(){HANDLE h=GetStdHandle(STD_OUTPUT_HANDLE);int c=0;for(int i=0;i<52;++i){while(c<78){if(c<26){SetConsoleTextAttribute(h,FOREGROUND_BLUE);cout<<"F";}else if(c<52){SetConsoleTextAttribute(h,FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_RED);cout<<"F";}else{SetConsoleTextAttribute(h,BACKGROUND_RED);cout<<" ";}++c;}c=0;cout<<endl;}}

```

My first submission! It's quite long, partly because setting console colour in Windows is long, and partly because I have no idea what I'm doing!

# Answer
> 1 votes
# ImageScript, 63 bytes

`rgb(0,85,164)rect(0,0,200,400)rgb(239,65,53)rect(400,0,200,400)`

# Answer
> 1 votes
# Python, ~~67~~ 63 bytes

Straightforward as PPM:

```
print"P6 78 52 255 "+(26*"\x00U\xff"+78*"\xff"+26*"\xefA5")*52

```

Usage:

```
python golf_france.py > france.ppm

```

Edit1: Binary PPM is shorter, haven't figured out how to use to strange codes directly in the strings.

# Answer
> 1 votes
# PostScript, 48 bytes

Based on earlier (supposedly dodgy) postscript entry, optimized with a loop and 2-byte synonyms, also includes exact colours.

Hex dump:

```
00000000: 3020 2e33 3333 202e 3634 3388 0030 881a  0 .333 .643..0..
00000010: 8834 2e39 3337 202e 3235 3520 2e32 3038  .4.937 .255 .208
00000020: 8834 3088 1a88 3432 7b92 9d92 807d 9283  .40...42{....}..

```

# Answer
> 1 votes
# SmileBASIC, 55 bytes

```
GCLS-1GFILL.,0,26,52,-16755292GFILL 52,0,78,52,-1097419

```

# Answer
> 1 votes
# Tcl/Tk, ~~81~~ 80

```
gri [can .c -bg #fff]
.c cr r 0 0 26 52 -f #0055A4
.c cr r 52 0 78 52 -f #EF4135

```

# Answer
> 1 votes
**Processing, 128 bytes**

```
void setup(){size(90,60);fill(0,0,255);rect(0,0,30,60);fill(255);rect(30,0,60,60);fill(255,0,0);rect(60,0,90,60);}void draw(){}

```

# Answer
> 1 votes
# Bash, 35 bytes

```
echo -e "\033[44m \033[m \033[41m "

```

# Answer
> 1 votes
# Processing, 111 bytes

```
size(78,52);noStroke();fill(#0055a4);rect(0,0,26,52);fill(255);rect(26,0,26,52);fill(#ef4135);rect(52,0,26,52);

```

# Answer
> 1 votes
## C# (.NET Framework), 190 bytes

```
using System;class P{static void Main(){for(int j=0;j<52;j++)for(int i=0;i<3;i++){Console.ForegroundColor=(ConsoleColor)new[]{9,15,12}[i];Console.Write("".PadRight(26,'F')+(i>1?"\n":""));}}}

```

# Answer
> 1 votes
# 05AB1E, ~~22~~ 16 bytes

*-4 bytes thanks to Kevin Cruijssen.*

```
Ƶsç4«Ž1ÙSA««J₂F,

```

Try it online! Beats all other answers.

# Answer
> 1 votes
**Asymptote 123 bytes**

Run on http://asymptote.ualberta.ca/

```
fill(box((0,0),(26,52)),rgb(0,85,164));fill(box((26,0),(52,52)),rgb(255,255,255));fill(box((52,0),(78,52)),rgb(239,65,53));

```

# Answer
> 1 votes
# Applesoft BASIC, 122 bytes

```
1GR
2COLOR=2
3M=13
4X=-1
5X=X+1
6VLIN0,25ATX
7IFX<M GOTO5
8IFM==26GOTO12
9COLOR=15
10M=26
11GOTO5
12COLOR=1
13M=39
14GOTO5

```

# Answer
> 1 votes
# Chipmunk BASIC, 116 bytes

Chipmunk Basic v368b2.02 on MacOS.

```
graphics 0
graphics color 0,33,64
graphics fillrect 0,0,44,88
graphics color 94,25,21
graphics fillrect 88,0,132,88

```

A nice variant of TinyBasic. Colour values adjusted by `0.392157` due to the lang's slightly different implementation of RGB.

# Answer
> 1 votes
# Japt, 56 bytes

```
Ol"%c "³$,...$"0055a4  ef4135"¸ùf Ëi`padÜA:9%6%;baå®":#

```

Test it (Open your browser's console)

# Answer
> 1 votes
# Haskell, 120 bytes

```
c=concat
r=replicate
p=('P':).unwords.(show<$>).([3,78,52,255]++).c.r 52.c$r 26=<<[[0,85,164],[255,255,255],[239,65,53]]

```

Try it online!

# Answer
> 1 votes
## Batch, 120 bytes

```
@Mode 78,53&Set #=\E[48;2;#m\E[26X\E[26C
@For /l %%i in (1 1 52)Do @Echo(%#:#=;35;149%%#:#=255;255;255%%#:#=237;41;57%\E[0m

```

Explainer:

* Uses Virtual terminal sequences to:
    + Insert n spaces at cursor pos: `\E[nX`
    + Move cursor n cells right: `\E[nC`
    + change color: `\E[48;2;#m`
        - `Set #=\E[48;2;#m\E[26X\E[26C` \- Defines variable # as a macro.
        - substring modification is used to replace # with RGB color values `%#:#=#=;35;149%`

\E represents the Escape character, which does not display on Codegolf. The raw code can be obtained at: https://pastebin.com/yqwn0R1m

# Answer
> 0 votes
# Python, 45 Bytes

```
print((''*26+'⬜'*26+''*26+'\n')*52)

```

Another answer using emojis!

---
Tags: code-golf, kolmogorov-complexity, graphical-output, geometry
---


title: Minkowski's ?(x) for rational x

text:
# Question
Title: Minkowski's ?(x) for rational x
Here is Minkowski's question mark function:

It is a strictly increasing and continuous function from the reals to themselves that, among other unusual properties, maps rational numbers to dyadic rationals (those with a power-of-two denominator). Specifically, suppose the continued fraction representation of a rational number \\$x\\$ is \\$\[a\_0;a\_1,\dots,a\_n\]\\$, then $$?(x)=a\_0+\sum\_{i=1}^n\frac{\left(-1\right)^{i+1}}{2^{a\_1+\cdots+a\_i-1}}$$ For example, 58/27 has continued fraction representation \\$\[2;6,1,3\]\\$, so $$?(58/27)=2+\frac1{2^{6-1}}-\frac1{2^{6+1-1}}+\frac1{2^{6+1+3-1}}=2+2^{-5}-2^{-6}+2^{-9}=\frac{1033}{2^9}$$ so the pair (1033, 9) should be returned in this case. Similarly for 30/73 with expansion \\$\[0;2,2,3,4\]\\$: $$?(30/73)=2^{-1}-2^{-3}+2^{-6}-2^{-10}=\frac{399}{2^{10}}$$ and (399, 10) should be returned here. Note that it does not matter whether the form ending in 1 is used or not.

## Task

Given a rational number \\$x\\$, determine \\$?(x)=a/2^b\\$ as a rational number in lowest terms (so that \\$b\\$ is a non-negative integer, as small as possible, and \\$a\\$ is odd unless \\$b=0\\$) and output \\$a\\$ and \\$b\\$ (not \\$2^b\\$). \\$x\\$ may be taken in any reasonable format, and if you take a pair of integers you may assume the corresponding fraction is in lowest terms.

This is ; fewest bytes wins.

## Test cases

```
x -> a, b
0/1 -> 0, 0
1/1 -> 1, 0
1/2 -> 1, 1
-1/2 -> -1, 1
2/1 -> 2, 0
1/3 -> 1, 2
1/8 -> 1, 7
2/5 -> 3, 3
8/5 -> 13, 3
58/27 -> 1033, 9
30/73 -> 399, 10
144/89 -> 853, 9
-17/77 -> -767, 13
-17/99 -> -133, 12
355/113 -> 12648447, 22
16000/1 -> 16000, 0

```

# Answer
# Python, 95 bytes

```
lambda n,d:g(d-n%d,n%d,1,n//d,0)
g=lambda n,d,s,N,D:d and g(d,n%d,-s,(N<<n//d)+s,D+n//d)or(N,D)

```

Attempt This Online!

Rather verbose implementation. Essentially calculates the cf (by Euclidean algo) and converts the terms on the fly.
> 6 votes

# Answer
# Python 3.8, 95 bytes

```
q=lambda x,y,k=0:y>=2*x>0and q(x,y-x,k+1)or(x and-(-x//y<<(r:=q(-x%y,y))[1])-r[0],x and r[1]+k)

```

Try it online!

### How it works

Uses the recurrence

\begin{align\*} ?(0) &= 0, \\ ?(x) &= \frac{?{\left(\frac{x}{1 - x}\right)}}{2} \quad\text{if }0 \< x ≤ \frac12, \\ ?(x) &= ⌈x⌉ - {?(⌈x⌉ - x)}. \end{align\*}
> 5 votes

# Answer
# Wolfram Language (Mathematica), 77 or 124 bytes

```
(s=Sign@#;{s Numerator@#,Log[2,Denominator@#]}&@MinkowskiQuestionMark@Abs@#)&

```

Try it online!

Or without overkill builtin:

```
(s=Sign@#;c=ContinuedFraction@Abs@#;{s Numerator@#, Log[2,Denominator@#]}&@(r=c[[1]];t=-1;Do[t=-t/2^e;r+=2t,{e,Rest@c}];r))&

```

Try it online!
> 3 votes

# Answer
# Haskell, 186 bytes

```
import Data.Ratio
c r=let f=floor r;d=r-f%1 in if d==0 then[f]else f:c(1/d)
m(a:b)=a%1-2*sum[(-1)^i/2^sum(take i b)|i<-[1..length b]]
p x=(numerator x,until((denominator x==).(2^))(1+)0)

```

Try it online!
> 3 votes

# Answer
# julia, 111 bytes

Expects a single argument of type `Rational{Int64}`

This approach traverses the Stern-Brocot tree for \\$\mathrm{mod}(p,1)\\$, adding \\$1/2^k\\$ at the \\$k\\$-th recursion whenever we take a right branch in the tree.

The case where \\$p \notin (0, 1\]\\$ is handled in the default arguments.

```
m(p,L=[0,1],U=[1,0],q=mod1(p,1),r=p-q,s=0,M=//(L+U...),g=q>=M,l=r+g)=q==M ? (l,s) : m(0,L+g*U,U+L-g*L,q,2l,s+1)

```

Attempt This Online!
> 3 votes

# Answer
# JavaScript (ES6), 88 bytes

Expects `(p)(q)` for \\$x=p/q\\$. Returns `[a,b]`.

This is heavily based on loopy walt's answer.

```
p=>g=(q,s=p<(b=0)?p/(p=-p):1,a=p/q,d=p%=q,n=q-p)=>d?g(b+=n/d|0,-s,s+=a<<n/d,n%d,d):[a,b]

```

Try it online!
> 2 votes

# Answer
# PARI/GP, 67 bytes

```
x->s=0;[(x\1+2*sum(i=2,#r=contfrac(x),(-1)^i/2^s+=r[i]))<<s-=!!s,s]

```

Attempt This Online!
> 2 votes

# Answer
# Jelly, 28 bytes

```
Ḋ;%/ƊẠÐ¿Ṗ:/€ḢW+Ṭ€NÐeFƊƲL’ṭḄƲ

```

A monadic Link that accepts a pair of integers, `[numerator, denominator]`, and yields a pair of integers, `[numerator, denominator's exponent]`.

**Try it online!**

### How?

```
Ḋ;%/ƊẠÐ¿Ṗ:/€ḢW+Ṭ€NÐeFƊƲL’ṭḄƲ - Link: pair of integers = [N, D]
      Ð¿                     - collect while...
     Ạ                       - ...condition: all truthy - i.e. while no zero present
    Ɗ                        - ...do: last three links as a monad - f(current=[n, d]):
Ḋ                            -          dequeue -> [d]
   /                         -          reduce ([n, d]) by:
  %                          -            modulo -> n%d
 ;                           -          concatenate -> [d, n%d]
        Ṗ                    - pop - remove the final result (with a zero in)
          /€                 - reduce each by:
         :                   -   integer division -> continued fraction part list
                      Ʋ      - last four links as a monad - f(Parts=that):
            Ḣ                -   head -> remove and yield the integer part
             W               -   wrap (the integer part) in a list
                     Ɗ       -   last three links as a monad - f(remaining parts):
               Ṭ€            -     untruth each (e.g. 4 -> [0,0,0,1])
                 NÐe         -     negate those at even indices (the 2nd, 4th, ...)
                    F        -     flatten
              +              -   ([integer part]) add (that) (vectorises) - adds the integer
                                     part to the first one. If none just gets [integer part]
                           Ʋ - last four links as a monad - f(A=that):
                       L     -   length (A)
                        ’    -   decrement -> the denominator's exponent
                          Ḅ  -   convert (A) from base two -> the numerator
                         ṭ   -   tack -> [numerator, denominator's exponent]

```
> 2 votes

# Answer
# Charcoal, 63 bytes

```
ＮθＮη≔÷θηζＷ﹪θη«≔ηθ≔ιη⊞υ⁻÷θη¬υ»Ｆ﹪Ｌυ²⊞⊞Ｏυ⊖⊟υ¹Ｉ⟦⁺×ζＸ²Συ⍘⭆υ×Ｉ﹪κ²ι²Συ

```

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

```
ＮθＮη

```

Input the numerator and denominator.

```
≔÷θηζ

```

Calculate the integer part of the fraction.

```
Ｗ﹪θη«≔ηθ≔ιη⊞υ⁻÷θη¬υ»

```

Calculate the rest of the continued fraction, except decrement the first value.

```
Ｆ﹪Ｌυ²⊞⊞Ｏυ⊖⊟υ¹

```

If the fraction has odd length then decrement the last value and append a `1`.

```
Ｉ⟦⁺×ζＸ²Συ⍘⭆υ×Ｉ﹪κ²ι²Συ

```

Transform the fraction into run-length-encoded binary and convert from binary to decimal, adding on the original integer part with an appropriate shift, which is also the second output value.
> 1 votes

# Answer
# Factor \+ `koszul math.continued-fractions`, ~~156~~ 154 bytes

```
[ dup sgn swap abs 1vector [ dup last ratio? ] [ dup next-approx ] while
unclip -rot cum-sum vneg [ -1^ 2 rot 1 + ^ * ] map-index sum * + >fraction log2 ]

```

Try it online!

```
                      ! -17/99
dup                   ! -17/99 -17/99
sgn                   ! -17/99 -1
swap                  ! -1 -17/99
abs                   ! -1 17/99
1vector               ! -1 V{ 17/99 }
[ dup last ratio? ]   ! -1 V{ 17/99 } [ dup last ratio? ]
[ dup next-approx ]   ! -1 V{ 17/99 } [ dup last ratio? ] [ dup next-approx ]
while                 ! -1 V{ 0 5 1 4 1 2 }
unclip                ! -1 V{ 5 1 4 1 2 } 0
-rot                  ! 0 -1 V{ 5 1 4 1 2 }
cum-sum               ! 0 -1 V{ 5 6 10 11 13 }
vneg                  ! 0 -1 V{ -5 -6 -10 -11 -13 }
[ -1^ 2 rot 1 + ^ * ] ! 0 -1 V{ -5 -6 -10 -11 -13 } [ -1^ 2 rot 1 + ^ * ]
map-index             ! 0 -1 { 1/16 -1/32 1/512 -1/1024 1/4096 }
sum                   ! 0 -1 133/4096
*                     ! 0 -133/4096
+                     ! -133/4096
>fraction             ! -133 4096
log2                  ! -133 12

```
> 1 votes

# Answer
# Scala 3, ~~238~~ 186 bytes

Modified from @loopy walt's answer.

---

\\$ \color{black}{\text{In scala, it's weird to mimic \`%\` \`//\` of python}} \\$

```
/*
Python's % operator returns a result with the same sign as the divisor, and // rounds towards negative infinity.

In Scala, % and / don't behave the same way. The % operator returns a result with the same sign as the dividend, and / performs truncating division, rounding towards zero.
*/

def pythonMod(a: Int, b: Int): Int = ((a % b) + b) % b

def pythonDiv(a: Int, b: Int): Int = {
  if ((a > 0 && b > 0) || (a < 0 && b < 0)) a / b
  else if (a % b == 0) a / b
  else a / b - 1
}

```

---

Golfed version. Attempt this online!

Saved 52 bytes thanks to the comment of @ceilingcat

```
type T=Int;def f(n:T,d:T)={@annotation.tailrec def g(n:T,d:T,s:T,N:T,D:T):(T,T)=if(d!=0)g(d,n%d,-s,(N<<n/d)+s,D+n/d)else(N,D);val r=(n%d+d)%d;g(d-r,r,1,if(n*d>0|n%d==0)n/d else n/d-1,0)}

```

Ungolfed version. Attempt this online!

```
import scala.io.Source
object Main {
  def f(n: Int, d: Int) = {
    @annotation.tailrec
    def g(n: Int, d: Int, s: Int, N: Int, D: Int): (Int, Int) = {
      // println(s"$n $d $s $N $D")
      if (d != 0) g(d, n % d, -s, (N << (n / d)) + s, D + (n / d)) else (N, D);
    }
    def pythonMod(a: Int, b: Int): Int = ((a % b) + b) % b

    def pythonDiv(a: Int, b: Int): Int = {
      if ((a > 0 && b > 0) || (a < 0 && b < 0)) a / b
      else if (a % b == 0) a / b
      else a / b - 1
    }

    val q = pythonDiv(n, d);
    val r = pythonMod(n, d);
    g(d - r, r, 1, q, 0)
  }

  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().toList

    for (line <- lines) {
      val Array(i, o) = line.split("->")
      val nums = i.split("/").map(_.trim.toInt)
      val result = f(nums(0), nums(1))
      println(s"${nums.mkString("/")}, $result, $o")
    }
  }
}

```
> 1 votes

# Answer
# Python3, 217 bytes:

```
C=lambda n,d:[n//d]+C(d,n-d*(n//d))if d else[]
def f(N,d):n=abs(N);c=C(n,d);k=[(c[0],0)]+[(pow(-1,i+1),sum(c[1:i+1])-1)for i in range(1,len(c))];b=max(B for _,B in k);return([1,-1][N<0]*sum(2**(b-B)*N for N,B in k),b)

```

Try it online!
> 0 votes

# Answer
# Pyth, 46 bytes

```
M?tH+/GHgH%GH]GJtstKgEE+*hK^2JaF_m^2-Jtsd._tKJ

```

Try it online!

### Explanation

First we define `g(G,H)` to find the continued fraction of its input.

```
M                  # define g(G,H)
 ?tH               # if (H != 1):
    +/GH           #   prepend floor(G/H) to
        gH%GH      #   recurse on g(H, G%H)
                   # else:
             ]G    #   return [G]

```

Then we compute the function

```
    KgEE                           # assign K to g applied to two inputs
Jtst                               # assign J to sum(K[:-1]) - 1
                          ._tK     # all prefixes of K[:-1]
                  m                # map on lambda d
                   ^2              #   2 to the power of
                     -J            #   J minus
                       tsd         #   sum(d) - 1
               aF_                 # take the alternating sum
        +                          # add to this
            ^2J                    # 2 ^ j
         *hK                       # times K[0]
                              J    # print(J)

```
> 0 votes

---
Tags: code-golf, math, binary, rational-numbers
---


title: Enumerate all binary trees with n nodes

text:
# Question
Title: Enumerate all binary trees with n nodes
Given an integer n, enumerate all possible full binary trees with n internal nodes. (Full binary trees have exactly 2 children on every internal node). The tree structure should be output as a pre-order traversal of the tree with 1 representing an internal node, and 0 representing an external node (Null).

Here are examples for the first few n:

0:
0

1:
100

2:
11000
10100

3:
1110000
1101000
1100100
1011000
1010100

This is a code golf with the prize going to fewest characters. The trees should be output one per line to stdout. The program should read n from the commandline or stdin.

# Answer
> 3 votes
## Perl - 125 79 chars

Count includes 4 chars for "`-ln`" options. Takes n from stdin.

New constructive approach:

```
@a=0;map{%a=();map{$a{"$`100$'"}=1while/0/g;}@a;@a=keys%a}1..$_;print for@a

```

Form the solution for n by substituting a new internal node ("100") for each leaf ("0"), in turn, in each tree from the solution for n-1.

(I owe this concept to other's solutions that use the internal node to leaf \[100-\>0\] substitution for verifying sequentially-generated strings, and I believe I saw--after writing my answer based on that concept--this same 0-\>100 method of construction in someone's intermediate edit.)

Previous recursive approach:

```
sub t{my$n=shift;if($n){--$n;for$R(0..$n){for$r(t($R)){for$l(t($n-$R)){push@_,"1$l$r"}}}}else{push@_,"0"}@_}print for t$_

```

Recursive ungolfed:

```
sub tree {
  my ($n) = @_;
  my @result = ();
  if ( $n ) {
    for $right_count ( 0 .. $n-1 ) {
      for $right ( tree( $right_count ) ) {
        for $left ( tree( ($n-1) - $right_count ) ) {
          push @result, "1$left$right";
        }
      }
    }
  }
  else {
    push @result, "0";
  }
  return @result;
}
foreach $tree ( tree($_) ) {
  print $tree;
}

```

# Answer
> 2 votes
## PHP (142) (138) (134) (113)

Runs from the command line, i.e. "php golf.php 1" outputs "100".

EDIT: Cut 4 characters with an alternate method, building up the strings from 0 rather than recursing down from $n. Uses PHP 5.3 for the shortened ternary operator; otherwise, 2 more characters are needed.

EDIT 2: Saved 4 more characters with some changes to the loops.

EDIT 3: I was trying a different approach and I finally got it below the old method.

All of the trees can be considered as binary representations of integers between 4^n (or 0, when n=0) and 2\*4^n. This function loops through that range, and gets the binary string of each number, then repeatedly reduces it by replacing "100" with "0". If the final string is "0", then it's a valid tree, so output it.

```
for($i=$p=pow(4,$argv[1])-1;$i<=2*$p;){$s=$d=decbin($i++);while($o!=$s=str_replace(100,0,$o=$s));echo$s?:"$d\n";}

```

# Answer
> 2 votes
### Ruby, 99 94 92 89 87 characters

```
(n=4**gets.to_i).times{|i|s=(n+i-1).to_s 2;t=s*1;0while s.sub!'100',?0;puts t if s==?0}

```

The input is read from stdin.

```
> echo 2 | ruby binary_trees.rb
10100
11000

```

*Edit 1:* Changed IO (see Lowjacker's comments)

```
b=->n{n==0?[?0]:(k=[];n.times{|z|b[z].product(b[n-1-z]){|l|k<<=?1+l*''}};k)}
puts b[gets.to_i]

```

*Edit 2:* Changed algorithm.

```
b=->n{n==0?[?0]:(k=[];b[n-1].map{|s|s.gsub(/0/){k<<=$`+'100'+$'}};k.uniq)}
puts b[gets.to_i]

```

*Edit 3:* The version now takes the third approach (using the idea of migimaru).

*Edit 4:* Again two characters. Thank you to migimaru.

# Answer
> 1 votes
## Ruby 1.9 (80) (79)

Using the non-recursive, constructive approach used by DCharness.

EDIT: Saved 1 character.

```
s=*?0;gets.to_i.times{s.map!{|x|x.gsub(?0).map{$`+'100'+$'}}.flatten!}
puts s&s

```

# Answer
> 0 votes
## Haskell 122 chars

```
main=do n<-readLn;mapM putStrLn$g n n
g 0 0=[['0']]
g u r|r<u||u<0=[]
g u r=do s<-[1,0];map((toEnum$s+48):)$g(u-s)(r-1+s)

```

Since the IO is a non-trivial portion of the code in haskell, maybe someone can use a similar solution in another language. Essentially random walks in a square from bottom left to top right stopping if the diagonal is crossed. Equivalent to the following:

```
module BinTreeEnum where

import Data.List
import Data.Monoid

data TStruct = NonEmpty | Empty deriving (Enum, Show)
type TreeDef = [TStruct]

printTStruct :: TStruct -> Char
printTStruct NonEmpty = '1'
printTStruct Empty = '0'

printTreeDef :: TreeDef -> String
printTreeDef = map printTStruct

enumBinTrees :: Int -> [TreeDef]
enumBinTrees n = enumBinTrees' n n where
  enumBinTrees' ups rights | rights < ups = mempty
  enumBinTrees' 0   rights = return (replicate (rights+1) Empty)
  enumBinTrees' ups rights = do
    step <- enumFrom (toEnum 0)
    let suffixes =
          case step of
            NonEmpty -> enumBinTrees' (ups - 1) rights
            Empty -> enumBinTrees' ups (rights - 1)
    suffix <- suffixes
    return (step:suffix)

mainExample = do
  print $ map printTreeDef $ enumBinTrees 4

```

# Answer
> 0 votes
## Golfscript, 60 83

```
~[1,]\,{;{[:l.,,]zip{({;}{~:a;[l a<~1 0.l a)>~]}if}/}%}/{n}%

```

I built a golfscript mode for Emacs for working on this, if anyone's interested.

# Answer
> 0 votes
# Haskell, 54 bytes

```
t 0=["0"]
t n=['1':l++r|m<-[0..n-1],l<-t m,r<-t$n-1-m]

```

Try it online!

# Answer
> 0 votes
# Scala, 115 bytes

It reminds me of Catalan number.

---

Golfed version. Try it online!

```
n=>n match{case 0=>Seq("0");case _=>(for(m<-0 until n)yield{for{l<-t(m);r<-t(n-1-m)}yield "1"+l+r}).toList.flatten}

```

Ungolfed version. Try it online!

```
object Main {
  def t(n: Int): List[String] = n match {
    case 0 => List("0")
    case _ =>
      (for (m <- 0 until n) yield {
        for {
          l <- t(m)
          r <- t(n - 1 - m)
        } yield "1" + l + r
      }).toList.flatten
  }

  def main(args: Array[String]): Unit = {
    (0 to 3).foreach(n => println(t(n)))
  }
}

```

---
Tags: code-golf, combinatorics, binary-tree
---


title: Playing the Name Game

text:
# Question
Title: Playing the Name Game
Write a program to play the name game.

**Input**

Your program should accept a single name as input from the user in some way (e.g read from standard input or as a command-line argument). You can assume that the name is a single word consisting of an upper case letter followed by one or more lower case letters.

**Output**

Your program must print the rhyme for the given name, as explained in the song, by filling out the following template:

```
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!

```

Here, `(X)` is the original name, and `(Y)` is the name in lower case with any initial consonants removed.

There is one exception, however. If the original name began with `m`, `f` or `b`, it should be written without this letter on the corresponding line. E.g. if the name was `Bob`, the "b" line should end with `bo-ob`. Note that in this case, any other consonants are kept, so for `Fred` it's `fo-red`, not `fo-ed`.

**Examples**

Shirley:

```
Shirley, Shirley, bo-birley
Banana-fana fo-firley
Fee-fi-mo-mirley
Shirley!

```

Arnold:

```
Arnold, Arnold, bo-barnold
Banana-fana fo-farnold
Fee-fi-mo-marnold
Arnold!

```

Bob:

```
Bob, Bob, bo-ob
Banana-fana fo-fob
Fee-fi-mo-mob
Bob!

```

Fred:

```
Fred, Fred, bo-bed
Banana-fana fo-red
Fee-fi-mo-med
Fred!

```

**Scoring**

Shortest code wins.

# Answer
> 4 votes
## vi, 118 115

```
Y2PA,<ESC>Ypj~Y2PIbo-b<c-o>wBanana-fana fo-f<c-o>wFee-fi-mo-m<c-o>2$!<ESC>HJJ:%s/\vo-(([bfm])\2([^aeiou]*))?([bfm]?)[^aeiou]*/o-\3\4
ZZ

```

The code includes 5 control characters, which I've put in brackets. Each only counts as a single character towards the character count.

EDIT: Moving the first join (J) to later and changing the paste-before (P) to a paste-after (p) saved me 1 character. Also, not capturing the o- in the regex saved me 2 more characters.

# Answer
> 4 votes
# SNOBOL4, ~~437~~ 430 bytes

```
 N = TRIM(INPUT)
 D = REPLACE(N,'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
+'abcdefghijklmnopqrstuvwxyz')
 B = "b" D
 F = "f" D
 M = "m" D
 &ANCHOR = 1
 D SPAN('bcdfghjklmnpqrstvwxyz') . I REM . R :F(Y)
 B = "b" R
 F = "f" R
 M = "m" R
 I "b" :S(U)
 I "f" :S(V)
 I "m" :S(W) F(Y)
U D "b" REM . B :(Y)
V D "f" REM . F :(Y)
W D "m" REM . M
Y OUTPUT = N ", " N ", bo-" B
 OUTPUT = "Banana-fana fo-" F
 OUTPUT = "Fee-fi-mo-" M
 OUTPUT = N "!"
END

```

Ungolfed (plus I added a prompt; the one above just waits for a name to be typed):

```
      OUTPUT = "Please enter your name."
      Name = TRIM(INPUT)
      UC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      LC = 'abcdefghijklmnopqrstuvwxyz'
      Low = REPLACE(Name, UC, LC)
      BName = "b" Low
      FName = "f" Low
      MName = "m" Low
      Consonants = SPAN('bcdfghjklmnpqrstvwxyz')
      &ANCHOR = 1
      Low Consonants . First REM . Rest  :F(READY)
      BName = "b" Rest
      FName = "f" Rest
      MName = "m" Rest
      First "b"                   :S(BINIT)
      First "f"                   :S(FINIT)
      First "m"                   :S(MINIT) F(READY)
BINIT Low "b" REM . BName         :(READY)
FINIT Low "f" REM . FName         :(READY)
MINIT Low "m" REM . MName
READY OUTPUT = Name ", " Name ", bo-" BName
      OUTPUT = "Banana-fana fo-" FName
      OUTPUT = "Fee-fi-mo-" MName
      OUTPUT = Name "!"
END

```

This is the first SNOBOL program I've ever written.

SNOBOL is a line-oriented language, like FORTRAN, COBOL, or BASIC. Each line consists of an optional label starting in column 1, the code for the line which can involve assignments and pattern matching, and an optional branch. Yes, lines end with (optional) GOTOs. They come in two forms:

```
        :(TARGET)

```

Branches to label `TARGET`, while

```
        :S(SUCCESS) F(FAILURE)

```

Branches to `SUCCESS` if the pattern match succeeded, or `FAILURE` otherwise. You can also just branch on success and fall through to the next line on failure, or vice versa.

Continuation lines begin with a `+` or `.`. Comments begin with a `*`.

### How does it work?

Read in a name, convert it to lower case. Set up the B-, F-, and M-names assuming it begins with a vowel. Then check if it begins with a span of consonants. If not, we're ready to go! If so, strip the leading consonants and set up the B-, F-, and M-names assuming it doesn't begin with any of those letters. Finally, check if it starts with each of those letters in turn, fixing up the names as needed. Then we're ready to play the name game!

Sample run:

```
 # $RUN *SNOBOL4 5=GOLF.SNO+*SOURCE* 6=*DUMMY*(1,28)+*SINK*(1,4)+*DUMMY*
 # Execution begins   16:57:25
   Snowman
   Snowman, Snowman, bo-bowman
   Banana-fana fo-fowman
   Fee-fi-mo-mowman
   Snowman!
 # Execution terminated   16:57:30  T=0.013

```

I ran this on the Hercules S/370 mainframe emulator running the 6.0a release of the Michigan Terminal System using SNOBOL4 version 3.10 from April 1, 1973 built for MTS on May 1, 1975, but there are probably easier ways to run SNOBOL4 on a modern system. :)

**Edit:** Removed a redundant success branch that was equivalent to a fallthrough (I didn't realize I could put just a failure branch by itself) which eliminates an unneeded branch label, and turned an unconditional goto into a failure branch on the prior line, for a savings of 7 bytes.

Now that TIO has SNOBOL4 support you can Try it online! Note: It shows the size as 429 rather than 430 because when I pasted it there, the final linefeed got removed. I tried changing the continuation line (the one beginning with `+`) to a single line, which wasn't legal on the mainframe version because the line was too long, and it worked and brought it down to 427. Obviously CSNOBOL4 allows longer lines. I'm going to leave my score at 430, though, because that's how many bytes the script was on my machine, and besides, SNOBOL is pretty non-competitive.

# Answer
> 2 votes
## , 149 characters

```
1!:2&2>|.(n,'!');('Fee-fi-mo-';'Banana-fana fo-';n,', ',n,', bo-'),&.>;/'mfb'(,`(}.@])`($:}.)@.((=+.2*5='aeiou'i.]){.)"0 _)a.{~32(23 b.)a.i.n=.1!:1]3

```

# Answer
> 2 votes
**Javascript, 115 Bytes**

```
r=x=>x.match(/[aeiou]\w*/i)[0];f=x=>`${x}, ${x}, bo-b${r(x)}\nBanana-fana fo-f${r(x)}\nFee-fi-mo-m${r(x)}\n${x}!`

```

Explanation:

this function returns the name without the initial consonants

```
r=x=>x.match(/[aeiouAEIOU]\w*/)[0]

```

Then the rest is a function returning the string complete string.

```
f=x=>`${x}, ${x}, bo-b${r(x)}\nBanana-fana fo-f${r(x)}\nFee-fi-mo-m${r(x)}\n${x}!`

```

Edit: from 119 to 115 bytes thanks to @Martin Ender

# Answer
> 1 votes
## Clojure, 292 characters after minimizing

Here's a first attempt, almost positive I can widdle it down further:

```
(defn name-game
  [n]
  (let [[b f m] (map (fn [x] (if (some #(= % (first n) (last x)) "bfm")
                              (str (apply str (butlast x)) (apply str (rest n)))
                              (str x (apply str (drop-while (fn [x] (not (some #(= % x) "aeiou"))) n))))) [", bo-b" "\nBanana-fana-fo-f" "\nFee-fi-mo-m"])]
    (str n ", " n b f m "\n" n "!")))

```

I'm just learning clojure and thought it'd be fun to give this a shot. Here's my reasoning:

> \- To strip off consonants from beginning of string: `(drop-while (fn [x] (not (some #(= % x) "aeiou"))) name)`
> \- To handle the extra rules for "b", "f" and "m", I broke text into list of phrases: `[", bo-b" "\nBanana-fana-fo-f" "\nFee-fi-mo-m"]`
> \- Then, I applied a function that asks whether the phrase ends with the same letter that the name starts with, and used that to transform those 3 phrases based on the rules of the puzzle
> \- Final step is to build a string with results

# Answer
> 1 votes
### Scala 281

I replaced (X) and (Y) in the pattern with `#` and `012`. `S` is just a new name for `String` and `a(b,c,d)` is shorthand definition for `b.replaceAll(c,d)`

```
val v="""#, #, bo-b0
Banana-fana fo-f1
Fee-fi-mo-m2
#!"""
type S=String
def a(b:S,c:S,d:S)=b.replaceAll(c,d)
def r(t:S,n:S,i:Int)=if(n(0)=="bfm"(i).toUpper)a(t,"."+i,n.tail)else
a(t,""+i,a(n,"^[^AEIOUaeiou]*([aeiou].*)","$1")).toLowerCase
def x(n:S)=a(r(r(r(v,n,0),n,1),n,2),"#",n)

```

Test invocation:

```
val l = List ("Shirley", "Arnold", "Bob", "Fred")
for (n <- l) println (x (n) + "\n")

```

And ungolfed:

```
val templ = """#, #, bo-b0
Banana-fana fo-f1
Fee-fi-mo-m2
#!"""

val names = List ("Shirley", "Arnold", "Bob", "Fred")
val keys = "bfm"

def recode (template: String, n: String, i: Int) =
 if (n(0) == keys(i).toUpper)
   template.replaceFirst ("." + i, n.tail) else
 template.replaceAll ("" + i, (n.replaceAll ("^[^AEIOUYaeiouy]*([aeiou].*)", "$1").toLowerCase))

for (name <- names)
  println (recode (recode (recode (templ, name, 0), name, 1), name, 2).replaceAll ("#", name) + "\n")

```

# Answer
> 1 votes
# Python 3, ~~148~~ ~~145~~ 142 bytes

*Yes I know it's a little late but...*

```
n=input();i=0
r=n[i:].lower()
while n[i]not in'aeiouAEIOU':i+=1;r=n[i:]
print(f'{n}, {n}, bo-b{r}\nBanana-fana fo-f{r}\nFee-fi-mo-m{r}\n{n}!')

```

It uses the new f-strings to format the resulting string.

I don't think TIO supports f-strings yet, unfortunately.

**Old Version**

```
def f(n,i=0):
 r=n[i:].lower()
 while n[i].lower()not in'aeiou':i+=1;r=n[i:]
 return f'{n}, {n}, bo-b{r}\nBanana-fana fo-f{r}\nFee-fi-mo-m{r}\n{n}!'

```

*Saved 3 bytes thanks to @officialaimm*

# Answer
> 1 votes
# Sed, 162 bytes

```
sed 'h;G;G;G' |sed '1s/.*/&, &, bo-b\L&/i;2s/^.*/Banana-fana fo-f\L&/;3s/^.*/Fee-fi-mo-m\L&/;4s/$/!/;tx;:x;s/o-\([bfm]\)\1/o-/i;tz;s/\(o-[bfm]\)[^aeiou]\+/\1/;:z'

```

I did not know sed very well before I did this. I, uh, know it a *lot* better, now. The first sed in the pipeline duplicates the name three times so it becomes "Bob\nBob\nBob\nBob" instead of just "Bob". The next sed does the heavy lifting.

Expects input on stdin like `echo Name |sed ...`

Ungolfed:

```
sed 'h                           ;# copy to hold buffer
G                                ;# append newline + hold buffer to pattern
G                                ;# ditto for next two G's
G' |sed '1s/.*/&, &, bo-b\L&/i   ;# 1st line -> X, X bo-bx (lowercase)
2s/^.*/Banana-fana fo-f\L&/      ;# 2nd line -> Banana-fana fo-fx
3s/^.*/Fee-fi-mo-m\L&/           ;# 3rd line -> Fee-fi-mo-mx
4s/$/!/                          ;# bang the 4th line!
tx                               ;# jump to :x if any s/// has matched
:x                               ;# spoiler alert: it has! reset t-flag
s/o-\([bfm]\)\1/o-/i             ;# match some o-cc where c = [bfm]
tz                               ;# if that matched, branch to :z
s/\(o-[bfm]\)[^aeiou]\+/\1/      ;# replace o-[bfm] plus consonants with o-[bfm]
:z                               ;# target of tz, skips over previous s///'

```

A couple of notes. The first four matches, 1s, 2s, 3s, 4s, transform the output into something not quite correct. Bob has become bo-bbob, Fred has become fo-ffred, and Mike has become mo-mmike. Kay would become mo-mkay, mkay?

Then, we need to replace either bo-bbob with bo-ob, or bo-bkay with bo-bay. To do that, we can use a feature where we do one s/// substitution, and then branch if it succeeded, jumping over the second one that we now want to skip. But if it missed, we want to fall through the branch and do the next substitution.

The t\[label\] command does that, branching only if a previous s/// matched. But at the beginning of the script I already did one s/// for each line (the leading numbers in 1s, 2s, etc. are addresses; they mean the command is only performed if the address matches). So no matter what line we're on, 1, 2, 3, or 4, at least one s/// has matched. (I tried doing it the other way around, massaging the names and then adding the "Banana-etc." after, but got stuck that way, and trying to do it all at once would cause some repetition.) Fortunately, the flag can be cleared by taking a branch, so we do that with "tx ; :x". tx branches to the x label, and :x is the x label.

Whew! That clears the palate for the final two substitutions. We try one, and if it succeeds we branch over the other, otherwise we do the second one. Either way we end up at the :z label and the pattern buffer contains one line of lyrics which is printed to stdout.

Thanks for tricking me into spending enough time with the sed man page and Texinfo manual to finally understand how do to more than sed s/foo/bar/

# Answer
> 1 votes
# Go, ~~193~~ ~~186~~ 173 bytes

```
import(."fmt";."regexp")
func f(s string){y:=MustCompile(`^[^AEIOUaeiou]+`).ReplaceAllString(s,"")
Printf(`%s, %s, bo-b%s
Banana-fana fo-f%s
Fee-fi-mo-m%s
%s!`,s,s,y,y,y,s)}

```

Attempt This Online!

Prints to STDOUT.

* -7 bytes by not using explicit indexes
* -13 bytes by @The Thonnu by not using the `strings` package

# Answer
> 0 votes
**Python, 161**

```
x=raw_input('')
a,b,c=x[0],x[1:],'bfm'
if b[0] in c:b=b[1:]
d="X, X, bo-@\nBanana-fana fo-@\nFee-fi-mo-@\nX!".replace('X',a)
for y in c:d=d.replace('@',y+b,1)
print d

```

Just realised my code fails...
\- Doesn't remove initial constonants.
\- Doesn't manage the 'bo-ob' business.

It's the furthest I got, maybe somebody can finish it.

# Answer
> 0 votes
# Groovy, 146

```
r={n->m={n[0]==it[0]?n[1..-1]:it[1]+(n.toLowerCase()=~'[aeiou].*')[0]};"$n, $n, bo-${m 'Bb'}\nBanana-fana fo-${m 'Ff'}\nFee-fi-mo-${m 'Mm'}\n$n!"}

assert ['Shirley', 'Arnold', 'Bob', 'Fred'].collect { r(it) } == [
'''Shirley, Shirley, bo-birley
Banana-fana fo-firley
Fee-fi-mo-mirley
Shirley!''',
'''Arnold, Arnold, bo-barnold
Banana-fana fo-farnold
Fee-fi-mo-marnold
Arnold!''',
'''Bob, Bob, bo-ob
Banana-fana fo-fob
Fee-fi-mo-mob
Bob!''',
'''Fred, Fred, bo-bed
Banana-fana fo-red
Fee-fi-mo-med
Fred!'''
]

```

# Answer
> 0 votes
# R, 189 chars

```
x=scan(,'');f=function(b)if(grepl(b,x))sub('.','',x)else tolower(sub('^[^aoueiy]*',b,x,i=T));cat(sprintf('%s, %1$s, bo-%s\nBanana-fana fo-%s\nFee-fi-mo-%s\n%1$s!\n',x,f('B'),f('F'),f('M')))

```

But with just one more character, you can entry many names in one go:

```
x=scan(,'');f=function(b)ifelse(grepl(b,x),sub('.','',x),tolower(sub('^[^aoueiy]*',b,x,i=T)));cat(sprintf('%s, %1$s, bo-%s\nBanana-fana fo-%s\nFee-fi-mo-%s\n%1$s!\n',x,f('B'),f('F'),f('M')))

```

# Answer
> 0 votes
# Pyth, 111 bytesSBCS

```
V"BFM"IqhzN=aYtrz0.?=aY+rN0:rz0"^[^aeiou]+"k))+%." sÞXY:lÍ"*]z2@Y0+." o1}1ÃÐ¬ÛJî½"@Y1+."-o Âkq°ë¹è"@Y2+z\!

```

**Test suite**

### Code uses unprintable characters, and as such does not display properly on Stack Exchange. The link provided contains these characters and is the correct version of the program.

# Answer
> 0 votes
# Perl 5 `-na`, 93 bytes

```
s/^[FMB]//||s/^[^aeiou]*//i;$,=$_.$/;say"@F, @F, bo-b","Banana-fana fo-f","Fee-fi-mo-m","@F!"

```

Try it online!

# Answer
> 0 votes
# Japt, ~~55~~ 54 bytes

```
+Si,)²+`¾-b
Ba-fa fo-f
Fee-fi-¶-m
{U}!`rRRiUv e"^%c

```

Try it

```
+Si,)²+`¾...{U}!`rRRiUv e"^%c     :Implicit input of string U
+                                 :Append
 S                                :  Space
  i,                              :  Prepend ","
    )                             :End append
     ²                            :Duplicate
      +                           :Append
       `¾...   !`                 :Compressed string "bo-b\nBanana-fana fo-f\nFee-fi-mo-m\n...!"
            {U}                   :Interpolate U
                 r                :Replace
                  R               :  Newline with
                   Ri             :    Prepend newline with
                     Uv           :      U lowercased
                        e"^%c     :      Recursively replace RegEx /^[^aeiou]/i

```

# Answer
> 0 votes
# JavaScript, 100 bytes

```
s=>s+`, ${s}, bo-b${t=/[aeiou].+/.exec(s.toLowerCase())}
Banana-fana fo-f${t}
Fee-fi-mo-m${t}
${s}!`

```

Try it online!

# Answer
> 0 votes
# Haskell, 151 bytes

```
z x|let y=last$(snd$break(`elem`"AEIOUaeiou")x):[tail x|elem(x!!0)"BFM"]=unlines[x++", "++x++", bo-b"++y,"Banana-fana fo-f"++y,"Fee-fi-mo-m"++y,x++"!"]

```

Try it online!

# Haskell, 152 bytes

```
z x|let y=last$dropWhile(`notElem`"AEIOUaeiou")x:[tail x|elem(x!!0)"BFM"]=unlines[x++", "++x++", bo-b"++y,"Banana-fana fo-f"++y,"Fee-fi-mo-m"++y,x++"!"]

```

Try it online!

# Answer
> -1 votes
# Python

```
n=raw_input('')
if n[0].lower() in ("m", "f", "b"): r=n[1:]
else:
    i = iter(n.lower())
    for a in range(len(n)):
        if i.next() in ("a","e","i","o","u"):
            r = n[a:]
            break
print "%s, %s, bo-b%s\nBanana-fana fo-f%s\nFee-fi-mo-m%s\n%s!" %(name,name,rhyme,rhyme,rhyme,name)

```

---
Tags: code-golf
---