title: Play "Taps"

text:
# Question
Title: Play "Taps"
Today, November 11, 2015, is Veterans Day in the United States. "Taps" is the bugle call played at U.S. military funerals:

("Taps" on SoundCloud from vtmiller)

It is a simple melody, only twenty-four notes long and using only four different notes. Here is the sheet music:

(source)

# Challenge

Write a program or function that plays "Taps" or outputs an audio file of "Taps" in any common audio file format (e.g. MP3, WAV, MIDI). It may be played in any key, using any type of instrument or beep noise available to your language. For example, it might sound like a piano instead of a bugle. (Though still only one instrument type should be used.)

All twenty-four notes must be played with accurate pitch, duration, and spacing. Someone who is familiar with "Taps" should be able to run your code and easily recognize the song being played.

The duration of the melody (from the start of the first note to the end of the last note) must be between 30 and 70 seconds. You may optionally have up to 5 seconds of silence padding the start and/or end of your sound file, so an 80 second file is the longest allowed.

You may not, of course, simply download the song online somewhere or extract it from an audio library that happens to have it as as sample. You may, however, use audio libraries that can play/compose individual notes and create audio files.

# Scoring

This is , so the shortest answer in bytes wins. However, for this particular challenge I encourage you to not focus on your byte count, especially at the expense of sound quality. Golf your submissions but allow yourself to be creative with your instrument choice or sound output methodology. This challenge is meant to be about honoring veterans, not about screeching out a barely recognizable version of "Taps".

Note that you can embed SoundCloud audio files directly into posts by just pasting the link on an empty line. If you have a SoundCloud account this would be a great way to share your output.

# Answer
> 4 votes
# qb64, ~~100~~ 84 bytes

Updated version of old Qbasic, downloadable at http://www.qb64.net/

Count excludes the spaces, which are not required and only there to split the data into three-note phrases for clarity.

```
PLAY"T99L4C.L8CL1F. L4C.L8FL1A. L4CFL2A L4CFL2A L4CFL1A. L4F.L8AL1>C< L2AFL1C. L4C.L8CL1F."

```

**Commands in the play string**

```
T99     set tempo to 99 quarter notes per minute (default is 120, only just too short)
CDEFGAB play notes in the current octave
><      up or down one octave
Lx      following notes are of note of 1/x duration
.       extend previous note duration by 50%

```

**Golfing history:**

First post: 4/4 time to 4/2 time, which means I have some whole notes, but no sixteenth notes.

Edit 1: Key changed from C (range G-G) to F (range C-C). Now I only have to perform an octave change once, for the high C, which only occurs once, rather than all the low G's as before.

Having got rid of all those octave changes, I don't think there's any more to golf. There are total of 20 `L`'s but there is no obvious way to avoid them.

