title: A British find-a-movie challenge

text:
# Question
Title: A British find-a-movie challenge
This is a more difficult version of It's a find-a-movie challenge .

**Input**

Your code should take a BBFC rating and a number from 1 to 5 as input. It can do this in any way you find convenient.

**Output**

Your code should return the name of any movie which has a) that film rating and b) that number of stars in a Guardian film review.

If there is no such movie it can output anything you like.

The possible BBFC film ratings are `U, PG, 12, 12A, 15, 18, R18, TBC`.

Your code may report one or more movies, that is up to you.

To clarify, your code is meant to access the web to get the answers to queries.

**Example**

Say the input is `U, 5` then your code could output "My Neighbour Totoro".

Please show an example of your code working with the film rating `PG` and score `4` along with your answer.

**Notes**

The Guardian does have an API but this requires registration. For this challenge you may not use it.

**Example code**

The following Python 3 code gets all the movies along with their score out of 5, although not 100% perfectly.

```
from bs4 import BeautifulSoup
import requests
import sys

for i in range(1,837):
    print("Page", i,file=sys.stderr)
    result = requests.get("https://www.theguardian.com/film+tone/reviews?page={0}".format(i))
    data = result.text
    soup = BeautifulSoup(data, "lxml")

    tags = soup.find_all("div", {"class":"stars"})

    for tag in tags:
        stars = 0
        for star in tag.find_all("span", {"class":"star__item--grey"}):
            stars +=1
        main = tag.parent
        title = main.find("h2")
        if title:
            a = title.find("span", {"class":"js-headline-text"})
            print("{} - {}".format(5 - stars, a.text))

```

# Answer
> 3 votes
# NodeJS

I'm an awful golfer tho

The inputs must be passed like this `node filename 12,12A,15,18 4` for fetching a movie with one of the ratings comma separated and at least 4 stars

```
var fetch=require('node-fetch');
var {JSDOM, VirtualConsole}=require('jsdom');

var f=x=>fetch(x).then(r=>r.text());
var vc = new VirtualConsole(); // ignore annoying css errors
var [bbfc='U,PG,12',stars='3']=process.argv.slice(2);

var Z=async()=>{
    for(var i=0;i<10;i++){ // 10 max pages, can be anything
        var t= await f(`https://www.theguardian.com/film+tone/reviews?page=${i}`);
        var w=new JSDOM(t, {virtualConsole:vc}).window;
        for(var h of w.document.querySelectorAll('.fc-item__header')){
            if (h.querySelectorAll('.star__item--golden').length>=stars){
                var title=h.querySelector('.js-headline-text').textContent.split(' review')[0].trim();
                var t=await f('http://www.bbfc.co.uk/search/releases/'+title);
                var rating=t.match(/BBF\w_(\w+)_/)[1];
                if(bbfc.includes(rating)) return title;
            }
        }
    }
};

Z()
.then(console.log)
.catch(console.error)

```

# Answer
> 2 votes
# Javascript/JQuery - ~~517~~ ~~504~~ 494 bytes

Not really golfed at all, just wanted to write an answer.

```
x=>y=>{t=n=i=1;f=()=>{if(t){$.get("https://www.theguardian.com/film+tone/reviews?page="+i,d=>{l=$(d).find("div.stars").toArray().slice(1);for(k=0;k<l.length&&t;k++){((j,m)=>($.get('http://www.bbfc.co.uk/search/releases/'+encodeURI(n=$(m[j].parentNode).find("h2 span.js-headline-text").text().split(" review")[0]),(p=>b=>{if(/BBFC_(.*?)_/.exec($(b).find(".symbol img")[0].src)[1]==y&&$(m[j]).find(".star__item--golden").length==x){if(t)alert(p);t=0}})(n))))(k,l)}});i++;setTimeout(f,2000)}};f()}

```

It waits 10 sec before trying another page to stop the program from doing too many requests concurrently, so it may take some time with some inputs.

## Examples:

# Answer
> 1 votes
# Python + BS4 - 631 bytes

Lembik wanted a Python answer so he could run it, so I made one, but its way longer.

```
from bs4 import BeautifulSoup as b
import requests
def f(x,y):
 i=n=1
 while 1:
  for m in b(requests.get("https://www.theguardian.com/film+tone/reviews?page="+`i`).text,'lxml').find_all('div',{'class':'stars'}):
         a=m.parent.find('h2')
         if a:
          e=a.find('span',{'class':'js-headline-text'}).text.split(" review")[0]
          s=b(requests.get('http://www.bbfc.co.uk/search/releases/'+requests.utils.quote(e)).text,'lxml').find("p",{"class":"symbol"})
          if s and s.find("img").get('src').split("BBFC_")[1].split("_")[0]==y and len(m.find_all('span',{'class':'star__item--golden'}))==x:return e
  i+=1

```

---
Tags: code-golf, internet
---


title: Make the PPCG Favicon

text:
# Question
Title: Make the PPCG Favicon
Come November 1, Programming Puzzles and Code Golf will graduate, so in the next 11 months, we'll want to save some memories from when we were ungraduated.

Write a program that produces the PPCG favicon, seen below.

* The image must be at least 64x64 pixels.
* The blue must be the color #62B0DF. The background can be white or a light gray.
* The image need not be pixelated like it is here.
* Alternatively, create text (with dimensions at least 64x64 non-whitespace characters) using standard bright ANSI color codes of Cyan and White.
* Built in images and importing the PPCG logo are not allowed.

---

This is code golf, so standard rules apply. Shortest code in bytes wins.

# Answer
# Bash (OSX), ~~33~~ ~~27~~ ~~23~~ 18 Bytes

You heard the man, any way we like.

```
open http:yon.se/q
```

~~I am aware that this is a popularity contest. But hey, when you can code golf it, why not?~~

It is now a code golf. \o/ This was valid at the time of posting.

>

There was even an exception made for me at some point! But, as @AlexA. pointed out...

> "*You can use whatever methods you want (except loading the image, with the exception of VoteToClose's response)*" It isn't fair to allow exceptions for specific users/answers. - Alex A.

I agree with this, and, as of such, do not wish this to be picked as the answer. Doesn't mean I won't still try to golf it down more. ;)

Thanks to @ΚριτικσιΛίθος for shaving off 6 bytes with a fancy short URL!

Thanks to @ev3commander for shaving off ANOTHER 5 bytes with an even fancier, shorter URL!

Thanks to @kennytm for pointing out that I can reduce the protocol size *and* remove the quotes, saving me another 4 bytes!
> 18 votes

# Answer
# BitShift, 2795 bytes

```
10100110010101101001010111001010110100101011100101011010010101110010101101001010111001010110100101011100101011010010101110010101101001010111001010110100101011100101011010010101110010101101111011101010000000110101001011010100011010100010101101010010101101010010101101010010101101010010101101010010101101010011010100101101010001101010010110101001100110010101111111001010111010100101011010100101011010100101011010100101011010100101011010100101011010100101011010100101011001010110100101011001100110101000000011010100010101101010010101101010010101101010010101101010010101101010010101101010010101101010010101101010011010100101101010011001100101011111110010101110101001010110101001010110101001010110101001010110101001010110101001010110101001010110101001010110010101101001010110011001101010000000110101000101011001010110100101011100101011101010010101101010011010100101101010001010110101001010110010101101001010111001010111010100110101001011010100110011001010111111100101011101010011010100010101101010011010100010101100101011101010010101100101011101010011010100010101101010010101101010011010100101101010011001100101011111110010101110101001101010010110101000110101000101011010100110101000101011010100101011010100110101000101011001010110100101011101010011010100101101010011001100101011111110010101110101001101010001010110101001010110101001101010001010110101001101010001010110010101110101001010110010101110101001101010010110101001100110010101111111001010111010100110101000101011010100101011010100101011001010110100101011101010010101101010011010100101101010001010110101001101010010110101001100110010101111111001010111010100101011010100101011010100101011010100101011010100101011010100101011010100101011010100101011001010110100101011001100110101000000011010100101101010001010110101001010110101001010110101001010110101001010110101001010110101001010110101001101010010110101000110101001000010001010111111100101011010010101110010101110101001010110101001010110101001010110101001010110101001010110101001010110010101101001010111001010110100101011001100110101000000011010100101101010001101010010110101000110101001011010100011010100101101010001101010001010110101001010110010101101001010111001010110100101011100101011010010101110010101101111011101010000000110101001011010100011010100101101010001101010010110101000110101001011010100011010100010101101010011010100101101010001101010010110101000110101001011010100011010100101101010011001100101011111110010101101001010111001010110100101011100101011010010101110010101101001010111001010111010100110101001011010100011010100101101010001101010010110101000110101001011010100011010100100001000101011111110010101101001010111001010110100101011100101011010010101110010101101001010111001010110100101011100101011010010101110010101101001010111001010110100101011100101011010010101110010101

```

This outputs

```
   @@@@@@@@@@@@
 @@@@@@@@@@@@@@@@
 @@@@@@@@@@@@@@@@
 @@@@@@@@@@@@@@@@
 @   @@@  @@@   @
 @ @@ @ @@ @ @@@@
 @   @@ @@@@ @  @
 @ @@@@ @@ @ @@ @
 @ @@@@@  @@@  @@
 @@@@@@@@@@@@@@@@
  @@@@@@@@@@@@@@
   @@@@@@@@@@@@
         @@@
         @@
         @

```

This is probably the shortest code with which you can actually still recognize the logo... I created a terrible language :(

Try it here

**Note**
This was submitted before the rules were changed, by the current rules this answer is invalid. I will leave it here to perhaps inspire people
> 12 votes

# Answer
# JavaScript

*Note: This answer was made before the rules were **significantly** changed so this answer is **not** competing.*

---

This prints in into the your browser console, through some crazy and awesome string processing.

I've made a shorter version of this but I can't seem to find it anywhere.

**Chrome/Firefox**

This version just doubles up on each pixel so it looks more proportional

```
var a = `<long_string_here>`;
console.log.apply(console, [].concat.apply( [Array(+a.split('\n')[1].split(' ')[1] ).join(' ').split(' ').map(function(l){return'%c█'.repeat(+a.split('\n')[1].split(' ')[0]).repeat(2)}).join('\n')], a.split`
`.slice(3).map(function(l){return [].concat.apply([], l.match(/\d+ \d+ \d+/g).map(function(l){return [l.replace(/(\d+) (\d+) (\d+)/,"color:rgb($1,$2,$3)"),l.replace(/(\d+) (\d+) (\d+)/,"color:rgb($1,$2,$3)")]}))})))

```

**Safari**

```
var a = `<long_string_here>`;
console.log.apply(console, [].concat.apply( [Array(+a.split('\n')[1].split(' ')[1] ).join(' ').split(' ').map(function(l){return'%c█'.repeat(+a.split('\n')[1].split(' ')[0])}).join('\n')], a.split`
`.slice(3).map(function(l){return l.match(/\d+ \d+ \d+/g).map(function(l){return l.replace(/(\d+) (\d+) (\d+)/,"color:rgb($1,$2,$3)")})})))

```

---

The `long_string_here` is an *ppm*, I wrote this script a while back to print an arbitrary image **to the console**.

---

How does this work? Well JavaScript has a feature in `console.log` where you can provide css to style the message.

I the unicode character  and color that the correct color, which is retrieved from the ppm.

---

To display any other image run: `convert my_img.png -resize 50x50 -trim -compress none -blur 1x2 -flatten -background white ppm:-`, then copy the output to `<long_string_here>`

### Full code

Because this is quite massive, I've put the full code in pastebins so you can run them

**Chrome/Firefox:** pastebin

**Safari:** pastebin

---

## Result

Firefox Result

Safari Result
> 12 votes

# Answer
# Ruby with Shoes

```
zoom = 10

Shoes.app(width: 19 * zoom, height: 18 * zoom) {
    background white

    stroke fill '#62B0DF'
    rect 1 * zoom, 1 * zoom, 17 * zoom, 13 * zoom, 3 * zoom

    skew 0, -45
    rect 10 * zoom, 11 * zoom, 5 * zoom, 4 * zoom

    stack(left: 1 * zoom, top: 3 * zoom) {
        para('PCG').style size: (5.66 * zoom).to_i, weight: 700, stroke: white
    }

}

```

Sample output:
> 11 votes

# Answer
## Javascript (ES2015), 199 bytes

*(+72 bytes of CSS)*

My code prints the logo into the `<body>` element of a page through some unicode sequences. Suggestions improving the code are welcome (especially for `0`-pads task)

> Demo (tested on MacOsX/Chrome 46): http://codepen.io/anon/pen/EVBmKN?editors=011

---

**Javascript** (newlines inserted for readability)

```
f=l=>{for(l of[49155,0,0,0,29070,19024,29206,16978,16780,0,0,32769,49155,65311,
65343,65407].map(r=>(1e15+r.toString(2)).slice(-16)))document.body.innerText+=
[...l].map(b=>["▉", " "][b]).join``+"\n"}

