title: Find the Mr of a Given Compound!

text:
# Question
Title: Find the Mr of a Given Compound!
## Challenge

Given the formula of a chemical, output the Mr of the compound.

## Equation

Each element in the compound is followed by a number that denotes the number of said atom in the compound. If there isn't a number, there is only one of that atom in the compound.

Some examples are:

* Ethanol (C2H6O) would be `C2H6O` where there are two carbon atoms, 6 hydrogen atoms and 1 oxygen atom
* Magnesium Hydroxide (MgO2H2) would be `MgO2H2` where there is one magnesium atom, two oxygen atoms and two hydrogen atoms.

Note that you will never have to handle brackets and each element is included only once in the formula.

Whilst most people will probably stick to the order they feel most comfortable with, there is no strict ordering system. For example, water may be given as either `H2O` or `OH2`.

## Mr

*Note:* Here, assume formula mass is the same as molecular mass

The Mr of a compound, the molecular mass, is the sum of the atomic weights of the atoms in the molecule.

The only elements and their atomic weights to 1 decimal place that you have to support (hydrogen to calcium, not including noble gases) are as follows. They can also be found here

```
H  - 1.0      Li - 6.9      Be - 9.0
B  - 10.8     C  - 12.0     N  - 14.0
O  - 16.0     F  - 19.0     Na - 23.0
Mg - 24.3     Al - 27.0     Si - 28.1
P  - 31.0     S  - 32.1     Cl - 35.5
K  - 39.1     Ca - 40.1

```

You should always give the output to one decimal place.

For example, ethanol (`C2H6O`) has an Mr of `46.0` as it is the sum of the atomic weights of the elements in it:

```
12.0 + 12.0 + 1.0 + 1.0 + 1.0 + 1.0 + 1.0 + 1.0 + 16.0
(2*C + 6*H + 1*O)

```

## Input

A single **string** in the above format. You can guarantee that the elements included in the equation will be actual elemental symbols.

The given compound isn't guaranteed to exist in reality.

## Output

The total Mr of the compound, to 1 decimal place.

## Rules

Builtins which access element or chemical data are disallowed (sorry Mathematica)

## Examples

```
Input > Output
CaCO3 > 100.1
H2SO4 > 98.1
SF6 > 146.1
C100H202O53 > 2250.0

```

## Winning

Shortest code in bytes wins.

> This post was adopted with permission from caird coinheringaahing. *(Post now deleted)*

# Answer
> 6 votes
# Jelly, 63 bytes

```
ḟØDOP%⁽¡ṛị“ÇṚÆ’BH+“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘¤÷5
fØDVȯ1×Ç
Œs>œṗ⁸ḊÇ€S

```

A monadic link accepting a list of characters and returning a number.

**Try it online!**

### How?

```
ḟØDOP%⁽¡ṛị“ÇṚÆ’BH+“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘¤÷5 - Link 1, Atomic weight: list of characters
                                            -                              e.g. "Cl23"
 ØD                                         - digit yield = "0123456789"
ḟ                                           - filter discard                      "Cl"
   O                                        - cast to ordinals                [67,108]
    P                                       - product                            7236
      ⁽¡ṛ                                   - base 250 literal = 1223
     %                                      - modulo                             1121
                                        ¤   - nilad followed by link(s) as a nilad:
          “ÇṚÆ’                             -   base 250 literal  = 983264
               B                            -   convert to binary = [    1,    1,     1,     1,   0,  0,  0,   0, 0,  0,  0, 0,     1,     1,     1, 0, 0,  0,  0,   0]
                H                           -   halve             = [  0.5,  0.5,   0.5,   0.5,   0,  0,  0,   0, 0,  0,  0, 0,   0.5,   0.5,   0.5, 0, 0,  0,  0,   0]
                  “Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘    -   code-page indexes = [177  , 34  , 160  , 200  , 135, 54, 60, 115, 0, 95, 45, 5, 121  , 140  , 195  , 0, 0, 70, 80, 155]
                 +                          -   addition          = [177.5, 34.5, 160.5, 200.5, 135, 54, 60, 115, 0, 95, 45, 5, 121.5, 140.5, 195.5, 0, 0, 70, 80, 155]
         ị                                  - index into (1-indexed and modular)
                                            -    ...20 items so e.g. 1121%20=1 so 177.5
                                         ÷5 - divide by 5                          35.5

fØDVȯ1×Ç - Link 2: Total weight of multiple of atoms: list of characters   e.g. "Cl23"
 ØD      - digit yield = "0123456789"
f        - filter keep                                                            "23"
   V     - evaluate as Jelly code                                                  23
    ȯ1   - logical or with one (no digits yields an empty string which evaluates to zero)
       Ç - call last link (1) as a monad (get the atomic weight)                   35.5
      ×  - multiply                                                               816.5

Œs>œṗ⁸ḊÇ€S - Main link: list of characters                             e.g. "C24HCl23"
Œs         - swap case                                                      "c24hcL23"
  >        - greater than? (vectorises)                                      10011000
     ⁸     - chain's left argument                                          "C24HCl23"
   œṗ      - partition at truthy indexes                          ["","C24","H","Cl23"]
      Ḋ    - dequeue                                                 ["C24","H","Cl23"]
       Ç€  - call last link (2) as a monad for €ach                  [  288,  1,  816.5]
         S - sum                                                                 1105.5

```

# Answer
> 6 votes
# Python 3,  ~~189 182~~  168 bytes

-14 bytes by using the hash from Justin Mariner's JavaScript (ES6) answer.

```
import re
lambda s:sum([[9,35.5,39.1,24.3,28.1,14,16,31,40.1,23,32.1,10.8,12,27,6.9,19,0,1][int(a,29)%633%35%18]*int(n or 1)for a,n in re.findall("(\D[a-z]?)(\d*)",s)])

```

**Try it online!**

---

Below is the 182 byte version, I'll leave the explanation for this one - the above just changes the order of the weights, uses `int` to convert the element name from base `29`, and uses different dividends to compress the range of integers down - see Justin Mariner's answer.

```
import re
lambda s:sum([[16,31,40.1,32.1,0,24.3,12,39.1,28.1,19,0,9,10.8,23,27,35.5,6.9,14,1][ord(a[0])*ord(a[-1])%1135%98%19]*int(n or 1)for a,n in re.findall("(\D[a-z]?)(\d*)",s)])

```

An unnamed function accepting a string, `s`, and returning a number.

**Try it online!**

### How?

Uses a regex to split the input, `s`, into the elements and their counts using:
`re.findall("(\D[a-z]?)(\d*)",s)`
`\D` matches exactly one non-digit and `[a-z]?` matches 0 or 1 lowercase letter, together matching elements. `\d*` matches 0 or more digits. The parentheses make these into two groups, and as such `findall("...",s)` returns a list of tuples of strings, `[(element, number),...]`.

The number is simple to extract, the only thing to handle is that an empty string means 1, this is achieved with a logical `or` since Python strings are falsey: `int(n or 1)`.

The element string is given a unique number by taking the product of its first and last character's ordinals (usually these are the same e.g. S or C, but we need to differentiate between Cl, C, Ca, and Na so we cannot just use one character).

These numbers are then hashed to cover a much smaller range of \[0,18\], found by a search of the modulo space resulting in `%1135%98%19`. For example `"Cl"` has ordinals `67` and `108`, which multiply to give `7736`, which, modulo `1135` is `426`, which modulo `98` is `34`, which modulo `19` is `15`; this number is used to index into a list of integers - the 15th (0-indexed) value in the list:
`[16,31,40.1,32.1,0,24.3,12,39.1,28.1,19,0,9,10.8,23,27,35.5,6.9,14,1]`
is `35.5`, the atomic weight of Cl, which is then multiplied by the number of such elements (as found above).

These products are then added together using `sum(...)`.

# Answer
> 4 votes
# PHP, 235 bytes

```
preg_match_all("#([A-Z][a-z]?)(\d*)#",$argn,$m);foreach($m[1]as$v)$s+=array_combine([H,Li,Be,B,C,N,O,F,Na,Mg,Al,Si,P,S,Cl,K,Ca],[1,6.9,9,10.8,12,14,16,19,23,24.3,27,28.1,31,32.1,35.5,39.1,40.1])[$v]*($m[2][+$k++]?:1);printf("%.1f",$s);

```

Try it online!

Instead of `array_combine([H,Li,Be,B,C,N,O,F,Na,Mg,Al,Si,P,S,Cl,K,Ca],[1,6.9,9,10.8,12,14,16,19,23,24.3,27,28.1,31,32.1,35.5,39.1,40.1])` you can use `[H=>1,Li=>6.9,Be=>9,B=>10.8,C=>12,N=>14,O=>16,F=>19,Na=>23,Mg=>24.3,Al=>27,Si=>28.1,P=>31,S=>32.1,Cl=>35.5,K=>39.1,Ca=>40.1]` with the same Byte count

# Answer
> 3 votes
# JavaScript (ES6), 150 bytes

```
c=>c.replace(/(\D[a-z]?)(\d+)?/g,(_,e,n=1)=>s+=[9,35.5,39.1,24.3,28.1,14,16,31,40.1,23,32.1,10.8,12,27,6.9,19,0,1][parseInt(e,29)%633%35%18]*n,s=0)&&s

```

Inspired by Jonathan Allan's Python answer, where he explained giving each element a unique number and hashing those numbers to be in a smaller range.

The elements were made into unique numbers by interpreting them as base-29 (0-9 and A-S). I then found that `%633%35%18` narrows the values down to the range of `[0, 17]` while maintaining uniqueness.

## Test Snippet

```
f=
c=>c.replace(/(\D[a-z]?)(\d+)?/g,(_,e,n=1)=>s+=[9,35.5,39.1,24.3,28.1,14,16,31,40.1,23,32.1,10.8,12,27,6.9,19,0,1][parseInt(e,29)%633%35%18]*n,s=0)&&s
```

```
Input: <input oninput="O.value=f(this.value)"><br>
Result: <input id="O" disabled>
```

# Answer
> 2 votes
## Clojure, ~~198~~ 194 bytes

Update: better to `for` than `reduce`.

```
#(apply +(for[[_ e n](re-seq #"([A-Z][a-z]?)([0-9]*)"%)](*(if(=""n)1(Integer. n))({"H"1"B"10.8"O"16"Mg"24.3"P"31"K"39.1"Li"6.9"C"12"F"19"Al"2"S"32.1"Ca"40.1"Be"9"N"14"Na"23"Si"28.1"Cl"35.5}e))))

```

Original:

```
#(reduce(fn[r[_ e n]](+(*(if(=""n)1(Integer. n))({"H"1"B"10.8"O"16"Mg"24.3"P"31"K"39.1"Li"6.9"C"12"F"19"Al"2"S"32.1"Ca"40.1"Be"9"N"14"Na"23"Si"28.1"Cl"35.5}e))r))0(re-seq #"([A-Z][a-z]?)([0-9]*)"%))

```

I'm wondering if there is a more compact way to encode the look-up table.

# Answer
> 2 votes
# Python 3, 253 bytes