The last phrase (11 characters) is the same as the first, but there is no way to insert it twice in under 11 characters. The repeated data would be only 9 characters if the initial `L4` were eliminated (It appears unnecessary as the default note length seems to be quarter note, but it's not documented so I left it in.)

# Answer
> 9 votes
# JavaScript, ~~203~~ ~~198~~ ~~196~~ 195 bytes

```
with(new AudioContext)for(t=i=0;n="301093301396202346202346202396331699464390301093"[i++];)with(createOscillator())i%2?l=n/2:(frequency.value=392+n*44,connect(destination),start(t+.1),stop(t+=l))

```

5 bytes saved thanks to Dendrobium and 1 thanks to @PatrickRoberts.

## Explanation

```
with(new AudioContext)        // use HTML5 audio
  for(                        // iterate through the note pitches and lengths
    t=i=0;                    // t = current time to place the note
    n=                        // n = note pitch (or temporarily length)

    // This string contains the values of each note alternating between length and pitch
    //     (l1, p1, l2, p2, etc...)
    // Length value is in 16th notes (1 = 1/16th note, 2 = 1/8th, etc...)
    //     The longer notes are limited to 9 but I think it still sounds OK
    // Pitch value 0 = G4, 3 = C5, 6 = E5, 9 = G5 (multiples of 3 saves 1 byte)
    "301093301396202346202346202396331699464390301093"

  [i++];)
    with(createOscillator())  // create the note oscillator
      i%2?                    // alternate between length and pitch characters
        l=n/2                 // l = length (stored for use in the next iteration)
                              // dividing it by 2 sets the speed to 60 beats per minute
                              //     and casts it to a number
      :(
        frequency.value=392   // base note = G5 (392hz)
          +n*44,              // there is (conveniently) roughly 132hz between each note
        connect(destination), // send the note's sound through the speakers
        start(t               // schedule the note to sound
          +.1),               // short delay to distinguish two notes of the same pitch
        stop(t+=l)            // schedule the end of the note and increment the time
      )
```

Test it here in the browser! Works on any browser that supports the HTML5 Web Audio API.

# Answer
> 8 votes
# Mathematica, ~~361~~ ~~287~~ 285 bytes

I went for accuracy here. Output is exactly as described in the score, played with the trumpet. You can find the file here.

```
"G"
e="E5";c="C5";EmitSound@Sound[SoundNote[#,5/#2,"Trumpet",SoundVolume->#3/17]&@@@{%,8,17,%,24,20,c,2,23,%,8,26,c,24,29,e,2,32,%,12,35,c,12,38,e,6,41,%,12,44,c,12,47,e,6,50,%,12,53,c,12,56,e,2,59,c,8,62,e,24,65,"G5",3,68,e,6,170/3,c,6,136/3,%,2,34,%,8,34,%,24,34,c,2,34}~Partition~3]

```

Thanks to @MartinBüttner for golfing suggestions.

# Answer
> 5 votes
# Sonic Pi, 899 bytes

The timing is a little off, but I think it's ok.

Lightly golfed:

```
use_synth:blade
use_synth_defaults sustain:0.70,release:0.0
play:G4,release:0.05
wait 0.75
play:G4,sustain:0.25
wait 0.25
hold=rrand_i(3,4)
play:C5,sustain:hold,release:0.5
wait hold+0.5
play:G4,release:0.05
wait 0.75
play:C5,sustain:0.25
sleep 0.25
hold=rrand_i(3,4)
play:E5,sustain:hold,release:1.25
sleep hold+1.25
play:G4
sleep 0.70
play:C5
sleep 0.70
2.times do
  play:E5,sustain:1,release:0.25
  sleep 1.25
  play:G4
  sleep 0.7
  play:C5
  sleep 0.7
end
hold=rrand_i(3,5)
play:E5,sustain:hold,release:0.75
sleep hold+1
play:C5,release:0.05
sleep 0.75
play:E5,sustain:0.25
sleep 0.25
play:G5,sustain:2.45,release:0.05
sleep 2.5
play:E5,sustain:1,release:0.25
sleep 1.25
play:C5,sustain:1,release:0.25
sleep 1.25
hold=rrand_i(3,5)
play:G4,sustain:hold,release:0.5
sleep hold+0.5
play:G4,release:0.05
sleep 0.75
play:G4,sustain:0.25
sleep 0.25
hold=rrand_i(3,5)
play:C5,sustain:hold,release:1.5

```

# Answer
> 4 votes
**MATLAB, 338 327 262 258 230 bytes**

```
o=@(L,f)sin(pi*.11*2^(f/12))*(1:600*L))
sound([o(3,-1) o(1,-1) o(12,2) o(3,-1) o(1,2) o(12,4) o(2,-1) o(2,2) o(4,4) o(2,-1) o(2,2) o(4,4) o(2,-1) o(2,2) o(12,4) o(3,2) o(1,4) o(8,6) o(4,4) o(4,2) o(12,-1) o(3,-1) o(1,-1) o(12,4)])

```

# Answer
> 2 votes
# Ruby + beep, 178 bytes

```
f=[260,346,416,499]
n=[12,*1..4]
l=(a="001012012012012123210001310310224224220318440310".chars.map(&:to_i))[24..-1]
`beep#{24.times.map{|i|" -f#{f[a[i]]} -l#{n[l[i]]}00"}*" -n"}`

```

Took me awhile to make this, I think I missed the boat, but whatever.

`f` holds the four frequencies used. `n` holds the five note lengths used, in multiples of 16th notes.

`a="00101...` holds all the note pitchs followed by all the note lengths, as indexes into the respective arrays. `l` is then set to the 24th indice and onward of `a`. Then a beep command is constructed by iterating through all of the above, and executed

# Answer
> 2 votes
# SmileBASIC, 73 bytes

```
BGMPLAY"@56T50L2.G8.G16B+G8.<C16E>[G8<C8E4>]2G8<C8EC8.E16G2E4C4>GG8.G16B+

```

All the notes and timings are correct. I used a trumpet because it's the closest thing in MIDI

```
<audio autoplay controls src="//12me21.github.io/resources/taps.mp3"></audio>
```

# Answer
> 1 votes
# Powershell, ~~183~~ ~~175~~ 159 bytes

Nostalgia trip, who doesn't like beeps?!

```
foreach($i in 0..23){[console]::beep((196,262,330,392)[(001012012012012123210001-split'')[$i]],(3,1,12,3,1,12,2,2,4,2,2,4,2,2,12,3,1,8,4,4,12,3,1,12)[$i]*400)}

```

Explanation (sortof)

```
foreach($i in 0..23) { # foreach loop which ranges from 0 to 23
    [console]::beep( # [console]::beep(Pitch, Duration)
        (196,262,330,392) # the notes in Hertz
            [ # select which note to use
                (001012012012012123210001-split'') # -split '' creates an array of [0,0,1,0,1 ...], spaces can be omitted
                [$i] # select the n-th element
            ],
        (3,1,12,3,1,12,2,2,4,2,2,4,2,2,12,3,1,8,4,4,12,3,1,12) # array of durations
        [$i]*400 # duration in milliseconds * 400
    )
}

```

This will play in about 45 seconds.

This is my first time using Windows' Powershell, any tips on golfing this are welome.

# Old versions

## ~~175~~

```
foreach($i in(0..23)){[console]::beep((196,262,330,392)[(0,0,1,0,1,2,0,1,2,0,1,2,0,1,2,1,2,3,2,1,0,0,0,1)[$i]],(3,1,12,3,1,12,2,2,4,2,2,4,2,2,12,3,1,8,4,4,12,3,1,12)[$i]*400)}

```

## ~~183~~

```
$d=3,1,12,3,1,12,2,2,4,2,2,4,2,2,12,3,1,8,4,4,12,3,1,12;$n=0,0,1,0,1,2,0,1,2,0,1,2,0,1,2,1,2,3,2,1,0,0,0,1;foreach($i in(0..23)){[console]::beep((196,262,330,392)[$n[$i]],$d[$i]*400)}

```

# Answer
> 1 votes
# BBC Basic, 111

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

Score excludes whitespace and newlines, which are non-essential and added for readability

```
FORk=1TO24
  x=ASC(MID$("')F'Lb(Ke(Ke(KbJhxeI#')F",k))
  SOUND1,-9,x DIV7*4+60,INT(12/1.4^(x MOD7))*5
  SOUND1,0,1,1
NEXT

```

Fairly standard compression, 1 ASCII character per note. Parameters of `SOUND` are as follows:

```
Channel (always 1 for the purposes of this challenge)
Amplitude (negative for on, 0 for off, positive is an envelope index)
Pitch (in increments of 1/4 semitone, with middle C at 100)
Duration (20ths of a second)

```

The range of the song is 13 notes, even though only 4 are used. To get this range into the 95-number range of printable ASCII, I had to squeeze the duration into an integer range of 7 and take it modulo 7. The following durations (in sixteenths) are used (with the exception of 6 which is never used): 1,2,3,4,6,8,12. To produce these numbers, I hit upon the idea of dividing 12 by a power of `sqrt(2)` (approximated by 1.4) and truncating.

The `SOUND1,0,1,1` is an annoyance, costing 12 bytes. It's necessary to provide a pause between notes of identical pitch.

# Answer
> 0 votes
# C - (Raw: 318 | WAV: 437)

8-bit (unsigned) mono PCM at 44800 Hz, 33.60 seconds.

The mezzo forte, fortissimo and forte dynamics are somewhat artistically implemented. The fermatas could be better.

Code relies on `unsigned long long` being 8 octets and system little endian.

```
#include<stdio.h>
#include<math.h>
#ifdef RAW
main(){unsigned long long D[]={0x422422c13c13,0xc13c44813c22},X[]={27863,37193,46860,55727},O=0x406e64924910,i=0,j;float Z,A,U=40,P;for(;i<24;D[i++/12]>>=4){Z=X[O&3]/1e6;P=0;O>>=2;A=i>18?--U:i<14?U+i/2:U+30;for(j=(D[i/12]&15)*13440;j;A-=--j<7e3&&A>0?.01:0)putchar(A*sin(P+=Z)+128);}}
#else
main(){unsigned long long D[]={0x422422c13c13,0xc13c44813c22},X[]={27863,37193,46860,55727},O=0x406e64924910,i=0,j;float Z,A,U=40,P;int W[]={0x46464952,1570852,0x45564157,544501094,16,65537,44800,44800,524289,0x61746164,1505280};fwrite(W,4,11,stdout);for(;i<24;D[i++/12]>>=4){Z=X[O&3]/1e6;P=0;O>>=2;A=i>18?--U:i<14?U+i/2:U+30;for(j=(D[i/12]&15)*13440;j;A-=--j<7e3&&A>0?.01:0)putchar(A*sin(P+=Z)+128);}}
#endif

```

Compile and run with something like:

```
gcc -std=c99 -o taps taps.c -lm
./taps > taps.wav
play taps.wav

```

Add  `-DRAW` to compile-line for raw variant.

Raw output can be played with e.g. SoX `play` as:

```
play -c 1 -b 8 -r 44800 -t u8 <file>
       |    |       |       |
       |    |       |       +--- Unsigned 8-bit
       |    |       +----------- Sample rate
       |    +------------------- 8 Bits
       +------------------------ 1 Channel

```

---
Tags: code-golf, kolmogorov-complexity, music, audio
---


title: Arbitrary PEMDAS

text:
# Question
Title: Arbitrary PEMDAS
Scrolling through social media, one might encounter something like this:

We can see that, following PEMDAS order of operations, the answer is clearly 1*1* 9.

For the sake of this challenge, PEMDAS means that multiplication will occur before division, so `a/b*c = a/(b*c)`, not `(a/b)*c`. The same goes for addition and subtraction. For example, using PEMDAS, `1-2+3 = -4`, but using PEMDSA, `1-2+3 = 2`.

However, the answer quickly changes if we use some other order of operations, say PAMDES: now the answer is 1*2*.

### The challenge

Given an expression and an order of operations, output the value it equals.

### Input

The input will contain two parts: the expression and the order of operations.

The expression will contain only `[0-9] ( ) ^ * / + -`. This means that it will contain only integers; however, you may not use integer division, so `4/3=1.33` (round to *at least* two decimal places), not `1`.

The order of operations may be taken in any reasonable format. For example, you may take a string array of operations (ex. `["()", "^", ... ]`), or something like `PEMDAS`. Parenthesis will always have the highest priority, and will therefore always come first in the input.

### Output

The inputted expression evaluated and rounded to at least two decimal places.

### This is , so shortest code in bytes wins!

### Test cases

```
PEMDAS 4*3-2+1             =  9
PDEMAS 2*4^3+2             =  130
PMDASE 17^2-1*2            =  1
PSEMAD 32*14/15-12+5^3+1/2 =  1.736
PEMDAS 6/2*(1+2)            =  1
PEDMAS 6/2*(1+2)            =  9
PDMSEA 2*(1*13+4)^3        =  39304

```

1. No joke: many thought the answer was 1.

2. Here we are using the "for the sake of this challenge" PEMDAS rules.

# Answer
# Maxima, ~~61~~ 67 bytes

```
f(O,E):=(for i:1 thru 5 do infix(O[7-i],i*20,i*20),eval_string(E));

```

A function that takes operators as a list of strings and the expression and returns the result.

Try it online!

Example:

```
f(["()","^","*","/","+","-"],"4*3-2+1");

```

result: `9`
> 1 votes

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


title: I HATE spaces in file names

text:
# Question
Title: I HATE spaces in file names
It is simple. I cannot stand when people use spaces when naming files. It sometimes wrecks console commands and makes the output of ls ugly.

The challenge is to write a program (only ascii characters) which

1. renames all files (including directories) in the current directory to versions with spaces removed or replaced by '\_'
2. on collision, you need to append a unique identifier (up to you)
3. descends recursively into all subdirectories

You can assume UNIX-style path names. Who would need this program on a Windows machine anyways?

This is code golf, the shortest program wins (#ascii characters). Since I hate spaces so much, each space has to be counted twice.

Please provide your language, score, program and a short description of how to run it.

The program must compile and execute with reasonable effort on my linux machine.

EDIT: As Etan requested a file structure for testing, here is the script I currently use to create a suitable file tree:

```
#!/bin/bash
rm -r TestDir

touchfiles()
{
    touch my_file
    touch my__file
    touch "my file"
    touch "my  file"
    touch " my_file  "
}

mkdir TestDir
cd TestDir

touchfiles

for dir in "Test Sub" Test_Sub "Te stSub" Te_stSub
do
    mkdir "$dir"
    cd "$dir"
    touchfiles
    cd ..
done

```

# Answer
## Zsh + GNU coreutils — 48 bytes (1 space)

```
for x   (**/*(Dod))mv   -T  --b=t   $x  $x:h/${${x:t}// }

```

It's weird that you hate (ASCII) spaces but are fine with tabs and newlines, but I guess it takes all kinds.

zmv solves a lot of file renaming problems concisely (and only slightly obscurely). However, it insists on the targets being unique; while you can easily add unique suffixes, adding a suffix only if it would be needed pretty much requires re-doing all the work. So instead I loop manually and rely on GNU mv to append a unique identifier in case of collision (`--backup` option, plus `--no-target-directory` in case a target is an existing directory, as otherwise `mv` would move the source inside that directory).

`(od)` is a glob qualifier to sort the output with directories appearing after their content (like find's `-depth`). `D` includes dot files in the glob. `:h` and `:t` are history modifiers similar to `dirname` and `basename`.

`mv` complains that it's called to rename files to themselves, because the glob includes file names without spaces. C'est la vie.

Ungolfed version:

```
for x in **/*\ *(Dod); do
  mv --no-target-directory --backup=numbered $x ${x:h}/${${x:t}// /}
done

```
> 10 votes

# Answer
## Bash 116 bytes, 16 spaces

```
find . -depth -exec bash -c 'B=${0##*/}
M="${0%/*}/${B// /_}"
while [ -e "$M" ]
do M=$M.
done
mv "$0" "$M"' {} \;

```

I didn't suppress errors to gain a couple more bytes. This will not have any collisions.

If non-posix GNU `find` can be expected, this can be shortened further:

## Bash 110 bytes, 15 spaces

```
find -d -exec bash -c 'B=${0##*/}
M="${0%/*}/${B// /_}"
while [ -e "$M" ]
do M=$M.
done
mv "$0" "$M"' {} \;

```

Removing spaces instead of replacing them uses two less bytes:

## Bash 108 bytes, 15 spaces

```
find -d -exec bash -c 'B=${0##*/}
M="${0%/*}/${B// }"
while [ -e "$M" ]
do M=$M.
done
mv "$0" "$M"' {} \;

```

Note: if tabs can be used instead of spaces, only 1 space is needed (the one in the match rule for substitution at line 2).

Thanks to Dennis for finding bug on double quote (and providing solution)
> 13 votes

# Answer
# Python 180 bytes

```
from    os  import*
t,c,h='.',chdir,path
def g(p):
    c(p)
    for x   in  listdir(t):
        if h.isdir(x):g(x)
        n=x.replace(' ','')
        while h.exists(n):n+=t
        if' 'in x:rename(x,n)
    c(t*2)
g(t)

```

only 2 spaces if you use tab for indentation :-)
> 10 votes

# Answer
If the order of collided file suffixes does not need to give precedent to the pre-existing file then the following works for me:

## bash/find/mv 84 bytes, 16 spaces

```
find -depth -execdir bash -c '[ "${0//[^ ]}" ] && mv -{T,--b=t} "$0" "${0// }"' {} \;

```

## bash/find/mv 82 bytes, 14 spaces

```
find -depth -execdir bash -c '[ "${0//[^ ]}" ]&&mv -{T,-b=t} "$0" "${0// }"' {} \;

```

Cuddled `&&` to save two space bytes.

## bash/find/mv 60 bytes, 11 spaces

```
find -d -execdir bash -c 'mv -{T,-b=t} "$0" "${0// }"' {} \;

```

Drops error protection so it gets errors from mv on files which have no spaces to start with.

Edit: Dropped the quotes from `{}` as reminded by Dennis. Also allowed `find` to scream about portability and deprecation in the shortest version where `mv` is already screaming about moving a file on top of itself.

Edit 2: Added `-T` to `mv` command to avoid nesting directories instead of renaming as pointed out by pqnet. Used brace expansion at cost of one character over just using one space.
> 5 votes

# Answer
## NodeJS – 209 bytes, 3 Whitespaces

```
s=require('fs');function a(d){s.readdirSync(d).forEach(function(f){f=d+'/'+f;i=0;r=f;if(/ /.test(f)){r=f.replace(' ','');while(s.existsSync(r))r+=i++;s.renameSync(f,r)}s.statSync(r).isDirectory()&&a(r)})}a('.');

```
> 4 votes

# Answer
## POSIX `sh` \+ GNU `find` \+ GNU `mv` 67 ASCII bytes + one *(literal)* space

```
find    -d  -exec   sh  -cf 'IFS=\ ;IFS=_   set $0;mv   --b=t   "$0"    "$*"'   {}  \;

```

I don't know if it fits, but with this any *sequence* of spaces is elided to a single `_` \- I like it anyway. Actually any *sequence* but leading/trailing spaces that is - those are automatically truncated *(which is also, I think, a beneficial behavior)*. Thanks to Gilles for pointing this out.

This just uses the internal field separator to separate fields.

It's fairly... *chatty*...

...oh man. I knew the tab thing was cheap, but I thought it was at least clever. Now I'm just late to the party...
> 3 votes

# Answer
## Bash + Perl `rename` 64

(`rename` is the Perl script on Debian and derivatives, not the util-linux command.)

```
find . -depth -name "* *" -execdir rename 'y/ /_/' * \;

```
> 2 votes

# Answer
# Bash - 86 bytes

```
find    .   -d|while    IFS=""  read    f;do    t=${f##*/};mv   --b=t   -T  "$f"    "${f%/*}"/${t// /};done

```
> 2 votes

# Answer
# PHP, ~~147~~ 145 bytes, ~~2~~ 1 space~~s~~ -\> 146

```
function    s(){foreach(glob("*")as$n){is_dir($n)&&chdir($n)&s()|chdir("..");if($n<$r=strtr($n," ",_)){while(file_exists($r))$r.=_;rename($n,$r);}}}

```

recursive function. Run with `s(".");`

Loop through `glob` results for given path:

* if directory, recurse
* replace spaces with underscore
* if strings differ
    + while new filename is taken, append underscore
    + rename file/directory
> 2 votes

# Answer
**POSIX(Tested on zsh) + basic Linux commands 151**

```
export IFS='
'
for f in $(ls -R1);do export n=$(echo $f|tr ' ' '_');yes n|mv $f $n || yes n|mv $f `echo $n;echo $f|md5sum`
done

```
> 1 votes

# Answer
## Ruby 194

```
require'find'
require'fileutils'
Find.find(?.).sort{|a,b| b.length<=>a.length}.each {|f|
if f.match(/ /)
o=f.tr(' ',?_)
begin
raise if File.exist? o
FileUtils.mv f,o
rescue
o+=?_
retry
end
end}

```
> 1 votes

# Answer
# Python, 187

165, plus 22 penalty points for the spaces.

```
from os import*
u='_';j=path.join
for t,d,f in walk('.',0):
 for z in f+d:
  n=z.replace(' ',u)
  if n!=z:
   while path.exists(j(t,n)):n+=u
   rename(j(t,z),j(t,n))

```

# 166, using Emanuele's \t trick:

Only a single space in this one!

```
from    os  import*
u='_';j=path.join
for t,d,f   in  walk('.',0):
    for z   in  f+d:
        n=z.replace(' ',u)
        if  n!=z:
            while   path.exists(j(t,n)):n+=u
            rename(j(t,z),j(t,n))

```
> 1 votes

# Answer
# LiveScript - 166

(Replace spaces with tabs.)

```
(a=->(s=require \fs)readdirSync(it)map (f)->f=it+'/'+f;r=f.replace /\s/g,i='';(while f!=r&&s.existsSync r=>r+=i++);s.statSync(f)isDirectory(s.renameSync f,r)&&a r) \.

```

Based on nderscore's optimized version of c.P.u1's answer.
> 1 votes

# Answer
**Bash 4+ 111 bytes**

```
shopt -s dotglob globstar
for f in **
do
n=${f// /}
while [[ $f != $n && -e $n ]]
do n+=1
done
mv "$f" $n
done

```
> 0 votes

# Answer
**Groovy, 139 characters**

```
def c
c={
f->
def g=new File(f.parent,f.name.replaceAll('\\s',''))
f.renameTo(g)
!g.directory ?: g.eachFile(c)
}
new File('.').eachFile(c)

```

according to @edc65 comment

**Groovy, handle collisions, 259 characters**

```
def c
c={
p,l,f->
def g=new File(p,f.name.replaceAll('\\s',''))
f==g?:
(g.exists()?f.renameTo(g.toString()+l.indexOf(f.name)):f.renameTo(g))
!g.directory?:g.eachFile(c.curry(g,g.list().toList()))
}
def r=new File('.')
r.eachFile(c.curry(r,r.list().toList()))

```
> 0 votes

---
Tags: code-golf, file-system
---


title: Play some of Pachelbel's Canon

text:
# Question
Title: Play some of Pachelbel's Canon
Output the following excerpt from Pachelbel's Canon in D as audio:

## Rules

* Any format/encoding may be used, so long as a codec existed prior to the creation of this challenge
* Any instrument (a real instrument, MIDI synthesis, etc.) may be used
* The tempo must be 65 BPM (as notated in the sheet music) - if you cannot get exactly 65 BPM, you may use any tempo within the (inclusive) range 64.75 - 65.25
* The sheet music is in concert pitch
* Equal temperament tuning must be used (specifically 12-ET with A4 = 440 Hz)

For reference, here is a Stack Snippet that will play the excerpt:

```
<audio controls><source src="https://a.clyp.it/h3y3isar.mp3"></audio>
```

# Answer
# Mathematica, ~~212~~ ~~152~~ ~~139~~ 135 bytes

```
{#~(s=##~SoundNote~41&)~1&/@LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu",{14,18,21}~s~16}~Sound~18.5

```

Outputs a `Sound` object that plays Pachelbel's Canon in D when the Play button is pressed. The instrument is MIDI instrument #41 "Violin".

**The Audio**

Click me!

**Explanation**

```
LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu"

```

Find the letter numbers of each character in the string ("a" -\> 1, "b" -\> 2, and so on), wrapped with a `List`. (This string represents Pachelbel's Canon in D)

```
#~(s=##~SoundNote~41&)~1&/@...

```

Set `s` to `SoundNote` function whose instrument is #41. Set the duration to 1 and map that function to each element in the `List` (thus making `SoundNote` primitive objects).

```
{14,18,21}~s~16

```

Make the last triad. (The duration `16` is there to make the last note 16 times longer--a whole note is sixteen times a sixteenth note.)

```
... ~Sound~18.5

```

Make a `Sound` object, `18.5` seconds long (because the tempo is 65 bpm \[5 measures of 4/4 with tempo 65 bpm = approximately 18.5 seconds\]).

**126 byte version, non-competing**

```
Sound[{(s=SoundNote)/@LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu",{14,18,21}~s~16},240/13]

```

Non-competing because the output contains two sixteenth notes instead of an eighth note, and the separation is quite noticeable.
> 8 votes

# Answer
# JavaScript (ES7), ~~249~~ ~~242~~ 241 bytes

```
with(new AudioContext)for(t=i=0;n=parseInt('l43l431db98643o86ogfdbdfdgfdzbdzgigikigfdbzbdv98db9864311480'[i++],36);)with(createOscillator())frequency.value=880*2**(-~-n%20/12),connect(destination),start(t),stop(i>56?t+q*8:t+=n>20?q=6/13:q/2)

```

Thanks to @Neil and @PatrickRoberts for some byte savings!

## Explanation

The notation is packed into the string where each character is a single note as a base-36 digit. The note values are determined by the formula `(19 - pitch) * time + 1` where `pitch` is the number of semitones less than A5 and `time` is `1` for a semiquaver or `20` for a quaver. The `0` at the end stops the `for` loop.

The tempo is ~~65.22bpm~~ *Edit: exactly 65bpm now, for 2 more bytes*.

This explanation/demo uses `Math.pow` instead of `**` for browser compatibility. It also sets the gain of the oscillators to `.3` so that the final chord does not make your ears bleed (default gain is `1`).

```
with(new AudioContext)            // use HTML5 audio
  for(                            // iterate through the note pitches and lengths
    t=i=0;                        // t = current time to place the note
    n=parseInt(                   // n = note pitch/length

      // Packed notation string
      'l43l431db98643o86ogfdbdfdgfdzbdzgigikigfdbzbdv98db9864311480'

    [i++],36);
  )
    with(createOscillator())      // create the note oscillator

      // Set the note frequency (using Math.pow for the demo).
      //frequency.value=880*2**(-~-n%20/12),
      frequency.value=880*Math.pow(2,-~-n%20/12),

      // Send the note's sound through the speakers (for the demo, we'll connect it to
      // a gain node so we can reduce the volume).
      //connect(destination),
      connect((g=createGain(),g.gain.value=.3,g.connect(destination),g)),

      start(t),                     // schedule the note to sound
      stop(                         // schedule the end of the note
        i>56?                       // if we are in the final chord
          t+                        //   do not increment the time
            q*8                     //   hard-code the length to a semibreve
        :t+=n>20?q=6/13:q/2         // else update the length based on the note value
      )
```

You can press the button above to test it in any browser that supports the HTML5 Web Audio API.
> 8 votes

# Answer
# Bubblegum, 203 bytes

```
00000000: e002 2800 c35d 0026 9509 6f34 76f2 ffad  ..(..].&..o4v...
00000010: 4150 0893 a735 bd02 a1eb 1237 18fe 5498  AP...5.....7..T.
00000020: 120a 83e1 6662 8a5e 9709 fe8a 3430 0f48  ....fb.^....40.H
00000030: 5008 54af d19a b44f 2be9 fb3b bf9d 206d  P.T....O+..;.. m
00000040: abbf 12f0 2151 6dae 4712 8c18 4d8e f5cd  ....!Qm.G...M...
00000050: eb85 404c 17cd bd5c 2775 38bd eb50 ab88  ..@L...\'u8..P..
00000060: e015 fb7e 4b1e 5ddb 515b 144c fc5e c1be  ...~K.].Q[.L.^..
00000070: 3d5d 20cd e950 4a1d 256e b56e d364 188b  =] ..PJ.%n.n.d..
00000080: 6fa1 afcc 2100 0235 ada0 2f23 411d 95dd  o...!..5../#A...
00000090: 6665 3b45 041d cbe2 8e3b 2456 fb8d 4e4c  fe;E.....;$V..NL
000000a0: 1a7f b814 a6cf 850e 9b6c 9285 3a6f 1ec3  .........l..:o..
000000b0: 02ed 505c 996b eb4d 209c 2776 a8aa 8380  ..P\.k.M .'v....
000000c0: 42cc b779 218e e75e 8000 00              B..y!..^...

```

Try it online!

This is a hexdump (reverse with `xxd -r`) of the source code. The MIDI file it produces is as follows (also a hexdump):

```
00000000: 4d54 6864 0000 0006 0001 0002 01e0 4d54  MThd..........MT
00000010: 726b 0000 0019 00ff 5902 0200 00ff 5804  rk......Y.....X.
00000020: 0402 1808 00ff 5103 0e15 c500 ff2f 004d  ......Q....../.M
00000030: 5472 6b00 0001 f200 c000 00ff 0405 5069  Trk...........Pi
00000040: 616e 6f00 9051 5f81 5880 5100 1890 4e5f  ano..Q_.X.Q...N_
00000050: 6c80 4e00 0c90 4f5f 6c80 4f00 0c90 515f  l.N...O_l.O...Q_
00000060: 8158 8051 0018 904e 5f6c 804e 000c 904f  .X.Q...N_l.N...O
00000070: 5f6c 804f 000c 9051 5f6c 8051 000c 9045  _l.O...Q_l.Q...E
00000080: 5f6c 8045 000c 9047 5f6c 8047 000c 9049  _l.E...G_l.G...I
00000090: 5f6c 8049 000c 904a 5f6c 804a 000c 904c  _l.I...J_l.J...L
000000a0: 5f6c 804c 000c 904e 5f6c 804e 000c 904f  _l.L...N_l.N...O
000000b0: 5f6c 804f 000c 904e 5f81 5880 4e00 1890  _l.O...N_.X.N...
000000c0: 4a5f 6c80 4a00 0c90 4c5f 6c80 4c00 0c90  J_l.J...L_l.L...
000000d0: 4e5f 8158 804e 0018 9042 5f6c 8042 000c  N_.X.N...B_l.B..
000000e0: 9043 5f6c 8043 000c 9045 5f6c 8045 000c  .C_l.C...E_l.E..
000000f0: 9047 5f6c 8047 000c 9045 5f6c 8045 000c  .G_l.G...E_l.E..
00000100: 9043 5f6c 8043 000c 9045 5f6c 8045 000c  .C_l.C...E_l.E..
00000110: 9042 5f6c 8042 000c 9043 5f6c 8043 000c  .B_l.B...C_l.C..
00000120: 9045 5f6c 8045 000c 9043 5f81 5880 4300  .E_l.E...C_.X.C.
00000130: 1890 475f 6c80 4700 0c90 455f 6c80 4500  ..G_l.G...E_l.E.
00000140: 0c90 435f 8158 8043 0018 9042 5f6c 8042  ..C_.X.C...B_l.B
00000150: 000c 9040 5f6c 8040 000c 9042 5f6c 8042  ...@_l.@...B_l.B
00000160: 000c 9040 5f6c 8040 000c 903e 5f6c 803e  ...@_l.@...>_l.>
00000170: 000c 9040 5f6c 8040 000c 9042 5f6c 8042  ...@_l.@...B_l.B
00000180: 000c 9043 5f6c 8043 000c 9045 5f6c 8045  ...C_l.C...E_l.E
00000190: 000c 9047 5f6c 8047 000c 9043 5f81 5880  ...G_l.G...C_.X.
000001a0: 4300 1890 475f 6c80 4700 0c90 455f 6c80  C...G_l.G...E_l.
000001b0: 4500 0c90 475f 8158 8047 0018 9049 5f6c  E...G_.X.G...I_l
000001c0: 8049 000c 904a 5f6c 804a 000c 9045 5f6c  .I...J_l.J...E_l
000001d0: 8045 000c 9047 5f6c 8047 000c 9049 5f6c  .E...G_l.G...I_l
000001e0: 8049 000c 904a 5f6c 804a 000c 904c 5f6c  .I...J_l.J...L_l
000001f0: 804c 000c 904e 5f6c 804e 000c 904f 5f6c  .L...N_l.N...O_l
00000200: 804f 000c 9051 5f6c 8051 000c 904a 5f00  .O...Q_l.Q...J_.
00000210: 904e 5f00 9051 5f8e 4c80 4a00 0080 4e00  .N_..Q_.L.J...N.
00000220: 0080 5100 8360 ff2f 00                   ..Q..`./.

```
> 6 votes

# Answer
# BBC BASIC, 141 ASCII characters (65.217BPM)

```
*TEMPO1
F.i=2TO71j=i>65SOUND1-j*(479+i/2),-9,ASCM." \\VX\\VX\DHLNRVXVVNRVV>@DHD@D>@D@@HD@@>:>:6:>@DH@@HDHHLNLDHLNRVXNNVV\\",i)*2,23-j*161N.

```

Revised to accomodate limit on tempo. Will update explanation later.

# BBC BASIC, 123 ASCII characters (noncompeting as 60BPM)

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

Plays the song directly when run.

```
F.i=1TO67j=i>64SOUND1-j*(447+i),-9,ASCM."\\VX\\VX\DHLNRVXVVNRVV>@DHD@D>@D@@HD@@>:>:6:>@DH@@HDHHLNLDHLNRVXNV\",i)*2,5-j*75N.

```

**Ungolfed**

```
  FOR i = 1 TO 67
    j = i > 64: REM j=0 for the first four bars composed of 16th notes, j=-1 for the final chord (whole note)
    SOUND 1 - j * (447 + i), -9, ASC(MID$("\\VX\\VX\DHLNRVXVVNRVV>@DHD@D>@D@@HD@@>:>:6:>@DH@@HDHHLNLDHLNRVXNV\", i)) * 2, 5 - j * 75
  NEXT i

```

**Explanation**

`j` is a flag indicating whether we are in the first 4 bars or the final chord. TRUE is `-1` in BBC BASIC.

The `SOUND` statement takes 4 parameters:

CHANNEL: for the first 4 bars this is channel 1. For the 3 notes of the chord in the 5th bar, the channel numbers are 201, 202 and 203 hex (513,514 and 515 decimal.) This means play on channels 1,2 and 3, the initial 2 meaning play simultaneously with 2 notes on other channels (i.e play a 3 note chord).

VOLUME: Given as a negative value because positive values represent other effects (sound envelopes.). Set at -9 (will go up to -15 which is loudest.)

PITCH: For this tune, ranges from D4=108 to A5=184. Each integer step is 1/4 of a semitone. Values are stored as ASCII codes in the range 54 to 92 and doubled to regenerate the correct value. 1/8th notes are stored as duplicate 1/16th notes. The final chord is stored as 3 separate pitches and the note length varied to whole note as below.

DURATION: in 1/20 of a second. Duration of 1/16th note is 5/20 of a second so 60 1/4 notes per minute (there is insufficient resolution to make the tempo more precise.) The whole note is 5-(-75)=80 units (4 seconds) long.
> 6 votes

# Answer
# Befunge, 242 bytes

The tune is written to stdout in the format of a MIDI file. You'll need to redirect that output to a *.mid* file in order to play the excerpt.

```
<v:"MThd"0006000101"MTrk"001+"~e"0*3"UQ"30*5"-\"9
v>9#:-#,_0"QONLJIGEJIGEGCGECB@>@B@BCEGCECBECEGECBNLJNONLJIGEQONQONQ"0\:
_v#:\%+77+1,"@",\,*8*82,+3*4!*-3::\,"@",:,*:*62,1
v>"QNJQNJ"0\:
_v#:\+1,"@",\,-**82/3\*:*62:,+!\**97!-3::\
@>,\"/U"3*,,,

```

Try it online!, although I don't think it's currently possible to save the output in such a way that it'll retain the binary integrity of the data.

**Explanation**

The first line is essential just a hard coded MIDI header, which is output at the start of line two. The rest of line two encodes the sequence of notes as their MIDI values, which are conveniently ASCII. The third line writes out the MIDI commands for playing those notes, with the duration being automatically calculated (every note is a semiquaver unless i%14 == 0). The final chord is handled as a special case on lines four and five (since that requires multiple keys being pressed simultaneously), and the sixth line writes out the final MIDI end of track marker.
> 4 votes

# Answer
# C, ~~248 228 210 198 193~~ 191 bytes

```
#define y(x)cos(.346*t*exp(x/17.))
d=1846,t;main(c){for(;t++<d*80;putchar(c=((t<d*64?y(("TTQRTTQRTHJLMOQRQQMOQQEFHJHFHEFHFFJHFFECECACEFHJFFJHJJLMHJLMOQRT"[t/d]-72)):y(12)+y(9)+y(5))+3)*42));}

```

This produces a sequence of 8 bit unsigned samples intended to be played at 8000 samples per second. If you have an older UNIX/Linux setup, you can redirect the output to `/dev/audio`. On some newer Linux distros, you may have to pipe the output to the ALSA command line player `aplay`
> 3 votes

# Answer
# SmileBASIC, 115 bytes

```
BGMPLAY"@305T65L16[A8F+G]2A{r}F#8>F#GABAGAF#GAG8BAG8F#EF#EDEF#GABG8BAB8<C#D{r}AA1:1[R1]4F#1:2[R1]4D1{r=>AB<C#DEF#G}

```

Using a nice instrument was worth 4 extra bytes :)
> 1 votes

# Answer
# JavaScript (ES6) using WAV.js, 325 bytes

```
w=new WAV();w.addProgression(btoa`9¹9¹8¹9¹y9y¸x¸x8¸8¸888¸x¸8xùxùy9`.replace(/[CF]./g,'$&#').split(/(?=[A-G])/g).map((f=t=>n=>({note:n,time:t}))(15/65)));['D5','F5#','A5'].map(n=>w.addNote(f(48/13)(n),.3,[],1,1));new Audio(URL.createObjectURL(w.toBlob())).play()
```

```
<script src="https://cdn.rawgit.com/patrickroberts/3b065ab94ce5094baacf45ed23e2a16e/raw/9c367e292fbee8341e1019d0d5953a2234449882/wav.babel.js"></script>
```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, music, audio
---


title: Dames, do some math!

text:
# Question
Title: Dames, do some math!
The order of operations, PEMDAS, is a basic rule in mathematics telling us which order operations should be performed:

"Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction"

The problem is, PEMDAS is not very versatile! What if you wanted to do it in another order? We won't mess with the parentheses, so we keep them where they are (first).

Create a program that takes two arguments:

* A string, telling which order the operations should follow. Some examples are `"DAMES"`, `"SAD, ME"`, `"ME SAD"`, `"MEADS"`. Yes, spaces and commas are OK, as it makes the order easier to remember.
    + *Following suggestions in chat: Supporting spaces and commas is now optional.*
    + If one of the letters is missing, or if there are additional letters that shouldn't be there, you can consider the input invalid and treat it however you like.
* A string, or an expression containing the expression that should be evaluated.

Return the result of the expression as either a decimal number, or an integer. If the answer is not an integer, it has to be returned as a decimal number.

Rules:

* It's OK to combine the two input arguments into one, if that's easier in your language.
* It doesn't have to be a string, but it has to have letters. You can't substitute Addition with 1, Division with 2, etc.
* You can choose which input is first.
* The expression is evaluated ~~right to left~~ left to right. (Change of rule. Any submissions poster the first 12 hours that have this the other way around are accepted).
* The operations use the symbols: `( ) ^ * / + -`. For instance, you can't use `¤` instead of `+` for addition.
* **Spaces in the input expression is not valid as input**
* Unary +/- is not valid as input if it directly follows + or -. Consider `3+-2` as invalid input. It can be treated however you like (doesn't have to produce an error). If `+` or `-` follows any other operator than plus or minus, it's treated the usual way: `3*-3 = -9`, `sin(-2)=-0.909`
* The program must strictly follow the letters, so `"EMDAS", 1-3+4 => -6`, and `"EMDSA", 1-3+4 => 2`.

Examples:

```
Input:   "EMDAS", "3+6*2/4-1"   // -> 3+12/4-1 -> 3+3-1 -> 6-1 -> 5
Output:  5

Input:   "DAMES", "3+6*2/4-1"   // -> 3+6*0.5-1 -> 9*0.5-1 -> 4.5-1 -> 3.5
Output:  3.5

Input:   "SAD, ME", "3+6*2/4-1"  // -> 3+6*2/3 -> 9*2/3 -> 9*0.66667 -> 6
Output:  6

Input:   "ME ADS", "3+5^4/2-3*2 // -> 3+5^4/2-6 -> 3+625/2-6 -> 628/2-6 -> 314-6 -> 308
Output:  308

Input:   "AM EDS", "4*3-sin(0.5^2)*3+1" // -> 4*3-sin(0.5^2)*4 -> 12-sin(0.5^2)*4 -> 4*3-(4*sin(0.5^2)) -> 12-(4*sin(0.5^2)) -> 12-(4*sin(0.25)) -> 12-(4*0.24740) -> 12-0.98961 -> 11.01038
Output:  11.01038

Input:   "DAMES", "4-5-6"   // -> (4-5)-6 -> = -7
Output:  -7                  // NOT: -> 4-(5-6) -> 4-(-1) -> 5

```

Note, the parentheses where added to show that the multiplication `4*sin(0.5^2)` is evaluated before the exponentiation.

This is code golf, so the shortest code in bytes win.

# Answer
> 7 votes
# JavaScript (ES6) 349 ~~353 387 400~~

... maybe still golfable

This old parser of mine sometimes comes in handy - (already used in other 2 challenges)

```
E=
(d,x,W=[],Q=['_'],h={'(':1,_:8,')':7},z=1,C=n=>{for(;h[q=Q.pop()]<=h[n];W.push(q=='^'?Math.pow(a,b):eval(`a${q}b`)))a=W.pop(b=W.pop());Q.push(q,n)})=>([...d].map(l=>h[l='+-/*^'['ASDME'.search(l)]]=(d+=!!l),d=1),(x+')').replace(/\D|\d+/g,t=>(u=~~h[t])-1?u-7?u?z&&t=='-'?z=-z:C(t,z=1):(W.push(z*t),z=0):Q.pop(Q.pop(C(t),z=0)):z=!!Q.push('_')),W.pop())

// TEST
console.log=(...x)=>O.innerHTML+=x.join` `+'\n'

console.log(E('MDASE','3+4*5^2'))
console.log(E("EMDAS", "3+6*2/4-1")) // 5
console.log(E("DAMES", "3+6*2/4-1")) //3.5
console.log(E("SAD, ME", "3+6*2/4-1")) // 6
console.log(E("ME ADS", "3+5^4/2-3*2")) // 308
console.log(E("AM EDS", "4*3-sin(0.5^2)*3+1")) // 11.01038 sin not supported
console.log(E("DAMES", "4-5-6")) // -7

// MORE READABLE
U=(d,x,W=[],Q=['_'],h={'(':1,_:8,')':7},z=1,
  C=n=>{
    for(;h[q=Q.pop()]<=h[n];
        W.push(q=='^'?Math.pow(a,b):eval(`a${q}b`)))
      a=W.pop(b=W.pop());
    Q.push(q,n)
  }
)=>(
  [...d].map(l=>h[l='+-/*^'['ASDME'.search(l)]]=(d+=!!l),d=1),
  (x+')').replace(/\D|\d+/g,t=>
     (u=~~h[t])-1
       ?u-7
         ?u
           ?z&&t=='-'?z=-z:C(t,z=1)
           :(W.push(z*t),z=0)
         :Q.pop(Q.pop(C(t),z=0))
       :(Q.push('_'),z=1)
  ),
  W.pop()
)
```

```
<pre id=O></pre>
```

**Ungolfed**

```
Evaluate=(oprec,expr)=>
{
  var tokens = expr.match(/\D|\d+/g).concat(')')
  var t,a,b,v, SignV
  var vstack=[]
  var ostack=['_']
  var op={ '(':8, _: 1, ')':2}
  oprec.match(/\w/g).map((l,p)=>op['+-/*^'['ASDME'.search(l)]]=7-p)
  var OPush=o=>ostack.push(o)
  var OPop=_=>ostack.pop()
  var VPush=v=>vstack.push(v)
  var VPop=v=>vstack.pop()

  var Scan=i=>
  {
    SignV = 1
    for (; t=tokens[i++]; )
    {
      if (t == '(')
      {
        OPush('_')
        SignV = 1
      }
      else if (t == ')')
      {
        CalcOp(t);
        OPop();
        OPop();
        SignV = 0
      }
      else if (op[t])
      {
        if (SignV && t=='-')
          SignV = -SignV
        else
          CalcOp(t), SignV = 1
      }
      else
      {
        VPush(SignV*t)
        SignV=0
      }
    }
  }
  var CalcOp=nop=>
  {
    for (; op[po = OPop()] >= op[nop];)
      b=VPop(), a=VPop(), CalcV(a,b,po);
    OPush(po), OPush(nop);
  }
  var CalcV=(a,b,o)=>
  {
//    console.log('CV',a,b,o)
    if (o=='+')
      a+=b
    if (o=='-')
      a-=b
    if (o=='*')
      a*=b
    if (o=='/')
      a/=b
    if (o=='^')
      a=Math.pow(a,b)
    VPush(a)
  }
  Scan(0)

  return VPop()
}

console.log=(...x)=>O.innerHTML+=x.join` `+'\n'

console.log(Evaluate('MDASE','3+4*5^2'))
console.log(Evaluate('EMDAS','3+6*2/4-1')) // 5
console.log(Evaluate("DAMES", "3+6*2/4-1")) //3.5
console.log(Evaluate("SAD, ME", "3+6*2/4-1")) // 6
console.log(Evaluate("ME ADS", "3+5^4/2-3*2")) // 308
console.log(Evaluate("AM EDS", "4*3-sin(0.5^2)*3+1")) // 11.01038 sin not supported
console.log(Evaluate("DAMES", "4-5-6")) // -7
```

```
<pre id=O></pre>
```

# Answer
> 6 votes
# R 3.3.2: 209 196 187 177 bytes

The idea is to "misuse" the non-arithmetic operators \<, &, |, ~, ? where we know the precedence (see `?Syntax` in R - but before the override ;)) and overriding them with the given arithmetic operators. The mapping is according to the desired order of operations.

Spaces and commas in the input are **not** supported.

Golfed version

```
f=function(a,b){s=substr;l=list(E='^',M='*',D='/',A='+',S='-');q="<&|~?";for(i in 1:5){x=s(q,i,i);y=l[[s(a,i,i)]];assign(x,.Primitive(y));b=gsub(y,x,b,,,T)};eval(parse(text=b))}

```

Ungolfed and commented:

```
f = function(a,b) {
  s = substr
  # All arithmetic operators
  l = list(E = '^', M = '*', D = '/', A = '+', S = '-')
  # Some non-arithmetic R operators in descending precedence
  q = "<&|~?"
  for (i in 1:5) {
    # The substituted symbol
    x = s(q, i, i)
    # The original operator which has to be substituted
    y = l[[s(a, i, i)]]
    # Substitute the operator for the R interpreter
    assign(x, .Primitive(y))
    # Substitute the operator in the input string
    b = gsub(y, x, b, , , T)
  }
  # Parse and evaluate
  eval(parse(text = b))
}

```

Examples:

```
> f("EMDAS", "3+6*2/4-1")
[1] 5
> f("DAMES", "3+6*2/4-1")
[1] 3.5
> f("SADME", "3+6*2/4-1")
[1] 6
> f("MEADS", "3+5^4/2-3*2")
[1] 308
> f("AMEDS", "4*3-sin(0.5^2)*3+1")
[1] 11.01038
> f("DAMES", "4-5-6")
[1] -7

```

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


title: Play the sound of Pi

text:
# Question
Title: Play the sound of Pi
Yup, you read the title right. play the sound of pi.

More specifically, for every digit of pi in the first 1000, map it to a musical note and output the resulting melody to a file.

Basically, each digit turns to a note on the C Major scale (basically the normal scale). so 1 turns to Middle C, 2 turns to D4, 3 turns to E4, 9 turns to D5 and so on.

# Rules

* Each note should be exactly 0.5 seconds long.
* The melody should contain the first 1000 digits of pi, including the starting 3.
* 1 to 7 represent Middle C to B4, 8 is C5, 9 is D5 and 0 is E5
* All well supported file formats are allowed, as long as they were created before this challenge.
* There may be no pauses anywhere in the file, including the start and end.
* The instrument played does not matter. It could be a piano, sine wave, anything really, as long as the **correct** sound is easily hearable.
* It must take no input and produce no output except for the file. Reading from other files is disallowed.
* Standard loopholes are forbidden.

Example mathematica code:

```
(*please forgive me for this horrible, horrible mess of code*)
digits = RealDigits[Pi, 10, 1000][[1]] /. {0 -> 10};
weights = {0, 2, 4, 5, 7, 9, 11, 12, 14, 16};
melody = {};
For[i = 1, i < 1001, i++, melody = {melody , Sound[SoundNote[weights[[digits[[i]]]], 0.5]]}]
final = Sound[Flatten[melody]];
Export["C:\\Mathematica Shenanigans\\pi.wav", final];

```

Example melody showing first 100 digits: http://vocaroo.com/i/s0cfEILwYb8M

For your sanity, A table of pitches for each note and what note does each digit represent:

```
Digit 1: C: 261.63 Hz
Digit 2: D: 293.66 Hz
Digit 3: E: 329.63 Hz
Digit 4: F: 349.23 Hz
Digit 5: G: 392.00 Hz
Digit 6: A: 440.00 Hz
Digit 7: B: 493.88 Hz
Digit 8: C5: 523.25 Hz
Digit 9: D5: 587.33 Hz
Digit 0: E5: 659.25 Hz

```

# Answer
# Mathematica, ~~107~~ 87 bytes

*Thanks to Martin Ender for saving 20 bytes!*

```
"t.au"~Export~Sound[SoundNote[⌊12Mod[#,10,1]/7⌋-1,.5]&/@#&@@RealDigits[Pi,10,1000]]

```

`#&@@RealDigits[Pi,10,1000]` gives the list of the first 1000 digits of π. `SoundNote[⌊12Mod[#,10,1]/7⌋-1` produces the correct pitch number (where 0 is middle C by default) from a digit. Then `SoundNote[...,.5]&/@` turns that pitch name into a sound object of duration 1/2 second, which `Sound` gathers into an actual audio snippet. Finally `"t.au"~Export~` exports to a Unix Audio Format file, mostly because the extension is the shortest supported one, but also because we get to make the filename a slap in the face to π!

Previous submission:

```
"t.au"~Export~Sound[StringSplit["E5 C D E F G A B C5 D5"][[#+1]]~SoundNote~.5&/@#&@@RealDigits[Pi,10,1000]]

```
> 9 votes

# Answer
# Python 2, 182 bytes

```
x=p=6637
while~-p:x=p/2*x/p+2*10**999;p-=2
s="MThd\0\0\0\6\0\1\0\1\342\4MTrk\0\0\13\301\0\220"
for i in`x`:s+="JHGECA@><L\260"[~ord(i)%29]+'{<'
open('p.mid','w').write(s+"\0\377/\0")

```

``x`` will produce `31415926...20198L`. The trailing `L` is used to produce the final channel message byte, via the mapping `~ord(i)%29`.

Outputs a single track Type 1 Midi file, named `p.mid` to the current working directory.

```
0000: 4d 54 68 64 00 00 00 06  MThd....  # Midi header, 6 bytes to follow
0008: 00 01 00 01              ....      # Type 1, 1 track
000c: e2 04                    â.        # (-)30 ticks per beat, 4 beats per second

000e: 4d 54 72 6b 00 00 0b c1  MTrk...Á  # Track header, 3009 bytes to follow
0016: 00 90 40 7b              ..@{      # Wait  0 ticks, play E4 (3), 97% volume
001a: 3c 3c 7b                 <<{       # Wait 60 ticks, play C4 (1), 97% volume
001d: 3c 41 7b                 <A{       # Wait 60 ticks, play F4 (4), 97% volume
0020: 3c 3c 7b                 <<{       # Wait 60 ticks, play C4 (1), 97% volume
0023: 3c 43 7b                 <C{       # Wait 60 ticks, play G4 (5), 97% volume
...
0bcf: 3c b0 7b 3c              <°{<      # Wait 60 ticks, all notes off
0bd3: 00 ff 2f 00              .ÿ/.      # End of track marker

```
> 10 votes

# Answer
# Scratch, 530 bytes

*Inspired by BookOwl's answer.*

Online Demonstration. Playback will begin immediately, press `space` to stop and reset. Click the cat to start again.

**Edit:** golfed down slightly. I found some golfing tips on the official wiki.

```
when gf clicked
set[c v]to[4e3
repeat(c
add[2e3]to[f v
end
repeat(250
set[b v]to(c
set[h v]to((d)mod(1e4
change[c v]by(-16
repeat(b
set[d v]to(((d)*(b))+((1e4)*(item(b)of[f v
set[g v]to(((2)*(b))-(1
replace item(b)of[f v]with((d)mod(g
set[d v]to(((d)-((d)mod(g)))/(g
change[b v]by(-1
end
change[h v]by(((d)-((d)mod(1e4)))/(1e4
repeat(4
add((h)mod(10))to[a v
set[h v]to(((h)-((h)mod(10)))/(10
end
repeat(4
say(item(last v)of[a v
play note((round((((item(last v)of[a v])-(1))mod(10))*(1.78)))+(60))for(0.5)beats
delete(last v)of[a v

```

**Graphical:**

Uses the Rabinowitz Wagon spigot to produce 4 digits at a time.
> 6 votes

# Answer
# R, 450 bytes

```
N=261.63*(2^(1/12))^c(16,0,2,4,5,7,9,11,12,14);S=44100;s=unlist(sapply(el(strsplit(as(Rmpfr::Const("pi",1e5),"character"),""))[c(1,3:1001)],function(x)sin(0:(0.5*S-1)*pi*2*N[(x:1)[1]+1]/S)));c=32767*s/max(abs(s));a=file("p.wav","wb");v=writeChar;w=function(x,z)writeBin(as.integer(x),a,z,e="little");v("RIFF",a,4,NULL);w(36+S*10,4);v("WAVEfmt ",a,8,NULL);w(16,4);w(c(1,1),2);w(S*1:2,4);w(c(2,16),2);v("data",a,4,NULL);w(2*length(s),4);w(c,2);close(a)

```

Uses package `Rmpfr` to get the correct precision on pi digits. Outputs a `.wav` file.

Indented, with new lines and comments:

```
N=261.63*(2^(1/12))^c(16,0,2,4,5,7,9,11,12,14) # Frequency of each notes
S=44100 #Sampling rate
s=unlist(sapply(el(strsplit(
                   as(Rmpfr::Const("pi",1e5),"character"), #get pi correct digits as a character string
                   ""))[c(1,3:1001)], #Grabs first 1000 digits
                function(x)sin(0:(0.5*S-1)*pi*2*N[(x:1)[1]+1]/S))) #Wave function
c=32767*s/max(abs(s)) #Normalize to range [-32767;32767] as per wav 16-bit standard
a=file("p.wav","wb")
v=writeChar
w=function(x,z)writeBin(as.integer(x),a,z,e="little")
v("RIFF",a,4,NULL)     #ChunkID
w(36+S*10,4)           #Chunksize
v("WAVEfmt ",a,8,NULL) #Format, followed by SubChunk1ID
w(16,4)                #SubChunk1Size
w(c(1,1),2)            #AudioFormat & NumChannels
w(S*1:2,4)             #SampleRate & ByteRate
w(c(2,16),2)           #BlockAlign & BitsPerSample
v("data",a,4,NULL)     #SubChunk2ID
w(2*length(s),4)       #Subchunk2Size
w(c,2)                 #Actual data
close(a)

```
> 3 votes

# Answer
## C (gcc) 572 bytes

```
p(float f){i;char b[10000];p=3.14;for(i= 0;i<5000;i++){b[i]=35*sin(f*(2*p*i)/10000);putchar(b[i]);}} f(){i;FILE *f;char p[1001];float n[10];n[0]= 261.63;for(i=1;i<=6;i++){if(i==3)n[i]=349.23;else n[i]=1.12231*n[i-1];}for(i=7;i<=9;i++)n[i]=2*n[i-7];f=popen("pi 1000","r");fgets(p,sizeof(p)-1,f);for(i=0;i<999;i++){switch(p[i]){case'1':p(n[0]);break;case'2':p(n[1]);break;case'3':p(n[2]);break;case'4':p(n[3]);break;case'5':p(n[4]);break;case'6':p(n[5]);break;case'7':p(n[6]);break;case'8':p(n[7]);break;case'9':p(n[8]);break;case'0':p(n[9]);break;default:p(n[0]);break;}}}

```

Ungolfed version:

```
void play(float freq)
{
    char buffer[10000];
    float pi=3.14;
    for(int i = 0; i<5000; i++)
    {
       buffer[i] = 35*sin(freq*(2*pi*i)/10000 );
       putchar(buffer[i]);
    }
}

void f()
{
    FILE *fp;
    char pi[1001];
    float note[10];
    note[0]= 261.63;

    for(int i=1;i<=6;i++)
    {
       if(i==3)
         note[i]=349.23;
       else
         note[i]=1.12231*note[i-1];
    }

    for(int i=7;i<=9;i++)
      note[i]=2*note[i-7];

   fp=popen("pi 1000","r" );
   fgets(pi, sizeof(pi)-1, fp);

   for(int i=0;i<1001;i++)
   {
    switch(pi[i])
    {
        case '1': play(note[0]);break;
        case '2': play(note[1]);break;
        case '3': play(note[2]);break;
        case '4': play(note[3]);break;
        case '5': play(note[4]);break;
        case '6': play(note[5]);break;
        case '7': play(note[6]);break;
        case '8': play(note[7]);break;
        case '9': play(note[8]);break;
        case '0': play(note[9]);break;
        default : play(note[0]);break;
    }

  }
}

```

Explanation:

* `play(float freq)` routine takes in the frequency as a parameter of the note (hardcoded) you want to play and stores a sine wave in a buffer.
* In the function `f()`, i stored the frequencies corresponding to notes ranging from C4 to E5 in a `notes` array.
* Store the `pi` value followed by 1000 digits in a buffer.In order to do this, I installed the `pi` package on my machine, and used `popen` to read the output of `pi 1000` and store it in a `char` buffer.
* Using a `for` loop and `switch` I called the `play()` function to produce notes that correspond to every single digit in the `pi` buffer. ,

Usage: `./binary_name.o | aplay` on modern Linux distributions, on older distributions you would redirect it to `/dev/audio`
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, pi, audio
---


title: Big code... for you!

text:
# Question
Title: Big code... for you!
At the opening scene of the *Dark Knight rises*, there is a rather awkward dialogue between a CIA agent and the villain Bane.

> **CIA agent:** “If I pull that \[mask\] off, will you die?”
>
> **Bane:** “It would be extremely painful…”
>
> **CIA agent:** “You’re a big guy.”
>
> **Bane:** “…for you.”

It’s unsure if Bane intends to say “painful for you” or “big guy for you”. Let’s settle this problem once for all through code golfing!

## Challenge

Your task is write a program that reorders the above dialogue depending on an integer given as input.

CIA agent dialogue words are: `If` `I` `pull` `that` `off` `will` `you` `die?` `You're` `a` `big` `guy.`

Bane’s dialogue words are: `It` `would` `be` `extremely` `painful...` `for` `you!`

Please note that `die?`, `You’re`, `painful...` and `you!` are considered as single words.

1. Given an integer n as input, convert it to binary
2. Reading the binary digits from left to right, output the next word from CIA agent dialogue if the digit is `1`, and the next word from Bane dialogue if the digit is `0`. The words should be separated by a space. When the speaker changes, add a line feed. Also, prefix each dialogue line with the speaker name (`BANE:`  or `CIA:` ).

You can assume that the input always starts with a 1 in binary form, and has 12 ones and 7 zeroes.

## Example

`522300`

1. Converted to binary: `1111111100000111100`
2. The number starts with 8 ones, so we output the 8 first words from CIA’s agent dialogue, and prefix them with CIA: `CIA: If I pull that off will you die?`
3. Then we got 5 zeroes, so we get the 5 first words from Bane’s dialogue: `BANE: It would be extremely painful...`
4. Then there are 4 ones, so we output the 4 next CIA words: `CIA: You’re a big guy.`
5. Then 2 zeroes: `BANE: for you!`

**Final result:**

```
CIA: If I pull that off will you die?
BANE: It would be extremely painful...
CIA: You’re a big guy.
BANE: for you!

```

## More test cases:

**494542**

```
CIA: If I pull that
BANE: It would be
CIA: off
BANE: extremely
CIA: will you die? You're
BANE: painful... for
CIA: a big guy.
BANE: you!

```

**326711**

```
CIA: If
BANE: It would
CIA: I pull that off will you
BANE: be extremely painful... for
CIA: die? You're
BANE: you!
CIA: a big guy.

```

# Answer
# Pyth - 138 bytes

I should look into compressing the movie script.

```
K_cc"guy big a You're die? you will off that pull I If you! for painful... extremely be would That"d12jmj;++@c"BANECIA"4ed\:m.)@Kedhdr8jQ2

```

Test Suite.
> 10 votes

# Answer
## JavaScript (ES6), ~~203~~ 201 bytes

*Edit: saved 2 bytes by shamelessly borrowing the `trim()` idea from ETHproductions answer*

```
n=>"If I pull that off will you die? You're a big guy. It would be extremely painful... for you!".split` `.map((_,i,a)=>[`
BANE: `,`
CIA: `,' '][j^(j=n>>18-i&1)?j:2]+a[k[j]++],k=[j=12,0]).join``.trim()

```

### Test cases

```
let f =

n=>"If I pull that off will you die? You're a big guy. It would be extremely painful... for you!".split` `.map((_,i,a)=>[`
BANE: `,`
CIA: `,' '][j^(j=n>>18-i&1)?j:2]+a[k[j]++],k=[j=12,0]).join``.trim()

console.log(f(522300))
console.log(f(494542))
console.log(f(326711))
```
> 7 votes

# Answer
## JavaScript (ES6), ~~209~~ ~~202~~ 201 bytes

```
(n,a="It would be extremely painful... for you! If I pull that off will you die? You're a big guy.".split` `,b=[6,18])=>(F=(s,p=n%2)=>n?F((p^(n>>=1)%2?p?`
CIA: `:`
BANE: `:` `)+a[b[p]--]+s):s.trim())``

```

Old approach:

```
(n,a="If I pull that off will you die? You're a big guy. It would be extremely painful... for you!".split` `,b=[12,0])=>(F=p=>p^n%2?F(n%2)+(p?`
CIA:`:`
BANE:`):n?F(p,n>>=1)+" "+a[b[p]++]:``)(n%2).trim()

```

### Test snippet

```
f=(n,a="It would be extremely painful... for you! If I pull that off will you die? You're a big guy.".split` `,b=[6,18])=>(F=(s,p=n%2)=>n?F((p^(n>>=1)%2?p?`
CIA: `:`
BANE: `:` `)+a[b[p]--]+s):s.trim())``

console.log(f(522300))
console.log(f(494542))
console.log(f(326711))
```
> 7 votes

# Answer
## C++11 (GCC), ~~298~~ 293 bytes

```
#include<sstream>
[](int i){std::stringstream b("It would be extremely painful... for you!"),c("If I pull that off will you die? You're a big guy.");std::string s,w;int n=0,t=i,p;while(t/=2)n++;for(;n>=0;p=t)((t=i>>n&1)?c:b)>>w,s+=p^t?t?"CIA: ":"BANE: ":" ",s+=t^(i>>--n)&1?w+"\n":w;return s;}

```

A lambda function that takes an integer and returns the dialogue as a `std::string`. You can see it in action here.

Ungolfed version (with some explanation):

```
#include<sstream>

[](int i) {
    std::stringstream bane("It would be extremely painful... for you!"),
                      cia("If I pull that off will you die? You're a big guy.");
    std::string s, w;
    int n = 0, t = i, p;
    // Find the position of the most significant bit (n)
    while (t/=2) n++;

    for (; n>=0; p=t) {
        t = i>>n&1; // Current bit
        // Append the speaker name if the previous bit was different
        if (t != p) s += (t ? "CIA: " : "BANE: ");
        else s += " ";

        // Read the next word from one of the streams
        if (t) cia >> w;
        else bane >> w;

        s += w;

        if (t != ((i>>--n)&1)) // Append a newline if the next bit is different
            s += "\n";
    }

    return s;
}

```
> 6 votes

# Answer
# JavaScript (ES6), ~~252 227~~ 226 bytes

```
n=>[...n.toString(2,b="If I pull that off will you die? You're a big guy.".split` `,c="It would be extremely painful... for you!".split` `)].map((a,i,j)=>(a!=j[i-1]?+a?i?`
CIA: `:`CIA: `:`
BANE: `:``)+(+a?b:c).shift()).join` `

```

# Usage

```
f=n=>[...n.toString(2,b="If I pull that off will you die? You're a big guy.".split` `,c="It would be extremely painful... for you!".split` `)].map((a,i,j)=>(a!=j[i-1]?+a?i?`
CIA: `:`CIA: `:`
BANE: `:``)+(+a?b:c).shift()).join` `
f(522300)

```

# Notes

This is golfing-in-progress, I think I can still shave off some bytes, but feel free to leave suggestions in the comments.
> 4 votes

# Answer
# Python 3.6, 232 bytes

```
from itertools import*
c="you! for painful... extremely be would It".split(),"guy. big a You're die? you will off that pull I If".split()
for n,r in groupby(f'{int(input()):b}',int):
 print("BCAINAE::"[n::2],*[c[n].pop()for _ in r])

```

**Edit**, equivalently:

```
from itertools import*
c="It would be extremely painful... for you!".split(),"_ If I pull that off will you die? You're a big guy.".split()
for n,r in groupby(map(int,f'{int(input()):b}')):
 print("BCAINAE::"[n::2],*map(c[n].pop,r))

```
> 4 votes

# Answer
# Japt, 121 bytes

```
A=[`It Ùd ¼ extÚ+ pafª... f y!`¸`If I pªl È     f Øi y ¹e? Y' a big guy.`¸]¢®^T?["
BANE:""
CIA:"]gT=Z :P +S+AgZ vÃx

```

Contains many unprintables, so you'd just be better off testing it online.
> 3 votes

# Answer
# Perl 6, 211 bytes

```
{.put for map |*,zip map {.[0]X .[1].rotor: .[2..*]},zip <CIA: BANE:>,(<If I pull that off will you die? You're a big guy.>,<It would be extremely painful... for you!>),|(.base(2)~~m:g/(.)$0*/)».chars.rotor(2)}

```
> 2 votes

# Answer
# C#, ~~398~~ ~~390~~ ~~385~~ ~~396~~ 389 bytes

```
class P{static void Main(string[] a){string s="2"+System.Convert.ToString(int.Parse(a[0]),2),e="CIA: ",r="BANE: ",o="";int k=0,l=0,i=1;string[] c="If I pull that off will you die? You're a big guy.".Split(' '),b="It would be extremely painful... for you!".Split(' ');for(;i<s.Length;i++)o+=(s[i-1]==s[i]?" ":(i<2?"":"\n")+(s[i]>'0'?e:r))+(s[i]>'0'?c[k++]:b[l++]);System.Console.Write(o);}}

```

Launch with input number as parameter.

Ungolfed:

```
class P
{
    static void Main(string[] a)
    {
        string s = "2" + System.Convert.ToString(int.Parse(a[0]), 2), e = "CIA: ", r = "BANE: ", o = "";
        int k = 0, l = 0, i = 1;

        string[] c = "If I pull that off will you die? You're a big guy.".Split(' '), b = "It would be extremely painful... for you!".Split(' ');
        for (; i < s.Length; i++)
            o += (s[i - 1] == s[i] ? " " : (i<2?"":"\n") + (s[i] > '0' ? e : r))
                + (s[i] > '0' ? c[k++] : b[l++]);
        System.Console.Write(o);
    }
}

```

Back to 396 bytes because I didn't notice "no newline at the begining" rule.
> 2 votes

# Answer
# Ruby, 204+1 = 205 bytes

Requires the `-n` flag.

```
d=[%w"It would be extremely painful... for you!",%w"If I pull that off will you die? You're a big guy."]
n=%w"BANE CIA"
("%b"%$_).scan(/((.)\2*)/).map{|i,b|puts n[k=b.to_i]+': '+d[k].slice!(0,i.size)*' '}

```
> 2 votes

# Answer
# PHP, 198 bytes

```
while($i++<19)echo($t-$s=1&$argv[1]>>19-$i)?"
"[$i<2].($s?CIA:BANE).": ":" ",explode(0,"It0would0be0extremely0painful...0for0you!0If0I0pull0that0off0will0you0die?0You're0a0big0guy.")[$$s+++7*$t=$s];

```
> 2 votes

# Answer
# Perl, 205 bytes

```
@t=([qw/It would be extremely painful... for you!/],[qw/If I pull that off will you die? You're a big guy./]);$_=sprintf'%b',$0;print$n?'BANE':'CIA',": @{[splice$t[$n=1-$n],0,length$&]}"while s/(.)\1*//;

```

Put that into a file named 494542 and run like this:

```
perl -lX 494542

```

Tested on perl v5.22
> 1 votes

# Answer
## Clojure, 401 bytes

```
(require '[clojure.string :as s])(defn f[n](let[c(map #(-(int %) 48)(Integer/toString n 2))p[(s/split"It would be extremely painful... for you!"#" ")(s/split"If I pull that off will you die? You're a big guy."#" ")]a["BANE" "CIA"]](loop[i[0 0] g"" d c q 2](if(<(count d)1)g(let[b(first d)j(i b)](recur(assoc i b (inc j))(str g(if(= b q)" "(str(when(not= 2 q)"\n")(a b)": "))((p b) j))(rest d) b))))))

```

Invocation:

```
(f 522300)

```

# Ungolfed

```
(require '[clojure.string :as s])
(defn dialogue[num]
    (let [dacode (map #(- (int %) 48) (Integer/toString num 2))
          phrases [(s/split"It would be extremely painful... for you!"#" ")(s/split"If I pull that off will you die? You're a big guy."#" ")]
      actors ["BANE" "CIA"]]
      (loop [idxs [0 0] finaldial "" code dacode prevbit 2]
        (if (< (count code) 1) finaldial
            (let [bit (first code) idx (idxs bit)]
              (recur (assoc idxs bit (inc idx)) (str finaldial (if (= bit prevbit) " " (str (when (not= 2 prevbit) "\n") (actors bit) ": ")) ((phrases bit) idx)) (rest code) bit))))))

```
> 1 votes

---
Tags: code-golf
---


title: Alternating Power Fibonacci Sequence

text:
# Question
Title: Alternating Power Fibonacci Sequence
### Definition

The Alternating Power Fibonacci Sequence is formed as follows.

1. Start with the empty sequence and set **n** to **1**.
2. Compute **f**n, the **n**th non-negative Fibonacci number, with repetitions.
**0** is the first, **1** is the second and the third, **2** is the fourth. All others are obtained by summing the two previous numbers in the sequence, so **3 = 1 + 2** is the fifth, **5 = 2 + 3** is the sixth, etc.
3. If **n** is odd, change the sign of **f**n.
4. Append **2n-1** copies of **f**n to the sequence.
5. Increment **n** and go back to step 2.

These are the first one hundred terms of the APF sequence.

```
 0  1  1 -1 -1 -1 -1  2  2  2  2  2  2  2  2 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3
-3 -3 -3 -3 -3 -3  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5
 5  5  5  5  5  5  5  5  5  5  5  5  5 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8
-8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8

```

### Task

Write a full program or a function that takes a positive integer **n** as input and prints or returns the **n**th term of the APF sequence.

If you prefer 0-based indexing, you can alternatively take a non-negative integer **n** and print or return the APF number at index **n**.

This is ; may the shortest code in bytes win!

### Test cases (1-based)

```
    1 ->    0
    2 ->    1
    3 ->    1
    4 ->   -1
    7 ->   -1
    8 ->    2
  100 ->   -8
  250 ->   13
  500 ->  -21
 1000 ->   34
11111 ->  233
22222 -> -377
33333 ->  610

```

### Test cases (0-based)

```
    0 ->    0
    1 ->    1
    2 ->    1
    3 ->   -1
    6 ->   -1
    7 ->    2
   99 ->   -8
  249 ->   13
  499 ->  -21
  999 ->   34
11110 ->  233
22221 -> -377
33332 ->  610

```

# Answer
# Jelly, 5 bytes

```
BLCÆḞ

```

**Try it online!**

### How?

Extending the Fibonacci series back into negative indexes such that the relation `f(i) = f(i-2) + f(i-1)` still holds:

```
  i   ...   -8  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   4   5 ...
f(i)  ...  -21  13  -8   5  -3   2  -1   1   0   1   1   2   3   5   8 ...

```

Going back from `i=0` the numbers are those we need to repeat **2n-1** times, and Jelly's Fibonacci built-in, `ÆḞ`, will calculate these.

We can find the `-i` (a positive number) that we need by taking the bit-length of `n` and subtracting `1`.

Since we want `i` (a negative number) we can instead perform `1-bitLength` and Jelly has an atom for `1-x`, `C`, the complement monad.

```
BLCÆḞ - Main link: n               e.g.  500
B     - convert n to a binary list      [1,1,1,1,1,0,1,0,0]
 L    - get the length                   9
  C   - complement                      -8
   ÆḞ - Fibonacci                       -21

```
> 12 votes

# Answer
# Python 2, 30 bytes

```
f=lambda n:n<1or f(n/4)-f(n/2)

```

Try it online!

One-indexed.

The sequence felt like a puzzle, something that Dennis generated by having a short way to express it. The power-of-two repetitions suggest recursing by bit-shifting (floor-dividing by 2). The alternating-sign Fibonacci recursion `f(n)=f(n-2)-f(n-1)` can be adapted to bitshift in place of decrementing. The base case works out nicely because everything funnels to `n=0`.
> 22 votes

# Answer
# Mathematica, ~~43~~ ~~36~~ 24 bytes

```
Fibonacci@-Floor@Log2@#&

```

7 bytes saved thanks to @GregMartin, and a further 12 thanks to @JungHwanMin.
> 6 votes

# Answer
# MATL, ~~19~~ ~~17~~ ~~16~~ 11 bytes

```
lOiB"yy-]x&

```

Input is 1-based.

Try it online! Or verify all test cases.

### How it works

For 1-based input **n**, let **m** be the number of digits in the binary expansion of **n**. The **n**-th term in the output sequence is the **m**-th term in the Fibonacci sequence, possibly with its sign changed.

One idea would be to iterate **m** times to compute terms of the Fibonacci sequence. This is easy with a `for each` loop using the array of binary digits. If the Fibonacci sequence were initiallized with **0**, then **1** as usual, iterating **m** times would result in **m+2** terms on the stack, so the top two numbers would have to be deleted. Instead, we initiallize with **1**, then **0**. That way the next generated terms are **1**, **1**, **2**, ... and only *one* deletion is needed.

The sign could be dealt with by using another loop to change sign **m** times. But that's costly. It is better to integrate the two loops, which is done simply by *subtracting* instead of adding in the Fibonacci iteration.

```
l       % Push 1
O       % Push 0
iB      % Input converted to binary array
"       % For each
  yy    %   Duplicate top two elements
  -     %   Subtract. This computes the new Fibonacci term with the sign changes
]       % End
x       % Delete top number
&       % Specify that implicit display should take only one input
        % Implicitly display the top of the stack

```
> 5 votes

# Answer
# Python 2, ~~83~~ ~~82~~ 79 bytes

```
def f(n,a=0,b=1):
 l=bin(n)[2:]
 for _ in l:a,b=b,a+b
 return a*-(len(l)%2or-1)

```

Try it online!
> 4 votes

# Answer
## JavaScript (ES6), 33 bytes

```
f=(n,p=1,c=0)=>n?-f(n>>1,c,p+c):p

```

1-indexed.

A port of xnor's answer would be 23:

```
f=n=>n<1||f(n/4)-f(n/2)

```
> 4 votes

# Answer
# Jelly, 9 bytes

```
BLµ’ÆḞN⁸¡

```

Uses one-based indexing.

Try it online!

## Explanation

This method works if your Fibonacci function only supports non-negative arguments.

```
BLµ’ÆḞN⁸¡  Input: integer n
B          Binary digits of n
 L         Length. len(bin(2)) = floor(log2(n)))
  µ        Start new monadic chain on x = len(bin(2))
   ’       Decrement
    ÆḞ     Get Fibonacci(x-1)
       ⁸¡  Repeat x times on that
      N      Negate.
           Return Fibonacci(x-1) if x is even else -Fibonacci(x-1)

```
> 3 votes

# Answer
# Japt, 6 bytes

```
Mg1-¢l

```

Test it online!

### How it works

As mentioned in other answers, the **n**th term in the alternating-sign Fibonacci series is the same as the **-n**th term in the regular series. **n** can be found by taking the bit-length of the input and subtracting one; negating this results in 1 minus the bit-length.

```
Mg1-¢l
    ¢l  // Calculate the length of the input in binary.
  1-    // Subtract this from 1.
Mg      // Get the Fibonacci number at this index.

```
> 3 votes

# Answer
# 05AB1E, ~~11~~ 10 bytes

Uses 1-based indexing

**05AB1E**'s Fibonacci function returns positive fib numbers less than *n*, meaning we'd have to generate more than necessary, get the correct one by index and then calculate the sign. So I doubt any method based around that will be shorter than calculating the numbers iteratively.

Uses the realisation that we can initialize the stack with `1, 0` reversed to handle the case when `n=1` as described in Luis Mendo's MATL answer.

```
XÎbgG‚D«`-

```

Try it online!

**Explanation**

```
X             # push 1
 Î            # push 0 and input
  b           # convert input to binary
   g          # get length of binary number
    G         # for N in [1...len(bin(input))-1] do:
     ‚        # pair the top 2 elements of the stack in a list
      D       # duplicate the list
       «      # concatenate the 2 lists together
        `     # split into separate elements on the stack
         -    # subtract the top 2 elements

```
> 3 votes

# Answer
# Julia 0.5, 19 bytes

```
!n=n<1||!(n/=4)-!2n

```

Try it online!

### How it works

This uses the same formula as @xnor's Python answer. The recurrence relation
**g(n) = g(n-2) + g(n-1)** generates the negative terms of the Fibonacci sequence, which equal the positive terms with alternating signs. From anywhere in a run of **2**k repetitions of the same number, we can pick any repetition of the previous run of **2**k-1 numbers and the run of **2**k-2 numbers before those by dividing the index by **2** and **4**.

Rather than the straightforward

```
f(n)=n<1||f(n÷4)-f(n÷2) # 25 bytes

```

we can redefine an operator for our purposes. Also, **f** will work just as fine with floats, so we get

```
!n=n<1||!(n/4)-!(n/2)   # 21 bytes

```

Finally, if we update **n** with a division by **4**, wwe can write **n/2** as **2n** and omit a pair of parens, leading to the 19-byte function definition in this answer.
> 2 votes

# Answer
# Perl 6, 53 bytes

```
{flat(((0,1,*+*...*)Z*|<-1 1>xx*)Zxx(1,2,4...*))[$_]}

```

Straightforward implementation of the sequence, the way it was described.
Zero-based.
> 2 votes

# Answer
# , 18 bytes

```
(%>:-*:)t.@<:@#@#:

```

Uses one-based indexing. Takes an input integer *n* \> 0 and computes `floor(log2(n))` by finding the length of its binary representation and then decrements that value by one. It then finds the `floor(log2(n))-1`*th* coefficient of the generating function *x*/(1 + *x* \- *x*2) which is the g.f for the negative-indexed Fibonacci values.

Try it online!

## Explanation

```
(%>:-*:)t.@<:@#@#:  Input: integer n
                #:  Binary
              #@    Length
           <:@      Decrement
(      )            The generating function x/(1+x-x^2)
  >:                  Increment x
     *:               Square x
    -                 Subtract
 %                    Divide x by previous
        t.          Get series coefficient at the index given by previous value

```
> 1 votes

---
Tags: code-golf, math, sequence, array, fibonacci
---


title: Negative Regexp

text:
# Question
Title: Negative Regexp
Write the shortest function that takes one string, and returns a regular expression that matches anything EXCEPT the input string, in parenthesis. Escape necessary characters like Perl `quotemeta`.

```
Input:
  helloworld
Output:
  ([^h]|h[^e]|he[^l]|hel[^l]|hell[^o]|hello[^w]|hellow[^o]|hellowo[^r]|hellowor[^l]|helloworl[^d])
Input:
  */
Output:
  ([^\*]|\*[^\/])

```

See also:

# Answer
> 2 votes
**Python, 49 chars**

```
import re
f=lambda x:'(^(?!%s$).*$)'%re.escape(x)

```

The answer matches anything but the input. It gives an output using conditional groups so is suited for the problem:

> regular expression that matches anything EXCEPT the input string

The answer uses Howard's regex (fixing my regex)

You can use the same approach on Perl with a few less chars:

**Perl, ~~40~~ 38**

```
sub f{'(^(?!'.quotemeta(pop).'$).*$)'}

```

Examples:

```
f('hello') -> (^(?!hello$).*$)

f('*/')    -> (^(?!\*\/$).*$)

```

# Answer
> 1 votes
# Perl, 32 bytes

```
sub{qr/^\Q$_[0]\E\z(*COMMIT)a|/}

```

Try it online!

This is actually a general-purpose negator for any regular expression that doesn't use control flow commands. The basic idea is that we do `(*COMMIT)` ("if this doesn't match, nothing can"), followed by something that can't possibly match (a true general-purpose negator would use `(?!)`, but we can use just `a` in this context because we know it can't appear after the end of the string `\z`), in order to force a failure in cases where the initial regular expression matches; `|` then allows a success in all other cases.

Out of the 31 bytes here:

* `sub{`, `$_[0]`, `}` (10 bytes) handle I/O (because the original question asked specifically for a *function*);
* `qr/^\Q`, `\E\z`, `/` (11 bytes) construct a regex that matches the string provided as input, and only that string (we return the regex as a regex object; a string would be 1 byte shorter, but the regex object happens to come with parentheses around it, as required by the question, and a string would require me to add parentheses manually);
* `(*COMMIT)a|` (11 bytes) are the regex negator that we use to negate that regex.

It's notable how much boilerplate there is here, and how the answer might be shorter if the question were more difficult (allowing the negation of arbitrary regexes, rather than just ones that match a single string).

# Answer
> 0 votes
JAVA 61

```
String f(String w){return "^(?!"+Pattern.quote(w)+"$)(.*)$";}

```

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


title: 8 ought to become Infinity

text:
# Question
Title: 8 ought to become Infinity
Let's take a look on a typical loop, which usually performs 8 iterations:

```
for (int x=0; x<8; ++x);

```

You have to make it infinite!

---

It's a for all languages that support such form of `for` loop. So solution with highest score (upvotes minus downvotes) wins.

If your language has the other form of `for` loop, but you are sure, you can make something cool with it, feel free to post the answer and mark it as noncompeting. I reserve the right to enlarge scope of available constructions and languages, but it will never be shrinked, so don't be afraid of dropping previously correct solutions.

---

# What is solution?

Solution consists of *two programs.*

The first program is a *clean* program. It's the typical program in your language with the `for` loop making 8 iterations. It should be the normal program, any developer could write. No any special hacks for preparation purposes. For example:

```
int main()
{
  for (int x=0; x<8; ++x);
  return 0;
}

```

The second program is *augmented.* This program should contain all the code from clean program and some additional code. There are limited number of *extension points,* see complete rules section for details. An augmented program for the clean one above can be

```
inline bool operator < (const int &a, const int &b)
{
  return true;
}

int main()
{
  for (int x=0; x<8; ++x);
  return 0;
}

```

That's just an example (noncompilable in C++) to show an idea. The real correct augmented program have to be compilable, working and having infinite loop.

# Complete rules

### Both programs:

* Any language with support of such `for` loops is ok.
* The loop body has to be empty. More precisely, you can place some output or other code into the loop, but loop behavior should be the same in case of empty loop.

### Clean program:

* Loop uses integer or numeric counter and performs 8 iterations:

```
for (int          x=0; x<8; ++x);   // C, C++, C#
for (var          x=0; x<8; ++x);   // C#, Javascript
for (auto         x=0; x<8; ++x);   // C, C++
for (auto signed  x=0; x<8; ++x);   // C, C++
for (register int x=0; x<8; ++x);   // C, C++

```
* User-defined types are disallowed.
* Using of property (except of global variable) instead of loop variable is disallowed.
* Declaration of variable can be inside or outside of the loop. Following code is ok:

```
int x;
for(x=0; x<8; ++x);

```
* Either prefix or postfix increment can be used.
* Loop limit `8` should be written as a constant literal without saving to named constant or variable. It's made to prevent solutions based on declaring variable or constant equal to 8, and then reassigning, overriding or shadowing it by the other value:

```
const double n = 8;

int main()
{
  const double n = 9007199254740992;
  for (double x=0; x<n; ++x);
  return 0;
}

```

### Augmented program:

* Must contain all the code from the clean one.
* Should extend clean program in limited number of extension points.
* Must execute *same* `for` loop as an infinite loop itself.
Placing of the loop into another infinite construction is not ok.
* Runtime or compile-time patching of the code is allowed as long as textual representation of it is unchanged.
* Placing the construction into a string and passing to `eval` is disallowed.

### Extension points:

* Anywhere outside of the fragment with clean code, including other files or other assemblies.
* `for` statement (as single piece - `for` construction and its body) must be kept unchanged.
* Variable declaration must be kept the same.
* Any place between simple statements can be used as extension point.
* If and only if variable was declared outside of the loop and without immediate assignment of the value, such assignment can be added.

```
/* extension point here */
int main()
/* extension point here */
{
  /* extension point here */
  int x /* extension point for assignment here */;
  /* extension point here */
  for (x=0; x<8; ++x);
  /* extension point here */
  return 0;
  /* extension point here */
}
/* extension point here */

```

```
int main()
{
  /* BEGIN: No changes allowed */ int x = 0; /* END */
  /* extension point here */
  /* BEGIN: No changes allowed */ for (x=0; x<8; ++x); /* END */
  return 0;
}

```

PS: If possible, please provide a link to online IDE.

# Answer
> 32 votes
# Python3

### Clean Program:

This is just a standard countdown while loop.

```
n = 8
while n != 0:
  n -= 1
print("done")

```

### Augmented Program:

```
import ctypes

ctypes.cast(id(8), ctypes.POINTER(ctypes.c_int))[6] = 9

n = 8
while n != 0:
  n -= 1
print("done")

```

It uses the int cache to redefine `8` as `9` which effectively makes the `n -= 1` a no-op, since `9-1 = 8` which just sets `n` back to `9` again, causing the infinite loop.

You can see the int cache in action online here (though obviously without the infinite loop cuz its online).

# Answer
> 22 votes
# Python 3

**Clean Program:**

The standard way to do something 8 times in python is:

```
for i in range(8):
    # Do something
    pass

```

**Augmented Program:**

However, if we override the range generator function to infinitely yield 1, it becomes an infinite loop...

```
def range(x):
    while 1: yield 1

for i in range(8):
    # Infinite loop
    pass

```

We can take this further and create a generator function which, rather than infinitely yielding 1, counts up forever:

```
def range(x):
    i = 0
    while 1: yield i; i+=1

for i in range(8):
    # Counting from 0 to infinity
    pass

```

**Test on repl.it**

# Answer
> 22 votes
# Perl

**Clean**

```
for($i=0; $i<8; $i++) { }

```

**Augmented**

```
*i=*|;
for($i=0; $i<8; $i++) { }

```

Ideone.

# Answer
> 10 votes
# ES5+ (Javascript)

*EDIT*: Removed explicit variable declaration, as otherwise it was hoisted and a non-configurable *window.x* property was created (unless run line by line in the REPL console).

Explanation:

Makes advantage of the fact that any globally scoped variable is also a property of the *window* object, and redefines "window.x" property to have a constant value of 1.

**Clean**

```
for(x=0; x<8; x+=1) console.log(x);

```

**Augmented**

```
Object.defineProperty(window,'x',{value:1});
for(x=0; x<8; x+=1) console.log(x);

```

*NOTE*: To make this work in Node.js, just replace *"window"* with *"global"* (tested in Node.js 6.8.0)

# Answer
> 10 votes
## C

**Clean program**

```
int main()
{
  for (int x=0; x<8; ++x);
  return 0;
}

```

**Augmented program**

```
#define for(ever) while(1)

int main()
{
  for (int x=0; x<8; ++x);
  return 0;
}

```

# Answer
> 8 votes
# Java

**Clean program:**

```
public class Main {
    public static void main(String[] args) throws Exception {
        for (Integer i = 0; i < 8; i++);
    }
}

```

**Augmented program:**

```
import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws Exception {
        Class cache = Integer.class.getDeclaredClasses()[0];
        Field c = cache.getDeclaredField("cache");
        c.setAccessible(true);
        Integer[] intcache = (Integer[]) c.get(cache);
        intcache[129] = intcache[128];

        for (Integer i = 0; i < 8; i++);
    }
}

```

Sets the Integer in the Integer cache that should contain 1 to 0, effectively making `i++` do nothing (it sets `i` to the cached Integer that should contain 1, but since that Integer actually contains 0, nothing changes).

# Answer
> 7 votes
# C++

```
int main()
{
#define int bool
  for (int x=0; x<8; ++x);
  return 0;
}

```

`bool` can only be 0 or 1. Inspired by primo's Perl answer.

# Answer
> 6 votes
## Python 3 (3.5.0)

**Clean Program:**

```
for i in range(8):
    print(i)

```

**Augmented**

```
import sys

from ctypes import *

code = sys._getframe().f_code.co_code

cast(sys._getframe().f_code.co_code, POINTER(c_char*len(code))).contents[len(code)-4] = 113
cast(sys._getframe().f_code.co_code, POINTER(c_char*len(code))).contents[len(code)-3] = 160

for i in range(8):
    print(i)

```

This solution is unlike the others written in Python in that it actually changes the source code on the fly. All the stuff in the for loop can be changed to whatever code is wanted.

The code changes the second to last opcode to be `113` or more readably - `JUMP_ABSOLUTE`. It changes the operand to `160` \- the instruction where the for loop begins, in effect creating a GOTO statement at the end of the program.

The augmented program prints the numbers `0..7` infinitely many times without stack-overflowing or similar.

# Answer
> 6 votes
# PHP

I think this is following the extension point rules; I'm not totally clear on point 4. It's very similar to @primo's perl answer so I think it counts.

**Clean**

```
for(;$i<8;$i++);

```

**Augmented**

```
$i='a';
for(;$i<8;$i++);

```

PHP lets you increment certain strings, like so:

```
'a' -> 'b'
'b' -> 'c'
'z' -> 'aa'
'aa' -> 'ab'
'aab' -> 'aac'
etc

```

All of these strings evaluate to 0, so this will loop practically forever (barring somehow running out of memory).

# Answer
> 6 votes
# Perl

## Clean code

```
for ($x = 0; $x < 8; $x++) {}

```

## Augmented code

```
sub TIESCALAR {bless []}
sub FETCH {}
sub STORE {}
tie $x, "";

for ($x = 0; $x < 8; $x++) {}

```

Most Perl variables are just variables. However, the language also has a `tie` feature, which allows you to effectively give variables getters and setters. In this program, I make the main package (whose name is the null string) into the equivalent of a class from an object-oriented language, whilst also having it be a program. That allows me to tie the `for` loop counter to the program itself. Implementing `TIESCALAR` allows `tie` to succeed; the return value of `TIESCALAR` is meant to be a reference to any internal state we need to keep around associated with the variable, but because we don't need any, we return an empty array reference as a placeholder. We then give the simplest possible implementations of the getter and setter; neither of them do anything, so attempts to assign to `$x` have no effect, and attempts to read it always return `undef`, which is numerically less than 8.

# Answer
> 5 votes
# WinDbg

### Clean

```
.for (r$t0 = 0; @$t0 < 8; r$t0 = @$t0 + 1) { }

```

### Augmented

```
aS < |;                                            * Create alias of < as |
.block {                                           * Explicit block so aliases are expanded
    .for (r$t0 = 0; @$t0 < 8; r$t0 = @$t0 + 1) { } * Condition is now @$t0 | 8, always true
}

```

This approach creates an alias for `<` as `|`, so when `<` is encountered in the code the alias is expanded to `|` and bitwise-or is done instead of less-than. In WinDbg all non-zero values are truthy so `anything | 8` is always true.

Note: The `.block` is not actually needed if the `aS` and `.for` are actually entered as two different lines as shown here, it's only required when the `aS` and `.for` are on the same line.

# Answer
> 5 votes
## Common Lisp

### Clean code

```
(dotimes(i 8))

```

### Augmented

```
(shadowing-import(defmacro :dotimes(&rest args)'(loop)))
(dotimes(i 8))

```

A macro named `keyword:dotimes`, a.k.a. `:dotimes` (see 11.1.2.3 The KEYWORD Package) is defined which expands as an infinite loop. The `defmacro` macro returns the name of the macro being defined, which can be fed to `shadowing-import`. Thus, this new `dotimes` symbols shadows the standard one (which should not be redefined or lexically bound to another macro in portable programs).

### Augmented (2)

```
(set-macro-character #\8 (lambda (&rest args) '(loop)))
(dotimes(i 8))

```

When we read character 8, we replace it by `(loop)`. That means that the above reads as `(dotimes (i (loop)))` and so the code never terminates computating the upper-bound. This impacts all occurrences of 8, not only the one in the loop. **In other words, 8 really stands for infinity.** If you are curious, when the readtable is modified like above, then character 8 becomes "terminating", and detaches itself from other numbers/symbols currently being read:

```
(list 6789)

```

... reads as:

```
(list 67 (loop) 9)

```

You can run tests on Ideone: https://ideone.com/sR3AiU.

# Answer
> 5 votes
# Mathematica

## Clean

```
For[x = 0, x < 8, ++x,]

```

## Augmented

```
x /: (x = 0) := x = -Infinity;
For[x = 0, x < 8, ++x,]

```

# Answer
> 4 votes
# Ruby

## Clean

This sort of for loop is not much used in Ruby, but a typical tutorial will tell you that this is the way to go about it:

```
for x in 1..8
  # Some code here
end

```

# Augmented

The for loop just calls `(1..8).each` with the given block of code, so we change that method:

```
class Range
  def each
    i = first
    loop { yield i; i+= 1 }
  end
end

for x in 1..8
  # Some code here
end

```

# Answer
> 4 votes
# Haskell

## Clean version:

```
import Control.Monad (forM_)

main = forM_ [0..8] $ \i -> print i

```

Augmented version:

```
import Control.Monad (forM_)

data T = C

instance Num T where
    fromInteger _ = C

instance Enum T where
    enumFromTo _ _ = repeat C

instance Show T where
    show _ = "0"

default (T)

main = forM_ [0..8] $ \i -> print i

```

It's quite basic, really: we just define our own type `T` such that its `enumFromTo` instance is an infinite sequence, then use type defaulting so that the un-type-annotated values `0` and `8` are taken as type `T`.

# Answer
> 3 votes
# ///

*There are no explicit `for` loops in ///, but can be simulated (it's turing complete after all).*

## Clean:

```
/1/0/
/2/1/
/3/2/
/4/3/
/5/4/
/6/5/
/7/6/
/8/7/
8

```

## Augmented:

```
/0/0/
/1/0/
/2/1/
/3/2/
/4/3/
/5/4/
/6/5/
/7/6/
/8/7/
8

```

What's going on?

While the former program counts down from 8 to 0, the latter one's `/0/0/` rule will replace `0` by `0` until eternity.

# Answer
> 3 votes
# Javascript ES6

OK, here's a version that works using the ES6 for...of loop construct. I'll even give you a clean array so that we're sure there's no funny business:

### Clean

```
for(a of [0,1,2,3,4,5,6,7]);

```

Of course, that doesn't stop someone from messing with the Array prototype...

### Augmented

```
Array.prototype[Symbol.iterator]=function(){return {next: function(){return {done: false}}}}
for(a of [0,1,2,3,4,5,6,7]);

```

This works by over-writing the default iterator so that it never terminates, therefore locking everything into an infinite loop. The code doesn't even have a chance to run the stuff inside the loop.

# Answer
> 2 votes
# C++

Uses 2 extension points:

```
struct True {
  True(int x){}
  bool operator<(const int&){
    return true;
  }
  void operator++(){}
};

int main()
{
#define int True
  for (int x=0; x<8; ++x);
  return 0;
}

```

Clean program is same as in the description.

# Answer
> 2 votes
# Brainfuck

I print a '0' each iteration, just to make it easy to count iterations. But any code could be inserted there without changing how the loop works.

## Clean

```
>> ++++++ [-<++++++++>] <<                   b = '0' (value to be printed each iteration)

>> ++++++++ [-<< ++++++++ ++++++++ >>] <<    for (a = a plus 128;
[                                              a;
++++++++ ++++++++                              a = a plus 16 (mod 256)) {
>.<                                              loop body (print b)
]                                            }

```

Try it online

The augmented version relies on the common Brainfuck implementation with 8 bit cells. On these implementations, "increment" is actually "increment (mod 256)". Thus to find a loop that will iterate exactly 8 times in the clean version and endlessly in the augmented version, we can simply find a solution to the following system of inequalities.

* a + b\*8 (mod 256) == 0 (for clean version)
* c + a + b\*n (mod 256) \> 0 for all n (for augmented version)
* a \> 0

In this case, we let a = 128, b = 16, and c = 1. Obviously 128 + 16 * 8 = 256 (and 256 (mod 256) = 0) and 128 \> 0, and since b is even, c + a + b * n is odd for any odd a + c, and thus will never be an even multiple of 256 in such cases. We select c = 1 for simplicity's sake. Thus the only change we need is a single `+` at the beginning of the program.

## Augmented

```
+                                            increment a (only change)
>> ++++++ [-<++++++++>] <<                   b = '0' (value to be printed each iteration)

>> ++++++++ [-<< ++++++++ ++++++++ >>] <<    for (a = a plus 128;
[                                              a;
++++++++ ++++++++                              a = a plus 16 (mod 256)) {
>.<                                              loop body (print b)
]                                            }

```

Try it online

I leave it to the OP to determine if this entry is competing. Brainfuck doesn't have an explicit for loop, but the loop form I used is as close as you're likely to get. `++++++++` is also as close to a literal `8` as you can get; I've included quite a few of those.

The clean version almost certainly constitutes a typical program written in this language, as even the shortest known Brainfuck Hello World depends on a modular recurrence relation to work.

# Answer
> 2 votes
# Haskell

## Clean

```
import Control.Monad (forM_)

main = forM_ [0..8] $ \i -> print i

```

## Augmented

```
import Control.Monad (forM_)

import Prelude hiding (($))
import Control.Monad (when)

f $ x = f (\i -> x i >> when (i == 8) (f $ x))

main = forM_ [0..8] $ \i -> print i

```

Replaces the usual function application operator `$` with one that repeats the loop again every time it finishes. Running the clean version prints 0 to 8 and then stops; the augmented version prints 0 to 8 and then 0 to 8 again, and so on.

I cheat a little, in that `forM_ [0..8] $ \i -> print i` isn't necessarily the "cleanest" way to write that loop in Haskell; many Haskellers would eta-reduce the loop body to get `forM_ [0..8] print` and then there's no `$` to override. In my defense I copied the clean code from Cactus' answer, who didn't need that property, so at least one Haskell programmer actually wrote that code with no motivation to unnecessarily add the `$`!

# Answer
> 1 votes
# C++

```
int main()
{
  int y;
#define int
#define x (y=7)
  for (int x=0; x<8; ++x);
  return 0;
}

```

Lets `x` evaluate to 7. Does not work in C because it requires an lvalue at assignement and increment.

# Answer
> 1 votes
# Nim

The idiomatic version, using `countup`:

### Clean

```
for i in countup(1, 8):
  # counting from 1 to 8, inclusive
  discard

```

### Augmented

```
iterator countup(a: int, b: int): int =
  while true:
    yield 8

for i in countup(1, 8):
  # counting 8s forever
  discard

```

Simple, and very similar to the Python answer which redefines `range`. We redefine `countup`, the idiomatic Nim way of iterating from one int (inclusive) to another, to give 8s infinitely.

The more interesting version, using the range operator `..`:

### Clean

```
for i in 1..8:
  # counting from 1 to 8, inclusive
  discard

```

### Augmented

```
iterator `..`(a: int, b: int): int =
  while true:
    yield 8

for i in 1..8:
  # counting 8s forever
  discard

```

Very similar to the previous solution, except we redefine the range operator `..`, which normally would give an array `[1, 2, 3, 4, 5, 6, 7, 8]`, to the iterator from before.

# Answer
> 1 votes
# GolfScript

## Clean

```
0{.8<}{)}while;

```

## Augmented

```
{.)}:8;
0{.8<}{)}while;

```

It assigns the function returning n+1 to the variable 8

# Answer
> 1 votes
# tcl

Normal:

```
for {set i 0} {$i<8} {incr i} {}

```

Augmented:

```
proc incr x {}
for {set i 0} {$i<8} {incr i} {}

```

The idea is to redefine the `incr` command that is used to increment the variable `i`, to actually not increment!

Can be tested on: http://rextester.com/live/QSKZPQ49822

# Answer
> 1 votes
# x86\_64 Assembly

Clean program:

```
mov rcx, 8
loop_start:
sub rcx, 1
cmp rcx,0
jne loop_start
mov rax, 0x01
mov rdi, 0
syscall

```

The sort of loop any Assembly programmer would use, followed by an exit syscall so as not to enable adding a `jmp loop_start` instruction afterwards.

Augmented program:

```
global start
section .text
start:
mov rcx, -1
jmp loop_start
mov rcx, 8
loop_start:
sub rcx, 1
cmp rcx,0
jne loop_start
mov rax, 0x01
mov rdi, 0
syscall

```

Also, sorry if it's bad that the clean program doesn't have an entrypoint or a `section .text`

# Answer
> 0 votes
# JavaScript

## Clean:

```
for (var i = 0; !(i > Math.PI * 2.5); i++);

```

## Augmented:

```
window.Math = {PI: NaN};
for (var i = 0; !(i > Math.PI * 2.5); i++);

```

# Answer
> 0 votes
# C++

## Clean Program

A nice, normal loop, iterating from numbers 0 to 7.

```
#include <iostream>

int main() {

  for (short i = 0; i < 8; i++) {
    // Print `i` with a newline.
    std::cout << i << std::endl;
  }

}

```

## Augmented Program

The preprocessor of C++ is quite a dangerous feature...

```
#include <iostream>
#define short bool

int main() {

  for (short i = 0; i < 8; i++) {
    // Print `i` with a newline.
    std::cout << i << std::endl;
  }

}

```

The only line we had to add was `#define short bool`. This makes `i` a boolean instead of a short integer, and so the increment operator (`i++`) does nothing after `i` reaches 1. The output then looks like this:

```
0
1
1
1
1
1
...

```

---
Tags: popularity-contest, restricted-source
---