```

**CSS**

```
*{letter-spacing:-.1em;font:1em/.96 arial;white-space:pre;color:#62B0DF}

```

---

**Result**

---

**Ungolfed and Explained**

If we consider the original 16x16 PCG icon originally posted, we could encode the information in a binary format.

E.g. the first line would be encoded as `1100 0000 0000 0011` where `[0, 1]` maps to `[blue, white]`. Every binary number can be easily stored in decimal format so `1100 0000 0000 0011` is `49155`. The array

```
[49155,0,0,0,29070,19024,29206,16978,16780,0,0,32769,49155,65311,65343,65407]

```

contains all the information (in decimal format) about each pixel color. Each element of the array represents a line to draw. Note that some lines are `0` (full-blue lines) or their length is less than `16` digits (a line starting with a blue pixel): then we need to right-pad these binary numbers

```
[...].map(r=>(1e15+r.toString(2)).slice(-16))

```

The `map` function add 15 zeroes to the left plus the binary number concatenated. Thus the result is sliced by `16` pixel to the left. Now the array is actually

```
0:  "1100000000000011"
1:  "0000000000000000"
2:  "0000000000000000"
3:  "0000000000000000"
4:  "0111000110001110"
5:  "0100101001010000"
6:  "0111001000010110"
7:  "0100001001010010"
8:  "0100000110001100"
9:  "0000000000000000"
10: "0000000000000000"
11: "1000000000000001"
12: "1100000000000011"
13: "1111111100011111"
14: "1111111100111111"
15: "1111111101111111"

```

Take a look closer at the digits above: we can almost see the PCG logo. :)
*Note that if we store this information in the array, we need to use 16x18 bytes (288 bytes). This approach requires instead 135 bytes*

The next step is draw each line. The construct

```
for(l of [...].map(...))

```

loop over the array `values` (ES6 feature) and we add to the body

```
document.body.innerText += [...l]

```

where `[...l`\] represent the binary string as an array . E.g. the first line would be read as

```
["1", "1", "0", "0" ... , "0", "0", "1", "1"]

```

then again we use `map()` to transform each value:

```
 b=>["▉", " "][b]

```

if the value is `0` then it becomes a `LEFT SEVEN EIGHTHS BLOCK (U+2589)` otherwise it is a space `EM SPACE (U+2003)`. In short this assignment

```
document.body.innerText += [...l].map(b=>["▉", " "][b]).join``+"\n"

```

converts each `0` or `1` either into a squared block or into a space: then the array is joined and, along with a trailing newline sequence, is appended to the body.

The CSS I've used fixes the `line-height` and the `letter-spacing` (I've tested on Chrome, so the result may slightly vary in other browsers)
> 10 votes

# Answer
# Brainfuck, 120148 bytes

### This answer is now non-competitive. This was before the rules were changed, and this has absolutely no hope of winning as code-golf.

Brainfuck code to output hex value of image. Very, very, long.

Here is a pastebin link, and the first couple lines. https://paste.ee/p/LtcCy

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

```
> 7 votes

# Answer
# Javascript ES6, 461 bytes

I need to work on the compression more.

```
x.style.cssText='display:block;font:4px/2px monospace;color:#62B0DF',x.innerHTML=`  28
 38
 31
${a=`5
`.repeat(8)}6   a   a    7
6  8  8 8  8  8  6
6  8  +  7  71
6      +9 6
6  a9 6
6  6a 8  1 6
698   +  6
6  7+   1+    7
${a} 31
 38
  3+
   28
47
46
41+
41
48
4+`[r='replace'](/a/g,'  1')[r](/9/g,'  7  +  ')[r](/8/g,'++')[r](/7/g,11)[r](/6/g,'1++')[r](/5/g,'31+')[r](/4/g,Array(18).join` `)[r](/3/g,21)[r](/2/g,11111111)[r](/1/g,'+++')
```

```
<pre id=x></pre>
```
> 6 votes

# Answer
# Snap, 16 blocks

Tell me if this is invalid.
> 6 votes

# Answer
# Bubblegum, 175 bytes

One of the rare times Bubblegum is useful for !

Run in a terminal that supports ANSI escape codes.

```
0000000: e060 3e00 a75d 000d 97c4 b1da c813 35e1  .`>..]........5.
0000010: 9ebb 75d8 b95a ea28 a23d e9c6 5d80 7ce0  ..u..Z.(.=..].|.
0000020: 8d72 884f 2eb0 23f0 a6dc 406b 5724 9b78  .r.O..#...@kW$.x
0000030: 229d 11b7 29c8 9be6 7b76 26d4 f41a 69e0  "...)...{v&...i.
0000040: e626 1923 061a 07fc 4ca6 3cc9 f947 7760  .&.#....L.<..Gw`
0000050: 86df 1d86 37a8 6825 dd9d a3b4 a050 573c  ....7.h%.....PW<
0000060: 7efa 920a 446d 98f8 eeb9 91f7 f912 ca3b  ~...Dm.........;
0000070: 9360 ddba 3450 30ff cee0 fb32 31d1 06cd  .`..4P0....21...
0000080: 0d46 2f2d 5371 896c 6bb0 5fb8 3d6d f096  .F/-Sq.lk._.=m..
0000090: 67e9 8cb8 f92f 9eaa 7d35 0914 a742 6315  g..../..}5...Bc.
00000a0: 1a62 f54d b969 b980 c832 8a3f 8c00 00    .b.M.i...2.?...

```

Reverse the hexdump with `xxd -r`

Here's a screenshot of output:

Note: On my Windows machine with the MinGW terminal, the Windows Python binary doesn't output ANSI codes correctly so the above was `python <esolangs reference implementation>.py <infile> | cat` but it should work correctly on Linux machines.
> 5 votes

# Answer
## Javascript (ES6), 192 bytes

```
document.body.innerHTML='<svg><path fill=#62B0DF d="'+"m01Q0010L60Q7071L74Q7565L55L37L35L15Q0504z".split('').map(v=>v*20||v).join(" ")+'"/><text y=65 fill=#FFF style="font:38pt arial">\xa0PCG'

```

This takes a compressed version of a SVG D path. Spaces are removed, so all arguments have to be a single decimal, so any number is multiplied by 20 before being written to the actual svg.

Output:
Demo: https://jsfiddle.net/Luy6qj80/
> 4 votes

# Answer
# LibreLogo, ~~122~~ ~~116~~ 115 bytes

> Using Logo to create a Logo. Does this count as recursion?

**Code:**

```
fontsize 20 fontcolor [3]fontweight "bold pc [24]fc 6402271 bk 40 rt 45 fd 40 fill home rectangle[64,52,5]text "PCG

```

**Result:**

**Explanation:**

```
fontsize 20             ; Font Size   = 20pt
fontcolor [3]           ; Font Color  = white
fontweight "bold        ; Font Weight = bold
pc [24]                 ; Pen Color   = invisible
fc 6402271              ; Fill Color  = #61B0DF
bk 40                   ; Move Back 40pt
rt 45                   ; Turn Clockwise 45 Degrees
fd 40                   ; Move Forward 40pt
fill                    ; Close and Fill the Line Shape
home                    ; Reset Initial Turtle Settings and Position
rectangle[64,52,5]      ; Draw a Rectangle with Rounded Corners
text "PCG               ; Set Text of the Actual Drawing Object as "PCG"

```

**Previous Attempts:**

116 Bytes:

```
fontsize 20 fontcolor [3]fontweight "bold pc [24]fc 0x61b0df bk 40 rt 45 fd 40 fill home rectangle[64,52,5]text "PCG

```

122 Bytes:

```
ht fontsize 20 fontcolor [3]fontweight "bold pc [24]fc [97,176,223]bk 40 rt 45 fd 40 fill home rectangle[64,52,5]text "PCG

```
> 4 votes

# Answer
# JavaScript, 680 bytes

Well, I had this already finished for the original contest, which rules were changed drastically. This is definitely not the shortest code you can come up with. It was designed for the popularity contest and it creates the original favicon pixel by pixel. It has some more features, too. :)

```
f=c=>{x=(d=document).body.appendChild(d.createElement`canvas`).getContext`2d`;if(c.b)x.scale(4,4);x.fillStyle=c.m?'#2d2d2d':'#62b0df';x.fillRect(0,0,16,16);x.fillStyle='#fff';for(i=0;i<(w=[0,0,1,0,14,0,15,0,0,11,15,11,0,12,1,12,14,12,15,12,0,13,1,13,2,13,3,13,4,13,5,13,6,13,7,13,11,13,12,13,13,13,14,13,15,13,0,14,1,14,2,14,3,14,4,14,5,14,6,14,7,14,10,14,11,14,12,14,13,14,14,14,15,14,0,15,1,15,2,15,3,15,4,15,5,15,6,15,7,15,9,15,10,15,11,15,12,15,13,15,14,15,15,15,1,4,2,4,3,4,7,4,8,4,12,4,13,4,14,4,1,5,4,5,6,5,9,5,11,5,1,6,2,6,3,6,6,6,11,6,13,6,14,6,1,7,6,7,9,7,11,7,14,7,1,8,7,8,8,8,12,8,13,8,]).length;i++)(t=a=>setTimeout(_=>x.fillRect(w[a++],w[a++],1,1),(c.a||0)*i))(i++)}

```

You can call the function with up to three parameters:

```
f({});
f({m:true});
f({b:true});
f({a:50});
f({m:true,b:true,a:50});

```

`m` goes *meta* and changes the color accordingly. And if you find it to small, use `b` to supersize it from *16x16px* to *64x64px*. Finally `a` animates the logo, like it is engraved into a blue board. The value is the speed for each animation step.

**Ungolfed**

```
f=c=>{
    x=(d=document).body.appendChild(d.createElement`canvas`).getContext`2d`;
    if (c.b) x.scale(4,4);
    x.fillStyle = c.m?'#2d2d2d':'#62b0df';
    x.fillRect(0,0,16,16);
    x.fillStyle='#fff';
    for(i=0;i<(w=[0,0,1,0,14,0,15,0,0,11,15,11,0,12,1,12,14,12,15,12,0,13,1,13,2,13,3,13,4,13,5,13,6,13,7,13,11,13,12,13,13,13,14,13,15,13,0,14,1,14,2,14,3,14,4,14,5,14,6,14,7,14,10,14,11,14,12,14,13,14,14,14,15,14,0,15,1,15,2,15,3,15,4,15,5,15,6,15,7,15,9,15,10,15,11,15,12,15,13,15,14,15,15,15,1,4,2,4,3,4,7,4,8,4,12,4,13,4,14,4,1,5,4,5,6,5,9,5,11,5,1,6,2,6,3,6,6,6,11,6,13,6,14,6,1,7,6,7,9,7,11,7,14,7,1,8,7,8,8,8,12,8,13,8,]).length;i++)
        (t=a=>setTimeout(_=>x.fillRect(w[a++],w[a++],1,1),(c.a||0)*i)
        )(i++);
}

```

**Output**

*Default*

*Animated*
> 3 votes

# Answer
# Python 3, 10,069 bytes

Writes the hex from the original logo to a new file.

