title: Regex, Paper, Scissors, Lizard, Spock

text:
# Question
Title: Regex, Paper, Scissors, Lizard, Spock
## Warm up: Regex, Paper, Scissors

This is the challenge I originally wanted to post, before realising that some very short solution exist. Nevertheless, it can be an interesting problem to think about in preparation for the actual challenge below.

Write three regexes **R**, **P** and **S** such that they match each other in a cyclic Rock, Paper, Scissors fashion. In particular, **R** matches **S**, **S** matches **P** and **P** matches **R**, but **R** *doesn't* match **P**, **S** *doesn't* match **R** and **P** doesn't match **S**. Here's a handy table:

```
Regex   Matches   Doesn't match
R       S         P
P       R         S
S       P         R

```

It doesn't matter what **R**, **P** and **S** do on any other inputs, including themselves.

Here, **match** just means that some (possibly empty) substring of the input is matched. The match does not need to cover the entire input.

## The challenge: Regex, Paper, Scissors, Lizard, Spock

For this challenge, you'll solve a tougher version of the above problem, based on the RPS variant Rock, Paper, Scissors, Lizard, Spock (as popularised by *The Big Bang Theory*). In RPSLV, there are five different symbols, that beat each other in two cycles:

* Rock → Scissors → Lizard → Paper → Spock → Rock
* Rock → Lizard → Spock → Scissors → Paper → Rock

You should write five regexes **R**, **P**, **S**, **L** and **V** which mimic this structure when given to each other as input. Here is the corresponding table:

```
Regex   Matches   Doesn't match
R       L, S      V, P
L       V, P      S, R
V       S, R      P, L
S       P, L      R, V
P       R, V      L, S

```

Just to be clear, you should *not* match the string `R`, `P`, etc, but the other regexes. E.g. if your regex **R** is `^\w$` for example, then **P** and **V** have to match the string `^\w$`, whereas **S** and **L** shouldn't.

Again, **match** just means that at least one (possibly empty) substring of the input is matched. The match does not need to cover the entire input. For example `\b` (word boundary) matches `hello` (at the beginning and at the end), but it doesn't match `(^,^)`.

You may use any regex flavour, but please state the choice in your answer and, if possible, provide a link to an online tester for the chosen flavour. You may not use any regex features that let you invoke code in the flavour's host language (like the Perl flavour's `e` modifier).

Delimiters (like `/regex/`) are not included in the regex when given as input to another, and you cannot use modifiers that are outside of the regex. Some flavours still let you use modifiers with inline syntax like `(?s)`.

Your score is the sum of the lengths of the five regexes in bytes. Lower is better.

It turns out to be a lot simpler to find *a* working solution to this problem than it may seem at first, but I hope that finding an optimal solution is quite tricky.

# Answer
> 47 votes
# PCRE, ~~15~~ 14 bytes

Rock:
`B`

Paper:
`\b$`

Scissors:
`b|B.`

Lizard:
`\B.`

Spock:
`^\w`

# Answer
> 46 votes
# ~~PCRE~~ .NET, ~~35~~ 32 bytes

*-3 bytes thanks to Martin Ender*

Rock:

```
([*?]$)

```

Paper:

```
[)$]$+

```

Scissors:

```
[+?]$.*

```

Lizard:

```
[+$]$.?

```

Spock:

```
[*)]$

```

The idea here is to match characters at the end of other regexes which are reserved regex characters, but stop being treated as such when inside a character class.

# Answer
> 40 votes
## no fancy features, ~~35~~ 30 bytes

5 bytes saved by Neil's idea which uses that `]` needs no `\`.

This works for example with the python `re` module.

```
R='[SLR]]'
P='[RVP]]'
S='[PLS]]'
L='[PVL]]'
V='[SRV]]'

```

It searches for a `]` preceded by a letter that indicates which rule it is.

Previous version used `R='\[[RSL]'` etc.

An earlier attempt with score 40 was using `R='[SL]x|Rx'` etc.

# Answer
> 26 votes
# PCRE, ~~20~~ 19

Rock

```
W

```

Paper

```
^\w

```

Scissors

```
^\W

```

Spock

```
w?\x57$

```

Lizard

```
[w]W?

```

# Answer
> 21 votes
# 20 bytes

```
R = 'R|VP'
L = 'L|RS'
V = 'V|LP'
S = 'S|RV'
P = 'P|LS'

```

# Answer
> 8 votes
# JavaScript, 45 bytes

Another trivial solution.

```
R:
^R|^.[SL]
P:
^P|^.[RV]
S:
^S|^.[PL]
L:
^L|^.[PV]
V:
^V|^.[SR]

```

# Answer
> 6 votes
**POSIX, ~~50~~ 45 bytes**

```
Rock
.{5}RP?V?
Paper
.{5}PS?L?
Scissors
.{5}SR?V?
Lizard
.{5}LR?S?
Vulcan (Spock)
.{5}VP?L?

```

Could be done shorter but the (hide matches after $) trick got used, so I'm looking for another way

The first 5 chars of each string are ignored when matching. So the **effective** target string simplifies to just X?Y?. None of them have any double letters because "?" is an ordinary char, so the last 4 chars when used as a **regex** have to match (null string). So the patterns collapse down to "contains 5 chars followed by the target letter": meaning chars 6-9 of the target must contain the target letter (the 5th char in each string)

**Update: 35 byte version below, now!**

# Answer
> 4 votes
# PCRE, 65 bytes

This is a really trivial solution - and not very clever at all - but I'll try to golf it.

V:

```
(?#V).+[SR]\)

```

L:

```
(?#L).+[PV]\)

```

S:

```
(?#S).+[PL]\)

```

P:

```
(?#P).+[RV]\)

```

R:

```
(?#R).+[SL]\)

```

Essentially, each regex has an 'identifier', in the form of a comment, which tells the other regexes whether it should be matched or not.

# Answer
> 4 votes
# Vanilla RE, 40 characters

Not the most concise or elegant solution but has a pleasing quasi-semantic visual structure!

```
[^r][sl]
[^p][vr]
[^s][lp]
[^l][pv]
[^v][rs]

```

Rock beats Scissors or Lizard
Paper beats Vulcan or Rock
Scissors beats Lizard or Paper
Lizard beats Paper or Vulcan
Vulcan beats Rock or Scissors

# Answer
> 3 votes
# .NET, 50 bytes

In order they are `R, P, S, L, V`.

```
[^R]\^[SL]
[^P]\^[RV]
[^S]\^[PL]
[^L]\^[PV]
[^V]\^[SR]

```

Works by looking for the identifier group (for example, `[^R]`) in each of the other expressions.

Changing the expressions to `^R|\^[SL]`, or similar, seems to work but then it's a bit too similar to @dzaima's answer although it would get it to 45 bytes.

# Answer
> 3 votes
**POSIX, 35 bytes**

```
Rock
R?^[LS]
Paper
P?^[RV]
Scissors
S?^[LP]
Lizard
L?^[PV]
Vulcan (Spock)
V?^[RS]

```

A completely different way to "hide" behind a start/end symbol, so I feel OK about it :) I'm matching to start because "?" would always have to go between letter and end/$ if done the other way.

10 bytes less than my 1st solution, and conceptually simple which is a bonus I like.

---
Tags: code-golf, regular-expression
---


title: How many words are there?

text:
# Question
Title: How many words are there?
English is such an inefficient language. We've got enormous words when there are plenty of two or three letter words we never used! As computer scientists, every keystroke matters. We need to be more efficient. Just think of how many words we could have had! In fact, don't think about it, tell me.

Given a string (or list) of letters, I want you to output how many words we could make using those letters. You must use every letter in the string exactly one time.

Words can't just be any old string of letters though, how would you say "yffghtjrufhr"? To be a word, it has to satisfy the following conditions:

* It must contain at least one vowel ('y' is always a vowel).
* There must be no more than 2 vowels in a row.
* There must be no more than 3 consonants in row.
* The combinations "ch", "sh", and "th" count as one consonant.
* "s" counts as neither a consonant nor vowel ("length" is just as valid as "lengths").

For example:

```
Input    -> Output
a        -> 1       (a)
b        -> 0
ab       -> 2       (ab, ba)
abbbb    -> 3       (babbb, bbabb, bbbab)
abbbbbbb -> 0
essss    -> 5       (essss, sesss, ssess, ssses, sssse)
abbbth   -> 46      (thabbb, thbabb, thbbab, bathbb, ...)

```

Obviously, since this challenge is all about character efficiency, I think a challenge is in order. Standard rules apply!