```
def m(f,j=0):
 b=j+1
 while'`'<f[b:]<'{':b+=1
 c=b
 while'.'<f[c:]<':':c+=1
 return[6.9,9,23,40.1,24.3,27,28.1,35.5,31,32.1,39.1,1,10.8,12,14,16,19]['Li Be Na Ca Mg Al Si Cl P S K H B C N O F'.split().index(f[j:b])]*int(f[b:c]or 1)+(f[c:]>' 'and m(f,c))

```

Try it online!

# Answer
> 1 votes
# Python 3 - 408 bytes

*This is mainly @ovs' solution, since he golfed it down by over 120 bytes... See the initial solution below.*

```
e='Li Be Na Ca Mg Al Si Cl P S K H B C N O F'.split()
f,g=input(),[]
x=r=0
for i in e:
 if i in f:g+=[(r,eval('6.9 9 23 40.1 24.3 27 28.1 35.5 31 32.1 39.1 1 10.8 12 14 16 19'.split()[e.index(i)]))];f=f.replace(i,' %d- '%r);r+=1
h=f.split()
for c,d in zip(h,h[1:]):
 s=c.find('-')
 if-1<s:
  if'-'in d:
   for y in g:x+=y[1]*(str(y[0])==c[:s])
  else:
   for y in g:x+=y[1]*int(d)*(str(y[0])==c[:s])
print(x)

```

Try it online!

# Python 3 - ~~550 548~~ 535 bytes (lost the count with indentation)

Saved 10 bytes thanks to @cairdcoinheringaahing and 3 saved thanks to ovs

I had a personal goal to not use any regex, and do it the fun, old-school way... It turned out to be 350 bytes longer than the regex solution, but it only uses Python's standard library...

```
a='Li6.9 Be9. Na23. Ca40.1 Mg24.3 Al27. Si28.1 Cl35.5 P-31. S-32.1 K-39.1 H-1. B-10.8 C-12. N-14. O-16. F-19.'.split()
e,m,f,g,r=[x[:1+(x[1]>'-')]for x in a],[x[2:]for x in a],input(),[],0
for i in e:
 if i in f:g.append((r,float(m[e.index(i)])));f=f.replace(i,' '+str(r)+'- ');r+=1;
h,x=f.split(),0
for i in range(len(h)):
 if '-'in h[i]:
    if '-'in h[i+1]:
     for y in g:x+=y[1]*(str(y[0])==h[i][:h[i].index('-')])
    else:
        for y in g:
         if str(y[0])==h[i][:h[i].index('-')]:x+=(y[1])*int(h[i+1])
 else:1
print(x)

```

***Try it online!***

---

If anyone is willing to golf it down (with indentation fixes and other tricks...), it will be 100% well received, feeling like there's a better way to do this...

# Answer
> 1 votes
## Mathematica, ~~390~~ ~~338~~ 329 Bytes

Saved 9 bytes due to actually being awake now and actually using the shortening I intended.

Version 2.1:

```
S=StringSplit;Total[Flatten@{ToExpression@S[#,LetterCharacter],S[#,DigitCharacter]}&/@S[StringInsert[#,".",First/@StringPosition[#,x_/;UpperCaseQ[x]]],"."]/.{"H"->1,"Li"->3,"Be"->9,"B"->10.8,"C"->12,"N"->14,"O"->16,"F"->19,"Na"->23,"Mg"->24.3,"Al"->27,"Si"->28.1,"P"->31,"S"->32.1,"Cl"->35.5,"K"->39.1,"Ca"->40.1}/.{a_,b_}->a*b]&

```

Explanation: Find the position of all the uppercase characters. Put a dot before each. Split the string at each dot. For this list of substrings do the following split it based on letters and split it based on digits. For the ones split by letters convert string to numbers. For the ones split by digits replace each chemical with its molecular weight. For any with a molecular weight and an atom count replace it with the product of them. Them find the total.

Version 1:

I'm sure this can be golfed lots (or just completely rewritten). I just wanted to figure out how to do it. (Will reflect on it in the morning.)

```
F=Flatten;d=DigitCharacter;S=StringSplit;Total@Apply[Times,#,2]&@(Transpose[{F@S[#,d],ToExpression@F@S[#,LetterCharacter]}]&@(#<>If[StringEndsQ[#,d],"","1"]&/@Fold[If[UpperCaseQ[#2],Append[#,#2],F@{Drop[#,-1],Last[#]<>#2}]&,{},StringPartition[#,1]]))/.{"H"->1,"Li"->3,"Be"->9,"B"->10.8,"C"->12,"N"->14,"O"->16,"F"->19,"Na"->23,"Mg"->24.3,"Al"->27,"Si"->28.1,"P"->31,"S"->32.1,"Cl"->35.5,"K"->39.1,"Ca"->40.1}&

```

Explanation: First split the string up into characters. Then fold over the array joining lowercase characters and numbers back to their capital. Next append a 1 to any chemical without a number on the end. Then do two splits of the terms in the array - one splitting at all numbers and one splitting at all letters. For the first replace the letters with their molar masses then find the dot product of these two lists.

---
Tags: code-golf, kolmogorov-complexity, chemistry
---


title: Make me a fake loader

text:
# Question
Title: Make me a fake loader
Make a fake loader just like this :

## Parameters :

* Display `loading` (space) one of these cyclically`-\|/` (space) (percentage counter from 0-100) then a `%`.
* The percentage counter is supposed to increment by 1 every time the display changes.
* The time taken by counter to jump to next iteration is random. Any kind of random will do as long as the function/method is capable of generating all random integers having probability \> 0 in range `1<= ms <=750` here `ms` being time in milliseconds.
* **Start** at `loading - 0 %`.
* **End** at `loading - 100 %`.
* NO INPUT is required.
* submit a **full** program or **function** or whatever similar.

The code that I used :

## C++

```
#include<stdio.h>
#include<time.h>
#include<windows.h>

int main()
{
    srand(time(NULL));
    char a[15],b[]="-\\|/";
    int i=0,j=0,ms;
    while(j<101)
    {
        (i<3)?i++:i=0;
        wsprintf(a,"loading %c %d ",b[i],j++);
        printf(a);puts("%");
            //This part is to make the output look cool
        switch(rand()%9)
        {
            case 0:ms=1;break;
            case 1:ms=2;break;
            case 2:ms=5;break;
            case 3:ms=10;break;
            case 4:ms=15;break;
            case 5:ms=20;break;
            case 6:ms=25;break;
            case 7:ms=50;break;
            case 8:ms=500;
        }
        Sleep(ms);  //Otherwise this is supposed to be random
        if(j<101)   //like this Sleep(rand()%750+1);
        system("cls");
    }
}

```

## Winner

* the code with least bytes wins.

# Answer
# MATL, 45 bytes

```
101:"'loading'O'-\|/'@)O@qVO37&hD750Yr100/&Xx

```

Example run in the offline compiler:

Or try it at MATL Online!

### Explanation

```
101:          % Push array [1 2 ... 101]
"             % For each
  'loading'   %   Push this string
  O           %   Push 0. When converted to char it will be displayed as a space
  '-\|/'      %   Push this sring
  @)          %   Modular index into this string with iteration index
  O           %   Push 0
  @q          %   Iteration index minus 1
  V           %   Convert to string
  O           %   Push 0
  37          %   Push 37, which is ASCII for '%'
  &h          %   Concatenate horizontally into a string, Numbers are converted to char
  D           %   Display
  750Yr       %   Random integer with uniform distribution on [1 2 ... 750]
  100/        %   Divide by 100
  &Xx         %   Pause that many tenths of a second and clear screen
              % End (implicit)

```
> 6 votes

# Answer
## Powershell, ~~71~~ ~~68~~ 65 Bytes

Similar to https://codegolf.stackexchange.com/a/101357/59735

Saved 3 bytes by not being an idiot (left the ... on loading)

-3 thanks to VisualMelon

changed 750 -\> 751 to make sure 750 is included.

```
0..100|%{cls;"loading $("|/-\"[$_%4]) $_ %";sleep -m(random 751)}

```

Explanation:

```
0..100|%{                                  #For range 0-100...
    cls                                    #Clear Display
    "loading $("|/-\"[$_%4]) $_ %"    #Display the current string
    sleep -m(random 750)                  #Sleep random ms up to 750
}

```

Updated gif
> 16 votes

# Answer
# Python 2, ~~119~~ ~~113~~ 112 Bytes

I had originally gone with the random amount being `random()/.75`, however the endpoint wouldn't be included. There isn't much difference from this to the other question for the infinite load time except for the randomness and the fact that it actually ends.

```
import time,random as r
for i in range(101):print'\rLoading','-\|/'[i%4],i,'%',;time.sleep(r.randint(1,750)/1e3)

```

<sup>*thanks to Jonathan Allan for saving 6 bytes, and DJMcMayhem for saving a byte!*</sup>
> 8 votes

# Answer
## \*\>\<\> (Starfish), ~~86~~ 82 bytes

```
| v1*aoooooooo"loading K"&0"-\|/"
!0x1! +
%$<.0+af{od;?)*aa&:&Soono$&+1:&"  %"{o:}

```

Try it here!

~~This may be able to be golfed more, but I don't see anything super obvious. It sleeps 100ms, 400ms, or 700ms, if this isn't random enough, let me know!~~

Thanks to @TealPelican for saving me 4 bytes and making it much more random!

The biggest challenges I found (while still trying to keep it small) were randomness, and actually outputting "loading - 100 %" at the end, instead of just exiting at my nearest convenience :p.
> 6 votes

# Answer
## Batch, 185 bytes

```
@set s=-\!/
@for /l %%i in (0,1,100)do @call:l %%i
@exit/b
:l
@cls
@set c=%s:~0,1%
@set s=%s:~1%%c%
@echo Loading %c:!=^|% %1 %%
@set/aw=%random%%%751
@ping>nul 1.1 -n 1 -w %w%

```

The timing is fairly poor unfortunately, but Batch doesn't have anything better to use than `ping`.
> 6 votes

# Answer
# Perl 6, 67 bytes

```
for |<- \ | />xx* Z 0..100 {print "\rloading $_ %";sleep .750.rand}

```

## Expanded:

```
for

  # produce a list of all the pairs of values

  |<- \ | /> xx *   # a flat infinite list of "clock faces"
  Z                 # zipped with
  0 .. 100          # all the numbers from 0 to 100 inclusive

  # &zip / &infix:<Z> stop on the shortest list

{

  # ｢$_｣ will look something like ｢("/", 39)｣
  # when it is coerced to a Str, all of its elements
  # will be coerced to Str, and joined with spaces

  print "\rloading $_ %";

  sleep .750.rand

}

```
> 5 votes

# Answer
# Javascript (ES6), ~~128~~ ~~118~~ ~~116~~ ~~115~~ ~~112~~ ~~110~~ 109 bytes

This seems to work perfectly fine, even with this sketchy source of "random" numbers.

```
(X=_=>setTimeout(i>99||X,1+new Date%750,document.body.innerHTML=`<pre>Loading ${'-\\|/'[i%4]} ${i++}%`))(i=0)
```

---

**Alternative 1**, Javascript + HTML, 16 + 84 bytes

This one uses an already-existing element to display the remaining content:

```
(X=_=>setTimeout(i>99||X,1+new Date%750,a.innerHTML=`${'-\\|/'[i%4]} ${i++}%`))(i=0)
```

```
Loading <a id=a>
```

**Alternative 2**, 95 bytes

If I can assume a tab is opened and that you're pasting this into the console:

```
(X=_=>setTimeout(i>99||X,1+new Date%750,document.title=`Loading ${'-\\|/'[i%4]} ${i++}%`))(i=0)

```

Instead of showing the HTML, the title of the document will change.

---

Thank you to @user2428118 for saving 2 bytes!
> 4 votes

# Answer
# F#, 118 bytes

```
async{let r=System.Random()
for i in 0..100 do printf"\rLoading %O %d %%""|/-\\".[i%4]i;do!Async.Sleep(r.Next(1,750))}

```

In order to run this snippet, pass it into `Async.Start` or `Async.RunSynchronously`.
> 4 votes

# Answer
# PHP, ~~90~~ ~~83~~ ~~80~~ ~~78~~ ~~77~~ Bytes

**77:**

The closing `;` is not needed.

```
for(;$i<101;usleep(rand(1,75e4)))echo"\rloading ",'-\|/'[$i%4],' ',$i+++0,'%'

```

78:

While looking for another workaround to get a 0 initially without initializing the variable I came up with this:

```
for(;$i<101;usleep(rand(1,75e4)))echo"\rloading ",'-\|/'[$i%4],' ',$i+++0,'%';

```

Changed back to echo to win a few bytes as I only used printf to force-format as int. By incrementing the incremented $i with 0 I get a valid integer. By using single quotes as string delimiter the backslash does not need to be escaped, resulting in another byte freed

80:

Moving the increment of $i from the last for-section to the prinf gave me another 3 off. (See comments below)

```
for(;$i<101;usleep(rand(1,75e4)))printf("\rloading %s %d%%","-\\|/"[$i%4],$i++);

```

83:

Removed init of a variable with the loaderstates.

```
for(;$i<101;usleep(rand(1,75e4)),$i++)printf("\rloading %s %d%%","-\\|/"[$i%4],$i);

```

90:

I tried removing the init of $i to gain some bytes, as I had to add quite a few to enable the loader animation. printf adds 2 as opposed to echo, but formatting NULL as an integer results in 0.

```
for($l='-\|/';$i<101;usleep(rand(0,750)*1e3),$i++)printf("\rloading %s %d%%",$l[$i%4],$i);

```
> 4 votes

# Answer
# Groovy, ~~113~~ 87 bytes

***-36 bytes thanks to lealand***

```
{p=-1;101.times{print"\rLoading ${"-\\|/"[p++%4]} $p%";sleep Math.random()*750as int}}

```
> 3 votes

# Answer
**C#, 170 149 135 Bytes**

```
()=>{for(int i=0;i++<=100;System.Threading.Thread.Sleep(new Random().Next(1,750)))Console.Write($"\rloading {@"-\|/"[i % 4]} {i} %");};

```

Ungolfed:

```
static void l()
{
    for (int i = 0; i <= 100; System.Threading.Thread.Sleep(new Random().Next(1, 750)))
        Console.Write($"\rloading {@"-\|/"[i % 4]} {i} %");
}

```

I won't guarantee that every character in this is right, please correct me if there are compilation errors. I had to type the whole thing on my phone so I might have accidentally included some errors... ¯\_(ツ)\_/¯ I hope you guys forgive me that

Tested it on my PC, works like a charm and I even saved a whole 20 bytes thanks to pmbanka :)
> 3 votes

# Answer
# Bash, ~~162~~ 104 bytes

Modification of Zachary's answer on a related question, with massive improvements by manatwork:

```
s='-\|/'
for x in {0..100};{
printf "\rloading ${s:x%4:1} $x %%"
sleep `printf .%03d $[RANDOM%750+1]`
}

```

I had to look up how to do random numbers in bash.

## Ungolfed / Explained

```
s='-\|/'
for x in {0..100}
{
    # \r returns the carriage to the beginning of the current line.
    # ${s:x%4:1} grabs a substring from s, at index x%4, with a length of 1.
    printf "\rloading ${s:x%4:1} $x %%"

    # "$RANDOM is an internal bash function that returns
    #   a pseudorandom integer in the range 0 - 32767."
    # .%03d is a dot followed by a base-ten number formatted to 3 places,
    #   padded with zeros if needed.
    # sleep accepts a floating point number to represent milliseconds.
    sleep `printf .%03d $[RANDOM%750+1]`
}

```
> 3 votes

# Answer
# C ~~112~~ 103 bytes

Saved 9 bytes thanks to @G. Sliepen. Not very exciting, just a golf of your C++ answer basically. Also not a very exciting random function. I thought about `Sleep(c[i%4])`, or `Sleep(i)` but they're not random at all!

```
#import<windows.h>
i;f(){for(;i<101;printf("\rloading %c %d %%","-\\|/"[i%4],i++),Sleep(rand()%750+1));}

```

Ungolfed:

```
#include <windows.h>
int i;
void f() {
  for(;i<101;) {
    printf("\rloading %c %d %%", "-\\|/"[i%4], i++);
    Sleep(rand()%750+1);
  }
}

```
> 2 votes

# Answer
# PHP, ~~66~~ 79 bytes

```
for($i=-1;++$i<101;usleep(rand(1,75e4)))echo"\rloading ","-\\|/"[$i%4]," $i %";

```

Unfortunately I had to assign $i in order to get it to print '0'.
Use like:

```
php -r 'for($i=-1;++$i<101;usleep(rand(1,75e4)))echo"\rloading ","-\\|/"[$i%4]," $i %";'

```

Edits: thanks to Titus confirming exactly what's allowed with Mukul Kumar we can save 3 bytes with a less restricted range, but not all 9 bytes with an unrestricted range. Thanks also for pointing out that I forgot the cycling character and providing a simple solution to do it.
> 2 votes

# Answer
## Mathematica, 133 Bytes

```
Dynamic[If[x<100,x++,,x=0];Row@{"Loading ",StringPart["-\|/",1+x~Mod~4]," ",x,"%"},
    UpdateInterval:>RandomReal@.75,TrackedSymbols:>{}]

```

This will run once, assuming x is undefined. `Clear@x` will restart it.

55 characters tied up in verbosity :/
> 2 votes

# Answer
## R - 94 bytes

```
for(i in 0:100){cat('\rLoading',c('-','\\','|','/')[i%%4+1],i,'%');Sys.sleep(sample(750,1)/1e3)}

```

Really nice that `sample(750,1) == sample(1:750,1)`.
> 2 votes

# Answer
# HTML + JS (ES6), 16 + 87 = 103 bytes

```
(f=_=>a.innerHTML='\\|/-'[i++%4]+` ${i<100&&setTimeout(f,Math.random()*750),i} %`)(i=0)
```

```
loading <a id=a>
```
> 2 votes

# Answer
# Noodel, noncompeting 40 bytes

Just going back through old challenges (as in challenges that were made before *Noodel*) and competing with *Noodel* to find where it is weak.

```
Loading¤”ḋḟƇḣ⁺s¤ṡ⁺Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ€Ḃ

```

If final output does not matter, then can save 2 bytes.

```
Loading¤”ḋḟƇḣ⁺s¤ṡ⁺Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ

```

*Noodel* pushes the top of the stack to the screen at the end of the program so by adding the `€Ḃ` it prevents that from happening.

Try it:)

### How It Works

```
Loading¤”ḋḟƇḣ⁺s¤ṡ⁺Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ€Ḃ # Main Noodel script.

Loading¤”ḋḟƇḣ⁺s¤ṡ⁺                       # Creates the array ["Loading¤-¤", "Loading¤\¤", "Loading¤|¤", "Loading¤/¤"]
Loading¤                                 # Pushes the string "Loading¤"
        ”Ƈḟḋḣ                            # Pushes the array ["-", "\", "|", "/"]
             ⁺s                          # Concats "Loading¤" to each element in the array by prepending.
               ¤                         # Pushes a "¤" onto the stack.
                ṡ                        # Pushes
                 ⁺

                  Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ   # Main loop that creates the animation.
                  Ḷ101                   # Loop the following code 101 times.
                      ạ                  # Pushes on a copy of the next animation element from the array.
                       ¤%                # Pushes the string "¤%"
                         ɱ               # Pushes on the current count of the number of times that have looped (zero based).
                          Ṡ              # Swaps the two items at the bottom of the stack.
                           Ė             # Pushes the item at the bottom of the stack to the top (which will be the string selected from the array).
                            ²⁺           # Concat twice appending the loop count then the string "¤%" to the string selected from the array.
                              Ç          # Pops the string off of the stack, clears the screen, then prints the string.
                               ṛ749      # Randomly generate an integer from 0 to 749.
                                   ⁺1    # Increment the random number producing a random number from 1 - 750.
                                     ḍ   # Pop off the stack and delay for that number of milliseconds.

                                      €Ḃ # Ends the loop and prevents anything else being displayed.
                                      €  # Ends the loop (new line could be used as well)
                                       Ḃ # Destroys the current stack therein, nothing gets pushed to the screen at the end of the program.

```

```
<div id="noodel" code="Loading¤”ḋḟƇḣ⁺s¤ṡ⁺Ḷ101ạ¤%ɱṠĖ²⁺Çṛ749⁺1ḍ€Ḃ" input="" cols="14" rows="2"></div>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 2 votes

# Answer
## C ~~126~~ 121 bytes

```
f(){i=0;char c[]="/-\\|";for(;i<101;i++){printf("\rloading %c %d %% ",c[i%4],i);fflush(stdout);usleep(1000*(rand()%75));}

```

Ungolfed version:

```
 void f()
 {
  int i=0;
  char c[]="/-\\|";
  for(;i<101;i++)
  {
    printf("\rloading %c %d %% ",c[i%4], i);
    fflush(stdout);
    usleep(1000*(rand()%75));
  }
 }

```

@Carcigenicate @ Mukul Kumar Did not read between the lines there, Thanks! :)
> 2 votes

# Answer
# Octave, ~~122~~ ~~120~~ ~~119~~ 108 bytes

I misread the challenge and created an infinite loader that restarted at 0 once it passed 100. Making it into a one time only loader:

```
a='\|/-';for i=0:100;clc;disp(['Loading ',a(1),' ',num2str(i),' %']);a=a([2:4,1]);pause(0.749*rand+.001);end

```

Circulating `a`, `a=a([2:4,1])` was flawr's idea here. Also, saved 2 bytes by skipping the parentheses after `rand` thanks to MattWH.
> 1 votes

# Answer
# **MATLAB, 108 bytes**

```
function k;for i=0:100;a='-\|/';pause(rand*.749+.001);clc;['loading ' a(mod(i,3)+1) ' ' num2str(i) ' %']
end

```
> 1 votes

# Answer
## Racket 110 bytes

```
(for((i 101))(printf"Loading ~a ~a % ~n"(list-ref'("-" "\\" "|" "/")(modulo i 4))i)(sleep(/(random 750)1000)))

```

Ungolfed:

```
(define(f)
  (for ((i 101))
    (printf "Loading ~a ~a % ~n" (list-ref '("-" "\\" "|" "/") (modulo i 4)) i)
    (sleep (/(random 750)1000))))

```

Testing:

```
(f)

```

Output:

(This gif file is showing slower display than actual)
> 1 votes

# Answer
# ForceLang, 250 bytes

Noncompeting, requires language features which postdate the question

```
def D def
D w io.write
D l e+"loading"+s
D z string.char 8
D s string.char 32
D d datetime.wait 750.mult random.rand()
D e z.repeat 24
D n set i 1+i
D k s+n+s+"%"
set i -1
label 1
w l+"-"+k
if i=100
exit()
d
w l+"\"+k
d
w l+"|"+k
d
w l+"/"+k
d
goto 1

```

I should probably fix some bugs related to string literal parsing soon.
> 1 votes

# Answer
# 107 75 Ruby

*-32 thanks to manatwork*

**Normal**

```
i=0
(0..100).each{|c|
system'clear'
puts"loading #{'\|/-'[i=-~i%4]} #{c} %"
sleep rand*(0.750-0.01)+0.01
}

```

**Golfed**

```
101.times{|c|$><<"\rloading #{'-\|/'[c%4]} #{c} %";sleep rand*0.749+0.001}

```
> 1 votes

# Answer
### Python 3, 149 bytes

```
import time,random;f=0;n=0
while n<=100:
 print("Loading...","|/-\\"[f],n,"%",end="\r");f+=1
 if f>=3:f=0
 n+=1
 time.sleep(random.uniform(.25,.75))

```

Similar to Loading... Forever, but I did have to edit my answer from there a lot.
> 1 votes

# Answer
# tcl, 116

```
set i 0;time {lmap c {- \\ | /} {puts -nonewline stderr "\rloading $c $i%";after [expr int(187*rand())]};incr i} 100

```

Playable in http://www.tutorialspoint.com/execute\_tcl\_online.php?PID=0Bw\_CjBb95KQMOXoybnVSOVJEU00
> 1 votes

# Answer
# TI-Basic, 80 bytes

```
For(I,0,100
For(A,0,randE2
End
Text(0,0,"loading "+sub("-\|/",1+fPart(I/4),1)+" ",I," %
End

```

The randomness comes from the `For(` loop (E is scientific E token) and since TI-Basic is interpreted there is also automatically some overhead. Remember that in TI-Basic, lowercase letters and some less common ASCII symbols are two bytes each (so specifically for this program, `l o a d i n g sub( \ | %` are the two-byte tokens
> 1 votes

# Answer
# Clojure, 109 bytes

```
(doseq[[c i](map vector(cycle"\\|/-")(range 101))](print"\rloading"c i\%)(flush)(Thread/sleep(rand-int 751)))

```

Loops over a list of the range of numbers from 0 to 100, zipped with an infinite list of `"\|/-"` repeating forever.

```
; (map vector...) is how you zip in Clojure
;  All arguments after the first to map are lists. The function is expected to
;  take as many arguments as there are lists. vector is var-arg.
(doseq [[c i] (map vector (cycle "\\|/-") (range 101))]
  ; \r to erase the old line
  (println "\rloading" c i \%)
  (Thread/sleep (rand-int 751)))

```
> 1 votes

# Answer
## Visual Basic, 371 Bytes

```
module m
sub main()
Dim s as Object
for i as Integer=0 to 100
Select Case new System.Random().next(0,9)
Case 0
s=1
Case 1
s=2
Case 2
s=5
Case 3
s=10
Case 4
s=15
Case 5
s=20
Case 6
s=25
Case 7
s=50
Case 8
s=500
End Select
Console.SetCursorPosition(0,0)
console.write("loading "+"-\|/"(i mod 4)+" "+i.tostring+" %")
system.threading.thread.sleep(s)
next
end sub
end module

```

# Expanded:

```
module m
    sub main()
        Dim s as Object
        for i as Integer=0 to 100
            Select Case new System.Random().next(0,9)
                Case 0
                s=1
                Case 1
                s=2
                Case 2
                s=5
                Case 3
                s=10
                Case 4
                s=15
                Case 5
                s=20
                Case 6
                s=25
                Case 7
                s=50
                Case 8
                s=500
            End Select
            Console.SetCursorPosition(0,0)
            console.write("loading " + "-\|/"(i mod 4) + " " + i.tostring + " %")
            system.threading.thread.sleep(s)
        next
    end sub
end module

```
> 1 votes

# Answer
# Java 8, 130 bytes

```
()->{for(int n=0;n<101;Thread.sleep((long)(1+Math.random()*750)))System.out.print("\rloading "+"-\\|/".charAt(n%4)+" "+n+++" %");}

```

**Explanation:**

```
()->{                           // Method without parameter nor return-type
  for(int n=0;n<101;            //  Loop from 0 to 100
      Thread.sleep((long)(1+Math.random()*750)))
                                //   And sleep randomly 1-750 ms
    System.out.print(           //   Print:
      "\r                       //    Reset to the start of the line
      loading "                 //    Literal "loading "
      +"-\\|/".charAt(n%4)+" "  //    + the spinner char & a space
      +n++                      //    + the number (and increase it by 1)
      +" %");                   //    + a space & '%'
                                //  End of loop (implicit / single-line body)
}                               // End of method

```

**Output gif:**
> 1 votes

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


# Question
Title: Smallest code to return sum of all characters in an array of strings
Smallest code to return sum of all characters of an array of C-strings, including null-byte-terminattor of each string in the array.

example in C:

```
    const char *a[] = { "abc", "bdef", "cee", "deee" };
    size_t n = sumOfAllBytes(a);
    printf("n = %d\n", n); // n = 18

```

e.g.,

```
   strlen(a[0]) + 1 + ... + strlen(a[n])

```

where `n` is `array-size-1`, ie, the last elemet in the array, in this case, `deee` word. Note that `n = 4` (starting from 0 as C does)

Each character is an ASCII character in C it's 1 byte-size.

# Answer
# GolfScript \[4 bytes\]

```
n*,)

```

There are no functions in GolfScript, so you should use a standard input instead:

```
["abc" "bdef" "cee" "deee"]
n*,)

>>> 18

```

**DEMO:** http://golfscript.apphb.com/?c=WyJhYmMiICJiZGVmIiAiY2VlIiAiZGVlZSJdCgpuKiwp
> 3 votes

# Answer
# Haskell, ~~21~~ 19 bytes

```
succ.length.unwords

```

Edit: Removed two bytes thanks to ais523!
> 4 votes

# Answer
# Mathematica ~~31~~ 29 bytes

-2 bytes thanks to numbermaniac

```
StringLength[""<>#]+Length@#&

```

Example

```
StringLength[""<>#]+Length@#&@{ "abc", "bdef", "cee", "deee" }

```

> 18
> 2 votes

# Answer
# bash+coreutils - function body 10 bytes

```
sumOfAllBytes()(wc -c<<<$@)

```

Call as follows:

```
$ a=("abc" "bdef" "cee" "deee")
$ sumOfAllBytes ${a[@]}
18
$

```
> 2 votes

# Answer
# Perl, function body: 15 bytes

```
sub sumOfAllBytes{!!@_+length"@_"}

```

Function `sumOfAllBytes` returns the sum of the string lengths including a "virtual" terminator byte. Perl does not have the concept of terminating a string with a null byte.

A variant without a "terminating byte":

```
sub sumOfAllBytes{$"=$;@_+length"@_"}

```

**Byte count:** The body of the functions are 15 or 17 bytes (with or without terminator). 7 bytes must be added, if the whole function with one-byte name should be counted.

**Test with degolfed version:**

```
sub sumOfAllBytes {
    # the argument(s) are put into array @_ by Perl
    !!@_ +       # short for: @_ ? 1 : 0
                 # (if the array is empty nothing should be added)
    length "@_"  # The array elements are interpolated into the double-
                 # quoted string; the elements are separated by a space ($").
    # without explicit return statement, the value of the last
    # statement is returned.
}

@a = qw[abc bdef cee deee];
print sumOfAllBytes(@a), "\n"; # prints 18

```
> 1 votes

# Answer
# Rebol (body: 18 chars, function: 30 chars)

```
1 + length? form x

```

Usage example in Rebol console:

```
>> f: func[x][1 + length? form x]

>> f ["abc" "bdef" "cee" "deee"]
== 18

```
> 1 votes

# Answer
## C, 78 minus declaration of a\[\]

Assumes 64 bit target and a\[\] containing at least one string.

```
char *a[]={"abc","bdef","cee","deee"};
f(int i){return strlen(a[i])+1+(i?f(i-1):0);}
main(){return f(sizeof(a)/8-1);}

```

To see the result, invoke thusly:

```
$ ./whatever || echo $?

```
> 1 votes

# Answer
# c preprocessor macros, 94 chars

The example in the question is not doable in c as a regular function as the function would have no idea the size of the array if just a pointer to the array is passed in. But we can do this as a couple of preprocessor macros:

```
#define c(s) sizeof(s)/sizeof(s[0])-1
#define sumOfAllBytes(s) s[c(s)]-s[0]+strlen(s[c(s)])+1

```

We assume that the array is declared, defined and initialised as in the question. That way the strings should be laid out sequentially in memory. We can then subtract the address of the first element from the last element and add the `strlen()` of the last element. No need to loop over all elements and `strlen()`.
> 1 votes

# Answer
# Haskell 24

```
s=sum.(map$(+1).length)

```

Usage, in ghci:

```
ghci> s ["abc", "bdef", "cee", "deee"]
18

```
> 1 votes

# Answer
# Java: 56 characters (body) 74 characters (full method)

*Hey, this is as good as it gets in Java!*

This is the method:

```
int z(String[]a){int s=0;for(String b:a)s+=b.length();return s+a.length;}

```

The main code is just *56* characters (witout spaces and comments):

```
int s=0;            // The sum variable.
for(String b:a)     // The 'for each' loop is handy
    s+=b.length();  // Adding the length of each String
return s+a.length;  // Adding the length of the array

```

**Calling this function:**

```
int answer = z(new String[]{ "abc", "bdef", "cee", "deee" }); // Stores 18

```
> 1 votes

# Answer
# 05AB1E, 5 bytes

```
JgIg+

```

Try it online!

-1 thanks to @Datboi
> 1 votes

# Answer
## C \[body: 48 chars, function: 107 chars\]

```
int f(const char** r, const char* c, const char** e) {
  return r-e?1+(*c?f(r,c+1,e):f(r+1,*(r+1),e)):0;
}

```

Ugly piece of code. Just trying to do it without loops by using recursion.

Call it this way:

```
    const char *a[] = { "abc", "bdef", "cee", "deee" };
    size_t n = f(a,*a,a+4);
    printf("n = %zu\n", n);

```

No warnings and result is OK:

```
$ gcc koe.c -Wall -Wextra -o koe
$ ./koe
n = 18

```
> 0 votes

# Answer
# C - Loop:64, Recursion:56 (-18 for function body overhead)

## Loop

```
s(char*a[],int n){int r=0;for(;n;)r+=strlen(a[--n])+1;return r;}

```

## Recursion

```
r(char*a[],int n){return n?strlen(a[0])+1+r(a+1,n-1):0;}

```
> 0 votes

# Answer
# PHP 5.3 - 60

```
array_sum(array_map(function($v){return strlen($v)+1;},$a));

```

Where `$a` is the array.
> 0 votes

# Answer
## Python - 55 42 38

```
def s(v):print sum(1+len(x)for x in v)

```
> 0 votes

# Answer
# JavaScript - 42 characters without declaration

```
function s(x){return x.join(" ").length+1}

```

Usage:

```
a=["abc","bdef","cee","deee"];console.log(s(a));

```
> 0 votes

# Answer
## D - ~~58~~ 54 bytes

```
int x(T)(T t){return reduce!"a+b.length"(t.length,t);}

```

This requires `std.algorithm`, so add the characters necessary for making that import if you want to.

Example of usage:

```
import std.stdio,std.algorithm;

int x(T)(T t){return reduce!"a+b.length"(t.length,t);}

void main(){
    writeln(x!(string[])(["abc","bdef","cee","deee"]));
}

```
> 0 votes

# Answer
# Fortran 90+ - 75 total, 23 for function alone

Unfortunately, Fortran doesn't allow for implicit typing of character strings, but we can abuse F77+F90 for golfing purposes. The whole program would be:

```
character*4::c(4)=["abc","bdef","cee","deee"];print*,sum(len_trim(c)+1);end

```

The function alone, written using a statement function would be

```
k(s)=sum(len_trim(s)+1)

```

which would be called using `print*,k(c)`.
> 0 votes

# Answer
**in C# 34 Excluding "string \[\] a=new \[\] { "abc", "bdef", "cee", "deee" };"**

```
   string [] a=new [] { "abc", "bdef", "cee", "deee" };
                var i=string.Join(" ",a).Length+1;
sol:2
var j =  string.Concat(a).Length + a.Length;

```
> 0 votes

# Answer
# JavaScript - 20 17 Characters

```
s.join().length+1

```

Assumes that the array of strings is in variable 's' and outputs the answer to the console.
> 0 votes

# Answer
## APL 6

```
+/1+⍴¨a

```

where

```
a←"abc" "bdef" "cee" "deee"

```

yields

```
      +/1+⍴¨a
 18

```

Read as "Sum over 1 plus size of each element in a"
> 0 votes

# Answer
**C#, 52** including variable declaration

```
int c=0;for(int i=0;i<a.Length;i++)c+=1+a[i].Length;

```

Uncompressed version for ease of reading:

```
int count = 0;
for (int i = 0; i < a.Length; i++)
    count += 1 + a[i].Length;

```
> 0 votes

# Answer
# q/kdb+, 14 bytes

**Solution:**

```
sum 1+(#:)each

```

**Example:**

```
q)sum 1+(#:)each("abc";"bdef";"cee";"deee")
18

```

**Explanation:**

Evaluated right-to-left, thus:

```
// count (#:) length of each item in the list
q)(#:)each("abc";"bdef";"cee";"deee")
3 4 3 4
// add one to each item
q)1+ 3 4 3 4
4 5 4 5
// sum up the items
q)sum 4 5 4 5
18

```
> 0 votes

# Answer
# Jelly, 3 bytes

```
KL‘

```

Try it online!
> 0 votes

# Answer
## Clojure, 32 bytes

```
#(apply +(map(comp inc count)%))

```

Composition FTW. Aww it is the same length as `#(apply +(count %)(map count %))`.
> 0 votes

# Answer
# F#, 56 bytes

Still practicing with F#...

```
let f a=(a|>Seq.map String.length|>Seq.sum)+Seq.length a

```

Invoke with:

```
[<EntryPoint>]
let main argv =
    let sum = [| "abc"; "bdef"; "cee"; "deee" |] |> f
    printfn "%A" sum
    0

```
> 0 votes

---
Tags: code-golf
---


title: Count the videos in a Youtube Playlist

text:
# Question
Title: Count the videos in a Youtube Playlist
# Challenge

Given a Youtube playlist, output the number of videos in it.

# I/O

The playlist will be given as an URL; for example, `https://www.youtube.com/playlist?list=PL_3jnZNPYn7qUatgDYBS5NShkfXoehSRC` (this is a playlist a friend sent me to try to get me to listen to K-Pop because she's obsessed with it and I don't like it :P)

The link to a playlist is of the form `https://www.youtube.com/playlist?list=<id>`. The input is the URL, not the ID.

The output is to be a single integer indicating how many videos are in this playlist. You can either output the total number of videos or the number of non-deleted videos, whichever one is more golfy for you.

# Test Cases

```
https://www.youtube.com/playlist?list=PL_3jnZNPYn7qUatgDYBS5NShkfXoehSRC -> 12
https://www.youtube.com/playlist?list=PLIEbITAtGBebWGyBZQlkiMXwt30WqG9Bd -> 114 OR 1

```

Feel free to add more test cases.

# Answer
> 8 votes
# 05AB1E, 22 bytes

Assumes that the **URL** is passed *without* the `https://`.

### Code:

```
.w’®Ã-ƒ¢’¡`"<li>"¡2è#¬

```

Uses the **05AB1E** encoding. Cannot be tried online, because of internet access.

### Explanation:

```
.w                       # Receive implicit input and read all data from the url
  ’®Ã-ƒ¢’¡               # Split on the string "header-details"
          `              # Flatten once which leaves the last element on top of the stack
           "<li>"¡       # Split on the string "<li>"
                  2è     # Get the third element
                    #    # Split on spaces
                     ¬   # Retrieve the first element

```

This is what I get when running in the command line:

# Answer
> 6 votes
# MATL, 15 bytes

*Thanks to Hyper Neutrino for finding a mistake, now corrected.*

```
Xi'wner">\n'XXn

```

The input is a string enclosed with single quotes. The output is the number of undeleted videos.

Here's an **example run** with the two test cases. As of June 13, 2017 the number of undeleted videos in the playlists are 12 and 1 respectively.

### How it works

```
Xi          % Read string containing URL and get contents as a string
'wner">\n'  % Push this string
XX          % Regexp matching. Gives a cell array with the matched strings
n           % Number of elements. Implicitly display

```

# Answer
> 4 votes
# Scala 2.12, 138 bytes

```
print("""<li>.*?</li><li>(\d+).*?</li>""".r.findFirstMatchIn(scala.io.Source.fromURL(args(0),"utf-8").getLines.mkString("")).get.group(1))

```

Save it to `something.scala` and run by `scala something.scala {url}`.

# Answer
> 4 votes
# JS (ES6), 68 bytes

```
x=>fetch(x).then(x=>x.text()).then(x=>alert(x.match(/(\d+) vi/)[1]))

```

Paste this in to your console on youtube.com to try:

```
(x=>fetch(x).then(x=>x.text()).then(x=>alert(x.match(/(\d+) vi/)[1])))(prompt("Enter the URL"))

```

# Answer
> 4 votes
# bash + curl + gnu grep, 32 bytes

Finally giving Code Golf a go:

```
curl -s $1|grep -Po \\d+(?= vid)

```
* Use `curl -s` to download without any extra output.
* Pipe the output to grep (perl regex) which will output only the match
    + Match the first number that proceeds " vid"

This is golfed from how I would do this practically.

# Answer
> 3 votes
## PowerShell, 55 Bytes

```
"$(iwr "$args")"-match'(?s)(\d+) vid'>$null;$matches[1]

```

Browse to the site. Convert the object to a string which is the html source. Parse out the string that has a number preceding "vid" with regex.

Logic works with both test cases.

# Answer
> 0 votes
# Haskell 161 bytes

```
import Network.Curl.Download
import qualified Data.ByteString.Char8 as B
z=do u<-getLine;(Right b)<-openURI u;putStrLn$show$length$B.findSubstrings(B.pack"<tr")b

```

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


title: Menger Sponge Generator

text:
# Question
Title: Menger Sponge Generator
## **Challenge**

My challenge, is for you to generate a Menger Sponge based on the `level`/`iteration` given. You need to draw it in `3d`, anyway you can.

**Examples**

*Inputs:* `0, 1, 2, 3`

*Outputs:*

---

## **Background Information**

**What is a Menger Sponge**

> In mathematics, the Menger sponge (also known as the Menger universal curve) is a fractal curve. It is a three-dimensional generalization of the Cantor set and Sierpinski carpet

**Properties**

> See https://en.wikipedia.org/wiki/Menger\_sponge#Properties (too long to copy and paste)

**How do I construct the sponge?**

1. > Begin with a cube (first image).
2. > Divide every face of the cube into 9 squares, like a Rubik's Cube. This will sub-divide the cube into 27 smaller cubes.
3. > Remove the smaller cube in the middle of each face, and remove the smaller cube in the very center of the larger cube, leaving 20 smaller cubes (second image). This is a level-1 Menger sponge (resembling a Void Cube).
4. > Repeat steps 2 and 3 for each of the remaining smaller cubes, and continue to iterate ad infinitum.

> The second iteration gives a level-2 sponge (third image), the third iteration gives a level-3 sponge (fourth image), and so on. The Menger sponge itself is the limit of this process after an infinite number of iterations.

**Credit**

Background info taken from this wikipedia page on Menger Sponges.

---

## **Good Luck!**

Remember this is the shortest program wins!

# Answer
> 4 votes
anyway.. **here is the 3D answer**

# Mathematica, 15 bytes

```
#~MengerMesh~3&

```

new built-in in Mathematica 11.1

**input**

> 3

**output**

---
Tags: code-golf, math, geometry, 3d
---


title: Quote my quote!

text:
# Question
Title: Quote my quote!
A quotation is "the repetition of one expression as part of another one". In American English, a quotation is surrounded by double-quotation marks ("), as in the previous sentence. However, this rule differs when a quote appears inside another quote. In this case, the inner quote is surrounded by single-quotation marks (').

# Challenge

Given a string as input, output a quotable version of that string by exchanging double- and single-quotation marks that are used for inner quotation.

There's just one catch, though - not all single-quotation marks are used for quotation! For this challenge, single-quotation mark is used for quotation if and only if:

* The mark is preceded by a non-alphanumeric character, or
* The mark is followed by a non-alphanumeric character that is *not* a space

The marks used for quotations are guaranteed to be balanced; that is, you do not need to handle invalid input. Additionally, double-quotation marks will only be used in situations where single-quotation marks can be used to represent quotation.

# Test Cases

```
A man, a plan, a canal, Panama.
"A man, a plan, a canal, Panama."

Socrates once said, "An unexamined life is not worth living."
"Socrates once said, 'An unexamined life is not worth living.'"

@musicman523 said, "Socrates once said, 'An unexamined life is not worth living.'"
"@musicman523 said, 'Socrates once said, "An unexamined life is not worth living."'"

"Nested 'quotes "can 'cause "recursion," if,' it," runs,' deep!"
"'Nested "quotes 'can "cause 'recursion,' if," it,' runs," deep!'"

"Contractions' behaviors can't be easy to account for," he warned.
"'Contractions' behaviors can't be easy to account for,' he warned."

@carusocomputing said, "Nested, 'quotes, it's unfortunate', to be sure."
"@carusocomputing said, 'Nested, "quotes, it's unfortunate", to be sure.'"

```

# Scoring

This is , so the shortest answer in each language wins!

# Answer
> 2 votes
# Ruby, ~~64~~ ~~66~~ ~~65~~ 64+1 = ~~65~~ ~~67~~ ~~66~~ 65 bytes

+1 byte for the `-n` flag.

```
gsub(/"|(?<!\w)'|'(?!\w|\s)/){"'\""["\"'".index$&]}
$><<?"+$_+?"

```

Try it online!

# Answer
> 2 votes
# Retina, ~~34~~ 27 bytes

*-7 bytes thanks to @Leo*

```
T`'"`"'`\W'|"|'[^\w ]
^|$
"

```

Try it online!

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

Assumes the string doesn't contain `#`.

```
s=>'"'+s[r='replace'](/"/g,'#')[r](/(\W)'/g,'$1"')[r](/'([^\w ])/g,'"$1')[r](/#/g,"'")+'"'

```

```
f=
s=>'"'+s[r='replace'](/"/g,'#')[r](/(\W)'/g,'$1"')[r](/'([^\w ])/g,'"$1')[r](/#/g,"'")+'"'
;

`A man, a plan, a canal, Panama.
Socrates once said, "An unexamined life is not worth living."
@musicman523 said, "Socrates once said, 'An unexamined life is not worth living.'"
"Nested 'quotes "can 'cause "recursion," if,' it," runs,' deep!"
"Contractions' behaviors can't be easy to account for," he warned.
@carusocomputing said, "Nested, 'quotes, it's unfortunate', to be sure.`.split(`\n`).map(f).map(s=>console.log(s))
```

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


title: A Program that Prints Programs

text:
# Question
Title: A Program that Prints Programs
**Challenge**

Your goal is to write a program that prints another program. That printed program should print another program, and the new program should print another program, until the end.

**Rules**

1. Each program must less than 256 bytes. (If this needs to be changed, leave a comment)
2. The last program must be an empty program.
3. There must be a finite number of programs, so the program cannot be a quine.
4. The programs must all run in the same language.
5. No input is allowed.
6. The winning program is the program that prints as many programs as possible, counting itself.

Good Luck!

# Answer
> 20 votes
# CJam, 4.56 × 10526 programs

```
2D#2b{"\256b_(256b:c'\s`_:(er`":T~{;38'ÿ*`{:T~{;63'ÿ*`{:T~{;88'ÿ*`{:T~{;114'ÿ*`{:T~{;140'ÿ*`{:T~{;166'ÿ*`{:T~{;192'ÿ*`{:T~{;219'ÿ*`{Q?\"_~"}s(\T}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}_~

```

Exact score: **254219 \+ 254192 \+ 254166 \+ 254140 \+ 254114 \+ 25488 \+ 25463 \+ 25438 \+ 25413 \+ 3**

All programs have to be saved using the ISO-8859-1 encoding to comply with the file size limit.

*Thanks to @ChrisDrost who pointed out a bug and suggested the nesting approach.*

Try it online in the CJam interpreter.

## 254219 \+ 2 ≈ 4.56 × 10526 programs

The line share of the score can be achieved by the following, much simpler program1.

```
"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"
{\256b_(256b:c'\s`_:(er`Q?\"_~"}_~

```

Running this program produces the program

```
"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿþ"
{\256b_(256b:c'\s`_:(er`Q?\"_~"}_~

```

and after **254219 \- 1** more iterations, the program

```
{\256b_(256b:c'\s`_:(er`Q?\"_~"}_~

```

This last non-empty program exits with an error2 and prints nothing (the empty program).

### How it works

Assume the string is already on the stack.

```
{      e# Push a code block.
  \    e# Swap the string on top of the code block.
       e# This will cause a runtime error if there is no string on the stack.
  256b e# Convert the string (treated as a base-256 number) to integer (I).
  _(   e# Copy the integer and decrement the copy.
  256b e# Convert the integer into the array of its base-256 digits.
  :c   e# Cast each base-256 digit to character. Converts from array to string.
  '\s  e# Push a string that contains a single backslash.
  `    e# Push its string representation, i.e., the array ['" '\ '\ '"].
  _:(  e# Push a copy and decrement each character. Pushes ['! '[ '[ '!].
  er   e# Perform transliteration to replace "s with !s and \s with [s.
       e# This skips characters that require escaping.
  `    e# Push its string representation, i.e., surround it with double quotes.
  Q    e# Push an empty string.
  ?    e# Select the first string if I is non-zero, the empty string otherwise.
  \    e# Swap the selected string with the code block.
  "_~" e# Push that string on the stack.
}      e#
_~     e# Push a copy of the code block and execute it.
       e# The stack now contains the modified string, the original code block
       e# and the string "_~", producing an almost exact copy of the source.

```

## 254192 ≈ 5.35 × 10461 more programs

This is where things get a little crazy.

The first program is highly compressible. By writing a similar program that, instead of the empty program, eventually produces the first program from the above section, we can improve the score by **254192** programs3.

The program

```
"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"
{"\256b_(256b:c'\s`_:(er`":T~{;219'ÿ*`{Q?\"_~"}s(\T}?\"_~"}_~

```

is similar to the first program of the previous section, and running the former and its output for **254192** iterations produces the latter.

Assume the string is already on the stack:

```
{                           e# Push a code block.
  "\256b_(256b:c'\s`_:(er`" e# Push that string on the stack.
                            e# The characters inside it behave exactly as
                            e# they did in the previous section.
  :T~                       e# Save the string in T and evaluate it.
  {                         e# If the integer I is non-zero, keep the generated
                            e# string; else:
    ;                       e#   Pop the code block from the stack.
    219'ÿ*`                 e#   Push a string of 219 ÿ's (with double quotes).
    {Q?\"_~"}               e#   Push that block on the stack.
    s                       e#   Push its string representation.
    (\                      e#   Shift out the { and swap it with the tail.
    T                       e#   Push T.
  }?                        e#
  \                         e# Swap the selected string with the code block
                            e# or T with the tail of the code block.
  "_~"                      e# Push that string on the stack.
}                           e#
_~                          e# Push a copy of the code block and execute it.

```

## Moar programs

The first program of the previous section is still highly compressible, so we can apply a similar method and write a program that, after **254166** iterations, produces the aforementioned program.

Repeating this technique over and over again until we hit the 255 byte limit, we can add a total of **254166 \+ 254140 \+ 254114 \+ 25488 \+ 25463 \+ 25438 \+ 25413 \+ 1 ≈ 1.59 × 10399** programs to those of the previous sections.

---

1 Newline added for clarity.
2 Per consensus on Meta, this is allowed by default.
3 or 0.0000000000000000000000000000000000000000000000000000000000000012 %

# Answer
> 5 votes
# JavaScript, 1000 programs

```
x=999;
q=";alert(x=999?`q=${JSON.stringify(q)+q}`.split(x).join(x-1):``)";
alert(
    x ? `x=999;q=${JSON.stringify(q)+q}`.split(x).join(x-1) // basically .replaceAll(x, x-1)
      : ``
)

```

Whether this is valid depends on precisely how to understand the third rule.

# Answer
> 4 votes
# Python 2, 9.7\*10^229 programs

```
O=0
if len(hex(O))<191:print"O=0x%x"%(O+1)+open(__file__).read()[-68:]

```

# Answer
> 4 votes
# Ruby, 1.628 × 10^237 programs

```
a=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;_="a=%#x-1;_=%p;puts _%%[a,_]if a";puts _%[a,_]if a

```

Same approach as my Perl answer, but because Ruby handles big ints already, it's easier to store as hex.

---

# Ruby, 9.277 × 10^90 programs

```
a=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;b=0xf;(b<1)&&(a-=1)&&b=eval('0x'+'f'*(74-("%x"%a).length));_="a=%#x;b=%#x;(b<1)&&(a-=1)&&b=eval('0x'+'f'*(74-('%%x'%%a).length));_=%p;puts _%%[a,b-1,_]if a";puts _%[a,b-1,_]if a

```

So this attempt is a slightly different variation on the previous quine-like, but because of all the extra functions I'm not getting the number anywhere near as high as the other one... Was interesting to try another approach though!

# Answer
> 2 votes
# C, 2.2 * 10^177 programs

```
#define S(s)char*q=#s,n[]="#####################################################################################################";i;s
S(main(){while(n[i]==91)n[i++]=35;i==101?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})

```

It's not perfect, but pretty good. I mean it's exactly `255` bytes long and generates programs of the same length. You could probably fiddle arround some more to gain some more programs, but I'll leave it as it is for now.

The program is based of a simple C quine. Additionally there's a quite simple counting algorithm which counts through all possible values of the char array `n`. We have as many programs as permutations of the string `n`.

The char range is limmited to a range from `#` (=35) to `[` = (91). That's because I don't want any `"` or `\` in the string, because they need to be escaped.

The program generation ends when all values in the char array `n` are `[`. Then it outputs a simple dummy program `main(){}`, which itself outputs nothing.

```
#define  S(s) char *q = #s; /* have the source as a string */ \
char n[] = "#####################################################################################################"; \
int i; \
s /* the source itself */
S(main() {
    while(n[i]=='[') /* clear out highest value, so next array element be incremented */
        n[i++]='#';
    i==101 /* end of array reached? output dummy program */
        ? q = "main(){}"
        : n[i]++; /* count one up in the whole array */
    printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)", n, q);
})

```

As a demonstration that it should work I just changed the limits, so only characters between ASCII-Code `35` and `36` are used and only 4 array elements.

The resulting programs are

```
% echo > delim; find -iname 'program_*.c' | xargs -n1 cat delim

#define S(s)char*q=#s,n[]="####";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$###";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="#$##";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$$##";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="##$#";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$#$#";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="#$$#";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$$$#";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="###$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$##$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="#$#$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$$#$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="##$$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$#$$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="#$$$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$$$$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="####";i;s
S(main(){})

```

This outputs `2^4 + 1 = 17` different programs.

So the program above outputs `((91-35)+1)^101 + 1 = 57^101 + 1 ~= 2.2 * 10^177` different programs. I'm not entierly sure if this counts, or if my calculation is even correct

# Answer
> 1 votes
# Perl, 1 × 10^163

Otherwise this is a pretty basic quine, shrunk down to as few chars as possible, that only runs whilst the counter isn't `0`.

```
use bigint;$i=9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999||die;$_=<<'e';eval
print"use bigint;\$i=$i-1||die;\$_=<<'e';eval
${_}e
"
e

```

# Answer
> 1 votes
# Common Lisp, 10113-1

```
(LET ((X
       99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999))
  (WHEN #1=(PLUSP X)
    #2=(SETF *PRINT-CIRCLE* T)
    #3=(PRINT (LIST 'LET `((X ,(1- X))) (LIST 'WHEN '#1# '#2# '#3#)))))

```
* There are 113 nines.
* The next program has 112 nines followed by a 8
* The next program has 112 nines followed by a 7
* ...

The number of nines is limited by the maximum size of code, 256, *taking into account* the spaces introduced by the printer.

# Answer
> 1 votes
# Perl, 1.4\*10^225

```
use bignum;open$F,__FILE__;$_=<$F>;s/0x\w+/($&-1)->as_hex/e;0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff&&print

```

Similar approach to python; same result!

# Answer
> 1 votes
# Python, 1 × 10^194 programs

```
n=99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
if n:print open(__file__).read().replace(str(n),str(n-1))

```

This must be run from a file, **not** an interactive repl. It is not a quine.

Thanks to @The Turtle for helping me save 3 bytes, which is more room for nines!
Thanks to @poke for helping me save 2 bytes, which is more room for nines!

# Answer
> 0 votes
## \>\<\>, 65534 (?) Programs

I've added a question mark next to 65533 since I have yet to verify that it can print 65533 (although I have reason to believe it should). Once I have a bit more time, I'm going to figure out a way to test it.

```
":?!;1-r00gol?!;a0.�

```

You can try it online here.

The gist of this program is that it changes the output of the character at the very end and then decrements its numerical value before printing. I got 65534 programs because the ascii value of the character at the end of the code is 65533, so counting the first program we have 65534 (if you count the empty program 65535, I guess). The last program "returned" is nothing; it simply ends when the character value is 0.

I'm quite sure it will be able to print a character for all iterations: I couldn't find a definitive source for how many characters \>\<\> can print, but there are characters directly below 65533, numerically.

Let me know if there are any problems with this implementation; I'm a little unsure about the validity of my entry.

---

## Explanation

I have shamelessly stolen the idea of using a single quotation mark to create a pseudo-quine from the \>\<\> wiki and a comment I saw here once.

```
":?!;1-r00gol?!;a0.�
"                     begins string parsing
 :?!;                 terminates program if final character is 0, numerically
     1-               decrements final character by 1
       r              reverses stack
        00g           grabs quotation mark (fancy way of putting " ")
           ol?!;      prints and terminates if stack is empty
                a0.   jumps back to o to loop

```

What it does is parse everything after the quotation mark as characters, then decrement the last one. From there it just reverses the stack (so as to print in the right order), pushes a quotation mark onto the stack, and then prints until the stack is empty.

# Answer
> 0 votes
# Bash, 52 programs

Utterly uninspired, and (hopefully) solidly in last place.

```
echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo

```

---
Tags: code-challenge, code-generation
---


title: Construct a beacon

text:
# Question
Title: Construct a beacon
In the video game Minecraft, you can obtain beacons and put them on pyramid-like structures to give you special effects, such as speed or jump boost.

Your task is to, given an effect, construct the beacon pyramid required for it.

There are multiple sizes of beacon pyramids, required for different effects. The largest has a size `9` base, and the smallest has a size `3` base.

These are the effects you can get, and the required pyramid for them (as specified by the official Minecraft wiki:

```
3:
  Speed I
  Haste I
5:
  Resistance I
  Jump Boost I
7:
  Strength I
9:
  Regeneration I
  Resistance II
  Jump Boost II
  Speed II
  Haste II
  Strength II

```

Beacons are constructed with the base at the bottom, then it goes up, decreasing the size by 2. Once we hit 1, there should be a beacon `+` at the top.

A beacon is defined as a `+`, but it needs a supporting pyramid to work.

You may assume the input is valid (ie, it is one of the effects specified here), and, optionally, you may assume the input is all lowercase. The `#` character should be used in the pyramid, and `+` as the beacon.

## Examples:

```
Haste I
 +
###

Resistance I
  +
 ###
#####

Strength I
   +
  ###
 #####
#######

Regeneration I
    +
   ###
  #####
 #######
#########

Speed II
    +
   ###
  #####
 #######
#########

```

You must also take multiple effects as beacon pyramids can share blocks - however, one beacon cannot do more than one effect. You must use minimal blocks.

When taking multiple effects, you may use any reasonable input format such as a list, newline separated, etc. Additionally, you may take a singleton list for single beacons if you are using lists.

For these examples, I only list one possible solution, but there are multiple acceptable solutions.

```
Speed I, Haste II
    ++
   ####
  #####
 #######
#########
(another acceptable solution is the following,
these are both valid as they use the same amount of blocks)
    +
   ###
  #####
 #######+
##########
(the following is not valid for the same input; it doesn't use minimal blocks)
    +
   ###
  #####           +
 #######         ###
#########

Strength I, Strength I
   ++
  ####
 ######
########

```

(don't output things in brackets, if that isn't obvious enough)

# Answer
# Python 2, 216 195 bytes

```
def b(e):s=sorted(63372>>len(_)*2-14&3for _ in e)[::-1];f=s[0]+2;r=range(f);print"\n".join(reduce(lambda p,n:[p[i]+"+# "[cmp(i,f-n-2)]for i in r],s[1:],[" "*(f-i-1)+"+#"[i>0]*(2*i+1)for i in r]))

```

Try it online!

The function for printing the string with the pyramid structure is `b`, which is called with a list of the effects as its single argument.

This turned out longer than I expected, but I was at least happy that I was able to find the beacon size based on black magic.

**Edit:** was able to reduce byte count significantly by combining the reduce function into a `lambda` thanks to Python 2's `cmp` function.
> 9 votes

# Answer
# Charcoal, 75 71 60 54 48 bytes

```
Ａ⟦⟧βＷＳ⊞βＩ§14034244⁻Ｌι⁷ＦＵＰsorted⟦β⟧«Ｇ→→↖⁺ι¹#¦+Ｍι↙

```

Try it online!

The Python answer is also mine, but I wanted to try my first golf submission in Charcoal!

I also wanted to make sure I can hold down that bounty ;)

```
Ａ⟦⟧β                        assign an empty list to β
ＷＳ                         while the next string input ι is truthy: (aka while the input is not an empty line)
    ⊞βＩ§14034244⁻Ｌι⁷       push level for ι into β (explained below)
ＦＵＰsorted⟦β⟧«             for each level ι in the sorted version of β:
    Ｇ→→↖⁺ι¹#                draw a triangle of "#"s with side lengths ι + 1
    ¦+                       draw a "+" (already on top vertex)
    Ｍι↙                     move down and left by ι cells (preparation for next level)
                             implicit end of for

```

All of the beacon names of the same length share a beacon level. As such, we can determine the beacon level of an effect from mapping the length (minus 7 to base it at zero) to the numbers in the string "14034244" (there is a 0 for clarity because length 9 does not correspond to an effect). This same idea is used in my Python answer, but with bit shifting to produce the numbers 0-3.
> 7 votes

# Answer
# Jelly, 68 bytes

```
FṀ‘
0;Ṗ
|Ç€|Ḋ€Ç|
⁽lƑb4‘ị@L€ṢµI‘ż@IṚṭṀṭ0Fs2+\µḅÑ‘Ṭ;0sÑµ+ÇÐLị“#+ ”Y;”#

```

Try it online!

I think the reason this is longer than the Charcoal answer (even though I was able to do my 'black magic' in 10 bytes) is because Charcoal was built for two-dimensional drawing. I ended depending on a 2D cellular automaton to find the positions of `#`s given the positions of `+`s to create triangles.

**How it Works** (main link split for readability)

```
FṀ‘
0;Ṗ
|Ç€|Ḋ€Ç|
⁽lƑb4‘ị@L€ṢµI‘ż@IṚṭṀṭ0Fs2+\µḅÑ‘Ṭ;0sÑµ+ÇÐLị“#+ ”Y;”# - Main link, input is list of strings
⁽lƑb4‘ị@L€Ṣ     - list of strings to list of heights (1,2,3,4)
⁽lƑ               - the number 28147
   b4‘            - base 4 and incremented: [2, 3, 4, 2, 4, 4, 1, 4]
        L€        - lengths of each input string
      ị@          - index into the list to get a list of heights
          Ṣµ      - sort and store for the next link:
I‘ż@IṚṭṀṭ0Fs2+\ - get list of coordinates for `+`s
I‘ż@I             - [0,1] between each element. Add [1,1]*n between each pair of elements with difference n
     Ṛ            - Reverse
      ṭṀṭ0        - prepend [0,maximum]
          Fs2     - format the array as a list of coordinate pairs
             +\   - cumulative sum
ḅÑ‘Ṭ;0sÑ        - convert to binary rectangular matrix:
ḅÑ‘               - change each coordinate pair (y,x) to y*width+x (Ñ is the width)
   Ṭ              - boolean array with 1s at the above indices
    ;0            - append a zero for formatting reasons
      sÑ          - split into rows of the right width
µ+ÇÐL           - add locations of `#`s:  the matrix now has 2s at future `+`s, 1s at `#`s, and `0`s at spaces
  ÇÐL             - repeatedly apply a step of the cellular automoton: 1s at `#`s and `+`s, and 0s at space
µ+                - add this to the matrix of `+`s which has 1s at `+`s.
ị“#+ ”Y;”#      - format into a string
ị“#+ ”            - index into the string "#+ ".
      Y           - join by newlines.
       ;”#        - append a `#` character to finish up the formatting.

```
> 2 votes

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


title: Elo Rating Calculator

text:
# Question
Title: Elo Rating Calculator
Related

## Task

Your task is to calculate the new Elo rating (FIDE rating system) for a player after winning, losing or drawing a game of chess.

To calculate the Elo rating two formulas are needed:

```
R' = R0 + K*(S - E)
E = 1 / (1 + 10 ^ ((R1 - R0) / 400))

```

where:

* `R'` is the new rating for player0,
* `R0` is the current rating of player0 and `R1` is the current rating of player1,
* `S` is the score of the game: `1` if player0 wins, `0` if player0 loses or `0.5` if player0 draws,
* `K` = `40` if the given history has a length \< 30, even if it exceeds 2400
* `K` = `20` if the given history has a length \>= 30 and never exceeds 2400 (\<2400),
* `K` = `10` if the given history has a length \>= 30 and exceeds 2400 at any point (\>=2400)

(if history has a length \< 30 but a max value \>= 2400 `K` will equal 40)

## Input

* History of player0's ratings as an array of positive integers greater than 0, where the last item is the players current rating. If no history is given, the current rating will be 1000
* Rating of player1 as an integer
* Score, either 1, 0 or 0.5

## Output

`R'`, A decimal integer of player0's new rating

## Examples

```
input: [], 1500, 1
  K = 40 (length of history is less than 30)
  E = 1 / (1 + 10 ^ ((1500 - 1000) / 400)) = 0.0532
  R' = 1000 + 40*(1 - 0.0532) = 1038
output: 1038

input: [1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1625, 1650, 1675, 1700, 1725], 1000, 0
  K = 20 (length of history is more than 30 but never exceeds 2400)
  E = 1 / (1 + 10 ^ ((1000 - 1725) / 400)) = 0.9848
  R' = 1725 + 20*(0 - 0.9848) = 1705
output: 1705

input: [1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1625, 1650, 1800, 2100, 2500], 2200, 0.5
  K = 10 (length of history is more than 30 and exceeds 2400)
  E = 1 / (1 + 10 ^ ((2200 - 2500) / 400)) = 0.8490
  R' = 2500 + 10*(0.5 - 0.8490) = 2497
output: 2497

```

## Test cases:

```
[2256,25,1253,1278,443,789], 3999, 0.5 -> 809
[783,1779,495,1817,133,2194,1753,2169,834,521,734,1234,1901,637], 3291, 0.5 -> 657
[190,1267,567,2201,2079,1058,1694,112,780,1182,134,1077,1243,1119,1883,1837], 283, 1 -> 1837
[1665,718,85,1808,2546,2193,868,3514,436,2913,6,654,797,2564,3872,2250,2597,1208,1928,3478,2359,3909,581,3892,1556,1175,2221,3996,3346,238], 2080, 1 -> 248
[1543,2937,2267,556,445,2489,2741,3200,528,964,2346,3467,2831,3746,3824,2770,3207,613,2675,1692,2537,1715,3018,2760,2162,2038,2637,741,1849,41,193,458,2292,222,2997], 3814, 0.5 -> 3002

```

# Notes

You won't get an input with fewer scores than 30 and a maximum score higher than 2400

This is , so the shortest code in bytes wins!

# Answer
# Octave, 106 bytes

This assumes the history never contains a zero.

```
@(h,r,s)(h=[1e3,h])(n=nnz(h))+((40-(20*(n>30)))-(10*((n>30)&(max(h)>2401))))*(s-(1/(1+10^((r-h(n))/400))))

```

This outputs (after some formatting):

```
Correct - Calculated
1038    - 1037.87
1705    - 1705.3
2497    - 2496.51

```

Try it online!

---

Note: According to the FIDE-scoring system: If you play 41 games against a player having a score of 5000 (more than 2000 points higher than the highest achieved score ever), you'll end up with a score of **2400**. I believe that fewer scores than 30, and a maximum score higher than 2400 should be considered invalid input (but that's OP's decision).

Check it here
> 1 votes

# Answer
# JavaScript (ES7), 124 bytes

This is a valid JavaScript anonymous function. Add `f=` at the beginning and invoke like `f(arg1,arg2,arg3)`. Assumes that the first element of history is not 0 (which is allowed).

```
(a,r,s)=>(e=a.some(c=>c>2400),a=a[0]?a:[1e3],Math.round((y=a.pop())+((a.length<30?40:(e?20:10))*(s-1/(1+10**((r-y)/400))))))

```

```
let f=
(a,r,s)=>(e=a.some(c=>c>2400),a=a[0]?a:[1e3],Math.round((y=a.pop())+((a.length<30?40:(e?20:10))*(s-1/(1+10**((r-y)/400))))))

btnTrigger.onclick = () => {
  let a = inputA.value.split`,`.map(c=>parseInt(c,10)),
      r = parseInt(inputR.value,10),
      s = parseFloat(inputS.value,10);

  console.log(f(a,r,s));
}
```

```
<p>Add a Single Comma in History input box for empty History</p>

<input type="text" id="inputA" placeholder="Comma Separated History">
<input type="text" id="inputR" placeholder="Value for R1">
<input type="text" id="inputS" placeholder="Value for S">

<button type="button" id="btnTrigger">Submit</button>
```
> 1 votes

# Answer
# Python 3, 106 bytes

```
def f(h,b,s):a=([1e3]+h)[-1];return round(a+((len(h)<30)*4or-~(max(h)<2400))*10*(s-1/(1+10**((b-a)/400))))

```

Try it online!

---

**without rounding, 98 bytes**:

```
def f(h,b,s):a=([1e3]+h)[-1];return((len(h)<30)*4or-~(max(h)<2400))*10*(s-1/(1+10**((b-a)/400)))+a

```

Try it online!
> 1 votes

# Answer
# , 109 bytes

```
function(p,s,h=1000,l=length(h))round(h[l]+`if`(l<30,40,`if`(any(h>2400),10,20))*(s-1/(1+10^((p-h[l])/400))))

```

Returns an anonymous function that takes several arguments: `p`, player 1's rating, `s`, the score of the game, and `h`, the history. Technically takes another argument `l` but it defaults to the length of `h`. `h` defaults to `1000` so if there is no historical record of games, no value is provided for `h`.

Try it online!
> 1 votes

# Answer
# JavaScript, 105 bytes

```
(h,r,s,u=h.length?h.pop():1e3,k=h.length>28?h.some(v=>v>2400)?10:20:40)=>u+k*s-k/(1+10**((r-u)/400))+.5|0

```
> 1 votes

# Answer
# oK, 66 bytes

```
{*|x+_.5+(40-(10*2+|/2399<x)*29<#x)*z-1%1+exp((y-*|x)%400)*log 10}

```

Try it online.

For regular k, add two bytes by turning `log` and `exp` into ``log` and ``exp` respectively.
> 1 votes

# Answer
## Haskell 158 bytes

```
g h o s=round$p+k*(s-1/(1+10**((o-p)/400)))
 where
 p=if(l h<1)then 1000else last h
 k=40-(if(l h)>=30then 20else 0)-if(any(>=2400)h)then 10else 0
 l=length

```

`g` is a function that takes a list `h` representing the `h`istory of the player, `o`, the `o`pponent points and,`s` the `s`core of the game.
> 1 votes

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


# Question
Title: How many dice can you roll without rolling the most probable number
# Problem

Starting from `n=2` dice:

* Roll `n` dice, with each number 1 to 6 equally likely on each die.
* Check if their sum equals the most probable sum for `n` dice, that is `3.5*n`.
    + If they're equal, terminate.
    + Otherwise, print `n`, and repeat from the start with `n+2` dice

Your code doesn't have to do this procedure exactly, but should give random output probabilistically equivalent to it, based on our definition of randomness.

Your program should output all of the numbers on their own line; for example, if the program got up to 8 dice and rolled the most probable number with 8 dice, the output would be:

```
2
4
6

```

# Example Run

On 2 dice, `7` is the most probable sum. Let's say the numbers rolled were `2` and `3`. Then, you would print `2`.

On 4 dice, `14` is the most probable sum. Let's say the numbers rolled were `3`, `4`, `2`, and `5`. Then, the sum is `14`, so the program would terminate here.

The final output in this case is `"2"`.

# Rules

# Answer
> 17 votes
# Python 2, 70 bytes

```
from random import*
n=2
while eval("+randrange(6)-2.5"*n):print n;n+=2

```

Try it online!

The trick is to compute the sum by `eval`ing a string the looks like

```
'+randrange(6)-2.5+randrange(6)-2.5'

```

with `n` copies of the expression concatenated. The `randrange(6)` outputs a random number from `[0,1,2,3,4,5]`, which is shifted down by `2.5` to have average of `0`. When the sum if `0`, the `while` condition fails and the loop terminates.

An alternative using `map` was 4 bytes longer:

```
from random import*
n=2
while sum(map(randrange,[6]*n))-2.5*n:print n;n+=2

```

I've found a bunch of equal-length expressions for a die shifted to mean zero, but none shorter

```
randrange(6)-2.5
randint(0,5)-2.5
randrange(6)*2-5
uniform(-3,3)//1

```

# Answer
> 7 votes
# MATL, 13 bytes

```
`@E6y&Yrs@7*-

```

Try it online!

### Explanation

```
`       % Do...while top of the stack is truthy
  @E    %   Push 2*k, where k is the iteration index starting at 1
  6     %   Push 6
  y     %   Duplicate 2*k onto the top of the stack
  &Yr   %   Array of 2*k integers distributed uniformly in {1, 2, ..., 6}
  s     %   Sum
  @7*   %   Push 7*k
  -     %   Subtract
        % End (implicit). If the top of the stack is non-zero, the loop
        % proceeds with the next iteration. Else the loop is exited.
        % Display stack (implicit)

```

# Answer
> 6 votes
# Jelly,  ~~19~~  14 bytes

-5 bytes with help from Leaky Nun (moving from count up to recursion)

```
‘‘6ṗX_3.L⁶S?Ṅß

```

A full program printing the results separated by newlines (an extra space and newline are also printed, and the program errors at the end).

**Try it online!** \- any time 6 dice are surpassed TIO kills this due to memory usage, but it works in principle - it also takes ~40s to do so.

A more friendly 15 byte version that does not take so long or require so much memory is available **here**.

### How?

Recursively rolls 2 more dice until the sum of the faces each reduced by 3.5 is zero, printing the number of dice as it goes, when the zero is reached it attempts to use a space character causing a type error.

```
‘‘6ṗX_3.L⁶S?Ṅß - Main link: no arguments (implicit left=zero)
‘              - increment (initial zero or the previous result)
 ‘             - increment  (= # of dice to roll, n)
  6            - literal 6
   ṗ           - Cartesian power - all possible rolls of n 6-sided dice with faces 1-6
    X          - pick one of them
      3.       - literal 3.5
     _         - subtract 3.5 from each of the roll results
           ?   - if:
          S    -          sum the adjusted roll results (will be 0 for most common)
        L      - ...then: length (number of dice that were rolled)
         ⁶     - ...else: literal ' ' (causes error when incremented in next step)
            Ṅ  - print that plus a newline
             ß - call this link with the same arity (as a monad with the result)

```

# Answer
> 6 votes
# TI-BASIC, 28 bytes

```
2→N
While mean(randInt(1,6,N)-3.5
Disp N
N+2→N
End

```

**Explanation**

* `randInt(1,6,N)` generates a list of N random numbers from 1 to 6
* `mean(randInt(1,6,N)-3.5` gets the average of the rolls shifted down by 3.5
* `While` continues until the average expression equals zero (the most probable sum)

# Answer
> 5 votes
# , 49 bytes

```
n=2
while(sum(sample(6,n,T)-3.5)){print(n)
n=n+2}

```

`sample(6,n,T)` generates `n` (pseudo)random samples from the range `1:6` with replacement. Subtracting 3.5 from each element yields a result whose `sum` is 0 (falsey) if and only if it's the most common value.

Try it online!

Skips the odd dice rolls.

# Answer
> 4 votes
# Java 8, ~~123~~ ~~149~~ ~~113~~ 108 bytes

```
()->{for(int n=0,s=1,i;s!=n*7;){for(i=s=++n*2;i-->0;s+=Math.random()*6);if(s!=n*7)System.out.println(n*2);}}

```

Or **107 bytes** if we use an `Object null` as unused parameter instead.

+26 bytes for a bug-fix, correctly pointed out by *@Jules* in the comments.
-41 bytes thanks to *@OliverGrégoire*'s great thinking!

**Explanation:**

Try it here.

```
()->{                           // Method without parameter nor return-type
  for(int n=0,                  //  Amount of dice
          s=1,                  //  Sum
          i;                    //  Index
      s!=n*7;){                 //  Loop (1) as long as the sum doesn't equal `n`*7,
                                //  because we roll the dice per two, and 3.5*2=7
    for(i=s=++n*2;              //   Reset both the index and sum to `n`*2,
                                //   so we can use random 0-5, instead of 1-6
                                //   and we won't have to use `+1` at `Math.random()*6`
        i-->0;                  //   Inner loop (2) over the amount of dice
        s+=Math.random()*6      //    And increase the sum with their random results
    );                          //   End of inner loop (2)
    if(s!=n*7)                  //   If the sum doesn't equal `n`*7
      System.out.println(n*2);  //    Print the amount of dice for this iteration
  }                             //  End of loop (1)
}                               // End of method

```

# Answer
> 3 votes
# R, ~~48~~ ~~44~~ 42 bytes

A 5-byte improvement on Giuseppe's answer.

```
while(sum(sample(6,F<-F+2,1)-3.5))print(F)

```

This (ab)uses the fact that `F` is a variable by default assigned to `FALSE` which coerces to `0` and can then be incremented, saving us the need to initialize a counter variable.

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

-2 Bytes thanks to Emigna

```
[YF6L.RO}7Y*;ïQ#Y=ÌV

```

Try it online!

### Explanation

```
[YF6L.RO}7Y*;ïQ#Y=ÌV
[                    # Infinite loop start
 YF     }            # Y times... (Y defaults to 2)
   6L.R               # Push a random number between 1 and 6 (why does this have to be so looooong ._.)
       O              # Sum
         7Y*;ï       # Push 3.5 * Y as an int
              Q      # Is it equal to 3.5 * Y?
               #     # If so: Quit
                Y    # Push Y
                 =   # Print without popping
                  ÌV # Set Y to Y + 2

```

# Answer
> 2 votes
# PHP, 75 bytes

```
for($d=2;(++$i*7/2-$r+=rand(1,6))||$i<$d;)$i%$d?:$d+=1+print"$d
".$r=$i="";

```

Try it online!

# Answer
> 1 votes
# GolfScript, 41 bytes

```
0{2+.n\.[{6rand.+5-}*]{+}*!!*.}{}while;;;

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES2015), 75 78 bytes

```
f=(n=2)=>[...Array(n)].reduce(a=>a+Math.random()*6|0,n)==3.5*n?'':n+`
`+f(n+2)

```

Outputs a string of results separated by newlines

Edit: saved a byte thanks to Shaggy, added 4 bytes to start function at 2

**Explanation**

```
f=n=>
  [...Array(n)]                // Array of size n
    .reduce(                   // Combine each item
      a=>a+Math.random()*6|0,  // Add a random roll between 0 and 5 for each item
    n)                         // Start at n to correct rolls to between 1 and 6
    ==3.5*n                    // Compare total to most probable roll total
  ? ''                         // If true, end
  : n+'\n'+f(n+2)              // Otherwise, output n and continue

```

```
f=(n=2)=>[...Array(n)].reduce(a=>a+Math.random()*6|0,n)==3.5*n?'':n+`
`+f(n+2)

let roll = _ => document.getElementById('rolls').innerHTML = f();
document.getElementById('roll-button').onclick = roll;
roll();
```

```
<button id="roll-button">Roll</button>
<pre id="rolls"></pre>
```

# Answer
> 1 votes
# Mathematica, 47 bytes

```
For[n=1,Tr@RandomInteger[5,2n++]!=5n,Print[2n]]

```

*-5 bytes from LLlAMnYP*

# Answer
> 1 votes
# 05AB1E, 17 bytes

```
[N·ÌD6Lã.R7;-O_#,

```

Try it online!

**Explanation**

```
[                   # loop over N in 0...
 N·Ì                # push N*2+2
    D               # duplicate
     6L             # push range [1 ... 6]
       ã            # cartesian product (combinations of N*2+2 elements in range)
        .R          # pick one at random
          7;-       # subtract 3.5 from each dice roll
             O_#    # if sum == 0 exit loop
                ,   # otherwise print the copy of N*2+2

```

# Answer
> 1 votes
# C (gcc), ~~84~~ ~~80~~ ~~79~~ ~~77~~ ~~75~~ ~~80~~ ~~78~~ 76 bytes

```
i;f(s,j){for(;s;s?printf("%d\n",i):0)for(j=i+=2,s=i*7/2;j--;)s-=1+rand()%6;}

```

Try it online!

# Answer
> 1 votes
# Haskell ~~133~~ 132 bytes

```
import System.Random;import Control.Monad
s k=do n<-replicateM k$randomRIO(1,6);if sum n==7*div k 2 then pure()else do print k;s(k+2)

```

Credit to @Laikoni for the suggestions in the comments below.

# Answer
> 1 votes
## Batch, 109 bytes

```
@set/an=%1+2,s=n*5/2
@for /l %%i in (1,1,%n%)do @call set/as-=%%random%%%%%%6
@if %s% neq 0 echo %n%&%0 %n%

```

Rather annoyingly, `random` is a magic environment variable, so it only gets replaced with a random value during environment expansion, which normally happens before the for loop starts. `call` makes it happen each time through the loop, but then you need to double the `%` signs to prevent the expansion from happening before the loop. The fun starts because we want to modulo the result by 6, which requires a real `%` sign, which now has to be doubled twice. The result is six consecutive `%`s.

# Answer
> 1 votes
# php - 89 Characters

```
$r=0;$n=2;while($r!=$n*3.5){$r=$i=0;while($i<$n){$r+=rand(1,6);$i++;}print $n."
";$n+=2;}

```

# Answer
> 1 votes
# **Octave 55 bytes**

```
n=2;
while mean(randi(6,n,1))-3.5!=0
n
n=n+2;
end

```

Inspired by Andrewarchi's answer. If someone has any pointers to even shorten it, they are welcome.

# Answer
> 1 votes
# Pyth, 20 bytes

```
K2WnsmhO6K*K3.5K=+K2

```

Try it online!

# Answer
> 0 votes
# Ruby, 52 bytes

```
s=x=2;(s=0;p x.times{s+=rand(6)-2.5};x+=2)while s!=0

```

### Explanation

```
s=x=2;                                                # sum=2, x=2
      (                                  )while s!=0  # while sum != 0:
       s=0;                                           #  reset the sum
           p                                          #  print
             x.times{              };                 #  repeat x times:
                     s+=                              #   Add to sum:
                        rand(6)                       #    random int in 0..5
                               -2.5                   #    subtract average
                                                      #  (implicitly return x for printing)
                                     x+=2             #  Increment x by 2

```

Try it online!

# Answer
> 0 votes
# Calc2 0.7, ~~119~~ ~~118~~ 111 bytes

```
using"runtime";for(n=2,d=0;d!=3.5*n;Console.WriteLine(n),n+=2)for(i=d=0;i++<n;)d+=Math.Int(Random().Next(1,7));

```

ungolfed:

```
using "runtime";
var d = 0;
var r = Random();
for(var n = 2; d != 3.5 * n; Console.WriteLine(n), n += 2)
{
    d = 0;
    for(var i = 0; i < n; i++)
        d += Math.Int(r.Next(1,7));
}

```

I could do without the Math.Int() but unfortunately in 0.7 the Random().Next() functions have a bug where they all return doubles instead of ints. It has been fixed but only after this question was posted. I'm not gonna win anything, but hey, nice proof of concept.

Edit:

* removed unnecessary space between using and "runtime" (-1 byte)

Edit2:

* removed var r and create a new Random where it's needed (-4 byte)
* changed i=0,d=0 to i=d=0 (-2 byte)
* incremented i after check (-1 byte)

# Answer
> 0 votes
# QBIC, 40 bytes

```
{[1,r|g=g+_r1,6|]~g=r*3.5|_X\g=0?r┘r=r+2

```

Thispretty much literally does what the challenge asks for; seems the shortest way to get the distribution right.

## Explanation

```
{          DO infinitely
[1,r|      FOR a=1, a<=r (at start, r == 2), a++
g=g+       Add to g (0 at start)
  _r1,6|   a random number between 1 and 6 incl.
]          NEXT
~g=r*3.5   IF the result of all dice rolls equals the expected value
|_X        THEN quit
\g=0       ELSE, reset the dice total
?r┘        PRINT the number of dice used
r=r+2      and add 2 dice.
           END IF and LOOP are courtiously provided by QBIC at EOF.

```

# Answer
> 0 votes
# Rexx (Regina), 78 bytes

```
x=2
do forever
  t=0
  do x
    t=t+random(6)
  end
  if(t=x*3.5)then
    exit
  say x
  x=x+2
end

```

Try it online!

# Answer
> 0 votes
# JavaScript (ES6) - 69 Characters

```
r=n=>n?r(n-1)+(Math.random()*6|0)-2.5:0;f=(n=2)=>r(n)?n+`
`+f(n+2):""

console.log(f())
```

**Explanation**:

```
r=n=>                                     # Roll n dice
     n?                                   # If there is a dice left to roll
       r(n-1)                             #   Roll n-1 dice
             +(Math.random()*6|0)         #   Add a random number from 0 .. 5
                                 -2.5     #   Subtract 2.5 so sum of average is 0
                                     :0   # Else total is 0

```

and:

```
f=(n=2)=>                                 # Start with n = 2
         r(n)                             # Roll n dice
             ?n+"\n"+f(n+2)               # If non-zero then concatenate n, newline and
                                          #    result for n+2 dice
                           :""            # If zero (average) terminate.

```

# Answer
> 0 votes
# Javascript, 87 chars

```
for(n=2;eval('+'.repeat(n).replace(/./g,x=>x+(Math.random()*6|0)))!=2.5*n;n+=2)alert(n)

```

Test with `console.log` instead of `alert`:

```
for(n=2;eval('+'.repeat(n).replace(/./g,x=>x+(Math.random()*6|0)))!=2.5*n;n+=2)console.log(n)
console.log('Done')
```

# Answer
> 0 votes
## lua, 102 bytes

```
function r(n,t) for d=1,n do t=t+math.random(1,6)end return t==n*3.5 or print(n)or r(n+2,0)end r(2,0)

```

Or the more readable version

```
function r(n,t) --recursive function does its magic, t is given to safe usage bytes(no local)
    for d=1,n do --roll n dice and count them up to the total (t)
         t =t+math.random(1,6)
    end
    return t==n*3.5 or --check if t==n*3.5. If it is then it ends
           print(n) or --t != n*3.5 thus print n. print returns nil
           r(n+2,0) --both the check and the return value from print are false thus r gets executed.
end
r(2,0) --start the process

```

A more cheaty version for 96 bytes

```
function r(n,t,m)t=t+m(1,6)+m(1,6)return t==n*3.5 or print(n)or r(n+2,t,m)end r(2,0,math.random)

```

This pretty much works the same as the first but reuses the rolls from earlier calls. Because of this I can remove the for loop. Both are tested in lua 5.2

# Answer
> 0 votes
# Perl 6, 48 bytes

```
.say for 2,*+2...^{3.5*$_==sum (1..6).pick xx$_}

```

---
Tags: code-golf, random
---


title: How many valid programs can you write?

text:
# Question
Title: How many valid programs can you write?
# Backstory:

I think that my boss might finally realize that I don't any enough work, despite being paid by the hour. I want to throw him off track, by writing as many valid programs as I can to send to him. Unfortunately, due to budget cuts, my keyboard only allows each key to be pressed once.

# Specification:

Write as many different valid programs as you can for your language. You may not reuse any character at any time (even within the same program). A program is "valid" is it compiles and runs without any errors (warnings are acceptable), for any given input. Your score is the number of unique programs written.

It does not matter what the program actually does. It does not need to take input, produce output, or even terminate. The only restriction is that may never return an error.

# Example (JavaScript):

1. `b=1`
2. `alert(2)`

# Answer
> 1 votes
# APL (Dyalog Unicode) version 16.0, ~~83~~84 programs

```
⍝ empty program
 ⍝ single space
	⍝ single tab
0
1
2
3
4
5
6
7
8
9
+
-
×
÷
⌈
⌊
*
⍟
|
!
○
~
∨
∧
⍱
⍲
<
≤
=
≥
>
≠
≡
≢
⍴
,
⍪
⍳
↑
↓
?
⍒
⍋
⍉
⌽
⊖
∊
⊥
⊤
⍎
⍕
⌹
⊂
⊃
∪
∩
⍷
⌷
→
⎕
1 2 3           ⍝ input for above program
⍞
Hello, World!   ⍝ input for above program
/
⌿
\
⍀
¨
&
⍨
⌶
#
⊆
⊣
⊢
⌸
⍸
⍝
⋄
L:
⍬
{}
⍝ just a newline
⍝ this line belong with the previous one

```

Try it online! (except for two which cannot run on TIO's version 15.0)

### Explanations:

Most of the programs just print their content. Exceptions are:

* The four whitespace ones do nothing.
* terminates
* asks for evaluated input
* asks for character input
* is a comment
* is a statement separator (i.e. two statements that each do nothing)
* prints an empty numeric list (i.e. just a newline)

# Answer
> 1 votes
# Jelly, 225 programs

```
(empty program)
¢
¤
¥
¬
®
µ
½
Æ
Ç
Ñ
×
Ø
Œ
ß
æ
ç
ð
ı
ȷ
ñ
÷
ø
œ
  (space)
!
$
%
&
(
)
*
+
,
-
.
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
A
B
C
D
E
F
G
H
I
J
K
L
N
O
P
Q
R
S
U
V
W
X
Y
[
]
^
_
a
b
c
e
f
g
h
i
j
k
l
m
n
o
p
q
r
u
v
w
x
|
~
¶
°
¹
²
³
⁴
⁵
⁶
⁷
⁸
⁹
⁺
⁻
⁼
⁽
⁾
Ɓ
Ƈ
Ɗ
Ƒ
Ƙ
Ɱ
Ɲ
Ƥ
Ƭ
Ʋ
Ȥ
ɓ
ƈ
ɗ
ƒ
ɦ
ƙ
ɱ
ɲ
ƥ
ʠ
ɼ
ʂ
ƭ
ʋ
ȥ
Ạ
Ḅ
Ḍ
Ẹ
Ḥ
Ị
Ḳ
Ḷ
Ṃ
Ṇ
Ọ
Ṛ
Ṣ
Ṭ
Ụ
Ṿ
Ẉ
Ỵ
Ẓ
Ȧ
Ḃ
Ċ
Ḋ
Ė
Ḟ
Ġ
Ḣ
İ
Ṁ
Ṅ
Ȯ
Ṗ
Ṙ
Ṡ
Ṫ
Ẇ
Ẋ
Ẏ
Ż
ạ
ḅ
ḍ
ẹ
ḥ
ị
ḳ
ḷ
ṇ
ọ
ṛ
ṣ
ṭ
ụ
ṿ
ẉ
ỵ
ẓ
ȧ
ḃ
ċ
ḋ
ė
ḟ
ġ
ḣ
ṁ
ṅ
ȯ
ṗ
ṙ
ṡ
ṫ
ẇ
ẋ
ẏ
ż
«
»
‘
’
“
”

```

224 characters in Jelly's 256-byte codepage are valid, non-error-throwing programs on their own, plus an empty program. The other characters could be used in literals, but since all the literal-denoting characters are already in use on their own, no new programs can be made from them.

All of these were tested, one by one, on tio.run.

# Answer
> 0 votes
# Python REPL, 24 programs

```
[empty]
[space]
[tab]
[newline]
0
1
2
3
4
5
6
7
8
9
sum
pow
chr
next
id
()
{}
[]
#
\

```

---
Tags: code-challenge
---