```
with open('test.png', 'w+b') as image_file:
    for line in ['\x89PNG\r\n', '\x1a\n', '\x00\x00\x00\rIHDR\x00\x00\x00\x13\x00\x00\x00\x12\x08\x06\x00\x00\x00\xb9\x0c\xe5i\x00\x00\n', '\xa3iCCPICC Profile\x00\x00H\x89\x95\x97\x07T\x13\xe9\x16\xc7\xbf\x99I/\x94\x04"\x9d\xd0;R\x04\x02H\xaf\xa1\x08\xd2\xc1FH\x02\t%\x84@\x10\xb1#\xe2\n', '\xac\x05\x15\x91bAW)\n', "V@\xd6\x82\x88baQ\xec}A\x16\x01u],\xd8Py\x03<\xc2{\xef\xbc=\xef\xbc{\xce\x9d\xf9\x9d{\xee\xfc\xe7\xce7\xf3\x9d\xf3\x1f\x00(]\x1c\xb18\x15V\x00 M\x94%\t\xf3\xf3d\xc6\xc4\xc61\xf1\xbf\x03\x02\xc0\x00\x1ap\x02\xca\x1cn\xa6\xd8#44\x08\xfcm|\xbc\x07\xa0\x89\xf3m\x8b\t\xad\xbf\xef\xfb\xaf\xa1\xc8\xe3gr\x01\x80BQN\xe0er\xd3P>9\x91\\\xb1$\x0b\x00D\x80\xd6\xf5\x96f\x89'\xb8\x18e%\t: \xca{'8i\x8aONp\xc2\x14_\x99\xec\x89\x08\xf3B\xf9\t\x00\x04\n", "\x87#I\x02\x80<\x84\xd6\x99\xd9\xdc$T\x87B@\xd9J\xc4\x13\x8aPf\xa1\xec\xca\x15px(\xe7\xa0l\x9e\x96\x96>\xc1\x07P6N\xf8\x17\x9d\xa4\x7f\xd3L\x90ir8I2\x9ez\x96\xc9 x\x0b3\xc5\xa9\x9ce\xff\xe7r\xfc\xefHK\x95N\xdfC\x17M\x8a@\xe2\x1f6qF\xd7\xac&%=P\xc6\xa2\x84y!\xd3,\xe4M\xf6O\xb2@\xea\x1f9\xcd\xdcL\xaf\xb8i\xe6q\xbc\x03\xa7Y\x9a\x12\xe91\xcd\x1c\xc9\xcc\xb5\xc2,v\xc44K\xd2\xc3d\xfa\xfcL\x9fp\x99>\x9f\x1d$\x9b!u\x9e\x8c\x13\x85\xbe\xeci\xce\x15DDOs\xb60j\xde4g\xa6\x84\x07\xce\xf4x\xc9\xea\x12i\x98l\xe6D\x89\xaf\xec\x19\xd32gf\xe3rff\xc8\x12D\xf8\xcf\xcc\x16#\x9b\x81\xc7\xf7\xf6\x91\xd5E\x91\xb2~q\x96\xa7LS\x9c\x1a*\xeb\xe7\xa7\xfa\xc9\xea\x99\xd9\xe1\xb2k\xb3\xd0\x0fl\x9a\x939\x01\xa13:\xa1\xb2\xf5\x01^@\x08D\x80\x0f\xd2\x00'\x8b\x9f\x9351\xa8W\xbax\x99D\x98$\xc8bz\xa0;\x85\xcfd\x8b\xb8\x96\xe6L\x1b+k;\x00&\xf6\xdd\xd4k}\xcf\x98\xdcO\x10\xe3\xdaLm\xb91\x00\xeee\x00\xc053\xb5\xe8c\x00\x1cv\x07@\xf9\xecLM\xef;\x00t\xb4\xb7\xb5\x93+\x95dO\xd50\x13\x07, \x01y\xa0\x04T\x81\x16\xd0\x03\xc6\xc0\x02\xd8\x00{\xe0\x0c\xdc\x81\x0f\x08\x00! \x02\xc4\x82\xc5\x80\x0b\x04\xe8\xbc\x12\xb0\x14\xac\x00kA\x01(\x02[\xc0\x0eP\x0e\xf6\x80\xfd\xa0\x06\x1c\x01\xc7A38\x03.\x80\xcb\xe0:\xb8\t\xee\x82\xc7\xa0\x17\x0c\x80W`\x04|\x04c\x10\x04\xe1!*D\x87T!m\xc8\x002\x83l \x16\xe4\n", '\xf9@AP\x18\x14\x0b\xc5CI\x90\x08\x92B+\xa0uP\x11T\x02\x95C\xfb\xa0Z\xe8\x18t\x1a\xba\x00]\x85z\xa0\x87P\x1f4\x0c\xbd\x83\xbe\xc2\x08L\x81\x95`M\xd8\x10\x9e\r\xb3`\x0f8\x10\x8e\x80\x17\xc1Ip\x06\x9c\x0b\xe7\xc3\x9b\xe02\xb8\x1a>\x0c7\xc1\x17\xe0\xeb\xf0]\xb8\x17~\x05\x8f"\x00!#\x0cD\x07\xb1@X\x88\x17\x12\x82\xc4!\x89\x88\x04Y\x85\x14"\xa5H5\xd2\x80\xb4"\x9d\xc8m\xa4\x17y\x8d|\xc1\xe00t\x0c\x13c\x81q\xc6\xf8c"1\\L\x06f\x15\xa6\x18S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1\x7f\xc6?\x00\xea\xa4\xff\x86H\x07*\xad\x00\x00\x01\x9biTXtXML:com.adobe.xmp\x00\x00\x00\x00\x00<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 5.4.0">\n', '   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n', '      <rdf:Description rdf:about=""\n', '            xmlns:exif="http://ns.adobe.com/exif/1.0/">\n', '         <exif:PixelXDimension>19</exif:PixelXDimension>\n', '         <exif:PixelYDimension>18</exif:PixelYDimension>\n', '      </rdf:Description>\n', '   </rdf:RDF>\n', '</x:xmpmeta>\n', '\x92\xfc\xe9\xf6\x00\x00\x01\xdcIDAT8\x11\xad\x94\xdfM\x1cA\x0c\xc6?\xcf\xcc\xbe\x11@\xa9 u\xa0\x1c\xa2\x03\x8aH\x0b\x89\x94\x16\x82\xeeJ\xa0\x88T\x90\x874\x92\xe7D,\xdc\xf3\xee\x8c\xf9ya\xc2\xe9 \x12\x87\xe2\x95\xd6\xf3\xc7\xfe\xc6\x1e\x7fc\xbb\xbb\xbdu7W\xae\xae)\x15e\xb9Rn\x9a\xbdH6+M\xae6\x984I%\x9bfK\x12\xb6B\xbb5\x15g?\x99Z5\xc6\x8b\xfb\xa4Z\x92\xbe\xfc\x18u\x88\xacW\xa7\x80\x9aR\xe3\xb08\xfbf\xbb\xf5CA\xf6\x0f\xdc\x9c\xbfW\xf6\x16\x19\xd5\xfd\xbd\x83\xe7$\xaaVH\x93+\xfa\x0f\xc2=G\xa6\x1e\xf9"\xd7\x97\x1f\x16\x1d\xbfO\xdf\x7f\xfd\x1d\xf7\xf5\x97\xd6\xba-\xa5\x90G\x01Z\xa6:\x8f\xd2\x1d\x02 \xc6]\xc7v\x1fw\xdd}\x1et\xa2\xcaN\x9a\x94\xb7K\x18\x86t\xd0e\xf2\xf8\xdb_\xdb\xb5\r\x8a\xc0&\n', '\xe0\x0fiv\x90}\xa7\x0e\xd8\x9d\xfb|\xd7\xce=\xc3\xcb\x14<{\x8a\xac\x1bv\x1d\x0e\x1d\xa4;\xbf\xb4\x96\xa2\x88\xfcl\xbc\x19\xfd\xf3\xcfm\xf7\x7f\x93\xde\\\x1c\xa9R\xc8\xd2\xd2\xbf#{-rk\x03\xa4\x85\x1e\xaaI\xeb\x8f\'\xaf\xf5{f\xf7-|\t\xc8\xad*%\xee\xac\xc2\xde\xcd\xeap\xc0\xab\xf3\xd3x\x9aD\x14<\xcb\xb2\xdft\x8d<U\xd9@\x90\x00\x1b\x1d!\xca\xbc\x14\x19\x0e\xce\x0c\xbe\xee\xdc\xe9\xd5\xea\x1dl"\x00\x1f\x82\n', '\xf2\xb8x|\x88Me\x98]\x80\xaaE\xce\xf0\xc5(s\xe5\x13@\xf4&N}\x92\xf5\xea\x88\t\xb9\x10\xce\x90*\xfb\x94q\xc6>\xb8J\x8eeyM\xac\xe5\x16,6e\x98\x9chK\xd1\xb2\xc28\xee"d}v\xbc\x90(z\x9f\xe1\x14Y\x84\xa5\x91F\x99y\xe2t\r\xfb3\x8e\xd0\x8d-\xc0"\xf7\x16\xa4\xe1\x9d1\xa4\x19\xbaf\x80\x97\xce\xb2DOTX+s\xd9\x14N\x98Y#3\x0e\x8b\xfey\x0f\x08\xf5\xf5\xc8\xe0\xdd\\\x98\x00\x00\x00\x00IEND\xaeB`\x82']:
        image_file.write(line)

```
> 2 votes

# Answer
# R, 189 bytes

```
image(t(matrix(as.integer(sapply(c(32736,28784,62968,62968,64504,65528,63736,63352,63359,64254,65532,63736,63352,62840,29936,32736),intToBits)[1:16,]),nr=16)),ax=F,col=c("white","#62B0DF"))

```

With indents for clarity:

```
image(t(matrix(as.integer(sapply(c(32736,28784,62968,62968,
                                   64504,65528,63736,63352,
                                   63359,64254,65532,63736,
                                   63352,62840,29936,32736),
                                 intToBits)[1:16,]),nr=16)),
      ax=F,col=c("white","#62B0DF"))

```

I'm shamelessly stealing the method from an old answer of mine: I take the base-2 representation of 16 numbers, make it into a 16x16 matrix of 1s and 0s and plot it as is.
> 2 votes

# Answer
# Google Blockly, 140 blocks

Produces

Will add an explanation if requested. Try it here

Suggestions to reduce the massive function on the left are welcome!
> 2 votes

# Answer
# Python 2, 211 bytes

```
from PIL import Image
I=Image.new('P',(16,16))
I.putdata(map(int,bin(eval('0xc003'+'0'*12+'718e4a5072164252418c'+'0'*8+'8001c003ff1fff3fff7f'))[2:]))
I.putpalette([111,174,221]+[255]*3)
I.resize((64,64)).show()