(For clarification, an 's' breaks any streaks of vowels or consonants. The word "abbbsbbb" is ok, since there are no more than 3 consonants in a row".)

# Answer
# Python 3, 166 Bytes

```
import itertools as i,re;print(len([w for w in[re.sub('[cst]h','b',''.join(x))for x in set(i.permutations(input()))]if not re.search('[aeiouy]{3}|[^aeiouys]{4}',w)]))

```

Takes a string from input(). The string is passed to itertool's (built-in library) permutations function, in this case taking a string and returning tuples of unique combinations when wrapped in set(). ''.join() turns the tuples into strings again. Combinations 'th', 'ch', and 'sh' are replaced with an arbitrary consonant, 'b' using re's (regular expression, built-in library) sub function. Words (variable 'w' in the list comprehension) are are then filtered based on if they contain 4 or more consonants, or 3 or more vowels using re's search.
> 1 votes

# Answer
# JavaScript, 275 bytes

```
a=>(a.match(/[^aeiouys]/g)||[])[L='length']<a[L]*.85|0&&[...Array(1<<(n=(a=[...a])[L])*--n/2)].map((_,b)=>a.slice().sort(_=>(b/=2)*2&1?1:-1).join``).filter((a,b,c)=>c.indexOf(a)==b&&/[aeiouy]/[t='test'](d=a.replace(/[cst]h/,1))&!/[aeiouy]{3}/[t](d)&!/[^aeiouys]{4}/[t](d))[L]

```

Try it online
> 1 votes

---
Tags: code-golf, natural-language
---


title: Sierpinski Layers

text:
# Question
Title: Sierpinski Layers
Starting with `/\` you can create a Sierpinski triangle like pattern by adding a line beneath such that...

1. Any loose branch `/` or `\` splits again into two branches: `/\`.
2. Any collision of branches `\/` dies with nothing (but spaces) under it.

Repeating these rules yields

```
     /\
    /\/\
   /\  /\
  /\/\/\/\
 /\      /\
/\/\    /\/\
etc...

```

(Inspiration by ViHart)

Write a program or function that takes in a positive integer N and prints the first N lines of this pattern to stdout, with no more leading or trailing spaces than necessary.

For example, if the input is `1` the output must be

```
/\

```

If the input is `2` the output must be

```
 /\
/\/\

```

If the input is `8` the output must be

```
       /\
      /\/\
     /\  /\
    /\/\/\/\
   /\      /\
  /\/\    /\/\
 /\  /\  /\  /\
/\/\/\/\/\/\/\/\

```

And so on.

The code with the fewest bytes wins.

# Answer
> 9 votes
## GolfScript (42 bytes)

```
~,-1%1\{' '*\.2base{'  /\\'2/=}%n@.2*^}/;;

```

Online demo

This exploits a well-known relationship between Pascal's triangle and the Sierpinski triangle.

# Answer
> 6 votes
# CJam, ~~48~~ 46 bytes

```
li(_S*"/\\":T+\{_N@S+TW%/S2**" /"/"\ "f/:+T*}*

```

Simple recursive approach based on observations 1 and 2 in the question.

Try it online.

### How it works

```
li(         " L := int(input()) - 1            ";
_S*         " A := L * ' '                     ";
"/\\":T+    " A += (T := '/\')                 ";
\{          " do L times:                      ";
  _N        "   push A, '\n'                   ";
  @S+       "   A += ' '                       ";
  TW%/      "   B := A.split(reverse(T))       ";
  S2**      "   A := '  '.join(B)              ";
  " /"/     "   B := A.split(' /')             ";
  "\ "f/    "   C := { X.split('\ ') : X ∊ B } ";
  :+T*      "   A := T.join(sum(C, []))        ";
}*          "                                  ";

```

---

# CJam, 51 bytes

```
li__2mL,1a\{2_@##)1$f*+}/<f{2b_"  /\\"2/f=@@,-S*\N}

```

I like this approach better, but it can't compete with the recursive one. Even after eliminating `2mL` (which results in at least O(2n) execution time), I'm still at 48 bytes...

This approach encodes `/\`'s as 1's and double spaces between them as 0's. Considering the resulting arrays binary numbers, we see that the configuration of the *nth* row corresponds to the *nth* integer larger than 1 that can be expressed as a product of different Fermat numbers (integers of the form **22k+1**).

### How it works

```
li__2mL,1a         " push L := int(input()), L, R := range(log(L)/log(2)), A := [1] ";
\{2_@##)1$f*+}/    " for I in R: A += { a × 2**(2**I) : a ∊ A }                     ";
<                  " A := A[:L]                                                     ";
f{                 " for I in R: push L, I                                          ";
  2b_"  /\\"2/     "   push (B := base(I, 2)), B, S := [ '  ' '/\' ]                ";
  f=               "   for J in I: J := S[J]                                        ";
  @@,-S*\N         "   push (L - len(B)) * ' ', J, '\n'                             ";
}                  "                                                                ";

```

# Answer
> 5 votes
# Python 2 - ~~140 139 127 122 121 118~~ 116

```
N=input()
b,V,m,n=' V/\\'
s=b*~-N+m+n
R=str.replace
while N:print s;N-=1;s=R(R(R(R(s+b,b+m,V),n+b,V),n+m,b+b),V,m+n)

```

Based on temporary string replacements (https://stackoverflow.com/a/8687380/3419103):

1. `/` \> `V`
2. `\` \> `V`
3. `\/` \> `__` (2 spaces)
4. `V` \> `/\`

# Answer
> 4 votes
# Javascript - 117 bytes

Minified:

```
T=n=>{S=' '.repeat(n-1);a='/\\';for(t=s=S+a+S;--n;t+='\n'+s)s=s.replace(/\\\//g,'  ').replace(/ \/|\\ /g,a);return t}

```

Expanded:

```
T = n => {
    S = ' '.repeat( n-1 );
    a = '/\\';
    for( t = s = S + a + S; --n; t += '\n' + s )
        s = s.replace( /\\\//g, '  ' ).replace( / \/|\\ /g, a );

    return t;
}

```

Sample Output (for `n = 20`):

```
                   /\
                  /\/\
                 /\  /\
                /\/\/\/\
               /\      /\
              /\/\    /\/\
             /\  /\  /\  /\
            /\/\/\/\/\/\/\/\
           /\              /\
          /\/\            /\/\
         /\  /\          /\  /\
        /\/\/\/\        /\/\/\/\
       /\      /\      /\      /\
      /\/\    /\/\    /\/\    /\/\
     /\  /\  /\  /\  /\  /\  /\  /\
    /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
   /\                              /\
  /\/\                            /\/\
 /\  /\                          /\  /\
/\/\/\/\                        /\/\/\/\

```

Now if only the `repeat` and `replace` function names weren't so long. :P

# Answer
> 3 votes
# Haskell, ~~128~~ 112

```
g n=unlines$take n$i t([1..n]>>" ")%(i(\l->l++l%i(t.t)(t l>>"  ")%l)["/\\"]!!n)
t=tail
(%)=zipWith(++)
i=iterate

```

# Answer
> 3 votes
# Pyth, 45 bytes

```
K"/\\"Jt+*QdKVQpbJ=JjKsmcd"\ "cj*2dc+Jd_K" /"

```

### Example run

```
$ pyth -c 'K"/\\"Jt+*QdKVQpbJ=JjKsmcd"\ "cj*2dc+Jd_K" /"' <<< 16
               /\
              /\/\
             /\  /\
            /\/\/\/\
           /\      /\
          /\/\    /\/\
         /\  /\  /\  /\
        /\/\/\/\/\/\/\/\
       /\              /\
      /\/\            /\/\
     /\  /\          /\  /\
    /\/\/\/\        /\/\/\/\
   /\      /\      /\      /\
  /\/\    /\/\    /\/\    /\/\
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

```

### How it works

```
                            # Q = eval(input())
K"/\\"                      # K = "/\\"
      Jt+*QdK               # J = (Q * " " + K)[1:]
             VQ             # for N in range(Q):
               pbJ          #     print(J, end="\n")
                            #
=JjK                        #     J = K.join(
    sm                      #         sum(list(map(lambda d:
      cd"\ "                #             d.split("\ "),
            c               #                                                .split(    )
             j*2d           #              " ".join(                        )
                 c   _K     #                                .split(K[::-1])
                  +Jd       #                       (J + " ")
                       " /" #                                                       " /"
                            #     ))))

```

# Answer
> 3 votes
# Ruby, 90

```
f=->n{a=["/\\".center(2*n)]
2.upto(n){a<<a[-1].gsub("\\/","  ").gsub(/ \/|\\ /,"/\\")}
puts a}

```

## Explanation

* Input is taken as an argument to a lambda. It is expected to be an `Integer`.
* Use `String#center` to create a `String` `"/\"` with `n - 2` spaces on each side and put it into an `Array` (`a`).
* Add to `a` the last element of `a` with every occurrence of `"\/"` replaced with `" "` and every occurrence of `" /"` or `" \"` replaced with `"/\"`.
* Use `puts` to print each element in `a` on its own line.

# Answer
> 2 votes
# JavaScript (E6) 107 ~~106~~

Edit: fixed byte count, made recursive.

Not much different from the other JS answer ... at least this one 'prints' the pattern as requested. The core is replacing ' /' '\ ' with '/\\' and all the rest with ' ' on each new line.

```
F=(n,o=t='/\\',b=' ')=>
  n--&&
    console.log(b.repeat(n)+o)|
    F(n,(b+o+b).replace(/../g,s=>s==b+b|s=='\\/'?b+b:t))

```

**Test** In FireFox/FireBug console

```
F(15)

```

*Output*

```
                  /\
                 /\/\
                /\  /\
               /\/\/\/\
              /\      /\
             /\/\    /\/\
            /\  /\  /\  /\
           /\/\/\/\/\/\/\/\
          /\              /\
         /\/\            /\/\
        /\  /\          /\  /\
       /\/\/\/\        /\/\/\/\
      /\      /\      /\      /\
     /\/\    /\/\    /\/\    /\/\
    /\  /\  /\  /\  /\  /\  /\  /\

```

# Answer
> 2 votes
# Perl 5 - 56 bytes

\0's can be replaced by actual null byte characters

```
#!/usr/bin/perl -l
$p="/\\";$_=$"x~$_.$p,y/\0/ /,print,$p^="\0\0$p"for-<>..-1

```

It is using the fact that if you ignore leading spaces and represent '/\\' as 1 and ' ' as 0 the pattern in a given row f(n) = f(n-1) ^ (f(n-1) \<\< 1). However the calculations in the code above are executed on strings that are close to the expected output (no leading spaces, other spaces replaced by null bytes) thanks to perl's bitwise string manipulation.

```
$p="/\\";          # initialize
  $_=$"x~$_.$p,    # loop start, add spaces
  y/\0/ /,         # replace nulls with spaces
  print,           # output
  $p^="\0\0$p"     # calculate next string
for-<>..-1         # loop from -n to -1

```

# Answer
> 1 votes
## Python 2, 84 bytes

```
n=i=input()
while i:print' '*i+''.join("/ \ "[j&i+1>0::2]for j in range(n-i+1));i-=1

```

# Answer
> 1 votes
# Mathematica, 86 bytes

```
Column[Row/@Mod[Table[Binomial[n,k],{n,0,#-1},{k,0,n}],2]/.{1->"/\\",0->"  "},Center]&

```

# Answer
> 0 votes
## Javascript with lambdas, ~~141~~ 128

**141**

```
f=n=>{for(a="25",q=0;++q<n;a=a[r='replace'](/^|$/mg,1)[r](/(.*)$/,"$1\n$1")[r](/..(?=.*$)/g,x=>x%3?11:25));return a[r](/./g,x=>"  /  \\"[x])}

```

**128**

```
f=n=>(t=a=>--n?t(a[r='replace'](/^|$/mg,1)[r](/(.*)$/,"$1\n$1")[r](/..(?=.*$)/g,x=>x%3?11:25)):a)("25")[r](/./g,x=>"  /  \\"[x])

```

Can be tested at Firefox (n=16):

```
               /\
              /\/\
             /\  /\
            /\/\/\/\
           /\      /\
          /\/\    /\/\
         /\  /\  /\  /\
        /\/\/\/\/\/\/\/\
       /\              /\
      /\/\            /\/\
     /\  /\          /\  /\
    /\/\/\/\        /\/\/\/\
   /\      /\      /\      /\
  /\/\    /\/\    /\/\    /\/\
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```

# Answer
> 0 votes
# Python 2, 97 bytes

```
i=input()
x=1
while i:i-=1;print " "*i+bin(x)[2:].replace("0","  ").replace("1", "/\\");x^=2*x

```

---
Tags: code-golf, fractal
---


title: How Fermat is this number?

text:
# Question
Title: How Fermat is this number?
Fermat numbers are positive integers that can be expressed as 22x+1 with an integer x.

Let us now define an attribute of a number called "Fermat-ness":

* The Fermat-ness of the number is one less than the length of the chain of powers of two, starting from the base, with powers of two expanded so as to maximize the fermat-ness.
* A number that is not a Fermat number has the Fermat-ness of zero.

So, 17 (=22220+1) has Fermat-ness three.

## Challenge

Given a positive nonzero integer as input, output the Fermat-ness of the number.

## Rules

* You may take the input in binary, decimal, hexadecimal, as a bignum, or whatever format lets you golf best
* Your solution must be able to process numbers with bit-lengths over 64 whichever representation you use.
* Nonnegative integer powers only.
* Standard loopholes are of course prohibited.
* This is , so shortest answer wins.

## Test cases

These are in format `input->output`. The input is in hexadecimal to save space.

```
10000000000000000000000000000000000000000000000000000000000000001 -> 2
1000000000000BC00000000000000000000000000000000001000000000000001 ->0
1234567890ABCDEF -> 0
100000000000000000000000000000001 -> 1
5 -> 2
11 -> 3
10001 -> 4
101 -> 1

```

The same in decimal:

```
115792089237316195423570985008687907853269984665640564039457584007913129639937 -> 2
115792089237316497527923305698859709742143344804209838213621568094470773145601 -> 0
1311768467294899695 -> 0
340282366920938463463374607431768211457 -> 1
5 ->2
17 -> 3
65537 -> 4
257 -> 1

```

Thanks to geokavel for invaluable input in the sandbox.

# Answer
> 7 votes
# Jelly, ~~15~~ 14 bytes

1 byte thanks to Jonathan Allan.

```
’µBḊ⁸LṀ?µÐĿḊḊL

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~103~~ 81 bytes

```
n=input()-1
i=l=0
while 2**2**i<=n:
 if n==2**2**i:n=2**i;i=-1;l+=1
 i+=1
print l

```

Try it online!

I realized not being stupid would help lower my byte count, so I did that. Also exponentiation as opposed to logarithms.

# Answer
> 0 votes
# RProgN 2, 75 bytes

```
«\`n=1\]{1-\n*\]}:[»`^=«1-`n=001{]2\^2\^ne{2\^`n=1+0}{1+}?]2\^2\^n>¬}:[»`¤=

```

Try it online!

It's only 70 bytes if you don't add the `«»'¤=` which assigns the Fermatness calculation to the `¤` character. If you do that, you'll need to put the number in the Header section of TIO instead of in the Footer like it is now.

This effectively uses the same logic as my Python answer, so if you don't care about how RProgN 2 works, just look at that one for an explanation of what's going on. Otherwise

Code breakdown:

```
«\`n=1\]{1-\n*\]}:[»`^=
«                  »`^=`                            # Create a local function and assign it to the ^ character (x y ^ is x to the power of y)
 \`n=                                               # Swap the top two values of the stack and assign the new top to the variable n
     1\]                                            # Push a 1 (our starting point for x to the y), swap with the y value, then duplicate y
        {       }:                                  # Start a while loop that pops the top stack value and loops if it is truthy
         1-                                         # Subtract 1 from y to keep a tally of how many multiplications we've done
           \n*                                      # Swap the counter with our current value and multiply it by n
              \]                                    # Swap this new value with the current value of y, and duplicate it to be used as the truthy value for the loop

«1-`n=001{]2\^2\^ne{2\^`n=1+0}{1+}?]2\^2\^n>¬}:[»`¤=# The main Fermatness function (x ¤ to get the Fermatness of x)
«                                               »`¤=# Create another local function for this calculation
 1-`n=                                              # Decrement the input by 1 and assign it to n
      001                                           # Push a counter for Fermatness, a counter for calculating 2^2^i, and an initial truthy value
         {                                   }:     # Start a while loop for calculating the Fermatness
          ]2\^2\^ne                                 # Duplicate i, calculate 2^2^i, and compare it to n
                   {         }{  }?                 # Start an if statement based on the equality of 2^2^i and n
                    2\^`n=                          # n==2^2^i, so set n to 2^i (same as saying n=log_2(n))
                          1+0                       # Increment the Fermatness counter and reset i
                               1+                   # n!=2^2^i, so just increment i
                                   ]2\^2\^n>¬       # Duplicate the counter and check if 2^2^i<=n, if true the loop continues, else it exits
                                               [    # Pop i from the stack, leaving us with just the Fermatness counter

```

Unfortunately the log function `Š` and the normal exponentiation function `^` lack the precision to do this natively, so I had to redefine how exponentiation worked since multiplication carries much more precision. Without that redefine, this answer would be 23 bytes shorter.

# Answer
> 0 votes
# Perl 6, 62 bytes

```
{my@a=first :kv,*>=0,(^∞).map(2**2** *+1-$_);++@a[0]*!@a[1]}

```

Try it online!

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


title: Fake divisor sum polyglots

text:
# Question
Title: Fake divisor sum polyglots
## The task

In this challenge, your task is to write a program in a programming language **L** that takes a positive integer **n**, and outputs the sum of the proper divisors of **n** (sequence A001065 on OEIS). It should return the correct output for any **1 ≤ n ≤ 10 000**. Here are the first 10 outputs:

```
0, 1, 1, 3, 1, 6, 1, 7, 4, 8

```

Furthermore, your program must be a *fake polyglot*, which means the following. It is a valid program in another programming language **L'**, and for each input **1 ≤ n ≤ 10** (the test cases above), it returns the sum of proper divisors of **n**, but there exists some **11 ≤ n ≤ 10 000** for which it doesn't return the correct result. It may return something incorrect, loop forever, crash etc. It can give a wrong result for all **n ≥ 11**, for some of them or just one.

## Rules and scoring

You can write a full program or a function, and you can have different means of input and output in the two languages. The lowest byte count wins. Standard rules apply. In this challenge, different major versions or implementations of a language are considered distinct.

Note that if you use programming languages with non-ASCII encodings (as many do on this site), the same *sequence of bytes* must be used for both languages. This means that you must either convert between potentially different code pages or suffer penalties for multi-byte Unicode characters.

## Additional test cases

```
20 -> 22
36 -> 55
180 -> 366
997 -> 1
2875 -> 869
10000 -> 14211

```

# Answer
> 10 votes
## JavaScript (ES6), V8 / SpiderMonkey vs Chakra, ~~66~~ 63 bytes

```
n=>[...Array(n)].map((_,d)=>s+=n%d?0:d,[0,n>10].sort(x=>s=x))|s

```

### Demo

```
let f =

n=>[...Array(n)].map((_,d)=>s+=n%d?0:d,[0,n>10].sort(x=>s=x))|s

console.log(JSON.stringify(
  [...Array(20)].map((_, n) => n + 1).map(f)
))
```

### Output

Output of the above snippet on Chrome and Firefox (all correct):

```
[0,1,1,3,1,6,1,7,4,8,1,16,1,10,9,15,1,21,1,22]

```

Output on Edge (off by 1, starting at n = 11):

```
[0,1,1,3,1,6,1,7,4,8,2,17,2,11,10,16,2,22,2,23]

```

### Why?

No algorithm is imposed by the specification for the `.sort()` method. It's not even required to be stable. Therefore, each JavaScript engine uses its very own implementation.

However, `[0,1].sort(x=>x)` gives `[0,1]` with all engines.

So what's the difference?

What's happening here is that Chakra is passing `1` as the first parameter of the first (and only) iteration to the callback function (asking for a comparison of `1` with `0`), while V8 and SpiderMonkey are passing `0` (asking for a comparison of `0` with `1`).

You can use the following snippet to check what your browser is doing.

```
[0, 1].sort((x, y) => console.log("Let's compare " + x + " with " + y + "!"))
```

# Answer
> 8 votes
# Python 2 and Python 3, 58 bytes

TIO for Python 2

TIO for Python 3

```
lambda n:sum(i*(n<11or''==b'')for i in range(1,n)if n%i<1)

```

It works in python 2, but for every n \> 10 it would output 0 in python 3.
All because of different approaches in comparing strings with bytes:

* in Python 2 `'' == b''`
* in Python 3 `'' != b''`

# Answer
> 8 votes
# 05AB1E / Jelly,  ~~9~~  8 bytes

The byte-code (hexadecimal):

```
d1 a8 4f 71 0d ad 53 fa

```

Using Jelly's code-page returns incorrect results for any excessive number (e.g. an input of **12** returns `12` rather than `16`):

```
ẎƭOqÆḌS«

```

**Try it online!**

Using 05AB1E's code-page returns correct results:

```
Ñ¨OqмλSú

```

**Try it online!**

### How?

05AB1E parses up to and including the `71` (`q`) which instructs to quit and then stops parsing:

```
Ñ¨Oq - Takes input from stdin
Ñ    - get divisors
 ¨   - remove right-most (the input value itself - yielding proper divisors)
  O  - sum
   q - quit (causing an implicit print of the top of the stack)
...мλSú is never parsed

```

Jelly parses the whole program up-front as three links due to the effect of the bytes without an assigned meaning, `ƭ` and `q` acting as delimiters. The entry point of a program is it's final link:

```
Ẏ - Link 1 (never used), tighten list
...ƭ delimits links 1 & 2)

O - Link 2 (never used), cast from characters to their ordinals
...q delimits link 2 and the main link

ÆḌS« - Main link: number, n
ÆḌ   - proper divisors
  S  - sum
   « - minimum of that and n
     - as a full-program: implicit print

```

# Answer
> 7 votes
# JavaScript (Node.js) and PHP, ~~73~~ 70 bytes

```
function($n){for($d=$i=0;++$i<$n;)$d+=$i*!($n%$i);return"$n">10?0:$d;}

```

In both languages, this is an anonymous function. JavaScript gives the correct result, but PHP gives **0** for all **n \>= 11**.

Try it JS!

Try it PHP!

### How it works

Both languages do the same thing at first: iterate from 1 up to n-1, keeping a running sum of all numbers **i** for which **n % i = 0**.

What causes the difference in behaviour is the final part:

```
return"$n">10?0:$d;

```

In JavaScript, `"$n"` is just a string literal. The comparison `>` with `10` casts it to a number implicitly, but since it doesn't look like a number, it becomes NaN. NaN gives false when compared with a number in any way. As a result, `$d` is always returned.

However, in PHP, `"$n"` is a string containing the value of `$n`. When PHP casts this to a number, it simply becomes the value of `$n`. If it's greater than `10`, then `0` is returned instead of `$d`.

# Answer
> 6 votes
# Python 3 / Python 2, ~~64~~ ~~60~~ 58 bytes

*Thanks to @officialaimm for 2 bytes off*

```
lambda n:sum(d*(round((n>10)*.5)==n%d)for d in range(1,n))

```

In Python 3 this gives the correct results. In Python 2 the ouput is wrong for inputs exceeding `10`. The code exploits banker's rounding, which is done by Python 3 but not by Python 2.

Try it online! Python 3 (correct), Python 2 (wrong for `n > 10`).

# Answer
> 6 votes
# Python 3 / Python 2, 47 bytes

```
lambda n:sum(d*(n%d<1)for d in range(10/n>0,n))

```

An unnamed function, fake in Python 2.

Try it online for **Python 3** or **Python 2**

In Python 2 `/` is integer division with integer arguments, whereas in Python 3 it is division.

When `n` exceeds **10** `10/n` evaluates to **0** in Python 2, but to a small positive number in Python 3 (this is certainly true up to the maximum required of **10,000** at least).

As such `10/n>0` evaluates to `True` for Python 3 and `range(10/n>0,n)` is equivalent to `range(1,n)` while in Python 2 `10/n>0` evaluates to `False` when `n` exceeds **10** whereupon `range(10/n>0,n)` becomes equivalent to `range(0,n)` causing `n%d` to attempt to perform modulo zero arithmetic, raising a `ZeroDivisionError`.

# Answer
> 5 votes
# Jelly / 05AB1E, 12 bytes

What Jelly sees:

```
11⁻iẎƭO}qÆḌS

```

Try it online!

Explanation:

`q` is unsupported in Jelly, so Jelly only "sees" what's after the `q`.

```
ÆḌS
ÆḌ  Proper divisors
  S Sum

```

What 05AB1E sees:

```
11‹iÑ¨O}qмλS

```

Try it online!

Explanation:

```
11‹iÑ¨O}qмλS Implicit input multiple times
11           Push 11
  ‹          Less than 11?
   i   }     If equals 1, then
    Ñ         Divisors
     ¨        Remove last
      O       Sum
       q     Implicit print and quit
        м    Negative filter
         λ   Undefined, ignored error
          S  Split into chars

```

Of course everything after "quit" doesn't actually happen.

---
Tags: code-golf, sequence, polyglot
---


title: Reverse Fibonacci

text:
# Question
Title: Reverse Fibonacci
## Your task

You must write a program, to print a **reverse Fibonacci series**, given a number.

## Input

A **non-negative** integer ***N***.

## Output

You must output all the Fibonacci numbers from ***Fk*** to ***F0***, where ***k*** is the smallest non-negative integer such that ***Fk******N******Fk+1***.

## Example

```
IN: 5

OUT: 5 3 2 1 1 0

```

***If input isn't a Fibonacci number, the series should begin from the closest Fibonacci number less than the input.***

```
IN:  15

OUT: 13 8 5 3 2 1 1 0

```

***If input is 1, the series should be.***

```
IN:  1

OUT: 1 0

```

## Scoring:

This is , lowest byte count wins.

## Leaderboard

```
var QUESTION_ID=136123,OVERRIDE_USER=60869;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 2 votes
# Neim, 5 bytes

```
f₁>

```

Try it online!

# Explanation

```
f            infinite list of fibonacci numbers
 ₁>          get input and increment it
            first b elements of a
            reverse the list

```

I feel like this could be golfed more. `₁>` feels a bit inefficient...

# Answer
> 4 votes
# Haskell, 52 bytes

```
p=0:scanl(+)1p
f 1=[1,0]
f n=reverse$takeWhile(<=n)p

```

Second line is necessary for the `n = 1` edge-case. I wasn't able to get around it.

# Answer
> 3 votes
# Python 2, ~~62~~ 59 bytes

```
n,l,a,b=input(),[],0,1
while a<=n:l=[a]+l;a,b=b,a+b
print l

```

Try it online!

# Answer
> 3 votes
# Jelly,  ~~9~~  8 bytes

```
ḤḶÆḞṚ>Ðḟ

```

A monadic link taking a number and returning the list of numbers.

**Try it online!**

Note: I am assuming 1s are not both required, if they are the previous 9 byter works: `+2ḶµÆḞṚfṖ`

### How?

```
ḤḶÆḞṚ>Ðḟ - Link: number, n
Ḥ        - double n (this is to cater for inputs less than 6)
 Ḷ       - lowered range of that -> [0,1,2,...,2*n-1]
  ÆḞ     - nth Fibonacci number for €ach -> [0,1,1,...,fib(2*n-1)]
    Ṛ    - reverse that
      Ðḟ - filter discard if:
     >   -   greater than n?

```

...the reason this only outputs `[1,0]` for an input of `1` is that the unfiltered list does not contain `fib(2)`, the second `1`.

The 9 byter works by adding two, `+2`, to form the lowered range `[0,1,2,...,n,(n+1)]` rather than doubling and then filter keeping, `f`, any results which are in a popped, , version of that same list, `[0,1,2,...,n]` (the value accessed by making a monadic chain, `µ`).

# Answer
> 2 votes
# Mathematica, 46 bytes

```
Reverse@Select[Array[Fibonacci,t=1+#,0],#<t&]&

```

Try it online!

thanx to @JungHwan Min for -16 bytes

# Answer
> 2 votes
# Dyalog APL, 28 bytes

```
{x/⍨⍵≥x←⌽{1∧+∘÷/0,⍵/1}¨⍳2×⍵}

```

Requires `⎕IO←0`.

Try it online!

**How?**

`{1∧+∘÷/0,⍵/1}` \- apply fibonacci

`¨⍳2×⍵` \- to the range `0` .. `2n`

`x←⌽` \- reverse and assign to `x`

`x/⍨` \- filter x with

`⍵≥x` \- the function `x <= n`

# Answer
> 2 votes
# Python 2, 58 bytes

*Note: invalidated by recent specification change* (`1` -\> `(1, 1, 0)`)

```
n=input()
r=1,0
while r[0]<=n:r=(r[0]+r[1],)+r
print r[1:]

```

A full program accepting from stdin and printing (a tuple representation of) the numbers in the reversed order.

**Try it online!** or see a test suite

# Answer
> 2 votes
# Perl 6, 40 bytes

```
{[R,] 0,1,*+*...^{2>$_??$^a==1!!$^b>$_}}

```

Test it

## Explanation:

* `{…}` create a bare block lambda with implicit parameter `$_`
* `[R,] **LIST**` is a Left fold using the reverse meta-op `R` combined with the comma op `,`.
(shorter than `reverse`)
* `0, 1, *+* ...^ **Callable**` produces a Fibonacci sequence that stops on the value before **`Callable`** returns a `True` value.

The remaining code is a bit complicated as it has to return `True` if the original input is `1` and the second to latest value is `1`. This is so that the full lambda returns `(1,0)` instead of `(1,1,0)`.

```
{ # bare block lambda with two placeholder params ｢$a｣ and ｢$b｣

    2 > $_    # is the original input smaller than 2

  ??          # if it is
    $^a == 1  # check if the second to latest value is 1

  !!          # otherwise
    $^b > $_  # check if the latest value is bigger than the original input
}

```

---

If the code was allowed to return `(1,1,0)` when given the value `1`, it can be dramatically shorter at 22 bytes:

```
{[R,] 0,1,*+*...^*>$_}

```

Test it

In this case `* > $_` creates a *WhateverCode* lambda that in this use-case will return `True` if the generated value is greater than the original input.

Everything else is the same as above.

# Answer
> 2 votes
# Mathematica, ~~52~~ 41 bytes

```
{1,0}//.{a_,b_,c___}/;a+b<#:>{a+b,a,b,c}&

Fibonacci@Range[Floor[Log[GoldenRatio,1+√5#]],0,-1]&

```

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
ÎÅF)˜RIi¦

```

Try it online!

If `[1, 1, 0]` is valid output for **1** this would be `ÎÅF)˜R` at 6 bytes

# Answer
> 2 votes
# Husk, ~~20~~ ~~18~~ ~~17~~ 13 bytes

Thanks a lot @Zgarb for telling me about `İf` which is a built-in for Fibonacci numbers, this saved me `4` bytes:

```
§↓=1ȯ↔`↑:0İf≤

```

Try it online!

### Ungolfed/Explanation

```
               -- implicit input N
          İf   -- get all Fibonacci numbers,
        :0     -- prepend 0,
      `↑    ≤  -- take as as long as the number is ≤ N,
    ȯ↔         -- reverse and
§ =1           -- if input == 1:
 ↓             --   drop 1 element else no element

```

---

## Old answer without built-in (17 bytes)

The old answer is quite similar to shooqie's Haskell answer:

```
§↓=1ȯ↔`↑ȯƒo:0G+1≤

```

Try it online!

### Ungolfed/Explanation

A really short way to compute Fibonacci numbers in Haskell is to define a recursive function like this (also see the Haskell answer):

```
fibos = 0 : scanl (+) 1 fibos

```

Essentially that code computes the fixpoint of the function `\f -> 0 : scanl (+) 1 f`, so you can rewrite `fibos` in an anonymous way like this:

```
fix (\f -> 0 : scanl (+) 1 f)

```

Try it online!

This corresponds to the Husk code `(ƒo:0G+1)`, here's the remaining code annotated:

```
                   -- implicit input N
        ȯƒo:0G+1   -- generate Fibonacci numbers (ȯ is to avoid brackets),
      `↑        ≤  -- take as as long as the number is ≤ N,
    ȯ↔             -- reverse and
§ =1               -- if input == 1:
 ↓                 --   drop 1 element else no element

```

# Answer
> 1 votes
# C# (.NET Core), 70 bytes

```
n=>{var t="0";for(int a=0,b=1,c;b<=n;c=a,a=b,b+=c)t=b+" "+t;return t;}

```

Try it online!

Input is an integer into the Lambda. Output is a space-delimited string of the fibonacci sequence in reverse.

# Answer
> 1 votes
# Javascript (ES6), 42 bytes

```
f=(n,a=0,b=1)=>b>n|a>=n?a:f(n,b,a+b)+" "+a

```

Alternative, if `f(1)` = `1 1 0`

```
f=(n,a=0,b=1)=>b>n?a:f(n,b,a+b)+" "+a

```

Example code snippet:

```
f=(n,a=0,b=1)=>b>n|a>=n?a:f(n,b,a+b)+" "+a

console.log(f(5))
console.log(f(15))
console.log(f(1))
```

# Answer
> 0 votes
# Röda, 58 bytes

```
{|k|a=0;b=1{{[a];b=a+b;a=b-a}while[a<k,b<=k];[a]}|reverse}

```

Try it online!

---
Tags: code-golf, fibonacci, subsequence
---


title: Generate white noise

text:
# Question
Title: Generate white noise
The challenge is: generate an audio file made of white noise.
Requirements and instructions:

* Your program must generate an audio file containing only white noise, meaning its intensity is the same for all (reasonable) frequencies and nonzero \[see an example plot\];
* One must be able to play the audio file on the latest version of VLC \[at the time of writing your answer\];
* The program doesn't need cryptographically-strong randomness, `rand` functions or reading from `/dev/rand` is okay;
* The program must be able to generate at least 1 hour of audio, at least in theory (meaning system limitations like maximum filesize don't apply);
* Your score is the number of bytes in your source code, plus all bonuses that apply;
* Using any *third-party, external* library is okay;
* The program must work without access to the Internet.

Bonuses are:

* -15%: Allow to specify the format of the audio file (at least two choices; the number of possible choices doesn't change the score);
* -10%: Allow to specify the duration of the audio file;
* -5%: Allow to specify the bitrate of the audio file.

The settings can be stored in variables, files, or given as command line parameters, your choice. Percentages are calculated from the original number of bytes, before any bonus is applied.

# Answer
> 4 votes
# MATLAB, 25

```
wavwrite(rand(8e3,1),'a')

```

writes a new WAV file to disk called `a`. It has a sample rate of 8 kHz and a 16 bits per sample in signed integer format. The source data is uniformly distributed on the interval `[0,1]`, which is mapped to the interval `[0,32767]` after the conversion to integer format.

# MATLAB, 28 - 4 (10% + 5%) = 24

I'm not sure what the OP meant about how settings could be stored in variables, but I interpreted it in a way that is favorable to this case. Assuming that:

* The desired bit rate (in bits/second) is provided by the user in the variable `b`. The bits per sample is hard-coded at 16.
* The desired duration of the file (in samples) is given in the variable `d`.

The result is:

```
wavwrite(rand(d,1),b/16,'a')

```

# MATLAB, 16 - 4 (15% + 10%) = 12

Adding another layer of sleaze in pursuit of bonuses, I make another assumption: the desired function to use to output the file should be specified in the variable `f`. Then the code simplifies to:

```
f(rand(d,1),'a')

```

Allowable values for the function are:

```
f = @wavwrite

```

or

```
f = @auwrite

```

Each function will cause the above snippet to write out a file of the appropriate format (WAV or `.au`) at a sample rate of 8 kHz with the specified duration. I took off the bonus for specification of the bitrate here, because `auwrite` defaults to 8 bits per sample instead of 16 like `wavwrite` does. I don't see a way to harmonize the two without using more characters.

# Answer
> 10 votes
# Bash, 34

```
dd if=/dev/sda of=file.wav count=1

```

If you don't want hard drive 'randomness', (a lot slower)

```
dd if=/dev/random of=file.wav count=9

```

# SPIN, 28

```
word x=0
repeat
 word[?x]=?x

```

# Answer
> 5 votes
# Bash + ALSA, score:44 (52 chars - (10% + 5%) bonuses)

Longer than the other `bash` answer, but accepts duration and bitrate. Also adds a reasonably correct header to the file, so should be reasonably portable:

```
arecord -r$2|head -c44;head -c$[$2*$1] /dev/urandom

```

Save as a script, `chmod +x` it and run:

```
$ ./wav.sh 1 44100 > c.wav
Recording WAVE 'stdin' : Unsigned 8 bit, Rate 44100 Hz, Mono
$

```

Note, .wav output is to stdout, so it must be redirected to a file.

# Answer
> 4 votes
# Mathematica 52 - 5 = 47

`g` exports a white noise .wav file of `s` seconds and 8000 bps.

```
g@s_:=Export["p.wav",RandomReal@{-1,1}~Play~{t,0,s}]

```

---

Example: a 6 second white noise file is exported.

```
g[6]

```

> p.wav

# Answer
> 4 votes
## Supercollider, 89 - 10% = 80.1 bytes

Sadly, despite being deliberately made for generation of sound/audio, this language is not going to win here. But it's the first appearance of Supercollider on Code Golf, so that's cool!

This submission loses primarily because setting up recording and making it happen is a verbose process owing to the client/server design of this language. Still, it's a cool language with a lot of power in very little code when you ask it to do things more complex than mere white noise.

File duration is set by changing the wait() value. I could put it in a variable, but there's really no point to that as Supercollider has no stdio to speak of. The interactivity is in manipulating the code live while the server is still playing. Essentially, the IDE *is* the I/O (unless you build a UI for your creation).

Here's the golfed version:

```
{WhiteNoise.ar(1)}.play;s.prepareForRecord;Routine.run{s.record;wait(99);s.stopRecording}

```

Here's a golfed version with the option to record in either aiff or wav, and specify a sample format (int16, int8, and float are all options). Unfortunately, even with all the bonuses, the version above fares better. This would be 139 - 30% = 97.3 bytes.

```
s.recSampleFormat='int16';s.recHeaderFormat='wav';{WhiteNoise.ar(1)}.play;s.prepareForRecord;Routine.run{s.record;wait(99);s.stopRecording}

```

And here's an ungolfed version of the latter, so you can see what's going on.

```
s.recSampleFormat='int16';
s.recHeaderFormat='wav';

{WhiteNoise.ar(1)}.play;
s.prepareForRecord;

Routine.run{
    s.record;
    wait(99);
    s.stopRecording
}

```

# Answer
> 1 votes
# JavaScript, 167 bytes

**CAUTION: Decrease volume before run. White noise is nasty**

Don't generates file, maybe not what was expected.

*-4 bytes* hack play noise on left channel only

```
c=new AudioContext()
n=c.createScriptProcessor(s=512)
n.connect(c.destination)
n.onaudioprocess=e=>{a=s;while(a--){e.outputBuffer.getChannelData(0)[a]=Math.random()}}
```

# Answer
> 0 votes
# C ~~127~~ 115 bytes

```
#define H htonl
main(c){for(write(1,(int[]){H(779316836),H(24),-1,H(2),H(8000),H(1)},24);;write(1,&c,1))c=rand();}

```

The majority of the code writes the header for a \*.au file. This prints a pseudorandom sound file to standard out.

The sample rate can be adjusted by changing the `8000`.

The duration can be adjusted by hitting `ctrl-c` whenever you want to stop :-)

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


title: Happy Birthday, let's have some cake!

text:
# Question
Title: Happy Birthday, let's have some cake!
It's my friend's birthday soon and since he is a programmer and ASCII art lover, I thought I'd make him some ASCII cake!

Sadly, I keep forgetting his current age, so I would like to have a program for my ASCII oven, that bakes a cake with a specified number of candles, so I don't have to do it myself again if I am wrong with his age.

ASCII ovens only have limited memory and storage capacity, so it should use the *fewest bytes possible*.

---

## Your Task:

Write a program that outputs a birthday cake to the console, with as many candles as the input specifies.

Cake requirements are:

* It has to have a border, built up of horizontal `-` and vertical `|` lines, and vertices `+`.
* Atleast 5 characters wide (including cake border `|`)
* Atleast 5 characters high (including cake border `-`)
* There has to be a whitespace character  between the cake border and the first candle-base (not the flame), on each side, except if there is a flame in that space. A flame or candle-base should not be able to overlap the cake borders.
* The maximum width of the cake is 9 characters, so there is a maximum of 5 candles per row.
* Since we don't want our cake to be 2-dimensional, it has to be an extra 2 rows high, to give it some volume. Add another border at the bottom and connect the vertices with the ones above them, again using the ASCII characters from above (`-`, `|` and `+`).

Candle requirements are:

* Consists of the base `|` and the flame `*`, with the flame stacked on top of the base.
* Candles may not be directly adjacent to eachother, except diagonally.
* Candles are placed left-to-right, then top-to-bottom, with 5 in one line at maximum.
(Note: If there were 5 candles in the previous row, the next row can't possibly have 5 aswell, since then they would be adjacent.)

**Additional notes:**

* The cake width depends on the number of candles in the *first* row, but it has to be a minimum of 5 characters and a maximum of 9 characters wide.
* The candles are filled starting in the top-most row, going left to right. Once one row if full the next one should start in the row below the first one.

## Input:

You may accept a number in (reasonable) format you like.

For this challenge you may assume that the number is between 0 and 231 (not including 0), even though I don't acknowledge someone who is this old.

## Output:

You can either return a string or directly write the resulting cake into the output console.

## Rules:

* Standard loopholes are forbidden.
* This is , so shortest code in bytes, in any language, wins.

---

## Examples:

Input: `8`

```
+-----------+
| * * * * * |
| |*|*|*| | |
|  | | |    |
|           |
+-----------+
|           |
+-----------+

```

Input: `2`

```
+-----+
| * * |
| | | |
|     |
+-----+
|     |
+-----+

```

Input: `12`

```
+-----------+
| * * * * * |
| |*|*|*|*| |
| *|*|*| |  |
| | | |     |
|           |
+-----------+
|           |
+-----------+

```

---

Good luck!

# Answer
# Charcoal, ~~76~~ ~~71~~ ~~70 66~~ 46 bytes

```
ＮθＦ=+Ｂ⁺³⌊⟦χ⁺θθ⟧÷⁺℅ι⁺θθ⁹↘↘Ｆθ«↑|*¶¶¿‹⁶﹪⁺ιι⁹«Ｍ⁹←↓

```

Try it online! Link is to verbose version of code. Edit: Saved 1 byte thanks to @ASCII\_Only. Saved a massive 20 bytes by discovering a neat way of drawing the candles. Explanation:

```
ＮθＦ=+Ｂ⁺³⌊⟦χ⁺θθ⟧÷⁺℅ι⁺θθ⁹

```

Calculate the size both of the whole cake including extra volume and just the top of the cake so that they can be drawn. ((`=` = ASCII 61) = (`+` = ASCII 43) + 9 * 2 for the extra volume.)

```
↘↘Ｆθ«

```

Move the cursor to the first row of 5 candles. Loop through each candle.

```
↑|*¶¶

```

Print a candle and move right two characters for the next candle.

```
¿‹⁶﹪⁺ιι⁹«

```

However after the (zero-indexed) 4th, 8th, 13th, 17th, 22nd etc. candles (that are at the end of a row),

```
Ｍ⁹←↓

```

move the cursor to the first candle on the next row. This works on both odd and even rows!
> 10 votes

# Answer
# Jelly, 67 bytes

```
s9s€5Ẏa;⁶;⁶z⁶Z
ç”|ṙ-ż"ç”*$U⁸RḤ’¤¦Ẏ€j@€“| “|”Zj@€⁾--Z”+®¦€0,1©¦;ṫ¥-Y

```

A monadic link taking a number and returning a list of characters or a full program printing the output.

**Try it online!**

### How?

```
s9s€5Ẏa;⁶;⁶z⁶Z - Link 1, make some candle parts & topping: number, age; character, part
s9             - split (implicit range(age)) into chunks of 9 (or remainder)
  s€5          - split each chunk of 9 into chunks of 5 (a 5 and a 4 or remainder)
     Ẏ         - tighten (to a list of lists of length 5, 4, 5, 4, ..., remainder)
      a        - logical and with the part character (either | or * here)
       ;⁶      - concatenate a space (we all still want topping when no candles)
         ;⁶    - ...and another (we also want some extra topping below the last row)
           z⁶  - transpose with filler space (fill the top with topping!)
             Z - transpose (put it back around the right way again chef)

ç”|ṙ-ż"ç”*$U⁸RḤ’¤¦Ẏ€j@€“| “|”Zj@€⁾--Z”+®¦€0,1©¦;ṫ¥-Y - Main link: number, age
ç”|                                                  - call last link (1) as a dyad with '|'
   ṙ-                                                - rotate left by -1
          $                                          - last two links as a monad:
       ç”*                                           -   call (1) as a dyad with '*'
      "                                              - zip with the dyadic operation:
     ż                                               -   zip (interleave each)
                 ¦                                   - sparse application:
           U                                         - ...of: upend (reverse each)
                ¤                                    - ...to indexes: nilad+links as a nilad:
            ⁸                                        -   chain's left argument, age
             R                                       -   range
              Ḥ                                      -   double (vectorises)
               ’                                     -   increment
                  Ẏ€                                 - tighten €ach (from '|*' or '*|' pairs)
                       “| “|”                        - literal ["| ", "|"]
                    j@€                              - join (swap arguments) for €ach (add a little extra topping to the left, and add piping to the sides)
                             Z                       - transpose
                                 ⁾--                 - literal "--"
                              j@€                    - join (swap arguments) for €ach (add piping to the top and bottom edges)
                                    Z                - transpose (time to invest in a potters wheel!)
                                              ¦      - sparse application:
                                          0,1        - ...to indexes: [0,1] (both ends)
                                             ©       -   (copy that to the register)
                                         €           - ...of: for each:
                                        ¦            -   sparse application:
                                     ”+              -   ...of: '+' character
                                       ®             -   ...to indexes: recall from register (both ends)
                                                  -  - literal -1
                                                 ¥   - last two links as a dyad
                                                ṫ    -   tail from index (gets last two rows)
                                               ;     -   concatenate (repeats them underneath)
                                                   Y - join with newlines
                                                     - as a full program: implicit print

```
> 3 votes

# Answer
# Japt, 94 bytes

```
/4½ c ÆYu ç +Um5-Yu)ÇV°<U?Q:SÃ¸+(1+Yu)ç
"| {Ug ç}|"
Vd"|+ -"
[W¡"| {X}|"ÃVVWVW]c ·y rQ+S"*|" y

```

Try it online!
> 1 votes

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


title: Be My Navigator

text:
# Question
Title: Be My Navigator
Oh no, I am lost on the way to finding the great treasures of Marakov! And all I have are these useless instructions that look like `S10R10D30`... I have no idea what they mean! Can you help me?

## Challenge

Given directions consisting of `N E S W U D L R 1 2 3 4 5 6 7 8 9 0`, output how far I will be from where I started when I follow those directions (i.e. Euclidean Distance).

`N E S W` refer to me turning North, East, South, and West;

`U D L R` refer to me turning Up, Down, Left, and Right (So `NR` is the same as `E`, and so is `SL`; `SLL` is the same as `N`). Up means keep going forward; Down means turn around.

After each letter direction will be a number, which is how far I will go in that direction. `N10E20` means go North 10 units, then turn East, and go East 20 units.

## Input Details

* Input will always start with one of `NESW` (so blank input need not be accounted for).
* Two letter instructions in a row are allowed. `NE` should be interpreted, "Turn North, then immediately turn East". It's the same as just `E`. `SLL` is "Turn South, then immediately turn Left twice". It's the same as `N`.
* All numbers will be integers (note how `.` isn't in the character set)
* Input will only consist of `NESWUDLR1234567890` (If it *needs* something else, like '\0' in C; or if your language's input functions has a trailing newline, or something, that's fine.)

## Output

* The norm.
* If using a function, should output a numeric datatype or a string.
* Must be accurate to 3 decimal places.

## Test Cases

* `N10`: `10`
* `N10E10`: `14.1421`
* `N10S10`: `0`
* `NSEWUDLR10`: `10`
* `N100RR20E300D40L12`: `268.7452`
* `ERR10LL20UN30D100`: `70.71067`

The unimaginative Python program I used to make these.

## Winning

This is codegolf, so lowest bytes after a week wins!

# Answer
# (Go)Ruby, 111 bytes

```
x=0
c=1,1i,-1,-1i
gs.sc(/(\w)(\d*)/){|o,a|x+=c.ro!('URDL'.ix(o)||'NESW'.ix(o)+c.ix(1)).fs*a.toi}
p Mh::hy *x.rc

```

Try it online!

Takes input on STDIN, outputs it on STDOUT.

Basically, this approach uses complex numbers to store the current position, as well as a stack (`c`), containing offsets for each direction. If a direction is in `URDL`, the stack is rotated by the index of the direction in that string; if the direction is in `NESW`, it's rotated by the index of the direction in that string, plus the index of `1` in the stack. This transforms a rotation relative to the current position into a rotation relative to the position of 1. In any event, the top of the stack is multiplied by the number of steps in the direction and added to the current position.
> 2 votes

# Answer
# Python 3, 137 bytes

```
v=n=0
d=1
for i in input()+'U':x="NUERSDW0123456789".find(i);c=x<7;v+=d*n*c;n=[n*10+x-7,0][c];d=[d,d**(x%2)*1j**(~-x/2)][c]
print(abs(v))

```

Try it online!

-9 bytes thanks to Jonathan Allan
> 4 votes

# Answer
# JavaScript (ES6), ~~148~~ ~~142~~ ~~140~~ ~~138~~ ~~137~~ 134 bytes

```
s=>s.replace(/\d+|./g,_=>~(i='NESW'.search(_))?d=i:~(i='URDL'.search(_))?d+=i:a[d&3]+=+_,a=[0,0,0,0])&&Math.hypot(a[1]-a[3],a[0]-a[2])

```

```
f=

s=>s.replace(/\d+|./g,_=>~(i='NESW'.search(_))?d=i:~(i='URDL'.search(_))?d+=i:a[d&3]+=+_,a=[0,0,0,0])&&Math.hypot(a[1]-a[3],a[0]-a[2])

for(test of [
  'N10',
  'N10E10',
  'N10S10',
  'NSEWUDLR10',
  'N100RR20E300D40L12',
  'ERR10LL20UN30D100',
]) console.log(f(test))
```

-2 bytes: Use `.search()` instead of `.indexOf()` (@Shaggy)

-1 byte: Rearrange program to remove enclosing parentheses (@Shaggy)

-3 bytes: Use `.replace()` instead of `.match().map()` (@ThePirateBay)
> 2 votes

# Answer
# Perl 5, 149 + 1 (-p) = 150 bytes

```
while(s/(\D+)(\d+)//){$p=/N/?0:/E/?1:/S/?2:/W/?3:/L/?$p-1:/R/?$p+1:/D/?$p+2:$p for split//,$1;$m[$p%4]+=$2}$_=sqrt(($m[0]-$m[2])**2+($m[1]-$m[3])**2)

```

Try it online!

**Explained:**

```
# Each direction is assigned a number:
#
#     0     North
#     1     East
#     2     South
#     3     West
#
# Variables:
#     $p     present direction
#     @m     total movement in each direction
# Inside loop:
#     $1     a set of direction instructions
#     $2     distance

while(s/(\D+)(\d+)//)    # Remove and preserve the first direction set and distance
   for split//,$1        # Loop through individual letters to set new direction
      $p=/N/?0:          # North
         /E/?1:          # South
         /S/?2:          # East
         /W/?3:          # West
         /L/?$p-1:       # Turn left
         /R/?$p+1:       # Turn right
         /D/?$p+2:       # Turn around
         $p              # Do not change direction
   $m[$p%4]+=$2          # Add the directional movement to previous movements

   $_=sqrt(              # Calculate distance
       ($m[0]-$m[2])**2  # Net North/South movement
      +($m[1]-$m[3])**2  # Net East/West movement
      )

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Pi Hunting - find an index of Pi whose value matches its index
Given π to an arbitrary number of places, your challenge is to locate indices of π where the index (1,2,3,4...) and the string of numbers from that index carry the same value for the length of the index.

That sounds complex, so let's look at an example!

Indices will count from +1 upwards through natural whole integers, skipping 0 as the first index:

1, 2, 3, 4,.... up to an arbitrary whole positive number.

If the number being used (instead of π) was:

`123456789101112`

then for each index value 1... the sequence of numbers at that index position would match with the value of the index.

At position `1` the string '1' can be found

```
123456789101112
^

```

At position `2` the string '2' can be found

```
123456789101112
 ^

```

If this sequence continue to 10, you'd find that at position `10` the sequence '10' is found.

```
123456789101112
         ^

```

However, when you reach position `11`, you find '01', not '11'.

```
123456789101112
          ^

```

Given an input value of π of the format:

`3.14159...`

and taking off `3.` to give `14159...` using indices start at 1, so the first string found at index 1 is "1", the first string found at index 2 is "4", etc.

Find the shortest code to locate the first 4 indices where the set of characters at that index position have the same numerical sequence as the numbers that make up the index.

Shortest wins!

Built-ins are allowed

Examples of finding the nth digit of pi:

Find the nth decimal of pi

The major step here is to make the comparison of the nth digit and 'n' to determine if there's a match.

\** First Match \**

3.14159265

1 : finds '1'

A simple psuedo-code approach might be similar to the following, except this one doesn't account for "3." or the index being off by 1:

`assume input=pi to any arbitrary length supported with '3.' removed`

```
for(var index=0, maximumInputLength=input.length; index < maxmimumInputLength; index++) {
 var indexString = '' + i;
 var indexLength = indexString.length;
 if(indexString.substr(index, indexLength) == indexString) {
    // index found at index'th position
 } else {
    // index not found at index'th position
 }
}

```

This style of solution will return '6' found in the 6th index position and '27' found in the 27th index position.

Given 141 592 6 (6 is in the 7th position starting at 0).

To verify if an answer is correct, you can use the above code to find the nth digit of pi and compare to the value of 'n' in your language of choice!

**Thank you for the great feedback in helping me write a better first question.**

**Clarifications:**

* Is π given as an input - YES

# Answer
# Python 2, 64 bytes

```
i=1
while i<len(P):
	if int(P[i:i+len(str(i))])==i:print i
	i+=1

```

As you said, pi's digits are given, so I chose the variable `P` to contain the entire digit string.
The full code first downloads one billion digits of pi to a file using cURL and then reads in that file to process it.

```
"Setting up pi's digits."; exec'import os\nN,f=200000000,"pi.txt"\nif not os.path.exists(f):os.system("curl https://stuff.mit.edu/afs/sipb/contrib/pi/pi-billion.txt>"+f)\nP=open(f,"r").read()[1:N+2][:-1]'
"Search through pi.";      exec'i=1\nwhile i<len(P):\n\tif int(P[i:i+len(str(i))])==i:print i\n\ti+=1'

```

Though, when one knows the answer, a simple plaintext output is actually shorter (29 bytes).

```
print"1,16470,44899,79873884"

```

This series of numbers is also known to the OEIS (http://oeis.org/A057680).
> 1 votes

---
Tags: code-golf
---


title: Swap the Sequence

text:
# Question
Title: Swap the Sequence
Your task is to write some code that outputs an OEIS sequence, and contains the name of the sequence in the code (`A______`). Easy enough right? Well here's the catch, your code must also output a second separate sequence when the name of the sequence in the code is changed to the name of the second sequence.

## Input Output

Your code can be a function or complete program that takes **n** via a standard input method and outputs the **n**th term of the sequence as indexed by the provided index on the OEIS page.

You must support all values provided in the OEIS b files for that sequence, any number not in the b files need not be supported.

## Scoring

This is . Your score will be the number of bytes in your code, with less bytes being better.

## Example

Here's an example in Haskell that works for A000217 and A000290.

```
f x|last"A000217"=='0'=x^2|1>0=sum[1..x]

```

Try it online!

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

```
n=>4&~0xA000004

```

Works with A000004 (all 0s) and A010709 (all 4s).

Previous 17-byte solution works with A010850 to A010859 inclusive:

```
n=>~-0xA010850%36

```

Previous 25-byte solution works with A010850 to A010871 inclusive:

```
n=>"A010850".slice(5)-39

```
> 8 votes

# Answer
# C#, 28 bytes

```
n=>n*n*("A000290"[6]<49?1:n)

```

Works with A000290 (Squares) and A000578 (Cubes).

Try it online!
> 6 votes

# Answer
## Haskell, 28 bytes

```
f x|"A000012"!!6<'3'=1|1<2=x

```

The second sequence is A007953. Try it online!
> 3 votes

# Answer
# cQuents, 16 bytes

```
=A000007//5#|A:0

```

Try it online!, A000007, `1,0,0,0,0...`

```
=A000004//5#|A:0

```

Try it online!, A000004, `0,0,0,0,0...`

## Explanation

```
                    Implicit input A
=A000007            First item in the sequence equals A * 7
        //5                                                 intdiv 5 = 1
           #|A      n equals A
              :     Mode : (sequence): output nth item (1-based)
               0    Rest of the sequence is 0

```

```
                    Implicit input A
=A000004            First item in the sequence equals A * 4
        //5                                                 intdiv 5 = 0
           #|A      n equals A
              :     Mode : (sequence): output nth item (1-based)
               0    Rest of the sequence is 0

```

Thanks to Conor O'Brien for `4//5 = 0` and `7//5 = 1`.

If the spec was more flexible, it would be `O7A$` and `O4A$`.
> 3 votes

# Answer
# Cubix, 28 bytes

```
I:uU**...L..A000578@O\s<s(;?

```

returns the perfect cubes, `a(n)=n^3`.

Try it online!

On the other hand,

```
I:uU**...L..A068601@O\s<s(;?

```

returns the perfect cubes minus one, `a(n)=n^3-1`.
> 2 votes

# Answer
# dc, 13 bytes

**Edit:** Apparently OEIS lists the powers from `0`th to `30`th - I just did a search on these sequences and it turns out the original `13` byte solution is the golfiest. But I found another solution for just `1` byte more that works for `9` sequences.

Solution for A000012 (constant 1's sequence):

```
?A000012 4%^p

```

Try it online!

Solution for A001477 (non-negative integers):

```
?A001477 4%^p

```

Try it online!

Solution for A000290 (perfect squares sequence):

```
?A000290 4%^p

```

Try it online!

### Ungolfed/Explanation

These solutions make use of the fact that `dc` interprets `A` as `10`, so `A001477` becomes the value `10001477`. Further it exploits that the sequences are `n^0`, `n^1` and `n^2` which coincides with `10000012 % 4 == 0`, `10001477 % 4 == 1` and `10000290 % 4 == 2`.

So these sequences are `xyz(n) = n ^ (xyz % 4)`.

```
Command          Description          Example (3)
?              # Push the input       [3]
 A000290       # Push sequence name   [3,10000290]
         4%    # Top %= 4             [3,2]
           ^   # Pop x,y & push y^x   [9]
            p  # Print the top        [9]

```

### 14 byte solution for 9 sequences

The idea is still the same, this time we need to do a `% 97`, to get the right power - it works for sequences A010801, A010802, A010803, A010804, A010805, A010806, A010807, A010808 and A010809 (these are the sequences `n^13`,...,`n^21`).

Here's the first one:

```
?A010801 97%^p

```

Try it online!
> 2 votes

# Answer
# Neim, ~~10~~ 9 bytes

```
A000012ᛄ>

```

Explanation:

```
A            Push 42
 000012      Push 4
 or
 A007395     Push 7395
        ᛄ     Modulo 2
         >    Increment

```

A000012 (all ones) and A007395 (all twos)

A function that takes the input on the top of the stack and leaves the output on the top of the stack.

Try it online!
> 1 votes

# Answer
# Python 2, ~~25~~ 17 bytes

```
print'A000012'[5]

```

Works for A000004 and A000012. (input is ignored because the sequences are all constant terms).
> 1 votes

# Answer
# Befunge 98, 10 bytes

```
#A000012$q

```

Also works for A000004. Output by exit code.
> 1 votes

# Answer
# Jelly, 17 bytes

```
“A000578”OS%⁵ạ6*@

```

Try it online!

```
“A000578”OS%⁵ạ6*@  Main link
“A000578”          String
         O         Codepoints
          S        Sum (364 for A000290, 373 for A000578)
           %⁵      Modulo 10 (4 for A000290, 3 for A000578)
             ạ6    Absolute Difference with 6 (2 for A000290, 3 for A000578)
               *@  [left argument] ** [result of last link (right argument)]

```

Also works with A000290
> 1 votes

# Answer
# PowerShell, 23 bytes

```
+(0xA000012-eq160mb+18)

```

Try it online!

Uses A000012 (the all ones sequence) and A000004 (the all zeros sequence).

Leverages several neat tricks. We use `0x` as the hexadecimal operator onto the sequence which gives us `167772178`. That's compared to see if its `-eq`ual to `160mb+18` using the `mb` operator (`160mb` is `167772160`). That Boolean result is then cast as an int with `+` to output the proper `1` or `0`. Note that *any* sequence in the code other than A000012 will result in `0` being output.
> 1 votes

# Answer
# Gaia, 9 bytes

```
A000012₉/

```

Works with A000012 and A000004.

Try A000012!

Try A000004!

### Explanation

```
A          Undefined (ignored)
 000012    Push 12
       ₉   Push 9
        /  Integer division, results in 1

```

```
A          Undefined (ignored)
 000004    Push 4
       ₉   Push 9
        /  Integer division, results in 0

```
> 0 votes

# Answer
# PowerShell, 12 bytes

```
'A000012'[5]

```

Try it online!

Works for A000012 (the all ones sequence) and A000004 (the all zeros sequence).

Port of ppperry's Python answer.
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
A000004¨θ

```

Try it online!

Works for A000004 and A000012.
> 0 votes

# Answer
# Jelly, 10 bytes

```
6ị“A000004

```

Try it online!

Works for A000004 and A000012.
> 0 votes

# Answer
# Actually, 10 bytes

```
A000004X.⌂

```

Try it online!

Works for A000004 and A000012.
> 0 votes

# Answer
# Pyth, 11 bytes

```
@"A000004"5

```

Try it here.

Supports A000004 and A000012.
> 0 votes

# Answer
# Husk, 16 bytes

Both solutions are `1`-indexed.

This works for A000351 (powers of 5):

```
!¡*i!6"A000351"1

```

Try it online!

And this one for A000007 (powers of 0):

```
!¡*i!6"A000007"1

```

Try it online!

### Explanation

It makes use that the names A000351, A000007 contain the right digit D at the position 6, such that the sequence is `D^0,D^1,D^2,...`:

```
                  -- implicit input N
   i!6"AxxxxDx"   -- get the right digit D and convert to number,
 ¡*            1  -- iterate (D*) infinitely beginning with 1,
!                 -- extract the value at Nth position

```
> 0 votes

# Answer
# Husk, 20 bytes

This one returns a bit more interesting sequences, again solutions are `1`-indexed.

This works for A000040 (the prime numbers):

```
!!i→"A000040"e:0İfİp

```

Try it online!

And this one for A000045 (the Fibonacci numbers):

```
!!i→"A000045"e:0İfİp

```

Try it online!

### Explanation

This makes use of the fact that the last digit of the sequence names have a different parity:

```
                      -- implicit input N
             e        -- construct a list with:
              :0İf    --   list of Fibonacci numbers (prepend 0)
                  İp  --   list of the prime numbers
  i→"Axxxxx?"         -- get the last character and convert to number,
 !                    -- use it as modular index (0 -> primes, 5 -> Fibonacci)
!                     -- get the value at the Nth index

```
> 0 votes

# Answer
# AHK, 40 bytes

```
a:=SubStr("A000004",6)//9
Loop
Send %a%,

```

Output: `0,0,0,0,0,0,0,0,0,0,0,0,...`

```
a:=SubStr("A000012",6)//9
Loop
Send %a%,

```

Output: `1,1,1,1,1,1,1,1,1,1,1,1,...`

This might not be the shortest code but I bet it's the shortest sequence pair we can find. A000004 is the zero sequence and A000012 is the ones sequence. Simply floor divide the numbers by 9 and output the result forever.
> 0 votes

# Answer
# QBIC, 28 bytes

```
p=!_s@A000035`,-1|!?:%2+5-p

```

This switches between the sequences A000034 (1, 2, 1, 2, 1 ...) and A000035 (0, 1, 0, 1, 0, 1 ...)

## Explanation

```
p=                  Set p to
  !            !    A numeric representation of
   _s         |     a substring of
     @A000035`      our sequence code (either A0035 or A0034)
     ,-1            taking just one character from the right.
?:%2                PRINT <n> MOD 2 (gives us a either 0 or 1)
    +5-p            Plus 1 for seq A24 (5-4), or plus 0 for A35

```
> 0 votes

# Answer
# MATL, 14 bytes

A000027 The positive integers

```
A000027 3\Gw-&

```

Try it online!

A001477 The nonnegative integers

```
A001477 3\Gw-&

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence
---


title: The Counting Gate Keeper

text:
# Question
Title: The Counting Gate Keeper
> Related as it requires you to measure the time between the first and last input. But here you're required to count how many inputs in a period of time.

I was assigned a task to stand by a gate and count how many students enter it. The problem is that my memory is not as good as it was when I first started this job. I need some kind of program to help me count how many students enter the gate until my shift is over.

# Task

Given an integer `t` that represents the number of seconds until my shift is over. Tell me how many times I pressed the button during that time.

# Rules

* The button press can be any convenient user input, such as pressing the Return key;
* You can assume that `t` will allways be in range `[1; 60]`;
* You can assume that the number of students will be less than 231;
* When the time is up, you must output within 1 second;
* Your program does not need to end, as long as the only output to stdout is at the end of the shift;
* If your input method (such as Enter-key) repeats if held, you can choose to count it just once, or several times. Either way, you must still be able to handle separate inputs.

# Answer
# TI-Basic, 22 bytes

Fairly simple. Sets a time `Ans` seconds in the future which we call `T` which is when the loop stops. While the loop is going, we check for if a key is pressed. It's been a while since I had the fgitw :)

```
startTmr+Ans->T
0
While T≠startTmr
Ans+not(not(getKey
End

```
> 6 votes

# Answer
# Ruby, ~~38~~ 42 bytes

Uses the global variable `$.`, which counts how many times the standard input function `gets` has successfully been completed. As such, it will only give accurate results the first time it is called per program run.

Input via command-line argument, such as `ruby gatekeeper.rb 40`

```
Thread.new{loop{gets}}
sleep eval$*[0]
p$.

```
> 3 votes

# Answer
# AHK, 110 bytes

```
1*=-1000
c=0
Loop,255
Hotkey,% Format("vk{:x}",A_Index),s,On
SetTimer,q,%1%
Return
s:
c++
Return
q:
MsgBox,%c%

```

This is not as short as other submissions, but it distinguishes itself by allowing you to use practically ***any key*** as a counter. This includes mouse clicks and control keys like `Ctrl`, `Shift`, etc. *unless* you use special keys that can never be blocked such `Ctrl`+`Alt`+`Del` on Windows.

Two important notes:

* The key presses and mouse clicks are blocked from other software
* The program does not terminate

If you actually run this program, it will count for `1` seconds (where the variable `1` is the first passed parameter), all the while counting how many key presses you made and blocking each one. When that time expires, it pops up a message box with the total. However, seeing as how all keyboard and mouse inputs are still blocked, it's rather difficult to dismiss that message. That sounds like a job for the next gatekeeper.
> 3 votes

# Answer
## C++ 11, MSVC, ~~255~~ ~~254~~ ~~246~~ 244 bytes, MSVC without `/Za` flag : ~~204~~ 202 bytes

-1 byte thanks to Zacharý
-8 bytes thanks to Tas
-42 bytes for the second version thanks to Tas

Can be compiled with `/Za` flag ( disabled extensions ) :

```
#include<thread>
#include<conio.h>
#define S(t)std::this_thread::sleep_for(std::chrono::milliseconds(t))
int r=1;void k(int*a){while(r){if(_kbhit()&&_getch())++*a;S(1);}}int c(int n){int a=0;std::thread t(k,&a);S(n*1000);r=0;t.join();return a;}

```

Can't be compiled with `/Za` flag ( require enabled extensions ). For more details, see this answer

```
#include<thread>
#include<conio.h>
#include<Windows.h>
int r=1;void k(int*a){while(r){if(_kbhit()&&_getch())++*a;Sleep(1);}}int c(int n){int a=0;std::thread t(k,&a);Sleep(n*1000);r=0;t.join();return a;}

```

Ungolfed and explanations :

```
#include<thread> // For the thread standard library
// Console IO, C header used mostly by MS-DOS compilers. Not ISO C nor POSIX standard
#include<conio.h> // Used for _getch and _kbhit

//Macro that takes the number of milliseconds to make the current thread go to bed and sleep
#define S(t) std::this_thread::sleep_for(std::chrono::milliseconds(t))

//Global bool that will indicate the input thread if it continues to run or not
bool r=true;

/**
 * @brief: Function that increment a variable every time a key is pressed
 * @param a : a pointer to the memory location where to increment the counter
 * References are unfortunately forbidden
 */
void k(int* a) {
    while(r) {
        if(_kbhit() && _getch())
            ++*a;
        S(1);
    }
}

/** Function to call
 * @brief : Counts the number of time a key is pressed
 * @param : The number of seconds it have to capture the key presses
 * @return : the number of times a key was pressed
 */
int c(int n) {
    int a=0;
    std::thread t(k,&a);
    S(n*1000);
    r=false;
    t.join();
    return a;
}

```

Conio.h Wikipedia page
> 3 votes

# Answer
# JavaScript (ES6), 50 bytes

```
t=>setTimeout("alert(i)",1e3*t,i=0,onclick=_=>i++)

```

## Test Snippet

```
f=
t=>setTimeout("alert(i)",1e3*t,i=0,onclick=_=>i++)

;f(10)
document.write("click to count...")
```

```
*{user-select:none}
```
> 2 votes

# Answer
# Bash \+ coreutils, 39 bytes

This is an ugly way that creates a file `t` in the current directory because I couldn't get process substitution to work.. You count by pressing the return key and it continues counting if it's held down.

Use it like this: `$ f DURATION`

---

```
f(){ timeout -s3 $1 cat>t;cat t|wc -l;}

```

Try it online!
> 2 votes

# Answer
# C#, ~~132~~ 122 bytes

```
namespace System.Threading.Tasks{n=>{int c=0;Task.Run(()=>{for(;;++c)Console.ReadKey();});Thread.Sleep(n*1000);return c;}}

```

*Saved 10 bytes thanks to @DaveParsons.*

Full/Formatted version:

```
namespace System.Threading.Tasks
{
    class P
    {
        static void Main()
        {
            Func<int, int> f = n =>
            {
                int c = 0;

                Task.Run(() =>
                {
                    for (; ; ++c)
                        Console.ReadKey();
                });

                Thread.Sleep(n * 1000);

                return c;
            };

            Console.WriteLine(f(10));

            Console.ReadLine();
        }
    }
}

```
> 2 votes

# Answer
# Python 3, ~~116~~ 110 Bytes

```
import time
def f(t):
 s,l=time.time(),[]
 while True:
  l.append(input())
  if time.time()-s>t:return len(l)

```

This is my first post, so not sure if this follows the format correctly. Thanks for another few bytes Step
> 1 votes

# Answer
# C + gcc + Linux x86\_64, 89 bytes

```
d[999];f(n){for(*d=0,d[1]=n;d[5]=1;*d+=read(0,d+5,4))if(!select(1,d+5,0,0,d+1))return*d;}

```

Pass the number of seconds in as the argument `n`. Press Enter to count a student (and don't press other keys before or during the function). Returns the number of students counted when time is up.

Extremely unportable, and easily the most evil code I've ever written. It makes assumptions about the size and layout of `fd_set` and `struct timeval`, and about the behavior of `select`.

Anyway, `d[0]` is the student counter, `d[1]` through `d[4]` is the `struct timeval`, and `d[5]` through `d[260]` is the `fd_set`. `d[5]` is also the unused scratch space passed to `read`, and then gets immediately reset to `1` for the next `select` call.
> 1 votes

# Answer
# GameMaker Language, ~~49~~ 45 bytes

Make sure you have default that uninitialized variables are treated as 0. Also, default fps is 30. We're looking for any key to be pressed and this does repeat if held down.

In step:

```
while s<argument0*30{a+=keyboard_check(1)++s}

```

Alternatively,

```
while(get_timer()<argument0*1000000)a+=keyboard_check(1)

```
> 0 votes

# Answer
# JavaScript (Node.js), ~~112~~ 111 bytes

```
t=>require('readline').createInterface(process.stdin).on('line',_=>k++,k=0,setTimeout(_=>console.log(k),t*1e3))

```

I don't think it can be golfed more because Node.js function names are pretty verbose.
> 0 votes

# Answer
# Python 3, 88 bytes

Takes Enter as input and doesn't terminate.

```
from threading import*
l=[0]
Timer(int(input()),print,l).start()
while 1:input();l[0]+=1

```
> 0 votes

---
Tags: code-golf, date
---


# Question
Title: Ordered list of binary sequences of multiple dimensions
Given a positive integer `n`, output the `2^n` binary sequences of length `n` sorted in the following precise ordering.

Test cases:

0:

```
0 or 1 (defining this is a matter of debate)

```

1:

```
0
1

```

2:

```
00
01
10
11

```

3:

```
000
001
010
100
011
101
110
111

```

4:

```
0000
0001
0010
0100
1000
0011
0101
1001
0110
1010
1100
0111
1011
1101
1110
1111

```

etc.

Additionally, the pattern of combinatorics is related to Pascal's Triangle.

0:

```
1 (this is given regardless of the definition given to 2^0)

```

1:

```
1
1

```

2:

```
1
2
1

```

3:

```
1
3
3
1

```

4:

```
1
4
6
4
1

```

etc.

# Answer
> 3 votes
## Haskell, 78 bytes

```
import Data.List
f n=sortOn(\x->sum x:reverse(map(1-)x))$mapM id$[0,1]<$[1..n]

```

Usage example: `f 2` -\> `[[0,0],[0,1],[1,0],[1,1]]`.

How it works:

```
         [0,1]<$[1..n]  -- make n copies of the list [0,1]
     mapM id            -- make all lists where the ith element is from the ith list.
                        -- that gives us all binary sequences
sortOn                  -- sort this list of list
    sum x               -- first by number of ones
      reverse(map(1-)x) -- then by the reversed list with bits flipped

```

# Answer
> 2 votes
## Python 2, 146 bytes

```
from itertools import*
lambda i:sum([sorted({''.join(b)for b in permutations((i-n)*"0"+"1"*n)},key=lambda x:x[::-1])[::-1]for n in range(i+1)],[])

```

I'm still working on this, though any suggestions would be greatly appreciated!

Ungolfed

```
i=input()
import itertools
p=[]
for n in range(i+1):
    x=(i-n)*"0"+"1"*n
    t=[]
    for b in itertools.permutations(x):t+=[''.join(b)] if ''.join(b) not in t else []
    p.append(sorted(t, key=lambda x:x[::-1])[::-1])

p=sum(p,[])
print
for line in p:print line

```

# Answer
> 1 votes
# Python 2, ~~122~~ ~~120~~ ~~102~~ 98 bytes

*18 bytes saved thanks to Flp.Tkc*

*4 bytes saved thanks to xnor*

```
lambda x:sorted([bin(i)[2:].zfill(x)for i in range(2**x)],key=lambda x:(sorted(x),int(x[::-1],2)))

```

## Explanation

This makes all the binary strings of length x with:

```
[bin(i)[2:].xfill(x)for i in range(2**x)]

```

I then sort them according to:

```
lambda x:(sorted(x),int(x[::-1],2))

```

`sorted(x)` prioritizes the number of `1`s while `int(x[::-1],2)` prioritizes the second condition

Lastly these are joined with newlines and printed.

# Answer
> 1 votes
## Perl, 63 bytes

*-4 thanks to @Ton Hospel.*
*-2 thanks to @Gabriel Benamy.*

```
say~~reverse for sort{$b=~y/0//-$a=~y/0//||$b-$a}glob"{1,0}"x<>

```

Run with `-E` (which enable the feature `say`) :

```
perl -E 'say~~reverse for sort{$b=~y/0//-$a=~y/0//||$b-$a}glob"{1,0}"x<>' <<< 5

```

---

**Short explanations**:  * `"{1,0}"x$_` creates a string composed of `$_` times`{1,0}` (`$_` is the input). For instance with `3` : `{1,1}{1,0}{1,0}`.
* Then `glob` does some magic and generates all combinations of one element from each group of braces (that is, all the combinations we want to print).
* And then the sort : `$b=~y/1//c-$a=~y/1//c` compares the number of `1` in each string, and if they have the same number, `$b-$a` will sort according to the second rule.

# Answer
> 0 votes
# Perl, ~~116~~ ~~106~~ ~~105~~ 102 bytes

```
sub e{sprintf"%0$%b",@_}sub f{$_=e@_;/0*$/;$%*y/1//-$-[0]}map{say e$_}sort{f($a)<=>f$b}0..2**($%=<>)-1

```

Readable:

```
sub e{
    sprintf"%0$%b",@_
}
sub f{
    $_=e@_;/0*$/;$%*y/1//-$-[0]
}
map{
    say e$_
} sort {
    f($a)<=>f$b
} 0..2**($%=<>)-1

```

The subroutine `e` converts its argument into a binary value, padded with zeros, to be the input length (e.g. input of 5 pads with zeros until it's 5 characters long). The subroutine `f` takes such a binary value, and gives it sorting weight according to how it should be processed.

The range 0 .. \[input\]2-1 is then put through a stable sort, ordering by the weight (here, "stable" means that when two values have the same weight, they are returned in the same order they appear in the input), and then they are fed back to the subroutine `e` and output.

Some of you may have seen my original post, but I entirely misread the problem yesterday and deleted it immediately after I realized it.

# Answer
> 0 votes
## Racket 109 bytes

```
(let loop((s ""))(if(= n(string-length s))(displayln s)(for((i '("0" "1")))(loop(string-append s i)))))

```

Ungolfed:

```
(define (f n)
  (let loop ((s ""))
    (if (= n (string-length s))
        (displayln s)
        (for ((i '("0" "1")))
          (loop (string-append s i))))))

```

Testing:

```
(f 2)
(println "-------------")
(f 3)
(println "-------------")
(f 4)

```

Output:

```
00
01
10
11
"-------------"
000
001
010
011
100
101
110
111
"-------------"
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

```

# Answer
> 0 votes
# Ruby 2.x, 129 bytes

```
f=->(n){z='0';p=n.bit_length;(0..n).map{|i|sprintf("%0#{p}d",i.to_s(2))}.sort{|a,b|a=a.delete(z).size-(b=b.delete(z).size)||b-a}}

```

# Answer
> 0 votes
# PHP, 49 bytes

```
while($i<1<<$n=$argv[1])printf("%0${n}b\n",$i++);

```

Run with `-r`.

# Answer
> 0 votes
## MATLAB, 68 bytes

```
d=@(n)dec2bin(sortrows([sum(dec2bin(0:2^n-1)');0:2^n-1]')*~eye(2,1))

```

# Answer
> 0 votes
# Bash, 65 bytes

**Golfed**

```
seq -f "obase=2;%g+2^$1-1" $[2**$1]|bc|cut -c2-|tr 0 ~|sort|tr ~ 0

```

**Test**

```
>./binseq 4

0000
0001
0010
0100
1000
0011
0101
0110
1001
1010
1100
0111
1011
1101
1110
1111

```

# Answer
> 0 votes
# Jelly, 14 bytes

```
2Ḷṗ⁸TṪ$N$ÞSÞYȯ

```

Try it online!

Surprised this hadn't been posted yet.

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