```
> 2 votes

# Answer
# 05AB1E, 49 bytes

```
•(!o4¯ZD5µå¹p‹^Ô%í2\AO-Ö"w™ÈõžvlXäà`AF•bT„.@‡19ô»

```

Try it online!

```
...@@@@@@@@@@@@....
.@@@@@@@@@@@@@@@@..
.@@@@@@@@@@@@@@@@..
.@@@@@@@@@@@@@@@@..
.@...@@@..@@@...@..
.@.@@.@.@@.@.@@@@..
.@...@@.@@@@.@..@..
.@.@@@@.@@.@.@@.@..
.@.@@@@@..@@@..@@..
.@@@@@@@@@@@@@@@@..
..@@@@@@@@@@@@@@...
...@@@@@@@@@@@@....
.........@@@.......
.........@@........
.........@.........

```
> 2 votes

# Answer
# Excel VBA, ~~252~~ ~~246~~ ~~245~~ 237 Bytes

<sub><sup>Saved 6 bytes thanks to Taylor Scott.</sup></sub>
<sub><sup>Saved another 8 bytes thanks to inspiration from Taylor Scott</sup></sub>

```
Sub p()
Set s=Shapes.AddShape(106,0,0,99,82)
With s.TextEffect
.Text="PCG
.FontSize=56
.Alignment=2
End With
s.TextFrame2.WordWrap=0
s.Adjustments.Item(1)=.1
s.Adjustments.Item(2)=.9
s.Line.Visible=0
s.Fill.ForeColor.RGB=14659682
End Sub

```

The code must be run from a worksheet's code page and will add the shape to that worksheet. It's nothing fancy but it does directly use the rounded rectangular callout upon which the icon is based. (For `AddShape`, `106` corresponds to `msoShapeRoundedRectangularCallout`.)

Formatting doesn't add much but it does make it easier to read:

```
Sub p()
    Set s = Shapes.AddShape(106, 0, 0, 99, 82)
    With s.TextEffect
        .Text = "PCG"
        .FontSize = 56
        .Alignment = 2
    End With
    s.TextFrame2.WordWrap = 0
    s.Adjustments.Item(1) = 0.1
    s.Adjustments.Item(2) = 0.9
    s.Line.Visible = 0
    s.Fill.ForeColor.RGB = 14659682
End Sub

```

There's also a one-line solution meant to be run in the immediate window that is 1 byte longer:

```
Set s=Sheet1.Shapes.AddShape(106,0,0,99,82):s.TextEffect.Text="PCG":s.TextEffect.FontSize=56:s.TextEffect.Alignment=2:s.TextFrame2.WordWrap=0:s.Adjustments.Item(1)=.1:s.Adjustments.Item(2)=.9:s.Line.Visible=0:s.Fill.ForeColor.RGB=14659682

```
> 2 votes

# Answer
# MATLAB, ~~153 150~~ 140 bytes

```
a=65535;imshow(imresize(dec2bin([16380,a,a,a,36465,46511,36329,48557,48755,a,a,32766,16380,32*[7 6 4]],16)-47,8,'n'),[1 1 1;0.39 0.69 0.88])

```

The code takes an array of 16bit numbers (sadly there is no way of encoding them that reduces the byte count apart from reading from a presaved binary file). EDIT: With a little bit of creativity in how the array is made, I've saved 3 bytes, and with a little bit more and an extra variable, I can save another 10 on top of that.

With this array, it is converted to a binary string where an ascii '1' represents blue and an ascii '0' is white. The array is 2D at this point because each of the 16 numbers becomes a 16 character string.

I subtract 47 to convert this into an array of 1's and 2's (needed for the next bit), where each element represents one pixel. Again this remains as 2D and is our image data.

The image is then scaled up by a factor of 8 using nearest neighbour to produce an image which is at least the required 64x64px minimum size - in fact it is 128x128 because somehow I divided 64 by 16 to get 8 \>\_\< (don't ask!).

Finally this is displayed using a colour map where any 1 becomes white and any 2 becomes the required #62B0DF shade of blue.

This is the output:
> 1 votes

# Answer
## Processing, 211 bytes

```
noStroke();int[]n={49155,0,173175182,1245866062,12674,-2147418112,-117456893,-16777985};for(int x=0;x<256;x++){if(((n[floor(x/32)]>>(x%32))&1)>0)fill(255);else fill(98,176,223);rect(4*(x%16),4*floor(x/16),4,4);}

```

Storing the pixels inside signed integers (seems to be the most efficient way, I'll maybe try 2^64 integers) and then printing them in a frame.
> 1 votes

# Answer
# Swift (Playground), 599 Bytes

```
import UIKit;class P:UIView {var b=UIBezierPath();func a(x:CGFloat,y:CGFloat){b.addLineToPoint(CGPoint(x:x,y:y))};override func drawRect(rect:CGRect){UIColor(red:0.384,green:0.690,blue:0.875,alpha:1).setFill();UIBezierPath(roundedRect:CGRectMake(0,0,200,159),cornerRadius:45).fill();b.moveToPoint(CGPoint(x:102, y:146));a(102,y:200);a(157,y:146);a(102,y:146);b.closePath();b.fill();"PCG".drawInRect(CGRectMake(35,41,200,121),withAttributes:[NSFontAttributeName: UIFont(name:".AppleSystemUIFontBold",size: 64)!,NSForegroundColorAttributeName:UIColor.whiteColor()])}}
P(frame: CGRectMake(0,0,200,200))

```

I decided to give it a go, since drawing in Swift is pretty straightforward, and it's not usually golfed like this. Ended up loosing precious bytes with the text... Damn you `NSDescriptiveVariableNames`!

Here's how it looks in the playground:

I think I could golf it more by aliasing things like `CGRectMake`, grouping objects in the a function etc.
> 1 votes

# Answer
# PHP, 145 bytes, not competing

```
for(;$i<64;)echo strtr(sprintf("%016b\n",[49155,0,0,0,29070,19024,29206,16978,16780,0,0,32769,49155,65311,65343,65407][$i++/4]),["####","    "]);

```

I should use non-blank and colors instead, but I´m too tired atm.
Guess that will add 10 bytes or so to the count, maybe more.
> 1 votes

# Answer
# Excel VBA, 178 Bytes

Anonymous VBE Immediate window function that takes no input and outputs the PCG Favicon (exactly as in the prompt above) to the range

```
Cells.RowHeight=48:[C1:N13,A2:P11,B12:O12,I14:I16,J14:J15,K14].Interior.Color=&HDFB062:[B5:B9,C5:D5,C7:D7,E6,G6:G8,H5:I5,J6,J8,H9:I9,L6:L8,O7:O9,M5:O5,M9:N9,N7].Interior.Color=-1

```
> 1 votes

# Answer
# tcl/tk, 113

```
grid [canvas .c]
.c cr o 2 2 66 48 -f #62B0DF
.c cr t 36 24 -te PCG -fi #FFF
.c cr p 30 66 30 47 44 47 -f #62B0DF

```
~~Tcl/tk, 144
```
grid [canvas .c]
.c create oval 2 2 66 48 -fill #62B0DF
.c create text 36 24 -text PCG -fill #FFF
.c create poly 30 66 30 47 44 47 -fill #62B0DF

```~~
> 0 votes

# Answer
# C (gcc), 188 bytes

```
y;main(x){int d[]={16380,~0,~0,~0,36465,62893,38833,46525,52861,~0,~0,32766,16380,1792,768,256};for(;y<64;y++){for(x=0;x<16;)printf("\33[48;5;%dm%*s",(d[y/4]>>x++)&1?14:7,8,"");puts("");}}

```

Try it online!

Uses ANSI escape codes to print 128 horizontal and 64 vertical colored spaces.

*(Image resized.)*
> 0 votes

# Answer
## C++ with SFML, 607 bytes

```
#include<SFML\Graphics.hpp>
using namespace sf;using c=Color;using x=Vector2f;RenderWindow w(VideoMode(324,324),"");void p(){RectangleShape r({224.f,144.f});r.setFillColor(c(98,176,223));Vertex v[3]={x(162,324),x(243,224),x(162,224)};for(int i=0;i<3;++i)v[i].color=c(c(98,176,223));Font f;if(!f.loadFromFile("a.ttf"))return;Text t("PCG",f,150);t.setPosition(50,20);while(w.isOpen()){Event e;while(w.pollEvent(e))if(e.type==0)w.close();w.clear(c::White);for(int i=0;i<628;++i){r.setPosition(50+cos(float(i)/100.f)*50,50+sin(float(i)/100.f)*50);w.draw(r);}w.draw(v,3,PrimitiveType(3));w.draw(t);w.display();}}

```

Code that calls the function :

```
int main() {
    w.setFramerateLimit(60);
    w.setVerticalSyncEnabled(true);
    p();
}

```

Requirements :

* You need to have a valid ttf file called `a.ttf` in the current directory where the executable is running, so it can load the fonts to display the text
* You need to have the corresponding SFML DLLs in the current directory where the executable is running

Result :

Explanations :

```
#include<SFML\Graphics.hpp>

using namespace sf;
using c=Color;
using x=Vector2f;

//Create the window that will display stuff. 324x324 dimensions
RenderWindow w(VideoMode(324,324),"");

void p(){

    //Creation of the rectangle
    RectangleShape r({224.f,144.f});
    r.setFillColor(c(98,176,223)); //Logo Color wanted

    //Vertex to draw a blue triangle
    Vertex v[3]={x(162,324),x(243,224),x(162,224)};
    for(int i=0;i<3;++i)
        v[i].color=c(c(98,176,223));

    //Creation an load of the font
    Font f;
    if(!f.loadFromFile("a.ttf"))
        return;

    //Creating the text object that will be used to draw the PCG text
    Text t("PCG",f,150);
    t.setPosition(50,20);

    //Main loop, will run while the window is open
    while(w.isOpen()){
        Event e;
        while(w.pollEvent(e))
            //sf::Event::Close int value is 0
            //It will be triggered if you click on the red cross, or press Alt+F4
            if(e.type==0)
                w.close();

        //Clear the window in white
        w.clear(c::White);

        //6.28 = 2*PI, the number of radians that nearly equals 360 degrees
        for(int i=0;i<628;++i){
            //It draws 628 rectangles, the top left part of the rectangle will do a circle
            //Same for every points of the rectangle
            r.setPosition(50+cos(float(i)/100.f)*50,50+sin(float(i)/100.f)*50);
            w.draw(r);
        }

        //sf::PrimitiveType::Triangle int value is 3
        w.draw(v,3,PrimitiveType(3));
        //Draw the text
        w.draw(t);
        w.display();
    }
}

```
> 0 votes

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


title: Life and Death of Trees

text:
# Question
Title: Life and Death of Trees
## The Challenge

Write a program that takes an integer *N* as input, and outputs the stage of life or death that a tree is currently in. *N* will always be between 0 and 10.

**The Stages of Life and Death**

* **Life:** To draw a stage of life, simply draw a base of size *N*, consisting of `^` characters, then move up and substract 2 from *N*, if the result is greater than 0, and draw a line of `^` characters again, again with the size of the new *N*. Repeat while *N* is larger than 0. To finish off, place either a single `|` character if the startoff value of *N* is odd, or two `||` characters if it was even.
Example: `N = 5`

```
  ^
 ^^^
^^^^^
  |

```

Note that if *N* = 0, only the stem will be drawn, without the leaves (`^`) on them.
* **Death:** This is roughly the same as *Life*, except that the base is *10 - N*, you use `M` instead of `^` and you add 2 to *N* and redraw the lines with the same procedure as above, but this time you add 2 to *N* while it is smaller or equal to 10.
Example: `N = 3`

```
   M
  MMM
 MMMMM
MMMMMMM
   |

```

## The Goal

Your program has to run in 2 different languages both have to take a input *N*. The first language has to output the **life** stage of a tree according to *N*, the second language has to output the **death** stage.

## Rules

* This is , the shortest code in bytes that meets all the requirements wins.
* The code has to run in 2 different languages. Yes, Python 2 and Python 3 *are different languages*.
* Standard loopholes are forbidden.
* Trailing newlines or spaces are allowed.

## Test Cases

Input: `N = 1`

**First language (life):**

```
 ^
 |

```

**Second language (death):**

```
    M
   MMM
  MMMMM
 MMMMMMM
MMMMMMMMM
    |

```

---

Input: `N = 10`

**First language (life):**

```
    ^^
   ^^^^
  ^^^^^^
 ^^^^^^^^
^^^^^^^^^^
    ||

```

**Second language (death):**

```
||

```

---

**Good luck coding!**

# Answer
# Dyalog APL / SOGL, ~~70~~ ~~65~~ ~~63~~ 62 bytes

```
0000000: 7b0d 04eb c0fd 5832 5c49 e32a 2e4c ac20  {.....X2\I.*.L.
0000010: 4d2a 5b3a 836b 6b7d 01ea 500d 9b31 a90f  M*[:.kk}..P..1..
0000020: 7b0f c285 c8c7 b932 c00e f8b1 c70f 7db0  {......2......}.
0000030: 32c2 8531 9c85 80b2 b50f aa32 f97d       2..1.......2.}

```

### Interpreted in the classic Dyalog APL encoding: - life: (contains unprintables), expects `⎕IO←1`

```
{' ^|⎕X2I┤z.L?pMzÅÏÏ}ûP'[1+⍵{⍵,⍨⌽⍉(2|⍺)↓⍉⍵}↑2,⍨1/⍨¨⍳⌈⍵÷2]}

```

TryAPL here!

```
{' ^|..'[1+⍵{⍵,⍨⌽⍉(2|⍺)↓⍉⍵}↑2,⍨1/⍨¨⍳⌈⍵÷2]}

         1+      add 1 to every value
 ' ^|..'[  ....] index the array getten below into " ^|.." with SOGLs code never being indexed in

⍵{..}↑2,⍨1/⍨¨⍳⌈⍵÷2

          1/⍨¨      replace each with that many 1s
              ⍳     the first ... numbers
               ⌈      ceiling of
                ⍵÷2     the right argument divided by 2
       2,⍨          append 2
      ↑             mix; convert to a 2D array, padding with zeroes
⍵{..}               execute that function with the arguments ⍵ - my right argument and the result of above

   {⍵,⍨⌽⍉(2|⍺)↓⍉⍵}  helper function
    ⍵,⍨             append the right arg to
               ⍉⍵     the right arg transposed
              ↓       without the first ... rows
         (2|⍺)          remainder of left arg ÷ 2
       ⌽⍉             transposed and reversed

```

### Interpreted in SOGLs encoding \- death:

```
{∑⁴╝υ”X2\I┐*.Lκ M*[:≥kk}¹╚P∑Β1Ι»{»φ√ωΩΡ2υ«⌠ΝΩ»}μ2φ√1β√↓νΟ»ι2⌡}

```

Try it Here!

Explanation:

```
{∑⁴╝υ”X                         push "{∑⁴╝υ" and pop it - noop
       2\                       push input divides by 2
         I┐*                    get that many + 1 vertical bars
            .Lκ                 push 10-input
                M*              get that many "M"s as a string
                  [    }        while ToS isn't falsy (here: isn't "")
                   :              duplicate the string
                    ≥             put the duplicate at the stacks bottom
                     kk           remove the last 2 letters (does nothing when the string is empty)
                        ¹       wrap everything in an array
                         ╚      center horizontally
                          P     print that
                           ...  execute a bunch of random nonsense which luckily does nothing

```

This took way too long.. Golfing tips for the APL part are welcome, everything mostly should be applicable as long as it doesn't change anything before `ûP'`

You can load the file (after reversing `xxd`) in SOGL by selecting the file in the `Browse...` dialog and then clicking `load SOGL codepage encoded file`.
> 10 votes

# Answer
# Python 2 and Python 3, ~~119~~ ~~110~~ 109 bytes

```
r=p='';n=1/2>0;b=(-1)**n*int(input())+10*n
while b>0:r=p+'^M'[n]*b+'\n'+r;b-=2;p+=' '
print(r+p[1:]+'||'[b:])

```

Try it online! (Python 2, life)

Try it online! (Python 3, death)
> 7 votes

# Answer
# Python 2 / Python 3, 121 bytes

```
def f(n):
 m=-1;n,c=(n,10-n,'^','M')[1/2>0::2];s=''
 while n>0:s=' '*m+c*n+'\n'+s;m+=1;n-=2
 return s+' '*m+'|'*(n%2or 2)

```

Try it online! (Python 2)

Try it online! (Python 3)
> 5 votes

# Answer
# Python 3/Python 2, 128 bytes

```
def f(n,a=1/2>0):
 m=[n,10-n][a];k=-~m%2+1
 for j in range(k,m+1,2):print(" "*((m-j)//2)+"^M"[a]*j)
 print(" "*((m-k)//2)+"|"*k)

```

Try it online! (Python 3)

Try it online! (Python 2)
> 2 votes

# Answer
# C (gcc) / Python 2, 308 bytes

```
#define _\
"""
main(N,n,j,k){scanf("%d",&N);j=-~!(N%2);for(n=j;n<=N;n+=2){printf("%*c",(N-n)/2+1,94);for(k=n-1;k;k--)printf("^");puts("");}printf("%*c",++N/2,124);N%2?puts("|"):0;}
#define _"""
#define/*
N=10-input();j=[1,0][N%2]
for n in range(1,-~N,2):print(N-n)/2*" "+"M"*(n+j)
print~-N/2*" "+"|"*-~j
#*/_

```

Try it online!

# Python 2 / C (gcc), 308 bytes

```
#define _\
"""
main(N,n,j,k){scanf("%d",&N);j=-~!(N%2);for(n=j;n<=N;n+=2){printf("%*c",(N-n)/2+1,94);for(k=n-1;k;k--)printf("^");puts("");}printf("%*c",++N/2,124);N%2?puts("|"):0;}
#define _"""
#define/*
N=10-input();j=[1,0][N%2]
for n in range(1,-~N,2):print(N-n)/2*" "+"M"*(n+j)
print~-N/2*" "+"|"*-~j
#*/_

```

Try it online!
> 2 votes

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


title: Spaced-out numbers

text:
# Question
Title: Spaced-out numbers
Given a list of `N` non-negative integers, output those numbers with each left-padded by spaces to a length of `N`. (Alternatively, return a character/string list.) **You may assume that `N` is greater than or equal to the number of digits of the largest number in the list.** Trailing spaces are allowed in the output.

You may also take a string containing these numbers, but `N` is not the length of the string, but rather the number of elements in the list; also, you may take a list of strings e.g. `["1", "2", "3"]`.

This is a code-golf, so the shortest program in bytes wins.

## Test cases

```
input => 'output'
0 => '0'
1 => '1'
2 3 => ' 2 3'
2 10 => ' 210'
4 5 6 => '  4  5  6'
17 19 20 => ' 17 19 20'
7 8 9 10 => '   7   8   9  10'
100 200 300 0 => ' 100 200 300   0'
1000 400 30 7 => '1000 400  30   7'
1 33 333 7777 => '   1  33 3337777'
0 0 0 0 0 0 => '     0     0     0     0     0     0'

```

# Answer
# 05AB1E, 3 bytes

Code:

```
Dgj

```

Explanation:

```
D    # Duplicate the input array
 g   # Get the length
  j  # Left-pad with spaces to the length of the array

```

Try it online! or Verify all test cases.
> 8 votes

# Answer
## Python, 32 bytes

```
lambda l:'%%%ds'%len(l)*len(l)%l

```

An anonymous function that takes a tuple as input. Either numbers or strings work.

Example:

```
l=(1,33,333,7777)

'%%%ds'
## A "second-order" format string

'%%%ds'%len(l)           -> '%4s'
## Inserts the length as a number in place of '%d'
## The escaped '%%' becomes '%', ready to take a new format argument
## The result is a format string to pad with that many spaces on the left

'%%%ds'%len(l)*len(l)    -> '%4s%4s%4s%4s'
## Concatenates a copy per element

'%%%ds'%len(l)*len(l)%l  -> '   1  33 3337777'
## Inserts all the tuple elements into the format string
## So, each one is padded with spaces

```
> 16 votes

# Answer
# JavaScript (ES7), 37 bytes

```
a=>a.map(v=>v.padStart(a.length,' '))

```

Input: Array of strings
Output: Array of strings

```
f=
  a=>a.map(v=>v.padStart(a.length,' '))
;
console.log(f(['0']))
console.log(f(['1']))
console.log(f(['2','3']))
console.log(f(['2','10']))
console.log(f(['4','5','6']))
console.log(f(['17','19','20']))
console.log(f(['7','8','9','10']))
console.log(f(['100','200','300','0']))
console.log(f(['1000','400','30','7']))
console.log(f(['1','33','333','7777']))
console.log(f(['0','0','0','0','0','0']))
```
> 7 votes

# Answer
## PowerShell v2+, 36 bytes

```
param($a)$a|%{"{0,$($a.count)}"-f$_}

```

Takes input `$a` as an array of `int`egers. Loops through them with `$a|%{...}`. Each iteration, uses the `-f`ormat operator with the optional `Alignment Component` (based on `$a.count`) to left-pad the appropriate number of spaces. That resultant string is left on the pipeline. At end of program execution, the resulting strings are all left on the pipeline as an array.

---

### Examples

Output is newline-separated on each run, as that's the default `Write-Output` at program completion for an array.

```
PS C:\Tools\Scripts\golfing> @(0),@(1),@(2,3),@(2,10),@(4,5,6),@(17,19,20),@(7,8,9,10),@(100,200,300,0),@(1000,400,30,7),@(1,33,333,7777),@(0,0,0,0,0,0)|%{""+($_-join',')+" -> ";(.\spaced-out-numbers $_)}
0 ->
0
1 ->
1
2,3 ->
 2
 3
2,10 ->
 2
10
4,5,6 ->
  4
  5
  6
17,19,20 ->
 17
 19
 20
7,8,9,10 ->
   7
   8
   9
  10
100,200,300,0 ->
 100
 200
 300
   0
1000,400,30,7 ->
1000
 400
  30
   7
1,33,333,7777 ->
   1
  33
 333
7777
0,0,0,0,0,0 ->
     0
     0
     0
     0
     0
     0

```
> 5 votes

# Answer
# JavaScript, 49 bytes

```
a=>a.map(n=>" ".repeat(a.length-n.length)+n)

```

Takes the arguments as a list of strings and also returns a list of strings.

Explanation:

```
a=>                                                   An unnamed function, which takes one argument, a
   a.map(n=>                               )          Do the following to each element n in a:
            " ".repeat(a.length-n.length)             Generate the spaces needed to justify the number
                                         +n           Append the number

```
> 5 votes

# Answer
# Bash, 14

```
printf %$#d $@

```

Input list given at the command line.

Not much to explain here. Simply uses built-in `printf` facilities to do the necessary padding, based off the number of passed args:

* `$#` is the number of args passed
* `%<n>d` is a printf format specifier that prints an integer with up to n leading spaces
* `$@` is the list of all args passed
* The format specifier is reused for each member of `$@`.

Ideone.
> 5 votes

# Answer
## Perl, 26 bytes

*-4 bytes thanks to @Ton Hospel*

25 bytes of code + `-a` flag.

```
printf"%*s",~~@F,$_ for@F

```

Run with :

```
perl -ae 'printf"%*s",~~@F,$_ for@F' <<< "10 11 12"

```

(On some older version of Perl, you might need to add `-n`)
> 5 votes

# Answer
# Ruby, ~~40~~ ~~36~~ 34 bytes

```
->m{m.map{|i|$><<i.rjust(m.size)}}

```

Can be worked on more.

Call as a lambda.

Explanation:

```
->m{m.map{|i|$><<i.rjust(m.size)}}
->m{                             } # lambda taking array m
    m.map{|i|                   }  # map over array using variable i
             $><<                  # output to $> (stdout)
                 i.rjust(m.size)   # right justify i to m's length

```
> 4 votes

# Answer
# Vim, 19 bytes

`YPPG!{<C-F>|R%ri<CR>djVGgJ`

Takes a list of numbers one-per-line. Relies on `:set expandtab`, which is popular, but not universal.

You clearly want to use `:right` for this. The question is how to get the number of lines onto the command line. The traditional way is `:%ri<C-R>=line('$')`, but all that text is long.

The shorter, more enterprising approach is to form the command line using the normal mode `!` command. It involves some weird workarounds, expanding the file by 2 lines then removing them again, but it comes out 2 bytes shorter. And I'm kinda shocked the garbled command line I get (like `:%ri+4!`) actually works, but it does.
> 4 votes

# Answer
# Jelly, ~~7~~ 6 bytes

```
L⁶xaUU

```

Input is an array of strings. Try it online! or verify all test cases.

### How it works

```
L⁶xaUU  Main link. Argument: A (array of strings)

L       Yield the l, the length of A.
 ⁶x     Repeat ' ' l times.

    U   Upend; reverse all strings in A.
   a    Perform vectorizing logical AND, replacing spaces with their corresponding
        digits and leaving spaces without corresponding digits untouched.
     U  Upend; reverse the strings in the result to restore the original order of
        its digits, moving the spaces to the left.

```
> 2 votes

# Answer
# PHP, 55 Bytes

```
<?foreach($a=$_GET[a]as$i)printf("%".count($a)."s",$i);

```

Pevious Version 59 Bytes

```
<?foreach($a=$_GET[a]as$i)echo str_pad($i,count($a)," ",0);

```
> 2 votes

# Answer
# Mathematica, 25 bytes

```
#~StringPadLeft~Length@#&

```

Both input and output are lists of strings.

# Explanation

```
Length@#

```

Get the length of the input (number of element).

```
#~StringPadLeft~...

```

Pad left each element in the input so that their lengths match the length of the input.
> 2 votes

# Answer
# JavaScript (ES6), 47

Anonymous function, input: array of strings, output: array of strings
Using a recursive padding function

```
a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x))

```

For an integer/string array as input, 49 bytes:

```
a=>a.map(x=>p(x),p=x=>(y=' '+x)[a.length]?x:p(y))

```

**Test**

```
f=
a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x))

function update() {
  var l=I.value.match(/\d+/g)||[]
  O.textContent = f(l)
}

update()

```

```
<input id=I oninput='update()' value='1000,400,30,7'>
<pre id=O></pre>
```
> 2 votes

# Answer
# J, 4 bytes

```
":~#

```

**Try it online!**

Unary function taking the list of numbers on the right as an array and returning the padded string.

Here it is in use at the REPL. Note that input lines are indented three spaces.

```
   f=: ":~#
   f 2 3
 2 3
   f 2 10
 210
   f 1111 222 33 4
1111 222  33   4

```
> 2 votes

# Answer
## CJam, 11 bytes

```
lS%_,f{Se[}

```

Try it online! (As a test suite.)

### Explanation

```
l      e# Read input.
S%     e# Split around spaces.
_,     e# Copy and get length.
f{     e# Map this block over the list, passing in the length on each iteration.
  Se[  e#   Left-pad to the given length with spaces.
}

```
> 1 votes

# Answer
# Kotlin, 90 bytes

Golfed:

```
fun main(a:Array<String>){a.forEach{b->for(i in 1..a.size-b.length){print(" ")};print(b)}}

```

Ungolfed:

```
fun main(a: Array<String>) {
    a.forEach { b ->
        for (i in 1..a.size - b.length) {
            print(" ")
        }
        print(b)
    }
}

```
> 1 votes

# Answer
# MATL, 14 bytes

```
'%%%dd'inYDGYD

```

Try it out at MATL Online

This uses formatted string creation by first constructing the format string: `%(NUM)d` and then applies string formatting again using this format string and the input.
> 1 votes

# Answer
# Java, ~~83~~ 82 bytes

```
a->{String s="";for(int i=a.length,j=i;i-->0;)s+="%"+j+"s";return s.format(s,a);};

```

Constructs a format string designed to pad the given arguments by a number of spaces equal to the length of the array. The format string is used as an argument for `String.format`, and the result is then returned. The functional interface can accept either a `String[]` or an `Integer[]` or similar.

Full class:

```
public class Test {
    public static void main(String[] args) {
        java.util.function.Function<Integer[], String> f = a -> {
            String s = "";
            for (int i = a.length, j = i; i-- > 0;)
                s += "%" + j + "s";
            return s.format(s, a);
        };

        System.out.println(f.apply(new Integer[] {0}));
        System.out.println(f.apply(new Integer[] {2, 10}));
        System.out.println(f.apply(new Integer[] {7, 8, 9, 10}));
        System.out.println(f.apply(new Integer[] {1, 33, 333, 7777}));
        System.out.println(f.apply(new Integer[] {0, 0, 0, 0, 0, 0}));
    }
}

```

Try it on Ideone.

*-1 byte thanks to @KevinCruijssen.*
> 1 votes

# Answer
# Haskell, 47 bytes

```
k=length
f l=map(\s->replicate(k l-k s)' '++s)l

```

That’s a function from a list of strings to a list of strings, like the JavaScript answers. `replicate` allows one to get a list (Haskell strings are lists of characters) of a given size, so I use it — and the bolded assumption in the problem — to generate the padding (its length is `N` − \<length of element\>, for each element of the input list). I would have preferred to use a `printf` based solution rather than this one with `replicate` (it would have been shorter, for one thing) but the import statement kills any savings done on the function itself.
> 1 votes

# Answer
# Groovy, 36 Bytes

```
{a->a.collect{it.padLeft(a.size())}}

```

Takes in array of strings only, outputs array of padded strings.
> 1 votes

# Answer
# JavaScript 33 bytes

similar to @Hedi - but the default padding is ' ', so its 4 chars less

```
a=>a.map(s=>s.padStart(a.length))

```

```
f=a=>a.map(s=>s.padStart(a.length))

console.log(f(["0"]))
console.log(f(["1"]))
console.log(f(["2","3"]))
console.log(f(["2","10"]))
console.log(f(["17" ,"19" ,"2"]))
console.log(f(["1000" ,"400" ,"30" ,"7"]))
```
> 1 votes

# Answer
# K (oK), 11 bytes

**Solution:**

```
,/(-#x)$$x:

```

Try it online!

**Explanation:**

Interpretted right-to-left. Convert to string, and left-pad with length of list, then flatten:

```
,/(-#x)$$x: / the solution                      | example:
         x: / save as 'x'                       |
        $   / string                            | $10 20 30 -> "10","20","30"
       $    / pad right by left                 | 5$"abc" -> "abc  "
  (   )     / do the stuff in brackets together |
    #x      / count x                           | #10 20 30 -> 3
   -        / negate                            |
,/          / flatten (concatenate-over)        | ,/" a"," b"," c" -> " a b c"

```
> 1 votes

# Answer
# Pyth - 7 bytes

Straightforward answer using padding builtin.

```
sm.[;lQ

```

Test Suite.
> 0 votes

# Answer
# C#, 39 bytes

```
s=>s.ConvertAll(c=>c.PadLeft(s.Count));

```

Takes a `List<string>` and outputs a `List<string>`.

Explanation:

```
/*Func<List<string>, List<string>> Lambda =*/ s =>
    s.ConvertAll(c =>                                // Create a new List<string> by...
        c.PadLeft(s.Count)                           // ...padding each element by 'N'
    )
;

```

Would've been a few bytes shorter to use LINQ if the import isn't counted and then returning `IEnumerable<string>` instead of a full blown list:

### C#, 35+18 = 53 bytes

```
using System.Linq;s=>s.Select(c=>c.PadLeft(s.Count));

```
> 0 votes

# Answer
# R, 47 bytes

```
cat(sprintf("%*.f",length(n<-scan()),n),sep="")

```

Reads input from stdin and uses C-style formating with `sprintf`. There should be some way the `cat` function is not needed but couldn't find a way to suppress the quotes on each element without it. If we only want start and end quotes we could use the slightly longer option:

```
paste0(sprintf("%*.f",length(n<-scan()),n),collapse="")

```
> 0 votes

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


title: Prime Factorial

text:
# Question
Title: Prime Factorial
For the purposes of this question, the prime factorial of a number n is the result of multiplying all prime numbers smaller than n, and then multiplying the result by n.

## Your Task:

Write a program or function to find the prime factorial of a number, as outlined above.

## Input:

An integer n where n is greater than one, and the prime factorial of n is smaller than the largest integer your language can support. However, remember this standard loophole. Reasonable integer limits only.

## Output:

The prime factorial of the input.

## Test Cases:

```
4  -> 24
7  -> 210
32 -> 641795684160

```

## Scoring:

This is , lowest score in bytes wins!

# Answer
# Jelly, 5 bytes

```
’ÆRP×

```

**Try it online!**

## How?

```
’ÆRP×   Full program.

’       Decrement.
 ÆR     Inclusive prime range.
   P    Product.
    ×   Multiply by the input.

```

The non-built-in would be **7 bytes**: `’ÆPÐfP×`
> 1 votes

# Answer
# Pyth, 10 bytes

```
*Q*FfP_TSt

```

I'm pretty sure this can be golfed some more...

---

```
*Q*FfP_TSt     Full program, takes input from stdin and outputs to stdout
*Q             Implicitly output $input multiplied by
  *F           The product of
        St(Q)  All numbers less than $input (Q is added automtaically by Pyth)
    fP_T       As long as they are prime

```
> 0 votes

# Answer
# MATLAB/Octave, 23 bytes

```
@(n)prod(primes(n-1))*n

```

Try it online!
> 0 votes

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


title: Is this site down or is it just me?

text:
# Question
Title: Is this site down or is it just me?
## Challenge

The challenge is simple, using http://isup.me, determine whether an inputted website is up or down.

If the site is up, you should return a truthy value and if the site is down, you should return a falsey value.

## Rules

The input will be a web address such as `stackexchange.com` or `google.co.uk`. The input will never have `http://`, `https://` etc. at the start of the string, but may have `www.` or `codegolf.` at start etc.

You should use the site `isup.me/URL` where URL is the input.

When a site is up, it will look like:

http://isup.me/codegolf.stackexchange.com

If a site is down, it will look like:

http://isup.me/does.not.exist

URL shorteners are disallowed apart from isup.me.

## Example inputs

Probably up (depending on current circumstances):

```
google.de
codegolf.stackexchange.com
worldbuilding.meta.stackexchange.com
tio.run
store.nascar.com
isup.me

```

Will be down:

```
made.up.com
fake.com.us
why.why.why.delilah
store.antarcticrhubarbassociation.an

```

## Winning

Shortest code in bytes wins.

# Answer
# sh (+ curl + grep), ~~28~~ 26 bytes

```
curl -L isup.me/$1|grep ^I

```

Outputs via exit status (0 for up, 1 for down). Looks for an `I` at the beginning of a line, which matches when the domain is up (even for the special case of isup.me/isup.me).
> 16 votes

# Answer
# Stacked, 44 bytes

```
['http://isup.me/'\+[CS'!'eq sum 2=out]curl]

```

Asynchronous function that outputs `0` if the site is not up, and any other number greater than `0` if it is up.

Example a:

```
['http://isup.me/'\+['s u'split#'1-put]curl] @:isup

'Is google up?' put 'google.com' isup

```

Output (probably): `Is google up? 1`
> 5 votes

# Answer
# Kotlin REPL - 131 108 106 93 79 55 53 64 63 bytes

First try at Kotlin golfing.
Expects the website in a variable or value named `a`.

*Now with reduced whitespace.*
*Who said "loo" isn't enough?*
*Fixed and shorter, doesn't rely on http://isup.me anymore.*
*No need to open the connection ourselves, just get the stream of data (or not)*
*The task was to use http://isup.me, right? Also: `<` is not a valid character in a URL.*
*Now works with `isup.me` as the website*
*Now reads the website as a line, because one can't assume a variable to contain the website.*

```
"m h" !in java.net.URL("http://isup.me/"+readLine()).readText()

```

Reads one line containing just the website.
Checks for the `m h` part of `from here` that is sent when a site is down.

Returns "true" or "false" respectively.

---

# As a Lambda - 172 120 118 99 85 67 66 bytes

```
{a:String->"m h" !in java.net.URL("http://isup.me/$a").readText()}

```

Can be invoked directly:

```
{ ... }("google.com")

```
> 5 votes

# Answer
# Python3 141 133 113 192 141 bytes

Requires Selenium (including webdriver) for python.

*Thanks to @cairdcoinheringaahing for reducing 42 bytes!*
*Thanks to @V.Courtois for pointing out a simple fix!*

```
from selenium import*
d=webdriver.Firefox();d.get("http://isup.me/"+input());print("up"in d.find_element_by_xpath("//*[@id='content']/p[1]"))

```

Prints `1` if site is up and running, else prints `0`.

Ungolfed version:

```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
urlToTest = "www.f.com"
driver = webdriver.Firefox()
driver.get("http://downforeveryoneorjustme.com/"+urlToTest)
res = driver.find_element_by_xpath("//*[@id='content']/p[1]")
print(1 if "up" in res.text else 0)

```
> 2 votes

# Answer
# Python 2 or 3 with Requests (~~70~~ ~~69~~ 68 bytes)

```
from requests import*;lambda u:"u. "in get("http://isup.me/"+u).text

```

~~1 byte shaved: `"u. "``" u"`~~ Nope, not a valid optimisation.
1 byte shaved: `__import__('requests').``from requests import*;`

This is now really a REPL-only piece of code, and after running this line the function will be named `_`.
> 2 votes

# Answer
# Javascript (ES6), ~~74~~ 66 bytes

```
f=s=>fetch('//isup.me/'+s).then(r=>r.text()).then(t=>/u!/.test(t))

```

Thanks to @Shaggy, who brought to my attention that a resolved promise counts as output.

Problem with this solution that it will throw a CORS error unless I test it on a page that's already at `isup.me`. But currently, that gets redirected to `downforeveryoneorjustme.com`

Older version:

```
~~f=s=>fetch('//isup.me/'+s).then(r=>r.text()).then(t=>alert(t.match(/u!/)))~~
```
> 2 votes

# Answer
# 05AB1E, 22 bytes

```
"isup.me/ÿ".w#214è'‚‰Q

```

Try it online!

Unfortunately `"isup.me/ÿ".w§„ uå` doesn't seem to work.
> 1 votes

# Answer
# Pyth, 24 bytes

```
}" u"s'+"http://isup.me/

```

Return `True` if the site is up, `False` otherwise. The input URL must be quoted. That cannot be tested on the online interpreter because `'` is disabled on it for safety reasons; instead you will need a local copy of Pyth.

**Explanation**

```
                        Q    # Implicit input
       +"http://isup.me/     # Concatenate "http://isup.me/" with the input
      '                      # Open the URL
     s                       # Concatenate all the lines of the returned HTML page
}" u"                        # Test whether " u" is in the page or not

```
> 1 votes

# Answer
## PowerShell, 32 bytes

```
(iwr isup.me/$args)-notmatch'u!'

```
> 1 votes

# Answer
# Haskell (Lambdabot), 157 bytes

```
import Data.ByteString.Lazy.Char8
import Network.HTTP.Simple
f s=httpLBS(parseRequest_$"http://isup.me/"++s)>>=print.not.isInfixOf"u!".unpack.getResponseBody

```

Unfortunately you can't import `Network.HTTP.Simple` on `tio.run`, the easiest way to test would be to run this script (you'll need `stack`):

```
#!/usr/bin/env stack
-- stack --install-ghc --resolver lts-8.19 runghc --package http-conduit

import Data.ByteString.Lazy.Char8
import Network.HTTP.Simple
import Data.List

main :: IO ()
main = mapM_ test [ "google.de", "made.up.com"]
  where test url = print ("testing "++url) >> f url

f :: String -> IO ()
f s=httpLBS(parseRequest_$"http://isup.me/"++s)
 >>=print.not.isInfixOf"u!".unpack.getResponseBody

```
> 1 votes

# Answer
# PowerShell, 25 Bytes

```
!(irm isup.me/$args).html

```

Uses the fact that `Invoke-RestMethod` returns the page with a `.html` property only on failure. (no idea why exactly this happens...)

inverts the line to convert to bool, outputs `True` for a live site or `False` for a down site.

```
PS C:\Users\sweeneyc\Desktop> .\Test-SiteUp.ps1 "connorlsw.com"
True
PS C:\Users\sweeneyc\Desktop> .\Test-SiteUp.ps1 "connorlsw.notawebsite"
False
PS C:\Users\sweeneyc\Desktop> .\Test-SiteUp.ps1 "google.com"
True
PS C:\Users\sweeneyc\Desktop> .\Test-SiteUp.ps1 "isthisreallyasite.com"
False

```
> 1 votes

# Answer
# Halovi, 20 bytes

```
oisup.me/⁰
\p
ye$hd0

```

Outputs `p.` if the site is down, and `e.` if it is up.

Explanation:

```
oisup.me/⁰  ~# Open the concatination of "isup.me/" and arg0
\p          ~# Select first p element
ye$hd0      ~# Edit text with neovim and output result:
            ~#   Go one character before the end of the line and ..
            ~#   delete until beginning

```
> 1 votes

# Answer
# Go, 111 bytes

In typical Go fashion, the shortest method is to shell it out.

```
import"os/exec"
func h(a string)bool{return exec.Command("sh","-c","curl -L isup.me/"+a+"|grep ^I").Run()!=nil}

```

Other implementations here: https://play.golang.org/p/8T5HSDQFmC
> 0 votes

# Answer
# Clojure, 63 bytes

```
#(clojure.string/includes?(slurp(str"http://isup.me/"%))"'s j")

```

Checks if the HTML returned by `slurp` contains the string `"'s j"` (as in, "It **'s j**ust you"). I might be able to find a smaller string that's unique to the page, but it would at most save me 2 bytes. It would also potentially make it less accurate. "'s j" isn't going to appear in the markup anywhere except in that one scenario. A string like "u." however could potentially appear in the URL, which would break it.

```
(defn is-up? [site]
  (clojure.string/includes?
    (slurp (str "http://isup.me/" site))
    "'s j"))

```
> 0 votes

# Answer
# PHP, ~~82~~ 78 bytes

```
<?=$i=$argv[1],+!preg_match("/!.*$i/",file_get_contents("http://isup.me/$i"));

```

Example i/o runs:

```
$ php script.php google.com
> google.com1

```

**Example 2**

```
$ php script.php does.not.exist
> does.not.exist0

```
> 0 votes

# Answer
# Nim, 108 bytes

```
import httpclient,strutils
echo newhttpclient().getcontent("//isup.me/"&stdin.readline.string).find("ks ")<0

```

Unfortunate that `strutils` is needed for `contains`.

Learning Nim, tips appreciated!
> 0 votes

---
Tags: code-golf, internet
---


title: Primitive roots density of number

text:
# Question
Title: Primitive roots density of number
## Definition:

> A number **m** is called a primitive root of a prime **p** the condition that the smallest integer **k** for which **p** dividies **m**<sup>**k**</sup>**-1** is **p-1**

## Your task

Given a tuple **(a,b)** of positive integers, return the fraction:

(number of primes **p** equal to or less than **a** which has **b** as a primitive root) divided by (number of primes equal to or less than **a**)

## Test Cases

Assuming Artin's Conjecture to be true, giving **(A very big number, 2)** should return a value around **.3739558136...**

**The challenge is for the fastest code, not necessarily the shortest one.**

## Timing

My crappy code takes 10 seconds for a million on my PC (intel i3 6th Gen, 8GB RAM, others I forgot), so your code should naturally beat that speed.

This is my first challenge. Feeback is appreciated. :)

# Answer
# C (gcc)

Around 0.6 sec for 1,000,000.

```
int modpow(long b,int e,long n){
	long r=1;
	while(e){
		if(e&1) r=r*b%n;
		b=b*b%n;
		e>>=1;
	}
	return r;
}
float f(int a,int b){
	int ln=1;
	for(int p=2;p<=a;p*=ln,ln++);
	int* primes = malloc((a+1)*(sizeof(int)));
	int** factors = malloc((a+1)*sizeof(int*));
	primes[0] = 0;
	primes[1] = 0;
	for(int i=2;i<=a;i++){
		primes[i] = 1;
		factors[i] = malloc(ln*sizeof(int));
	}
	factors[1] = malloc(sizeof(int));
	factors[1][1] = 0;
	for(int p=2;p*p<=a;p++){
		if(primes[p]){
			for(int j=p*2;j<=a;j+=p){
				primes[j] = 0;
				factors[j][0]++;
				factors[j][factors[j][0]] = p;
			}
		}
	}
	int count1 = 0;
	int count2 = 0;
	for(int p=2;p<=a;p++){
		if(!primes[p]) continue;
		count2++;
		int n=p-1;
		int m=p-1;
		int prim=1;
		for(int j=1;j<=factors[n][0];j++){
			int q=factors[n][j];
			if(modpow(b,n/q,p)==1){
				prim=0;
				break;
			}
			while(m%q==0){
				m/=q;
			}
		}
		if(m>1){
			if(modpow(b,n/m,p)==1){
				prim=0;
			}
		}
		count1 += prim;
	}
	return (float)count1/count2;
}

```

Try it online!
> 3 votes

# Answer
# Mathematica

```
(t=0;
 f=PrimePi[#];
 d=#2;
 For[i=1,i<=f,i++,If[PrimitiveRoot[Prime[i],d]==d,t++]];
 N[t/f])&[1000000,2]//AbsoluteTiming

```

Try it online Paste the code and press shift-enter

Takes 3.2 sec to find 1.000.000
> 2 votes

# Answer
# C++11 + libop

1.23 sec on my slow laptop for 10,000,000.

```
#include <cstdint>
#include <vector>
#include <algorithm>
#include <iostream>
#include <utility>

#include "libop/op.h"

// Returns 2^-32 mod m, -m^(-1) mod 2^32
inline std::pair<uint64_t, uint64_t> mont_modinv32(uint64_t m) {
    uint64_t a = 1ull << 31;
    uint64_t u = 1;
    uint64_t v = 0;

    while (a > 0) {
        a = a >> 1;
        if ((u & 1) == 0) {
            u = u >> 1; v = v >> 1;
        } else {
            u = ((u ^ m) >> 1) + (u & m);
            v = (v >> 1) + (1ull << 31);
        }
    }

    return std::make_pair(u, v);
}

// Returns (ab)R mod n given aR mod n, bR mod n, n and -n^(-1) mod R, with R = 2^32
inline uint64_t montmul32(uint64_t a, uint64_t b, uint64_t n, uint64_t nneginv) {
    uint64_t T = a*b;
    uint32_t m = T*nneginv; // m = T*-n^(-1) (mod 2^32)
    uint64_t t = (T + m*n) >> 32;
    return t >= n ? t - n : t;
}

double f(uint32_t a, uint32_t b) {
    std::vector<uint32_t> primes;
    op::primes_below(a + 1, std::back_inserter(primes));

    int num_primitives = 0;

    for (auto p : primes) {
        if (p == 2) {
            num_primitives += b == 1;
            continue;
        }

        uint32_t s = p - 1;
        uint32_t pneginv = mont_modinv32(p).second;
        uint32_t montb = (uint64_t(b) << 32) % p;
        uint64_t mont1 = (1ull << 32) % p;

        uint32_t pows[32] = {montb};
        for (int i = 1; s >> i; ++i) {
            montb = montmul32(montb, montb, p, pneginv);
            pows[i] = montb;
        }

        bool primitive_root = true;
        for (auto& kv : op::factorization(s)) {
            uint32_t e = s / kv.first;

            uint64_t r = mont1;
            for (int i = 0; e; ++i) {
                if (e & 1) r = montmul32(r, pows[i], p, pneginv);
                e >>= 1;
            }

            if (r == mont1) {
                primitive_root = false;
                break;
            }
        }

        num_primitives += primitive_root;
    }

    return num_primitives / double(primes.size());
}

```
> 2 votes

---
Tags: math, number-theory, fastest-code
---


title: Generate triangular signal

text:
# Question
Title: Generate triangular signal
## Task:

Given sample index, x, calculate sample value f(x) of triangular wave, with period of 4 samples and amplitude 1. Offset can be negative and sample value could be either {0, 1, -1}.

## Test cases:

```
   -5 -> -1
   -4 -> 0
   -3 -> 1
   -2 -> 0
   -1 -> -1
    0 -> 0
    1 -> 1
    2 -> 0
    3 -> -1
    4 -> 0
    5 -> 1

```

Personally I know two approaches in C - the first is using lookup table, the second is using conditional instructions. For brownie points, could you impress me with a pure "math" approach? (I mean a pure functional approach, e.g. not using conditional instructions or using memory for LUT.) But this is not an restriction. If you can't, or your language does not support it - just post any solution

# Answer
# Mathematica, 8 bytes

```
Im[I^#]&

```

### Explanation

```
Im[I^#]&
   I^#    (* Raise the imaginary unit to the input power *)
Im[   ]   (* Take the imaginary part *)

```
> 12 votes

# Answer
# TI-Basic, ~~7~~ ~~5~~ 4 bytes

```
sin(90Ans

```

(Degree mode) -1 byte from @immibis from my old answer.

---

Old answer

```
imag(i^Ans

```

Pure-math approach on a calculator. :)

Just for fun, here's another pure-math (ish) solution for 9 bytes (In radian mode), or 8 bytes (Degree mode)

```
2/πsin<sup>-1</sup>sin(πAns/2 # Radians
90<sup>-1</sup>sin<sup>-1</sup>sin(90Ans # Degrees

```
> 7 votes

# Answer
# Python 2, 20 bytes

```
lambda n:n%2-n%4/3*2

```

Try it online!

I'm running a brute-force search for shorter arithmetic or bitwise expressions, I'll see if anything turns up. This one I hand-found.
> 6 votes

# Answer
# Julia 0.5, 12 bytes

```
!n=(2-n&3)%2

```

I like this approach because it's unlikely to be the shortest in any other language.

Try it online!

### How it works

Julia's operator precedence is a bit unusual: unlike most other languages, bitwise operators have the same precedence as their arithmetic counterparts, so `&` (bitwise multiplication) has the same precedence as `*`.

First, `n&3` takes the input modulo **4**, with positive sign.

The result – **0**, **1**, **2**, or **3** – is then subtracted from **2**, yielding **2**, **1**, **0**, or **-1**.

Finally, we take the signed remainder of the division by **2**, returning **0**, **1**, **0**, or **-1**.
> 5 votes

# Answer
# Jelly, 3 bytes

```
ı*Ċ

```

Try it online!

### How it works

```
ı*Ċ  Main link. Argument: n

ı*   Elevate i, the imaginary unit, to the n-th power.
  Ċ  Take the imaginary part of the result.

```
> 4 votes

# Answer
# dc, 13

Not sure if you count the modulo `%` operator as "pure math":

```
?1+d*v4%1-2%p

```

Try it online. Note that `dc` uses `_` instead of `-` to indicate negative numbers.

### Explanation

```
?              # read input
 1+            # add 1
   d*v         # duplicate, multiply, square root (poor-mans abs())
      4%       # mod 4
        1-     # subtract 1
          2%   # mod 2
            p  # print

```

Note that `dc`'s `%` mod operator is the standard "CPU" version that maps negative values to negative values.
> 4 votes

# Answer
# brainfuck, 136 bytes

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

```

Try it online!

There's probably a more trivial answer, but this essentially uses a table of values. Although brainfuck takes input as ASCII characters with positive values from 0 to 127, it still works as if it were able to accept negative values (to test, replace the `,` with `n` amount of `-` characters).

# How it works

```
>,                                   take input (X)
>++++<                               take second input for modulo (4)
[>->+<[>]>[<+>-]<<[<]>-]             calculate X mod 4
>>>>-[>+<-----]>--                   create initial '1' character
[-<+>>>+>>>+>>>+<<<<<<<<]            duplicate '1' four times as 1,1,1,1
<->>>>>>->--[>+<++++++]>++<<<<<<<<<< change 1,1,1,1 to 0,1,0,-1
[[->>>+<<<]>>>-]>[.[-]]>.            move to the right X%4 * 3 times, then print the following two characters ( 0, 1, 0,-1)

```
> 2 votes

# Answer
# Python, ~~26~~ ~~24~~ 21 bytes

```
lambda x:(1j**x).imag

```

-2 bytes thanks to ValueInk for realizing that the mathematical method is actually longer than the trivial approach :P
-3 bytes thanks to Dennis for pointing out that I don't need the `int(...)`, thus making this shorter :)
> 1 votes

# Answer
# Mathematica, 18 bytes

```
#~JacobiSymbol~46&

```
> 1 votes

# Answer
# Python, 20 bytes

```
lambda n:n%2*(2-n%4)

```

An unnamed function which returns the result.

**Try it online!**
> 1 votes

# Answer
# Pari/GP, 12 bytes

```
n->imag(I^n)

```

Try it online!
> 1 votes

# Answer
# PHP, 20 bytes

```
<?=2<=>($argn&3?:2);

```
> 1 votes

# Answer
# Haskell, 19 bytes

Port of Dennis's Julia solution, just because he said it wouldn't be shortest in any other language. (Someone might still prove me wrong that it's shortest in Haskell.)

```
f n=rem(2-n`mod`4)2

```

Try it online!

Haskell has two different remainder functions, one (`rem`) works like the Julia one, while the other (`mod`) gives a positive result even when the first argument is negative, and so is suitable for translating `&3`. (Haskell's *actual* `&`, called `.&.`, alas requires an `import Data.Bits`.)
> 1 votes

# Answer
# Octave, 22 bytes

```
@(x)round(sin(x*pi/2))

```

Try it online!
> 1 votes

# Answer
# Ruby, 20 bytes

Simple and clean.

```
->x{[0,1,0,-1][x%4]}

```
> 0 votes

# Answer
# C99, 27 bytes

Assuming you want the wave to be centered at the origin:

```
f(n){return cpow(1i,n)/1i;}

```

otherwise `f(n){return cpow(1i,n);}` will do. I originally had a `cimag` in there, but apparently trying to return an `int` from a `_Complex int` yields the real part, so I used that. It makes sense, but it'snnothing I would have predicted. Behavior is the same in `gcc` and `clang`
> 0 votes

# Answer
# 05AB1E, 5 bytes

```
4%<Ä<

```

Try it online!

---

**The output is reversed, but from what I understood this is allowed:**

+1 byte to multiply output by -1 using `(`.

```
   -5 -> 1
   -4 -> 0
   -3 -> -1
   -2 -> 0
   -1 -> 1
    0 -> 0
    1 -> -1
    2 -> 0
    3 -> 1
    4 -> 0
    5 -> -1

```

---

```
4%    # Amplitude of 4...
  <   # Period of 1...
   Ä  # Absolute value...
    < # Period of 1 centered at 0...

```
> 0 votes

# Answer
# Pyth - 7 bytes (possibly 6)

```
ta2%tQ4

```

Try it

If the phase of the wave isn't important, 6 bytes:

```
ta2%Q4

```

Try it

Explanation:

```
ta2%tQ4
     Q    # The input
    t     # Subtract 1 to get the phase right (might not be necessary)
   %  4   # Take mod 4
 a2       # Absolute value of the result - 2
t         # Subtract 1 so the result is in [-1,0,1]

```
> 0 votes

# Answer
# AWK, 26 bytes

```
{$0=(sqrt(($0%4)^2)-2)%2}1

```

Try it online!

This is an alternate approach using trig functions without the modulus operator.

```
{$0=int(sin($0*atan2(0,-1)/2))}1

```

Try it online !
> 0 votes

# Answer
# Javascript ES6, ~~18~~ 17 bytes

```
n=>n&1&&(++n&2)-1

```

Firstly, check if the input is even or odd and return 0 for all even values. For all odd inputs, increment and bitwise with `0b10` to remove any bits that don't interest us, then return the answer with an offset.

```
const f = n=>n&1&&(++n&2)-1;

for (let i = -5; i < 6; i++) {
  document.body.appendChild(document.createElement('pre')).innerHTML = `f(${i}) => ${f(i)}`;
}
```
> 0 votes

# Answer
# JavaScript, 15 bytes

```
n=>n&3&&2-(n&3)

```

Bitwise and 3 is equivalent to modulo 4 except without the weird rule on JavaScript's modulos of negative numbers. I did polynomial regression on the first four points at first but then realized I was being dumb because (1, 1), (2, 0), and (3, -1) is just 2-n.

```
a=n=>n&1&&2-(n&3);
console.log([a(-5), a(-4), a(-3), a(-2), a(-1), a(0), a(1), a(2), a(3), a(4), a(5)])
```
> 0 votes

# Answer
# , 19 bytes

```
function(n)Im(1i^n)

```

Try it online!

A port of JungHwan Min's Mathematica answer.
> 0 votes

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


title: Remove ambiguous plural(s)!

text:
# Question
Title: Remove ambiguous plural(s)!
Programming is very rigid. You can't tell a program to "output the banana count", you have to tell it to `print(bananas)`.

But when you do that, you end up with a problem: you don't know how many bananas you have beforehand, so you don't know whether to use a plural.

Sometimes, programmers go the lazy way. Instead of checking, they just print `there are X banana(s)`.

But that's ugly, so we need a program to fix this.

# The method(s)

To remove the ambiguous plurals in a string, follow the following steps:

1. Split the string on spaces into a list of words.
2. For every word that ends with `(s)`, do the following:

* If the preceding word is `a`, `an`, `1` or `one`, remove the `(s)` at the end of the word.
    * Otherwise, if the word is the first word in the string or the preceding word is not `a`, `an`, `1` or `one`, replace the `(s)` at the end of the word with `s`.
3. Join the list of words back together into a string, preserving the original whitespace.

### Example(s)

Let's take a string `there's a banana(s) and three apple(s)`.

First, we split the string into a list of words: `["there's", "a", "banana(s)", "and", "three", "apple(s)"]`

For the second step, we take the two words ending with `(s)`: `banana(s)` and `apple(s)`.

The word before `banana(s)` is `a`, so we remove the `(s)`, making it `banana`. The word before `apple(s)` is `three`, so we change the `(s)` to `s`, thus it becomes `apples`.

We now have `["there's", "a", "banana", "and", "three", "apples"]`. Joining the list back together, we get `there's a banana and three apples`. This is our end result.

# The challenge(s)

Create a program or function that takes an ambiguous string in any reasonable format and returns the un-ambiguated version of that string.

You may assume the string contains no newlines, tabs or carriage returns.

I forgot to specify whether to split on groups of spaces or spaces (i.e. whether `okay then` with two spaces should be `["okay", "then"]` or `["okay", "", "then"]`) when posting the challenge, so you may assume either form of splitting.

# Test case(s)

```
Input                                         -> Output
there are two banana(s) and one leprechaun(s) -> there are two bananas and one leprechaun
there's a banana(s) and three apple(s)        -> there's a banana and three apples
apple(s)                                      -> apples
one apple(s)                                  -> one apple
1 banana(s)                                   -> 1 banana
banana                                        -> banana
preserve    original      whitespace(s)       -> preserve    original      whitespaces
11 banana(s)                                  -> 11 bananas
an apple(s)                                   -> an apple
this is a te(s)t                              -> this is a te(s)t
I am a (s)tranger(s)                          -> I am a (s)tranger

```

# Scoring

As this is , the submission with the least bytes wins!

# Answer
# Mathematica, ~~151~~ 148 bytes

```
StringReplace[j=" ";k=Except@j;j<>j<>#<>j,j~~a:k...~~s:j..~~w:k..~~"(s)"~~j:>{j,a,s,w,If[FreeQ[a,"a"|"an"|"1"|"one"],"s",""]}<>j]~StringTake~{3,-2}&

```

### Explanation

```
j=" ";k=Except@j

```

Set `j` to a whitespace character(s). Set `k` to the pattern "not `j`" (= non-whitespace character).

```
j<>j<>#<>j

```

Prepend two whitespace(s) and append one whitespace(s) to the input.

```
j~~a:k...~~s:j..~~w:k..~~"(s)"~~j

```

For a substring(s) matching the pattern:

1. One whitespace(s), followed by
2. a length-zero or longer substring consisting of only non-whitespace character(s) (quantifier) (call this `a`), followed by
3. a length-one or longer substring consisting of only whitespace character(s) (call this `s`), followed by
4. a length-one or longer substring consisting of only non-whitespace character(s) (word) (call this `w`), followed by
5. the string `"(s)"`, followed by
6. a whitespace(s)

```
If[FreeQ[a,"a"|"an"|"1"|"one"],"s",""]

```

If `a` is not one of the singular word(s), evaluate to `"s"`, otherwise `""`.

```
StringReplace[..., ... :>{j,a,s,w,If[FreeQ[a,"a"|"an"|"1"|"one"],"s",""]}<>j]

```

Replace the matching pattern with `j`, `a`, `s`, `w`, `If[FreeQ[a,"a"|"an"|"1"|"one"],"s",""]`, and `j` joined together.

```
... ~StringTake~{3,-2}

```

Take from position 3 to position -2 (1-indexed; negative indices count from the end). This is because we added three space(s) in the beginning.
> 6 votes

# Answer
# Python 3, 94 bytes

```
lambda s,r=re.sub:r(r"\(s\)( |$)","s",r(r"\b(an?|1|one)(\s+)(.+)\(s\)",r"\1\2\3",s))
import re

```

Try it online!

-4 bytes thanks to i cri everytim (I think this is acceptable)
> 5 votes

# Answer
# Mathematica, 313 bytes

```
(Table[If[StringLength@z[[i]]>3&&StringTake[z[[i]],-3]=="(s)",z[[i]]=StringDrop[z[[i]],-3];t=1;While[z[[i-t]]=="",t++];If[FreeQ[{"a","an","1","one"},z[[i-t]]],z[[i]]=z[[i]]<>"s"]],{i,2,Length[z=StringSplit[#," "]]}];If[StringTake[z[[1]],-3]=="(s)",z[[1]]=StringDrop[z[[1]],-3];z[[1]]=z[[1]]<>"s"];StringRiffle@z)&

```
> 4 votes

# Answer
# Retina, 53 bytes

```
(( |^)(a|an|1|one) [^ ]*)\(s\)( |$)
$1
\(s\)( |$)
s$1

```

Try it online!
> 4 votes

# Answer
## Perl 5, 43 + 1 (-p) = 44 bytes

```
s/\b((one|1|an?) +)?\S+\K\(s\)\B/"s"x!$1/ge

```

Match every `(s)` at end of word, replace it with `!$1` (1 or 0) esses.
> 3 votes

# Answer
# Pyth - 53 bytes

Follows the algorithm pretty much as it is.

```
K+kczdjdt.e?q"(s)"gb_2+<b_3*\s!}@Ktk[\a"an""one"\1)bK

```

Try it online here.
> 2 votes

# Answer
# Jelly,  ~~52 51~~  49 bytes

Jelly has not got one regex(s) atom

```
Ṫ
Ñ;”s
Ṫḣ-3
UṪw“)s(”⁼1
“µḣ⁴µuʠg*»ḲċḢ‘×Ç‘
⁶;ḲÇĿ2ƤK

```

A full program accepting a string (using Python formatting if multiline or containing quotes) and printing the output.

**Try it online!** or see the test-suite.

### How?

```
Ṫ - Link 1, tail: two words (list of lists)
Ṫ - tail

Ñ;”s - Link 2, tail and replace last three chars with an 's': two words (list of lists)
Ñ    - call the next link (3) as a monad
  ”s - literal 's'
 ;   - concatenate

Ṫḣ-3 - Link 3, tail and remove the last three chars: two words (list of lists)
Ṫ    - tail
  -3 - literal minus three
 ḣ   - head from index (1-indexed and modular)

UṪw“)s(”⁼1 - Link 4, tail ends with "(s)"?: two words (list of lists)
U          - upend (reverse each word)
 Ṫ         - tail
   “)s(”   - literal [')', 's', '('] - that is "(s)" reversed
  w        - index of first sublist equal to that or 0 if not found
         1 - literal one
        ⁼  - equal?

“µḣ⁴µuʠg*»ḲċḢ‘×Ç‘ - Link 5, categorise: two words (list of lists)
“µḣ⁴µuʠg*»        - compression of string "a 1" + word " an" + word " one"
          Ḳ       - split on spaces = ["a", "1", "an", "one"]
            Ḣ     - head (the first word)
           ċ      - count occurrences (of head in the list - either 0 or 1)
             ‘    - increment
               Ç  - call the last link (4) as a monad - i.e. f(two words)
              ×   - multiply
                ‘ - increment - so we have: 1 for ["1", "blah"],
                  -             2 for ["blah", "blah(s)"] or 3 for ["1", "blah(s)"]

⁶;ḲÇĿ2ƤK - Main link: list of characters, the string
⁶        - literal space character
 ;       - concatenate (place a space at the beginning as we want to inspect pairs)
  Ḳ      - split on spaces (giving an empty list at the start)
     2Ƥ  - for all infixes of length two:
    Ŀ    -   call the link at the given index as a monad:
   Ç     -     call the last link (5) as a monad
       K - join the result with spaces
         - implicit print

```
> 2 votes

# Answer
# Java (OpenJDK 8), ~~91~~ ~~83~~ 96 bytes

```
s->s.replaceAll("((^| )(an?|1|one) +\\S+)\\(s\\)(?= |$)","$1").replaceAll("\\(s\\)(?= |$)","s");

```

Try it online!
> 2 votes

# Answer
# Perl 5, 56 + 1 (`-p`) = 57 bytes

```
s/\b(an?|1|one) +\S+\K\(s\)(?= |$)//g;s/\(s\)( |$)/s$1/g

```

Try it online!
> 1 votes

# Answer
## JavaScript (ES6), ~~88~~ 87 bytes

```
a=>a.replace(/(\S+)( +)(\S+)\(s\)/g,(m,f,s,w)=>f+s+w+(/^(a|an|1|one)$/.exec(f)?'':'s'))

```

Explanation coming soon.
> 0 votes

# Answer
## JavaScript (ES6), 84 bytes

```
s=>s.replace(/((^|\S+ +)\S+)\(s\)(?!\S)/g,(_,a)=>a+(/^(1|an?|one) /.test(a)?'':'s'))

```

Here's an interesting way to rearrange the last part, which is sadly 2 bytes longer:

```
s=>s.replace(/((^|\S+ +)\S+)\(s\)(?!\S)/g,(_,a)=>a+'s'.slice(/^(1|an?|one) /.test(a)))

```
> 0 votes

# Answer
# JavaScript (SpiderMonkey), 82 bytes

```
s=s.replace(/(\S+ +(\S+))\(s\)\B/g,(_,a)=>a+("s"[+/^(1|one|an?)\b/i.test(a)]||""))

```

Try it online!

### 78 Byte version (less robust)

```
s=s.replace(/(\S+ +(\S*))\(s\)/g,(_,a)=>a+("s"[+/^(1|one|an?)/i.test(a)]||""))

```

This is a modified version of ETHproductions' (I don't have 50 rep.)

### Explanation

* `/(\S+ +(\S+))\(s\)/g` \- the actual pattern to look for (`amount object(s)`)
* `(_,a)=>a` \- `_` is a catch all variable, `a` is the `(\S+ +(\S+))`
* `"s"[+/^(1|one|an?)/i.test(a)]||""` \- instead of slicing the array, just make a dummy array and get the index (`+/.../.test` returns a number)
    + should `"s"[+/^(1|one|an?)/i.test(a)]` return `undefined` (`true`, or `1` for the test) return `""`
> 0 votes

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


title: 90% fail this challenge?

text:
# Question
Title: 90% fail this challenge?
I guess I'm not the only one who have seen this kind of image on Facebook (and other sites).

The picture above was posted 16 days ago, and has accumulated 51 k comments. Some answers: 0, 4, 8, 48, 88, 120, 124 and so on.

# Challenge:

The mathematics in the question doesn't make sense1, so we can't find the correct answer by looking at the equation (or whatever you'd call that mess of numbers and operators). However, there's a very large number of people who have answered, and 10% of those people are right!

Let's find the right answer!

---

Take an integer, percent, decimal value in `0-1`, or fraction `N` representing how many percent of the test group who failed the question (or optionally how many answered correctly), and a list of numbers representing the answers people post.

Find the number that `100-N` percent of the test group answered and output it. If there are more than one answer that matches this criterion, then you must output all of them. If there are no answers that are represented `100-N` percent of the time then you must output the number that's closest (measured in number of answers from `100-N`).

To make the input rules for `N` clear: If 90 % fails, then you may input `90`, `10`, `0.9` or `0.1`. You must specify which one you choose. You may assume that the percentage numbers are integers.

---

### Test cases:

In the test cases below, `N` is the percentage that failed the test. You may choose to input using any of the allowed input methods.

```
N:  90   (meaning 90 % will fail and 10 % answer correctly)
List: 3 1 5 6 2 1 3 3 2 6
Output: 5   (because 90 % of the answers weren't 5)
---
N:  50   (50 % will answer correctly)
List: 3 6 1 6
Output: 6   (because 50 % of the answers weren't 6)
---
N:  69   (31 % will answer correctly)
List: 1 9 4 2 1 9 4 3 5 1 2 5 2 4 4 5 2 1 6 4 4 3
Output: 4    (because 31% of 22 is 6.82. There are 6 fours, which is the
              closest to 6.82)
---
N = 10   (90 % will answer correctly)
List: 1 2 3 4 5 6 7 8 9 10
Output: 1 2 3 4 5 6 7 8 9 10 (because 9/10 will answer correctly. All numbers
                              have been answered the same number of times, thus
                              all are equally likely to be correct.
---
N:  90
List: 1 1 1
Output: 1

```

---

1 Please don't argue with me here. If you "know" *the answer*, join the other 10% and post it on Facebook!

# Answer
# MATL, ~~16~~ 14 bytes

-1 byte thanks to @Giuseppe

-1 byte thanks to @LuisMendo

```
SY'ts/i-|tX<=)

```

**Explanation:**

```
        % implicit input
S       % sort
Y'      % run-length encoding
ts      % duplicate elements and sum (get number of elements)
/       % array right division (get array of probability for each answer)
i-|     % get absolute difference with second input
tX<     % duplicate and get minimum value
=)      % get each answer that match with the minimum value
        % (implicit) convert to string and display

```

Try it online! or verify all test cases
> 6 votes

# Answer
# , 65 bytes

```
function(N,A,x=table(A))names(x)[!(y=(abs(1-x/sum(x)-N)))-min(y)]

```

Try it online!

Takes `N` as a number between `0` and `1`, and `A` as a vector (sometimes taken from STDIN in the TIO link so I don't have to turn them to R vectors). Returns a list of strings, as allowed by the OP.

```
function(N,A){
 x <- table(A)               # count occurrences of each value in A
 pct <- 1 - x/sum(x)         # compute percentages different from each value
 y <- abs(pct - N)           # find distances from N
 idx <- y!=min(y)            # find the indices of the minimum/minima
 names(x)[idx]               # return the names of the table (strings)
}

```
> 4 votes

# Answer
# Jelly, 19 bytes

```
ĠL€÷⁸L¤e€ạÐṂ¥Tị⁸QṢ¤

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES7), ~~103~~ 99 bytes

Takes input as `(a, r)` where ***a*** is the list of answers and ***r*** is the expected success ratio in **\[0...1\]**. Returns a **`Set`**.

```
(a,r,m)=>a.map(n=>(d=a.reduce((p,c)=>p-=c==n,r*a.length)**2)>m||(d==m?s:(m=d,s=new Set)).add(n))&&s

```

### Test cases

```
let f =

(a,r,m)=>a.map(n=>(d=a.reduce((p,c)=>p-=c==n,r*a.length)**2)>m||(d==m?s:(m=d,s=new Set)).add(n))&&s

format = s => JSON.stringify(Array.from(s))

console.log(format(f([3, 1, 5, 6, 2, 1, 3, 3, 2, 6], 0.1))) // 5
console.log(format(f([3, 6, 1, 6], 0.5))) // 6
console.log(format(f([1, 9, 4, 2, 1, 9, 4, 3, 5, 1, 2, 5, 2, 4, 4, 5, 2, 1, 6, 4, 4, 3], 0.31))) // 4
console.log(format(f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0.90))) // 1 2 3 4 5 6 7 8 9 10
console.log(format(f([1, 1, 1], 0.10))) // 1
```
> 1 votes

# Answer
# 05AB1E, ~~19~~ ~~16~~ 15 bytes

Takes rate of success in the form `0.31` (meaning 31% succeeds).

```
{γD€gDO/IαWQÏ˜Ù

```

Try it online!
> 0 votes

# Answer
# Python 2, 91 bytes

```
def f(l,p):c=[(abs(len(l)*p-l.count(a)),a)for a in l];print{v for x,v in c if x==min(c)[0]}

```

Try it online!

Takes P as success (`0.1` = 10% correct)
> 0 votes

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