# Question
Title: Rosetta Stone Code Golf Challenge: Print Certain Numbers; all snippets must be same length
Rosetta Stone Code Challenges are challenges where you must complete the task in as many languages as possible.

## The Challenge

You will be given two numbers, `n` and `s`, in a list as input. The `n` will be a number you have to count up to. `n` will be any number from 2 to 10000. `s` will be the number you skip by when counting up to `n`. `s` will be from 1 to `n`/2 (half of `n`). If `n` was 600, `s` could not be greater 300. You have to output all of the numbers up to `n` skipping by `s` starting with 1. Each output number should either be on a newline, on the same line separated by spaces, or in a list.

## The Twist

For this Rosetta Stone Code Challenge, each snippet you write the program in must be the same length. ie: If your Python program has 56 characters then your Java program must also be 56 characters. Spaces and comments do not count as characters. Variable/function names can't be more than 10 characters. Remember, this is also code golf, so try to keep your code short.

## Example

### Input

```
[100, 7]

```

### Output

```
1
8
15
22
29
36
43
50
57
64
71
78
85
92
99

```

*Note: Output could be in single line separated by spaces or list format*

## Winning Criterion

The winner will be decided by this formula:

`numberOfLanguages/codeSize`

`codeSize` is not the total code size but the average code size of a snippet.

The user with the highest score will win. ie: An answer with 4 languages and a size of 31 bytes would win over an answer with 7 languages and a size of 80 bytes. A winner will be chosen at 2:00 UTC on March 9, 2015.

## Scoreboard

All scores are rounded to the nearest thousandth

Maltysen \- 14 languages / 24 characters = 0.583 ---- **Winner**

mbomb007 \- 15 languages / 29 characters = 0.517

Jakube \- 5 languages / 11 characters = 0.455

Teun Pronk \- 4 languages / 51 characters = 0.078

captncraig \- 1 language / 56 characters = 0.018

# Answer
# 14 Languages - 24 bytes = 0.58333333333

\**Facepalm\**. I forgot not to count the space in my Python answer. So I'm at 24 bytes now.

Learned about a lot of new languages from this challenge, which I will probably using in golfs. A site that really helped me find these languages was http://www.tutorialspoint.com/codingground.htm. Just don't expect my programs to run in it, it requires a full program format, and I just used it to learn about the languages and used other REPLs to run them.

## 1. Pyth:

Pyth doesn't have a range by step function unlike python, so I used regular range and chopped (thanks @Jakube) used mod operator on it.

```
M%Hr+Z+Z+Z+Z+Z+Z+Z+Z1+1G

```

Defines a function g(until, step)

```
M          Define g(G, H)
 %H        Every H elements
  r1+1G      Range 1->G+1

```

## 2. Golfscript:

This is my first golfscript program. Probably not the best way to do it.

```
000000000000000;\),1>\%p

\         swap
 )        increment
  ,       range
   1>     all but first element
   \      swap
    %     take every top of stack elements
     p    print array

```

## 3. Bash Utils:

Uses the seq command which has INCREMENT param.

```
seq 00000000000000001 $2 $1

```

## 4,5. Python, Sage:

Self-explanatory code.

```
lambda a,b:range(1,a+1,b)

```

Sage is a language based on Python used for math stuff.

## 6. Mathematica:

Again, self-explanatory.

```
r[a_,b_]:=Range[001,a,b]

```

## 7. Matlab:

Uses Matlab's range notation and defines an anonymous function.

```
@(a,b)00000000000001:b:a

```

## 8. Livescript:

Like Coffeescript it is a JS derivative. Has cool range syntax. Arrow notation again.

```
r=((((a,b)->[1 to a by b])))

```

## 9. Erlang:

Learned erlang just for this. Pretty self explanatory, defines function r.

```
r(a,b)->lists:seq(1,a,b)

```

## 10. F#:

Kind of obvious, F#'s function definitions are like variables.

```
let r a b=seq{000001..b..a}

```

## 11. Haskell:

Haskell's range notation has you give the first two in the range for the increment, and not an explicit increment.

```
r a b=[00000000001,a+1..b]

```

## 12. R:

Very cool language, even if function definitions are a little verbose.

```
function(a,b)seq(01,a,b)

```

## 13. Julia:

*Awesome* language, will be using for golfing in the future.

```
r(a,b)=[00000000001:b:a]

```

## 14. CJam:

Like my old golfscript answer except with input parsing and padding.

```
0000000000000;q~\),1>\%p

```
> 7 votes

# Answer
# 23 languages, 15 characters = 1.5333333

```
+---------------+----------------------+----------------+
|    Language   |         Code         |      Kind      |
+---------------+----------------------+----------------+
|          gs2  |  B/4[RRRRRRRRRRR     |  (stack)       |
|         Pyth  |  M%+Z+Z+Z+Z+ZHSG     |  (definition)  |
|   GolfScript  |  \),000000001>%p     |  (stack)       |
|         CJam  |  \),000000001>%p     |  (stack)       |
|          zsh  |  seq 00000001 $2 $1  |  (script)      |
|         Bash  |  seq 00000001 $2 $1  |  (script)      |
|   FlogScript  |  \),0000001>\%Pa     |  (stack)       |
|          APL  |  {00001+⍵×⍳⌈⍺÷⍵}     |  (lambda)      |
|      Mathics  |  00001~Range~##&     |  (lambda)      |
|  Mathematica  |  00001~Range~##&     |  (lambda)      |
|            J  |  ({.\00001+i.)~-     |  (lambda)      |
|       Matlab  |  @(a,b)00001:b:a     |  (lambda)      |
|       Octave  |  @(a,b)00001:b:a     |  (lambda)      |
|    Burlesque  |  jrojcoq-]m[m]uN     |  (stack)       |
|            K  |  {0001+&~(!x)!y}     |  (lambda)      |
|          Pip  |  {_%b=001FI,++a}     |  (lambda)      |
|      Haskell  |  ff a b=[1,b+1..a]   |  (definition)  |
|        Clean  |  ff a b=[1,b+1..a]   |  (definition)  |
|        Curry  |  ff a b=[1,b+1..a]   |  (definition)  |
|        Frege  |  ff a b=[1,b+1..a]   |  (definition)  |
|        Julia  |  ff(a,b)=[1:b:a]     |  (definition)  |
|       Scotch  |  f(a,b)=[1..a,b]     |  (definition)  |
|        Perl6  |  {1,$^b+1...$^a}     |  (lambda)      |
+---------------+----------------------+----------------+

```
> 9 votes

# Answer
## 15 languages, 29 characters = (15/29) ≈ 0.517

I've fixed all my code so far. Now I'm searching for other languages.

**1. Python** (24 golfed)

```
f=lambda n,s:range(0001,n+1,s)

```

**2. \>\<\> (Fish)** \- (19 + junk chars)

This program assumes that the number and the step size were are on the stack beforehand, pushed in that order. Uses `ao` to print newlines between numbers.

```
1           v
$:@+:{:}(?!;>:nao
~~~~~~~~~~

```

Explanation (code, stack after preceding code executes, comments):

```
1               1 s n           start n0=1. stack is (top)1 s n(bottom)
(skip to print code - last line of explanation, then come back)
 $:@            s 1 s n         swap, duplicate, rotate top 3 (this all is OVER in Forth)
   +:           n1 n1 s n       add step to x and dup
    {:}         n n1 n1 s n     compare to n
       (        n1>n n1 s n     if !(n1 > n), JUMP: dup and print (continue)
        ?!;     n1 s n          else exit
          :nao  n1 s n          dup, print n1, newline, loop around

```

**3. APL** (19 golfed)

```
fffffffff←{(⌈⍵÷⍺)↑1+⍺∘.×(⍳⍵)}

```

*Golfed*. Paste into here: http://ngn.github.io/apl/web/

```
f←{(⌈⍵÷⍺)↑1+⍺∘.×⍳⍵}

```

Call like this: `7 f 100`. This creates an array from 1 to n, multiplies every element by s, adds one to each element, then takes the first ceil(n/s) elements.

**4-7. Haskell**, **Clean**, **Curry**, **Frege** (14 golfed - spaces don't count)

This program is valid in Haskell, Clean, Curry, and Frege.

```
ffffffffff nnnn s=[1,s+1..nnnn]

```

*Golfed.* Run here: https://ideone.com/Ii0pgP

```
f n s=[1,s+1..n]

```

**8. Scotch** (15 golfed)

```
fffffffff(nnnn,s)=[1..nnnn,s]

```

**9. Jaskell** (24 golfed) - Built based on documentation.

Filter the list where the remainder modulo s is 1.

```
ffffff n s=filter(.%s==1)[1..n]

```

**10. CoffeeScript** (25 golfed) Run **here**

```
fffff=(n,s)->x for x in[1..n]by s

```

**11. R** (25 golfed) Run here: http://www.r-fiddle.org/#/fiddle?id=k3vRnCOW&version=2

```
fffff=function(n,s)seq(1,n,s)

```

**12. Cobra** (26 golfed)

```
def ffff(n,s)
    for i in 1:n:s
        print i

```

**13. S-Lang** (28 golfed)

```
define ff(n,s){return [1:n:s];}

```

**14. Boo** (29)

Not sure if range function can take 3 parameters...

```
def f(n,s):return range(n)[::s]

```

**15. Funge-98** (29, any help golfing?)

As close as I could get to my \>\<\> program. Since there's no "rotate" stack instruction, I had to use "put" and "get" instead. Befunge *really* needs some stack rotation/shift instructions, or even an "over" instruction.

```
22p1v
    >:.a,\:33p\33g+:22g\`!j@

```

Explanation:

```
        n s
22p     s           (store n at 2,2)
1       1 s         (push 1)
(v and > are direction changes, so the above only happens once)
\:      s s 1       (swap, dup)
33p     s 1         (store s at 3,3)
\33g    s 1 s       (get s)
+:      n1 n1 s     (add, dup)
22g     n n1 n1 s   (get n)
\`!     !(n1>n) n1 s    (swap, >, not)
j@      n1 s        (conditional exit)
:.a,    n1 s        (print n1, newline)

```

---

---

**NOT USING AT THE MOMENT, TOO LONG** \- My score is improved by not including these.

**Ruby** (35) Run here: http://ideone.com/yFZELR

```
def f(n,s)
    (1..n).select{|x|x%s==1}
end

```

**PowerShell** (38)

```
function f($n,$s){(1..$n|?{$_%$s-eq 1})}

```

**Perl** (39) Run here: https://ideone.com/HGoleN

```
sub f{join(" ",grep $_%@_[1]==1, 1..@_[0])}

```
> 4 votes

# Answer
# 5 languages 11 characters = 0.4545

Took this challenge as an opportunity to check out some new languages (CJam, Burlesque, zsh, gs2). First time I've worked with these languages.

The method behind creating the output is different in nearly each language. Only the CJam and the gs2 method are identical. The 4 methods are, creating a range \[1, 100\] and slice it with modulo (CJam and gs2), creating the range \[1, ..., 100\] and filter for elements that are 1 mod 7 (Pyth), creating the range \[1, ..., 100\], divide it into chunks of len 7 and use the first element of each chunk (Burlesque), and creating the sequence directly (zsh).

I tried to design each program in such a way, that it looks golfed to someone, who is not familiar with the language.

edit 1: added Burlesque, previous 2 languages with 10 characters = 0.2

edit 2: added gs2, previous 3 languages with 11 characters = 0.2727

edit 3: added zsh, previous 4 languages with 11 characters = 0.3636

## CJam

```
q~\1+,0-\%p

```

Test it online with the input `100 7`.

```
q~           push the evaluated input (100 7)
  \          swap (7 100)
   1         push 1 (7 100 1)
    +        add last to elements (7 101)
     ,        create the range (7, [0, 1, ..., 100])
      0       push 0 (7, [0, 1, ..., 100], 0)
       -      delete 0 from the range (7, [1, 2, ..., 100])
        \     swap ([1, 2, ..., 100], 7)
         %    use every 7th entry ([1, 8, ..., 99])
          p   print pretty

```

## Burlesque

```
jrojcoq-]m[

```

Beside zsh, this is the only golfed program. Burlesque is quite awesome, it has a very large range of different functions, like `ro`. Sadly there's nothing like the Python `[::a]` slicing operator.

There is no online interpreter, but you can get Burlesque here. Since Burlesque doesn't support functions or IO, you have to put the values onto the stack first, like `100 7 jrojcoq-]m[`

```
j            Swap (7 100)
 ro          Range (7 {1 2 ...  100})
   j         Swap ({1 2 ... 100} 7)
    co       ChunksOf ({{1 2 ..  7} {8 ... 14} ... {99 100}})
      q      Create Block ({{1 2 ..  7} {8 ... 14} ... {99 100}} {})
       -]    head (first element) ({{1 2 ..  7} {8 ... 14} ... {99 100}} {-]})
         m[  map the chunks to the head-block

```

## gs2

```
read-nums dup head inc range tail swap reverse head mod unlines

```

Yep, this is only 11 chars. In gs2 each byte has a different meaning. But because writing in bytes is quite hard and not any fun, you can also write in mnemonics, which you can compile to the actual gs2 code. The gs2 code, which gets executed is

```
W@!'."B !4+

```

or as hex-dump:

```
57 40 21 27 2e 22 42 20 21 34 2b

```

Fun fact: I didn't write in mnemonics, but directly the numbers of the hex-dump.

You can test it by downloading the compiler. Compile the mnemonics file with `python gs2c.py < mnemonics.txt > compiled` or simply copy `W@!'."B !4+` to a file named `compiled` and then execute it with `echo 100 7 | python gs2.py compiled`.

The mnemonics is pretty self explainable, but here's what's going on in the stack.

```
57 40 21 27 2e 22 42 20 21 34 2b
57                                 read-nums ([100 7])
   40                              dup ([100 7] [100 7])
      21                           head ([100 7] 100)
         27                        inc ([100 7] 101)
            2e                     range ([100 7] [0 1 ... 100])
               22                  tail ([100 7] [1 2 ... 100])
                  42               swap ([1 2 ... 100] [100 7])
                     20            reverse ([1 2 ... 100] [7 100])
                        21         head ([1 2 ... 100] 7)
                           34      mod ([1 8 ... 99])
                              2b   unlines ('1\n8\n...\n99')
                                   everything on the stack gets printed

```

Btw, 8 bytes are possible, maybe even less.

edit: I forked gs2, slightly manipulated a command and made a pull request, which is already merged. So now the task can be done with 6 bytes: `read-nums extract-array swap range1 mod unlines`, which translates to `57 0e 42 2f 34 2b`, which is even better than the optimal pyth.

## zsh

```
f() seq 1 $2 $1

```

This defines a function `f`, that creates the a sequence. To use it on Windows, I installed the babun shell, where you can simply type these commands. Simply write `f() seq 1 $2 $1` and in the next line `f 100 7`.

First I tried to write this in Bash, but there you have to write `()` around the code block, like `f() ( seq 1 $2 $1 )`. So I switched to zsh instead.

## Pyth

```
fq1%TeQUhhQ

```

This really hurts, since of course I see the obvious 7 byte golf. You can test it online with the input `100, 7`.

```
                 Q = input()
       UhhQ      the range [0, 1, ..., Q[0]]
f                filtered (only use those elements T, which satisfy the equation
 q1%TeQ             1 == T % Q[1]

```
> 4 votes

# Answer
# 4 languages 51 characters = (4/51) = 0,0784313725490196

No idea how many numbers after comma you want so i'll just leave it like this.
All snippets are 51 characters long when you remove all the whitespace.
Working on more and shorter code but it's a start.

# Log

**Initial answer**
Submitted Python(3.4), Lua(5.1) and Javascript.
Score: 3/51 = 0,0588235294117647

**Update 1**
Added Ruby
Score: 4/51 = 0,0784313725490196.

### Python 3.4

```
def f(NUMB,ST):
    CNT=1
    while CNT<=NUMB:
        print(CNT)
        CNT+=ST

```

### Lua 5.1

```
function f(num,st)
    for cn=1,num,st do
        print(cn);
    end;
end;

```

### Javascript

```
function f(n,s){
  for(i=1;i<=n;i+=s){
    console.log(i);
  }
}

```

### Ruby

```
def faa(numb,st)
  for i in 1..numb
    if i%st==1
      puts i
    end
  end
end

```
> 3 votes

# Answer
# 1 language - 56 characters = 0.01785714285

## piet (2x28) -
> 2 votes

---
Tags: code-challenge, rosetta-stone
---


title: Programming? No, it's Projamming

text:
# Question
Title: Programming? No, it's Projamming
Hopefully not duplicate, but I did not find one.

# Challenge

The challenge is to write full program, which compiles (without errors), but, when executed, will not finish the execution till the end, because an error appears during the execution.

# Rules

* It has to be full program, which is compile-able or interpret-able in such way, that it produces no syntax errors.
* You can use any mechanics, which will do something, so that the interpreter of your program kills the program. This includes (but is not limited to): exceptions, overflows, SIGSEGVs. However, asking the interpreter to kill the program explicitly does not count (by calling `exit()`-like functions).
* It may be compiler/OS dependent, as long as it's not using obvious bug in compiler/interpreter. So depending on Undefined behavior in C/C++ is valid, but using version 1.0.17b of `language` interpreter, which throws `random_exception` when run is not. If it depends on something, it's good to write so in the answer.
* The program will take no input, but it may (or may not) produce any output to STDOUT, or STDERR.
* This is , but it is not about finding the language with least amount of bytes, but to find a least bytes solution in all languages. So I will not accept any answer.

# Catalogue

I hope Martin Büttner won't get mad at me for copy-pasting his catalogue.

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

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

```
# Language Name, N bytes

```

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

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

```

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

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

```

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

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

```

```
/* Configuration */

var QUESTION_ID = 61390; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43365; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
> 10 votes
## C, 5 bytes

```
main;

```

On modern systems it will crash because `main` is not in an executable section. On older systems it will execute some junk and crash.

# Answer
> 5 votes
## Brainfuck, 1 byte

`[`

There's no matching `]` to jump to. Depending on how smart your compiler/interpreter is, it may give you a syntax error, but the original spec didn't allow for syntax errors - only runtime errors.

Try it online

# Answer
> 5 votes
# Python, 1 byte

```
_

```

NameError! :D

This works because NameErrors in Python occur at *run-time*, NOT *compile-time*.

# Answer
> 3 votes
# CJam, 1 bytes

```
;

```

This will try to pop from an empty stack.

Try it online.

# Answer
> 2 votes
# JavaScript Shell, 7 bytes

```
clear()

```

The `clear` function has been quite controversial but to clarify this uses the *SpiderMonkey* shell. It will throw a `Segmentation fault: 11`

# Answer
> 2 votes
# PHP, 7 Bytes

```
<?=o();

```

This Santa smiley crashes with `Fatal error: Call to undefined function o() in [...]`

# Answer
> 1 votes
# JavaScript, 1 byte

```
_

```

Tries to access the undefined variable `_`, which raises a ReferenceError. JS doesn't check for inexistent variables until runtime, so if you tried this code:

```
console.log("No error??/")
_
console.log("Huh...")

```

It would error out with `ReferenceError: _ is not defined`, then print `No error??/`, but not `Huh...`.

# Answer
> 1 votes
# C#, 36 bytes

```
class C{static void Main(){Main();}}

```

Throws a `StackOverflowException`. I can't remove the main function and still have it compile.

# Answer
> 0 votes
# T-SQL, 9 bytes

```
EXEC('@')

```

Causes the following error

```
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@".

```

# Answer
> 0 votes
# Pyth, 3 Bytes

```
/00

```

### Result:

> ```
>  Traceback (most recent call last):
>   File "pyth.py", line 671, in <module>
>   File "<string>", line 3, in <module>
>   File "/app/macros.py", line 506, in div
> ZeroDivisionError: integer division or modulo by zero
>
> ```

# Answer
> 0 votes
# PoGo, 2 Bytes

```
vi

```

### Result

> ```
> EXCEPTION_INT_DIVIDE_BY_ZERO
>
> ```

# Answer
> 0 votes
# Loader, 8 bytes

There are shorter solutions, but this is the shortest one that's actually legal syntax:

```
throw ""

```

Throws the empty string as an error message (which, in the reference implementation, corresponds to a popup error notification reading `Error:` followed by a single trailing space).

# Answer
> 0 votes
# C++, 23 bytes

```
int main() {
    main();
}

```

Crashes with `Segmentation fault: 11`

# Answer
> 0 votes
# Haskell, 10 bytes

```
main=[]!!0

```

Fails with the `Prelude.!!: index too large` error.

# Answer
> 0 votes
## STATA, 1 byte

`a`

Outputs `unrecognized command: a`, but this error occurs at run-time.

For an error not in the range 100 to 199 (considered syntax errors), use

```
set ob `=9^9'

```

This gave me the following to standard error: `op. sys. refuses to provide memory
 Stata ran out of room to track where observations are stored. Right now, Stata has 1m bytes allocated to track observations. Stata
 requested an extra 738m bytes (in 738 1m pieces) and the operating system said no. Stata is currently tracking 0 observations and was
 asked to track 0. You are up against the memory limits of this computer.`

---
Tags: popularity-contest
---


title: Play an RTTTL song

text:
# Question
Title: Play an RTTTL song
User quartata posted this challenge, but he neglected the fact that, for whatever reason, he's not able to play MIDI files on his computer.

Let's help him out by writing a full program that reads a song in RTTTL format from the standard input, prints the song name to the standard output and plays it (at the right speed and pitch).

**Format details**

RTTTL is a fairly dumb and underspecified ringtone format. It consists of a name, some default values, and a series of notes (only one note at a time) in a simple text format.

Example: `fifth: d=4,o=5,b=63: 8P, 8G5, 8G5, 8G5, 2D#5`

The name is a string terminated by a colon. Here the name is "fifth". Your program must accept names with at least 15 characters.

Next, the defaults section (also terminated by a colon) lists some default values for duration (d), octave (o) and the beats per minute (b) for the song. They are comma-separated and use a "key=value" syntax. There may be any number of spaces around each "key=value" part. You may assume that default values d, o and b are all present, in this order. The duration and octave will be explained below; the bpm refers to the number of beats (corresponding to quarter notes) that should be played in a minute, and you must support any integer value between 20 and 900 (inclusive).

Then the actual song is listed as a comma-separated series of notes using a "DPO" syntax, where D is the duration, P is the pitch (note) and O is the octave. There may be any number of spaces and newlines around each "DPO" part.

The duration is a power of 2 between 1 and 32 (inclusive), representing a fraction of a whole note. So for example a value of 4 (quarter note) is twice as long as a value of 8 (eighth note). The duration can be missing, in which case the default duration will be used. The duration may also be modified by the presence of a dot (`.`), specifically the dot makes the note last 50% longer. Since not everybody agrees about where the dot is supposed to be, you must accept a dot after the pitch or after the octave (i.e. both "DP.O" and "DPO." should work).

The pitch is one of A,B,C,D,E,F,G,A#,C#,D#,F#,G#,P where A-G# are the standard musical notes (note: no flats, use the corresponding sharp note) and P is a pause. The pitch is the only part of the note that is required, and is case-insensitive.

And finally, the octave is a number normally from 4 to 8, but you must support any number from 1 to 8 inclusive. For example, C4 is the standard middle C with a frequency of about 261.63Hz. The octave can be missing, in which case the default octave will be used. You can assume that pauses don't have an octave specified (as it has no meaning).

As mentioned in the other challenge, you can use this site to convert RTTTL songs to MIDI format for testing (but note that it may not follow the exact same specification).

**Requirements:**

Your program must play each note at the right speed and pitch. It can use any kind of sound (sine/triangle/square wave, piano sound, bell sound, whatever; also it can be a standard beep, wave sound or MIDI sound etc) as long as it is audible and the pitch is recognizable.

Each note must be played continuously for the specified duration or no more than a 64th note shorter than that, except if you're using something like an ADSR envelope, in which case the release phase may continue through the next pause or over the next note.

If two consecutive notes have the same pitch, they must be clearly distinguished, either through a short break (using no more than the length of a 64th note, as part of the first note's duration) or by using a non-uniform sound (such as the ADSR envelope mentioned above), or at least through a phase change if it's clear enough. Two consecutive pauses should be treated the same as a single pause with the total duration.

The program must be runnable in Linux using freely available software. It should read the song from the standard input, and print the song name to the standard output.

If the input does not match the specification above, the behavior is unspecified. Your program may ignore errors, or print a message, or play something wrong, hang or crash, it should just not do any damage.

Standard loopholes are not allowed.

**Scoring**

Code golf, shortest program (measured in UTF-8 bytes) wins.

# Answer
# Java, 813

```
import javax.sound.sampled.*;class R{public static void main(String[]a)throws Exception{Integer k=0;a=new
java.util.Scanner(System.in).useDelimiter("\\A").next().split(":");System.out.println(a[0]);int[]X=new
int[3],N={9,11,0,2,4,5,7};while(k<3)X[k]=k.valueOf(a[1].split(",")[k++].split("=")[1].trim());SourceDataLine
l=AudioSystem.getSourceDataLine(new AudioFormat(48000,8,1,1>0,1<0));l.open();l.start();for(String
t:a[2].toLowerCase().split(",")){a[k=0]=a[1]=a[2]="";for(char
c:t.trim().toCharArray())if(c!=46)a[k+=(c<48|c>57?1:0)^k]+=c;int
D=32/(a[k=0]==""?X[0]:k.valueOf(a[0]))*(t.contains(".")?3:2),m=a[1].charAt(0)-97,P=m>6?0:N[m]+12*(a[2]==""?X[1]:k.valueOf(a[2]))+(t.contains("#")?1:0);int
n=180000*D/X[2];for(;k<n;++k)l.write(new byte[]{(byte)(P>0&k<n-n/D?k*Math.pow(2,P/12.)/22.93:0)},0,1);}l.drain();}}

```

I'm still working on it.
It's a bit sensitive to CPU speed and busyness when starting.
> 3 votes

# Answer
# C++, 15186 bytes

**There's a link at the bottom where you can hear a sample**

I present one of the least practical ways to play music on your Linux machine:

```
#include <SFML/Audio.hpp>
#include <cmath>
#include <iostream>
#include <fstream>
#include <string>
namespace N{double a = 440.;double as = 466.16;double b = 493.88;double c = 523.25;double cs = 554.37;double d = 587.33;double ds = 622.25;double e = 659.25;double f =  698.46;double fs = 739.99 ;double g =  783.99;double gs =  830.61;    const unsigned SAMPLES = 10*44100;const unsigned SAMPLE_RATE = 44100;const unsigned AMPLITUDE = 10000;const double TWO_PI = 6.28318;    sf::Int16 a4raw[SAMPLES];sf::Int16 as4raw[SAMPLES];sf::Int16 b4raw[SAMPLES];sf::Int16 c4raw[SAMPLES];sf::Int16 cs4raw[SAMPLES];sf::Int16 d4raw[SAMPLES];sf::Int16 ds4raw[SAMPLES];sf::Int16 e4raw[SAMPLES];sf::Int16 f4raw[SAMPLES];sf::Int16 fs4raw[SAMPLES];sf::Int16 g4raw[SAMPLES];sf::Int16 gs4raw[SAMPLES];sf::Int16 pauseraw[SAMPLES];double inc = a/44100;double x=0;int i=0;void set1(){for(int i=0;i<SAMPLES;i++){a4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=as/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){as4raw[i]=AMPLITUDE*sin(x*TWO_PI);x += inc;}inc=b/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){b4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=c/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){c4raw[i]=AMPLITUDE * sin(x*TWO_PI);x+=inc;}inc=cs/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){cs4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=d/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){d4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=ds/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){ds4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=e/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){e4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=f/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){f4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=fs/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){fs4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=g/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){g4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;} inc=gs/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){gs4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}}sf::SoundBuffer a3; sf::SoundBuffer a4; sf::SoundBuffer a5; sf::SoundBuffer a6; sf::SoundBuffer a7;sf::SoundBuffer as3; sf::SoundBuffer as4; sf::SoundBuffer as5; sf::SoundBuffer as6; sf::SoundBuffer as7;sf::SoundBuffer b3; sf::SoundBuffer b4; sf::SoundBuffer b5; sf::SoundBuffer b6; sf::SoundBuffer b7;sf::SoundBuffer c3; sf::SoundBuffer c4; sf::SoundBuffer c5; sf::SoundBuffer c6; sf::SoundBuffer c7;sf::SoundBuffer cs3; sf::SoundBuffer cs4; sf::SoundBuffer cs5; sf::SoundBuffer cs6; sf::SoundBuffer cs7;sf::SoundBuffer d3; sf::SoundBuffer d4; sf::SoundBuffer d5; sf::SoundBuffer d6; sf::SoundBuffer d7;sf::SoundBuffer ds3; sf::SoundBuffer ds4; sf::SoundBuffer ds5; sf::SoundBuffer ds6; sf::SoundBuffer ds7;sf::SoundBuffer e3; sf::SoundBuffer e4; sf::SoundBuffer e5; sf::SoundBuffer e6; sf::SoundBuffer e7;sf::SoundBuffer f3; sf::SoundBuffer f4; sf::SoundBuffer f5; sf::SoundBuffer f6; sf::SoundBuffer f7;sf::SoundBuffer fs3; sf::SoundBuffer fs4; sf::SoundBuffer fs5; sf::SoundBuffer fs6; sf::SoundBuffer fs7;sf::SoundBuffer g3; sf::SoundBuffer g4; sf::SoundBuffer g5; sf::SoundBuffer g6; sf::SoundBuffer g7;sf::SoundBuffer gs3; sf::SoundBuffer gs4; sf::SoundBuffer gs5; sf::SoundBuffer gs6; sf::SoundBuffer gs7;sf::SoundBuffer pauseBuffer;void set2(){if (!a3.loadFromSamples(a4raw,SAMPLES,1,SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if(!a4.loadFromSamples(a4raw,SAMPLES,1,SAMPLE_RATE)){std::cerr<<"err: load fail";}if(!a5.loadFromSamples(a4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if(!a6.loadFromSamples(a4raw,SAMPLES,1,SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if(!a7.loadFromSamples(a4raw,SAMPLES,1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}  if (!as3.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!as4.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!as5.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!as6.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!as7.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!b3.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!b4.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!b5.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!b6.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!b7.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!c3.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!c4.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!c5.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!c6.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!c7.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!cs3.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!cs4.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!cs5.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!cs6.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!cs7.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!d3.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!d4.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!d5.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!d6.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!d7.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!ds3.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!ds4.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!ds5.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!ds6.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!ds7.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}    if (!e3.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!e4.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!e5.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!e6.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!e7.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!f3.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!f4.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!f5.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!f6.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!f7.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!fs3.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!fs4.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!fs5.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!fs6.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!fs7.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!g3.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!g4.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!g5.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!g6.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!g7.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!gs3.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!gs4.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!gs5.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!gs6.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!gs7.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if(!pauseBuffer.loadFromSamples(pauseraw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}}sf::Sound A3; sf::Sound A4;sf::Sound A5;sf::Sound A6;sf::Sound A7;sf::Sound AS3; sf::Sound AS4;sf::Sound AS5;sf::Sound AS6;sf::Sound AS7;sf::Sound B3; sf::Sound B4;sf::Sound B5;sf::Sound B6;sf::Sound B7;sf::Sound C3; sf::Sound C4;sf::Sound C5;sf::Sound C6;sf::Sound C7;sf::Sound CS3; sf::Sound CS4;sf::Sound CS5;sf::Sound CS6;sf::Sound CS7;sf::Sound D3; sf::Sound D4;sf::Sound D5;sf::Sound D6;sf::Sound D7;sf::Sound DS3; sf::Sound DS4;sf::Sound DS5;sf::Sound DS6;sf::Sound DS7;sf::Sound E3; sf::Sound E4;sf::Sound E5;sf::Sound E6;sf::Sound E7;sf::Sound F3; sf::Sound F4;sf::Sound F5;sf::Sound F6;sf::Sound F7;sf::Sound FS3; sf::Sound FS4;sf::Sound FS5;sf::Sound FS6;sf::Sound FS7;sf::Sound G3; sf::Sound G4;sf::Sound G5;sf::Sound G6;sf::Sound G7;sf::Sound GS3; sf::Sound GS4;sf::Sound GS5;sf::Sound GS6;sf::Sound GS7;sf::Sound pause;void set3(){A3.setBuffer(a3);A3.setLoop(true);A4.setBuffer(a4);A4.setLoop(true);A5.setBuffer(a5);A5.setLoop(true);A6.setBuffer(a6);A6.setLoop(true);A7.setBuffer(a7);A7.setLoop(true);AS3.setBuffer(as3);AS3.setLoop(true);AS4.setBuffer(as4);AS4.setLoop(true);AS5.setBuffer(as5);AS5.setLoop(true);AS6.setBuffer(as6);AS6.setLoop(true);AS7.setBuffer(as7);AS7.setLoop(true);B3.setBuffer(b3);B3.setLoop(true);B4.setBuffer(b4);B4.setLoop(true);B5.setBuffer(b5);B5.setLoop(true);B6.setBuffer(b6);B6.setLoop(true);B7.setBuffer(b7);B7.setLoop(true);C3.setBuffer(c3);C3.setLoop(true);C4.setBuffer(c4);C4.setLoop(true);C5.setBuffer(c5);C5.setLoop(true);C6.setBuffer(c6);C6.setLoop(true);C7.setBuffer(c7);C7.setLoop(true);D3.setBuffer(d3);D3.setLoop(true);D4.setBuffer(d4);D4.setLoop(true);D5.setBuffer(d5);D5.setLoop(true);D6.setBuffer(d6);D6.setLoop(true);D7.setBuffer(d7);D7.setLoop(true);DS3.setBuffer(ds3);DS3.setLoop(true);DS4.setBuffer(ds4);DS4.setLoop(true);DS5.setBuffer(ds5);DS5.setLoop(true);DS6.setBuffer(ds6);DS6.setLoop(true);DS7.setBuffer(ds7);DS7.setLoop(true);E3.setBuffer(e3);E3.setLoop(true);E4.setBuffer(e4);E4.setLoop(true);E5.setBuffer(e5);E5.setLoop(true);E6.setBuffer(e6);E6.setLoop(true);E7.setBuffer(e7);E7.setLoop(true);F3.setBuffer(f3);F3.setLoop(true);F4.setBuffer(f4);F4.setLoop(true);F5.setBuffer(f5);F5.setLoop(true);F6.setBuffer(f6);F6.setLoop(true);F7.setBuffer(f7);F7.setLoop(true);FS3.setBuffer(fs3);FS3.setLoop(true);FS4.setBuffer(fs4);FS4.setLoop(true);FS5.setBuffer(fs5);FS5.setLoop(true);FS6.setBuffer(fs6);FS6.setLoop(true);FS7.setBuffer(fs7);FS7.setLoop(true);G3.setBuffer(g3);G3.setLoop(true);G4.setBuffer(g4);G4.setLoop(true);G5.setBuffer(g5);G5.setLoop(true);G6.setBuffer(g6);G6.setLoop(true);G7.setBuffer(g7);G7.setLoop(true);GS3.setBuffer(gs3);GS3.setLoop(true);GS4.setBuffer(gs4);GS4.setLoop(true);GS5.setBuffer(gs5);GS5.setLoop(true);GS6.setBuffer(gs6);GS6.setLoop(true);GS7.setBuffer(gs7);GS7.setLoop(true);pause.setBuffer(pauseBuffer);pause.setLoop(true);}sf::Sound* naturalNotePtrs[7][5] = {{&A3,&A4,&A5,&A6,&A7}, {&B3,&B4,&B5,&B6,&B7}, {&C3,&C4,&C5,&C6,&C7}, {&D3,&D4,&D5,&D6,&D7}, {&E3,&E4,&E5,&E6,&E7}, {&F3,&F4,&F5,&F6,&F7}, {&G3,&G4,&G5,&G6,&G7}};sf::Sound* sharpNotePtrs[5][5]={   {&AS3,&AS4,&AS5,&AS6,&AS7}, {&CS3,&CS4,&CS5,&CS6,&CS7},  {&DS3,&DS4,&DS5,&DS6,&DS7},{&FS3,&FS4,&FS5,&FS6,&FS7},{&GS3,&GS4,&GS5,&GS6,&GS7}};sf::Sound getNote(char value, int octave, bool sharp){if (value =='p' || value=='P'){return A4;}if(sharp){switch(value){case 'a':return (*sharpNotePtrs[0][octave-3]);break;case 'c':return (*sharpNotePtrs[1][octave-3]);break;case 'd':return *sharpNotePtrs[2][octave-3];break;case 'f':return *sharpNotePtrs[3][octave-3];break;case 'g':return *sharpNotePtrs[4][octave-3];break;default:std::cerr<<"Invalid sharp\n";}}else {return *naturalNotePtrs[value-97][octave-3];}}void playNote(float duration,int bpm, char value, int octave, bool sharp) {sf::Clock clock;sf::Time time;sf::Sound sound;sound = getNote(value, octave,sharp);double beats=4/duration;double bps = bpm/60.;double trueTimeSecs = beats/bps;int sleepTime =trueTimeSecs*1000+1;while(1) {if(value!='p' && value!= 'P') {sound.play();}sf::sleep(sf::milliseconds(sleepTime));time = clock.getElapsedTime();if(time.asSeconds()>trueTimeSecs){sound.stop();clock.restart();break;}}}}char upperToLower(char input) {if(input>='A'&&input<='Z') {return input+32;}else {return input;}}int main(){using namespace std;using namespace N;using namespace sf;set1();set2();set3();bool delFile=false;ifstream test("x.rtttl"); if(test.good()) {cout<<"no input necessary, 'x.rtttl' already exists and will be read, as is.\n";}else {ofstream outf("x.rtttl");string in;cout<<"Please enter your rtttl file manually, in one line:\n";getline(cin,in);outf<<in<<endl;outf.close();delFile=true;}ifstream song("x.rtttl");song.seekg(0,ios::beg);float duration=0.;int octave=4;int bpm=0;float noteDuration =0.;int noteOctave =0;char noteValue='a';bool sharp = false;bool readIntro = false;bool readData = false;char c;std::cout<< "Now Playing: ";while(song){song>>c;if(c==':'&& !readIntro){readIntro=true;}else if (c==':') { readIntro=false; readData=true;}if(!readIntro && !readData){std::cout<<c;}c=upperToLower(c);if(readIntro) {if(c=='d') {song>>c;c=upperToLower(c);song>>c;c=upperToLower(c);duration = c-48;}if(c=='o'){song>>c;c=upperToLower(c);song>>c;c=upperToLower(c);octave = c-48;}if(c=='b') {song>>c;c=upperToLower(c);song>>c;c=upperToLower(c);int steps=0;while(c!=':'&&steps<5) {song>>c;steps++;}song.seekg(-steps-1, ios::cur);song>>c;c=upperToLower(c);if(steps==3) {bpm+=100*(c-48);song>>c;bpm+=10*(c-48);song>>c;bpm+=c-48;}if(steps==2){bpm+=10*(c-48);song>>c;bpm+=(c-48);}}}else if (readData){if(c<='9' && c>='0') {switch(c){case '1': song>>c;if(c=='6'){ noteDuration=16.;}else {noteDuration = 1.;}break;case '2': noteDuration = 2.;break;case '4':noteDuration = 4.;break;case'8':noteDuration =8.; break;case '3':noteDuration = 32.; song>>c; break;default:cerr<<"\nBad Duration:"<<c;return 1;}song>>c;c=upperToLower(c);noteValue = c;song>>c;c=upperToLower(c);if(c=='#'){sharp = true;song>>c;c=upperToLower(c);}else {sharp =false;}if(c<='9' && c>= '0' ) { noteOctave = c-48;song>>c;c=upperToLower(c); }else {noteOctave = octave;}if(c=='.'){noteDuration*=1.5; song>>c;c=upperToLower(c);}playNote(noteDuration,bpm, noteValue, noteOctave,sharp);}else if(c<='z' && c>='a') {noteDuration = duration;noteValue = c;song>>c;c=upperToLower(c);if(c=='#') { sharp = true;song>>c;c=upperToLower(c);}else {sharp =false;}if(c<='9' && c>= '0' ) { noteOctave = c-48;song>>c;c=upperToLower(c); }else {noteOctave = octave;}if(c=='.') { noteDuration*=1.5; song>>c;c=upperToLower(c);}playNote(noteDuration,bpm, noteValue, noteOctave,sharp);}}}if(delFile) {song.close();remove("x.rtttl");}return 0;}

```

I unfortunately I cannot include both the golfed and ungolfed code (space constraints), and the code could be golfed further.

A large part of the reason that the file is so long is that it has to create every pitch (12 notes * 5 octaves) individually using sine waves.

**Compiling** I compiled using the dev cmd prompt for visual studio, but it is very similar with g++ on Linux.

```
cl music.cpp /I SFML\SFML-2.3.1\include /link SFML\SFML-2.3.1\lib\sfml-system.lib SFML\SFML-2.3.1\lib\sfml-audio.lib

```

You just need to link things properly.

credit to SFML and this post for the idea.

I think the timings are correct, let me know if they are not.

**Give it a listen**

Here (Link to DropBox) is a screen recording of it playing a quick rendition of the Morrowind Theme that I whipped up. Note that in the video it doesn't ask for input because the file already exists.

```
MorrowindTheme: d=4,o=4,b=100: 8a, 8b, 2c, 8c, 8d, 2e, 8e, 8g, 2d, 16e, 16d, 8c, 8b, a, p,  8a, 8b, 2c, 8c, 8d, 2e, 8e, 8g, 2a5, g, 8b5, a5, 8a5, 8b5, c5, b5, a5, g, f, e, 2d, c, 8e, 2d, 8c, 8b, 1a

```
> 1 votes

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


title: Energy levels of electrons

text:
# Question
Title: Energy levels of electrons
## **Energy levels of electrons**

Electrons are ordered into "shells". However, sometimes electrons get excited, for example by heat, and leave their shell to go to another! These electrons will go back at some point, but they cannot go back to their original shell without emitting energy in the form of radio waves.

For example, the energy levels for hydrogen look like this:

The base energy level of an electron in hydrogen is at `n = 1`. If it gets 'excited', it might go to `n = 4`. However, on the way back, the electron does not always simply go from `n = 4` to `n = 1`, it has different options. See the example.

## **Task**

Write a program or function that takes an integer and outputs the amount of options the electron has to get back to its un-excited state. For this task, you can take granted that an electron can only emit energy from its excited state. It will not get more energy once it has been excited.

This is , the answer with the least amount of bytes wins.

If you are interested in these type of questions, check out this similar question. Also check out this for more info on these matters.

## **Input**

The input of your function/program is a whole integer. It is greater than `0` and less than 2^31.

## **Output**

An integer, the amount of options the electron has to return to its original state, which is `n = 1` (for hydrogen). When the input is 1, return 0, as it is already in its original energy level.

## **Examples**

```
Input: 4
Output: 4

```

Because the options are:

```
4 -> 3 -> 2 -> 1
4 -> 3 -> 1
4 -> 2 -> 1
4 -> 1

```

Visualised:

# Answer
# Pyth, 5 bytes

```
/^2Q4

```

I integer-divide by 4 instead of subtracting two from the power and flooring.
> 8 votes

# Answer
# CJam, ~~6~~ ~~8~~ 7 bytes

```
1li2-m<

```

Try it online

Unless I completely misunderstood the question, the result is simply 2^(n-2). For each level between n and 1, you can either skip or not skip it on the way back.

Using the left shift operator instead of the power operator is one byte more, but gives the specified result 0 for n=1, while the power operator gives 0.5 for that case.

Explanation:

```
1     Push 1 for later shift operator.
li    Get input and convert to int.
2-    Subtract 2.
m<    Left-shift 1 by (n-2).

```

If I shamelessly stole Thomas Kwa's approach, this would be 6 bytes in CJam:

```
2li#4/

```
> 7 votes

# Answer
# Dyalog APL, 6 bytes

```
⌊2*-∘2

```

This is a monadic function train. It is equivalent to the following, trainless function.

```
{⌊2*⍵-2}

```

Try it online on TryAPL.

### How it works

```
   -∘2  Take the right argument and subtract 2.
 2*     Elevate 2 to the difference.
⌊       Round down to the nearest integer.

```
> 4 votes

# Answer
# JavaScript ES7, ~~12~~ 11 bytes

```
i=>2**(i-2)

```

Defines an anonymous function.
> 3 votes

# Answer
## Python, ~~29~~ ~~22~~ 16 bytes

```
lambda n:2**n//4

```

Technique shamelessly stolen from Thomas's answer. Try it online
> 1 votes

# Answer
# Stuck, 6 bytes

```
2i2-^)

```

Hey look I ~~almost outgolfed Pyth~~ outgolfed CJam
> 1 votes

# Answer
# dc, 6

```
2?^4/p

```

Algorithm expertly lifted from other correct answers.

### Testcases:

```
$ for t in 1 4; do dc -e'2?^4/p' <<< $t; done
0
4
$

```
> 1 votes

# Answer
# Julia, 9 bytes

```
n->2^n÷4

```

Like several other answers, this uses Thomas's approach. `÷` performs integer division in Julia (but unfortunately is 2 bytes in UTF-8).
> 1 votes

# Answer
# PHP, 28 bytes

I hope I got it right. `floor` handles the case for `1` where it should output `0`

```
<?=floor(pow(2,$argv[1]-2));

```

Works from command line like:

```
electrons.php 4

```

<sub>+1 and thanks to Reto Koradi for providing the formula. ;)</sub>
> 0 votes

# Answer
## Minkolang 0.9, 7 bytes

Copying Thomas like everyone else...

```
2n;4:N.

```

This is a full program, and the first five characters are equivalent to `2**n//4` in Python 3. Try it online.
> 0 votes

---
Tags: code-golf, chemistry
---


# Question
Title: Implement an API for probability distributions
# Introduction

In this challenge, your task is to implement a collection of simple functions that together form a usable mini-library for simple probability distributions. To accommodate some of the more esoteric languages people like to use here, the following implementations are acceptable:

1. A code snippet defining a collection of named functions (or closest equivalents).
2. A collection of expressions that evaluate to named or anonymous functions (or closest equivalents).
3. A single expression that evaluates to several named or anonymous functions (or closest equivalents).
4. A collection of independent programs that take inputs from command line, STDIN or closest equivalent, and output to STDOUT or closest equivalent.

# The functions

You shall implement the following functions, using shorter names if desired.

1. `uniform` takes as input two floating point numbers `a` and `b`, and returns the uniform distribution on `[a,b]`. You can assume that `a < b`; the case `a ≥ b` is undefined.
2. `blend` takes as inputs three probability distributions `P`, `Q` and `R`. It returns a probability distribution `S`, which draws values `x`, `y` and `z` from `P`, `Q` and `R`, respectively, and yields `y` if `x ≥ 0`, and `z` if `x < 0`.
3. `over` takes as input a floating point number `f` and a probability distribution `P`, and returns the probability that `x ≥ f` holds for a random number `x` drawn from `P`.

For reference, `over` can be defined as follows (in pseudocode):

```
over(f, uniform(a, b)):
    if f <= a: return 1.0
    else if f >= b: return 0.0
    else: return (b - f)/(b - a)

over(f, blend(P, Q, R)):
    p = over(0.0, P)
    return p*over(f, Q) + (1-p)*over(f, R)

```

You can assume that all probability distributions given to `over` are constructed using `uniform` and `blend`, and that the only thing a user is going to do with a probability distribution is to feed it to `blend` or `over`. You can use any convenient datatype to represent the distributions: lists of numbers, strings, custom objects, etc. The only important thing is that the API works correctly. Also, your implementation *must* be deterministic, in the sense of always returning the same output for the same inputs.

## Test cases

Your output values should be correct to at least two digits after the decimal point on these test cases.

```
over(4.356, uniform(-4.873, 2.441)) -> 0.0
over(2.226, uniform(-1.922, 2.664)) -> 0.09550806803314438
over(-4.353, uniform(-7.929, -0.823)) -> 0.49676329862088375
over(-2.491, uniform(-0.340, 6.453)) -> 1.0
over(0.738, blend(uniform(-5.233, 3.384), uniform(2.767, 8.329), uniform(-2.769, 6.497))) -> 0.7701533851999125
over(-3.577, blend(uniform(-3.159, 0.070), blend(blend(uniform(-4.996, 4.851), uniform(-7.516, 1.455), uniform(-0.931, 7.292)), blend(uniform(-5.437, -0.738), uniform(-8.272, -2.316), uniform(-3.225, 1.201)), uniform(3.097, 6.792)), uniform(-8.215, 0.817))) -> 0.4976245638164541
over(3.243, blend(blend(uniform(-4.909, 2.003), uniform(-4.158, 4.622), blend(uniform(0.572, 5.874), uniform(-0.573, 4.716), blend(uniform(-5.279, 3.702), uniform(-6.564, 1.373), uniform(-6.585, 2.802)))), uniform(-3.148, 2.015), blend(uniform(-6.235, -5.629), uniform(-4.647, -1.056), uniform(-0.384, 2.050)))) -> 0.0
over(-3.020, blend(blend(uniform(-0.080, 6.148), blend(uniform(1.691, 6.439), uniform(-7.086, 2.158), uniform(3.423, 6.773)), uniform(-1.780, 2.381)), blend(uniform(-1.754, 1.943), uniform(-0.046, 6.327), blend(uniform(-6.667, 2.543), uniform(0.656, 7.903), blend(uniform(-8.673, 3.639), uniform(-7.606, 1.435), uniform(-5.138, -2.409)))), uniform(-8.008, -0.317))) -> 0.4487803553043079

```

# Answer
> 1 votes
# CJam, 58 bytes

```
{[\]}:U;
{[@]}:B;
{_,2={~1$-@@-\/0e>1e<}{6Yb@f*\.{O})[_1@-].*:+}?}:O;

```

These are postfix operators that work on the stack: `2.0 1.0 3.0 U O` is `over(2, uniform(1, 3))`.

### Score count

`{[\]}` is the function itself, `:U;` assigns it to the name `U` and pops it. Essentially this isn't part of the function, so by score counting rule 2, I'd only have to count `{[\]}`. `B` is defined similarly.

However, `O` is recursive, and if I don't specify a name, there's no way to recurse. So here, I'd be inclined to count the `:O;` part. Then my score is `5+5+48=58` bytes in total.

### Explanation

`U` pops two arguments and makes a pair in reverse order: `a b => [b a]`.

`B` pops three arguments and makes a triple in rotated order: `a b c => [b c a]`.

`O`'s structure is as follows:

```
{             }:O;   Define O as this function:
 _,2=        ?       If the argument list's length is 2:
     {~Γ}            Append the list to the stack and execute subprogram Γ.
         {~Δ}        Else, do the same, but execute subprogram Δ.

```

Subprogram *Γ* handles uniform distributions:

```
Executed ops      Explanation   Stack contents
============      ===========   ==============
                  Initial       f; b; a
1$                Copy b        f; b; a; b
  -               Difference    f; b; (a-b)
   @@             Rotate x2     (a-b); f, b
     -            Difference    (a-b); (f-b)
      \/          Flip divide   (f-b)/(a-b)
        0e>       Clamp low     max(0, (f-b)/(a-b))
           1e<    Clamp high    min(1, max(0, (f-b)/(a-b)))

```

Subprogram *Δ* handles blended distributions:

```
Executed ops              Explanation    Stack contents
============              ===========    ==============
                          Initial        f; [Q R P]
6Yb                       Push [1,1,0]   f; [Q R P]; [1 1 0]
   @                      Rotate         [Q R P]; [1 1 0]; f
    f*                    Multiply each  [Q R P]; [f f 0]
      \                   Swap           [f f 0]; [Q R P]
       .{O}               Pairwise O     [q r p]
           )              Uncons         [q r] p
            [_1@-]        [p, 1-p]       [q r] [p 1-p]
                  .*:+    Dot product    q*p+r*(1-p)

```

# Answer
> 2 votes
# Ruby, 103

```
u=b=->*a{a}
o=->f,d{d[2]?(p=o[0,d[0]])*o[f,d[1]]+(1-p)*o[f,d[2]]:(f<a=d[0])?1:(f>b=d[1])?0:(b-f)/(b-a)}

```

Defines three lambdas, `u`, `b`, and `o`. `u` and `b` just create two-element and three-element arrays respectively. `o` assumes a two-element array is a uniform distribution and a three-element one is a blend of three distributions. In the latter case it calls itself recursively.

# Answer
> 2 votes
# MATLAB, 73

Time for a little "functional programming" in MATLAB. These are 3 anonymous functions. Uniform and blend are called the same way as the examples, but for `over` the arguments should be swapped. I don't really need an `over` since the first two return functions, but as a formality `feval` is a function that can call a function.

```
%uniform
@(a,b)@(x)(x<b)*min(1,(b-x)/(b-a))
%blend
@(P,Q,R)@(x)P(0)*(Q(x)-R(x))+R(x)
%over
@feval

```

Now MATLAB's parsing and evaluation system is a little wonky to say the least. It doesn't allow you to directly call a function that was returned from a function. Instead, one must first save the result to a variable. The 4th example could be done as follows:

```
x=uniform(-5.233,3.384);y=uniform(2.767,8.329);z=uniform(-2.769,6.497);over(blend(x,y,z),0.738)

```

However, it is possible to get around this by using `feval` to call all the functions. If the following definitions are used, then the examples can be evaluated exactly as they are written.

```
uniform=@(a,b)@(x)(x<b)*min(1,(b-x)/(b-a))
blend=@(P,Q,R)@(x)feval(P,0)*(feval(Q,x)-feval(R,x))+feval(R,x)
over=@(x,f)feval(f,x)

```

# Answer
> 1 votes
# Mathematica, ~~129~~ 116 bytes

```
u=UniformDistribution@{##}&;b=If[x<0,z,y]~TransformedDistribution~{x\uF3D2#,y\uF3D2#2,z\uF3D2#3}&;o=Probability[x>=#,x\uF3D2#2]&

```

`u`, `b` and `o` are `uniform`, `blend`, and `over` respectively.Wrapper over the standard functions. Replace the `\uF3D2`s with the 3-byte character. Just returns `0` and `1` for cases 1, 4, and 7.

# Answer
> 1 votes
## Python, 146 bytes

```
u=lambda*a:a
b=u
x=lambda f,a,b:[int(f<=a),(b-f)/(b-a)][a<f<b]
y=lambda f,p,q,r:o(0,p)*o(f,q)+(1-o(0,p))*o(f,r)
o=lambda f,p:[x,y][len(p)-2](f,*p)

```

Same strategy as histocrat's Ruby answer, but in Python. To do recursion without a Z-combinator (which would be costly), `x` and `y` are defined as helper functions that evaluate `over` for 2- and 3-length argument tuples (`uniform` and `blend` arguments, respectively).

Test cases on ideone

# Answer
> 0 votes
# Matlab, 104 bytes

I hope this is still valid, as this only works for distributions with support in \[-10,10\] which is the requirement for languages that have no floating point support. The support vector and the accuracy can be easily adjusted by just altering corresponding numbers. `u,o,b` is for `uniform,blend,over`. The pdf is just represented as a discrete vector. I think this approach can easily be transferred to other languages.

```
D=1e-4;X=-10:D:10;
u=@(a,b)(1/(b-a))*(a<X&X<b);
o=@(x,d)sum(d.*(X>x))*D;
b=@(p,q,r)o(0,p).*q+(1-o(0,p)).*r;

```

You can test them if you define those functions first and then just paste this code:

```
[o(4.356, u(-4.873, 2.441)) , 0.0;
o(2.226, u(-1.922, 2.664)) , 0.09550806803314438;
o(-4.353, u(-7.929, -0.823)) , 0.49676329862088375;
o(-2.491, u(-0.340, 6.453)) , 1.0;
o(0.738, b(u(-5.233, 3.384), u(2.767, 8.329), u(-2.769, 6.497))) , 0.7701533851999125;
o(-3.577, b(u(-3.159, 0.070), b(b(u(-4.996, 4.851), u(-7.516, 1.455), u(-0.931, 7.292)), b(u(-5.437, -0.738), u(-8.272, -2.316), u(-3.225, 1.201)), u(3.097, 6.792)), u(-8.215, 0.817))) , 0.4976245638164541;
o(3.243, b(b(u(-4.909, 2.003), u(-4.158, 4.622), b(u(0.572, 5.874), u(-0.573, 4.716), b(u(-5.279, 3.702), u(-6.564, 1.373), u(-6.585, 2.802)))), u(-3.148, 2.015), b(u(-6.235, -5.629), u(-4.647, -1.056), u(-0.384, 2.050)))) , 0.0;
o(-3.020, b(b(u(-0.080, 6.148), b(u(1.691, 6.439), u(-7.086, 2.158), u(3.423, 6.773)), u(-1.780, 2.381)), b(u(-1.754, 1.943), u(-0.046, 6.327), b(u(-6.667, 2.543), u(0.656, 7.903), b(u(-8.673, 3.639), u(-7.606, 1.435), u(-5.138, -2.409)))), u(-8.008, -0.317))) , 0.4487803553043079]

```

---
Tags: code-golf, probability-theory
---


title: Ridiculous Runtime Errors

text:
# Question
Title: Ridiculous Runtime Errors
Write programs that produce crazy, obscure, ridiculous, or just plain nutty runtime errors. Obfuscation and golfitude (shortness) not required.

* solutions that look like they should work fine are better.
* solutions that look like they should break one way but break another are better.
* solutions that are nondeterministic are better as long as they are reproducible sometimes.
* solutions with long distance between error cause and manifestation are better.
* bonus points for producing errors that should be impossible.
* bonus points for errors that crash the runtime (like making python segment fault) or operating system.

The unit of score shall be upvotes.

**Addendum 1**

Compiler misbehaviors are fine too.

# Answer
The obligatory PHP one (which *still* hasn't been fixed as of 5.4):

```
<?::

```

Outputs:

```
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM on line 1
```

Whaa?
> 71 votes

# Answer
Gcc compile error:

```
int main()
{
        long long long a;
}

```

error: long long long is too long for GCC
> 62 votes

# Answer
## Windows Command Prompt

```
If you're happy and you know it clap your hands!

```

Output:

> happy was unexpected at this time.
> 53 votes

# Answer
# PHP

```
$ cat error.php
<?php
function echo_string(string $string) {
    echo $string;
}
echo_string("Hello, world!");
$ php error.php
PHP Catchable fatal error:  Argument 1 passed to echo_string() must be an instance of string, string given, called in error.php on line 5 and defined in error.php on line 2

```

You cannot pass a string to a function, you have to pass a string instead!

**Update:** This code is NOT an error in PHP 7. Hover on/click/touch a spoiler to check why (contains spoilers about how the code works).

> A new feature known as scalar type declarations was added in PHP 7. This feature allows using scalar types in function declarations.
> 42 votes

# Answer
# bash

```
$ echo "Hello, world!"
bash: !": event not found

```

And you would think that bash would accept a simple "Hello, world!" program.
> 34 votes

# Answer
# Python 2.7

```
# Look I'm actually coding: see my happy face?
print ':)'

```

Generates the rather unhelpful:

```
SyntaxError: encoding problem: with BOM

```

How can a simple comment generate an error?
> 32 votes

# Answer
## Mathematica

When using Mathematica to create graphical output, one sometimes triggers error messages formatted according to specifications being used in the program itself. Here is a trivial example.

```
Rotate[f/0, .6]

```
> 30 votes

# Answer
## TI-89 Graphing Calculator

I discovered this when learning about implicit differentiation in high school calculus. If you input:

```
d(xy+x=0,x)

```

You get the following:

```
1 = 0

```

With this caveat, printed in tiny letters at the bottom of the screen:

```
Warning: May produce false equation

```

This happens because `xy` is not interpreted as `x * y`, but rather as its own symbol, `xy`.

Oddly, if you do `d(xy=0,x)`, you get `0 = 0` with the same warning.
> 26 votes

# Answer
You can make the Haskell compiler's brain explode:

```
C:\Windows\system32>ghci
...
Prelude> :set -XExistentialQuantification
Prelude> data Foo = forall a. Foo a
Prelude> let foo f = 1 where Foo a = f

<interactive>:4:21:
    My brain just exploded
    I can't handle pattern bindings for existential or GADT data constructors.
    Instead, use a case-expression, or do-notation, to unpack the constructor.
    In the pattern: Foo a
    In a pattern binding: Foo a = f
    In an equation for `foo':
        foo f
          = 1
          where
              Foo a = f
Prelude>

```
> 24 votes

# Answer
## Ruby

Rules abuse.

```
class StandardError

  def to_s
    words = File.open('/usr/share/dict/words'){|f|f.readlines.map &:chop}.sample(100)
    words.last.capitalize!
    super.gsub(/\w+/){words.pop}
  end

  to_s(3)

end

```

If run on OSX, produces, e.g.

```
$ ruby weird_runtime_error.rb
weird_runtime_error.rb:9:in `to_s': Sculpturation contingence explicate tappet(phonendoscope ethopoeia nannandrous) (ArgumentError)
    from weird_runtime_error.rb:9:in `<class:StandardError>'
    from weird_runtime_error.rb:1:in `<main>'

```
> 24 votes

# Answer
**DOS Prompt**

```
c:\>make love

```

gives you

```
Fatal Error: 'love' does not exist. Don't know how to make it.

```

Stumbled upon this while I was trying to insult my computer for being uncooperative. Made me kinda sad for a while until I found out, that this only happens if love does not exist. If it exists he will gladly make it.
> 21 votes

# Answer
# Bash (Quine error)

This error is a Quine in Bash!

```
$ bash: bash:: command not found...
bash: bash:: command not found...

```

Of course you must have the relevant `locale` (english here).
> 17 votes

# Answer
# CSH

A really classical `csh` joke:

```
% make fire?
make: No match.

```
> 17 votes

# Answer
# Bash - accurate recreation of a rare historical error message

```
echo -ne $(tail -n +257 /usr/src/linux*/drivers/char/lp.c | head -1 | cut -d '"' -f 2 | sed 's/%d/0/')

```

Output:

```
lp0 on fire

```

Requires the linux kernel source to be unpacked in the usual place.

Fun fact: i once received this message in earnest, when running an old ribbon printer.
> 15 votes

# Answer
## Ruby

Feel like it's weird that this can happen in a high-level language.

```
$*<<$*<<$**$/

```

produces

```
ArgumentError: recursive array join

```
> 13 votes

# Answer
## C(++)

If compile-time errors count here's one (assuming a file named "crash.c").

```
#include "crash.c"

int main(){ return 0; }

```

It fills the screen with this upon compilation (have Ctrl-C ready)

```
                 from crash.c:1,
                 from crash.c:1:
crash.c:3:1: error: redefinition of ‘main’
crash.c:3:1: note: previous definition of ‘main’ was here
In file included from crash.c:1:0,
                 from crash.c:1,
                 from crash.c:1,

```

Another snippet which compiles perfectly well (no warnings under `-Wall` and illustrates the beautiful type safety of C \</s\>

```
#include <stdio.h>
int i;

int main(){
  sprintf(NULL, "%s", (char *) (void *) (1/i));
  return 0;
}

```

Running it gives:

```
Floating point exception (core dumped)

```
> 12 votes

# Answer
This is very old, but for those who remember BCPL,

```
GET "LIBHDR"

LET START() = VALOF
$8
        RESULTIS 0
$)

```

would complain

```
$8
 ^
"( ) or 8 expected"

```
> 11 votes

# Answer
# R

This is technically not an error but a warning but nevertheless it's ridiculous, and occurs for completely esoteric reasons.

\[\[EDIT\]\] It seems that the cause of some parts of the funny warnings resides in RStudio rather than R per se, so it's less interesting than I first thought. The first example i.e `plot(1:2, NotAGraphicalParameter = "ignore.me")` is, however, still reproducible in "naked" R and is funny enough on its own right.\[\[/EDIT\]\]

```
> plot(1:2, NotAGraphicalParameter = "ignore.me")
# produces a nice scatterplot with two points, [1,1] and [2,2]
Warning messages:
1: In plot.window(...) :
  "NotAGraphicalParameter" is not a graphical parameter
2: In plot.xy(xy, type, ...) :
  "NotAGraphicalParameter" is not a graphical parameter
3: In axis(side = side, at = at, labels = labels, ...) :
  "NotAGraphicalParameter" is not a graphical parameter
4: In axis(side = side, at = at, labels = labels, ...) :
  "NotAGraphicalParameter" is not a graphical parameter
5: In box(...) : "NotAGraphicalParameter" is not a graphical parameter
6: In title(...) : "NotAGraphicalParameter" is not a graphical parameter
> plot(2:3)
# another nice scatterplot: [2,2] and [3,3]
# but there should be nothing wrong this time!
# however ...
There were 12 warnings (use warnings() to see them)
> warnings()
Warning messages:
1: "NotAGraphicalParameter" is not a graphical parameter
2: "NotAGraphicalParameter" is not a graphical parameter
3: "NotAGraphicalParameter" is not a graphical parameter
4: "NotAGraphicalParameter" is not a graphical parameter
5: "NotAGraphicalParameter" is not a graphical parameter
6: "NotAGraphicalParameter" is not a graphical parameter
7: "NotAGraphicalParameter" is not a graphical parameter
8: "NotAGraphicalParameter" is not a graphical parameter
9: "NotAGraphicalParameter" is not a graphical parameter
10: "NotAGraphicalParameter" is not a graphical parameter
11: "NotAGraphicalParameter" is not a graphical parameter
12: "NotAGraphicalParameter" is not a graphical parameter
# but let's try once more:
> plot(2:3)
# yup. no warnings this time. we had to do it twice

```

It's like R remembers our insults. But not for long.

I can't really explain why this happens - but it is reproducible. Actually it occurs every time when you supply some "not a graphical parameter" to plot 1, and then do a plot 2 in a completely impeccable way. It is especially funny that we get 12 "not a graphical parameter" warnings for the second plot but only 6 for the first one. Another funny thing is that if you supply "not a graphical parameter" with a value NULL then no condition is thrown:

```
plot(1:2, Nonsense=NULL)
# no warnings
# however
plot(1:2, Nonsense="gibberish")
# gives the usual 6-pack of warnings

```

And to get even more ridiculous, let's draw some lines on top of the previously drawn plot:

```
plot(1:2)
# you will see the number of warnings growing with each line:
lines(1:2, 1:2, mumbo = 1)
lines(1:2, 1:2, jumbo = 2)
lines(1:2, 1:2, bimbo = 3)
lines(1:2, 1:2, cucaracha = 4)
lines(1:2, 1:2, karaoke = 5)
lines(1:2, 1:2, radiogaga = 6)
lines(1:2, 1:2, reptiles = 7)
lines(1:2, 1:2, cowsonmoon = 8)
lines(1:2, 1:2, stainlessSteelLadderToTheMoon = 9)
lines(1:2, 1:2, frambuesa = 10)
lines(1:2, 1:2, fresa = 11)
lines(1:2, 1:2, limonYNada = 12)
lines(1:2, 1:2, slingsAndArrows = 13)
# ... and now you have 25 warnings:
warnings()

Warning messages:
1: "mumbo" is not a graphical parameter
2: "jumbo" is not a graphical parameter
3: "bimbo" is not a graphical parameter
4: "cucaracha" is not a graphical parameter
5: "karaoke" is not a graphical parameter
6: "radiogaga" is not a graphical parameter
7: "reptiles" is not a graphical parameter
8: "cowsonmoon" is not a graphical parameter
9: "stainlessSteelLadderToTheMoon" is not a graphical parameter
10: "frambuesa" is not a graphical parameter
11: "fresa" is not a graphical parameter
12: "limonYNada" is not a graphical parameter
13: "mumbo" is not a graphical parameter
14: "jumbo" is not a graphical parameter
15: "bimbo" is not a graphical parameter
16: "cucaracha" is not a graphical parameter
17: "karaoke" is not a graphical parameter
18: "radiogaga" is not a graphical parameter
19: "reptiles" is not a graphical parameter
20: "cowsonmoon" is not a graphical parameter
21: "stainlessSteelLadderToTheMoon" is not a graphical parameter
22: "frambuesa" is not a graphical parameter
23: "fresa" is not a graphical parameter
24: "limonYNada" is not a graphical parameter
25: In plot.xy(xy.coords(x, y), type = type, ...) :
  "slingsAndArrows" is not a graphical parameter

```

~~This should~~ not ~~win big time unless there is no justice.~~
> 10 votes

# Answer
## Windows Command Script

*WARNING, this is a fork bomb!*

This will output garbage questions about quitting if you try to quit the console in any way.

```
%0|%0|%0

```

Bonuses:

* Will make the system pretty much unusable until restart
* Prevents quitting the script, which should be impossible
> 9 votes

# Answer
How about compiler optimisation errors:

```
#include <stdio.h>

#define N 4

int main(void)
{
    int sum;
    int i;
    int arr[N];

    for (i = 0, sum = 0; i < N; i++, arr[i] = sum) {
        sum += arr[i];
    }
    printf("%d\n", sum);
    return 0;
}

```

This is specific to gcc \>= 4.7. Compiles and runs fine with `gcc -O0 -Wall`. Compiles with `gcc -O2 -Wall` but results in an inf-loop.

Also note, how gcc does see the problem for smaller `N`, e.g. `N = 3`:

```
test.c:11:38: warning: array subscript is above array bounds [-Warray-bounds]
  for (i = 0, sum = 0; i < N; i++, arr[i] = sum) {
                                       ^
test.c:12:13: warning: 'arr[0]' is used uninitialized in this function [-Wuninitialized]
  sum += arr[i];
         ^

```

Btw, this has been taken from a bug report, I can't recall the bug number though.
> 6 votes

# Answer
# insults you

```
q)`u#1 1
'u-fail
q)

```

> \`\`\`u#\`\` tells `q` that every element in a list is unique (so it can build some sort of hash-based index, presumably). this is what happens when it's not actually true.
> 6 votes

# Answer
I've always liked this weirdness in APL:

```
      ⍝ obviously a syntax error
      { (] } 3
SYNTAX ERROR
      {(]}3

      ⍝ but:
      { (] } 1÷0
DOMAIN ERROR
      {(]}1÷0

      ⍝ it even works with statically defined functions
      ∇z←f x
[1]  z←[{]}x
[2]  ∇
      f 1÷0
DOMAIN ERROR
      f 1÷0
     ∧
      f 3
SYNTAX ERROR
f[1] z←[{]}x

```

It parses the inside of functions lazily!
> 5 votes

# Answer
# Python

## Nested blocks

```
for a in range(26):
 for b in range(26):
  for c in range(26):
   for d in range(26):
    for e in range(26):
     for f in range(26):
      for g in range(26):
       for h in range(26):
        for i in range(26):
         for j in range(26):
          for k in range(26):
           for l in range(26):
            for m in range(26):
             for n in range(26):
              for o in range(26):
               for p in range(26):
                for q in range(26):
                 for r in range(26):
                  for s in range(26):
                   for t in range(26):
                    for u in range(26):
                     for v in range(26):
                      for w in range(26):
                       for x in range(26):
                        for y in range(26):
                         for z in range(26):
                          print a

```

Python 2.7: `SystemError: too many statically nested blocks`

## Self-referencing lists

```
def printList(myList):
    for element in myList:
        if isinstance(element, list):
            printList(myList)
        else:
            print(element)

a = []
a.append(a)
printList(a)

```

# Python 2.7

## True is not a constant

The problem in the following example is that in Python 2.7, `True` and `False` are not constants. And `True` and `False` can automatically get casted to `1` and `0`:

```
True=False
a=10/True

Traceback (most recent call last):
  File "/home/moose/.config/pluma/tools/new-tool-2", line 11, in <module>
    exec(sys.stdin.read())
  File "<string>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

```

# Python 2.7:

## Intendation

```
def f(n):
    if n <= 1:
        return n
    else:
        return f(n-1)+f(n-2)

```

Do you get the error?

```
Traceback (most recent call last):
  File "/home/moose/.config/pluma/tools/new-tool-2", line 11, in <module>
    exec(sys.stdin.read())
  File "<string>", line 4
    else:
       ^
SyntaxError: invalid syntax

```

Mixing tabs and spaces was ok in Python 2.7 ... but mind the indentation level!
> 5 votes

# Answer
# PHP

```
<?php
[][] = 42;

```

`[]` is used in order to push elements. However, if you use it for array literal, the PHP makes crazy error message, even if you assign to it in order to push. Requires PHP \>= 5.4, as before that you couldn't have indexed array literals.

Output:

> **Fatal error**: Cannot use \[\] for reading in **\[...\]\[...\]** on line **2**
> 4 votes

# Answer
I'll start:

```
#include <iostream>

using namespace std;

class A
{
public:
    A()
    {
    }

    void doSomethingDiabolical()
    {
        delete this;
    }

    virtual void breakHorribly()
    {
        cout << "still alive" << endl;
        doSomethingDiabolical();
        cout << "still alive" << endl;
    }
};

class B : public A
{
public:
    B() : A()
    {
    }

    void breakHorribly()
    {
        cout << "still alive" << endl;
        ((A *) this)->breakHorribly();
        cout << "still alive" << endl;
        doSomethingDiabolical();
        cout << "still alive" << endl;
        breakHorribly();
        cout << "dead" << endl;
    }
};

int main()
{
    jane();
}

void jane()
{
    cout << "still alive" << endl;
    A * o = new B;
    cout << "still alive" << endl;
    o->breakHorribly();
}

```

Any guesses why this program crashes? :D

See `jane` run: http://ideone.com/gtaZ3
> 3 votes

# Answer
## CPython

```
import ctypes
import sys
(ctypes.c_char * sys.getsizeof(None)).from_address(id(None))[:4] = '\x00' * 4

```

The result:

```
Fatal Python error: deallocating None

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

```
> 3 votes

# Answer
# Bash

I got this today when I tried to find out whether it is possible to protect the system from `rm -rf /`.

```
mkdir /tmp/a
mkdir /tmp/a/b
sudo mount --bind /tmp/a /tmp/a/b
rm -rf /tmp/a

```

The error message with `LANG=C`:

```
rm: WARNING: Circular directory structure.
This almost certainly means that you have a corrupted file system.
NOTIFY YOUR SYSTEM MANAGER.
The following directory is part of the cycle:
  '/tmp/a/b'

```
> 3 votes

# Answer
# TeX

This simple TeX program:

```
\def~{x~}~

```

gives the following error in the log file:

```
! TeX capacity exceeded, sorry [main memory size=5000000].
l.1 \def~{x~}~

If you really absolutely need more capacity,
you can ask a wizard to enlarge me.

```

You better know which wizard it the right wizard :-)

---

# TeX: second error message

This is a small LaTeX table with 260 columns, for which we want a cell that spans all the columns.

```
\documentclass{article}
\begin{document}
\begin{tabular}{*{260}{l}}
\multicolumn{260}{c}{Table Title}
\end{tabular}
\end{document}

```

The error message is also hilarious:

```
! This can't happen (256 spans).
<template> \endtemplate

l.5     \end{tabular}

I'm broken. Please show this to someone who can fix can fix

```

How many programs are humble enough to admit they are broken?
> 3 votes

# Answer
## C# - Recursive, lazy Fibonacci generator

```
static void Main()
{
    Console.WriteLine(string.Join(",", fib().Take(141)));
    Console.ReadLine();
}

static IEnumerable<decimal> fib(decimal n = 0, decimal m = 1)
{
    if (n == 0)
    {
        yield return 0;
        yield return 1;
    }
    while (true)
    {
        yield return n + m;
        foreach(var x in fib(m, n+m))
        {
            yield return x;
        }
    }
}

```

This code looks fine, right? A fairly simple Fibonacci generator, spiced up with some recursion and lazy enumeration. Should work.

Nope! Running this will cause an OverflowException. This is because we are using decimal, and the 141st Fibonacci number (~8.1E28) exceeds the maximum value of decimal (~7.9E28).

The int, however does not throw an OverflowException when you exceed its maximum value. Instead it, as expected, overflows to a negative value. So if we replace int instead with decimal, like in the following code, it should work, right?

```
static void Main()
{
    Console.WriteLine(string.Join(",", fib().Take(141)));
    Console.ReadLine();
}

static IEnumerable<int> fib(int n = 0, int m = 1)
{
    if (n == 0)
    {
        yield return 0;
        yield return 1;
    }
    while (true)
    {
        yield return n + m;
        foreach(var x in fib(m, n+m).ToList())
        {
            yield return x;
        }
    }
}

```

If you read the code it should be obvious why this won't work. If you didn't... I didn't just change the type from decimal to int; I also snuck in a call to ToList() in the foreach statement. This will force the enumerator returned to be eagerly evaluated. This will cause not 141 recursions, but instead an infinite number of recursions. Actually, long before it hits infinity it will of course overflow the stack, causing the runtime to throw a StackOverflowException. (bonus: this exception cannot be caught, so it will crash the runtime)
> 2 votes

# Answer
# R

Another one which is not ridiculous and, again, a warning rather than an error, but still nice:

```
> sapply(as.list(-1:-51), log)
 [1] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
[20] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
[39] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
There were 50 or more warnings (use warnings() to see the first 50)

```

I like the last bit: 50 or more :)

And the actual warnings:

```
1: In lapply(X = X, FUN = FUN, ...) : NaNs produced
2: In lapply(X = X, FUN = FUN, ...) : NaNs produced
....
50: In lapply(X = X, FUN = FUN, ...) : NaNs produced

```

FUN = FUN!
> 2 votes

# Answer
# Bash - counterintuitive escape failure

```
echo "this should definitely work!!!11!"

```

returns

```
-bash: !11: event not found

```

(history expansion on the commandline is not prevented by double quotes)

## Bonus:

```
echo "I don't know what's gone wrong!! !echo is usually pretty foolproof!-1"

```

The output is unlikely to be what's expected. Press **up** to get the command again, and notice it's changed from what you typed. If you press up and enter a couple of times, it's likely your output will begin to look somewhat horrific. Try it for yourself.
> 2 votes

# Answer
Not to compete but Burlesque is pretty easy to crash :D.

```
blsq ) rs
blsq: Burlesque/Eval.hs:(2900,3)-(2904,33): Non-exhaustive patterns in case

```

and there are literally dozens of these crashes still hanging around. It's just that nobody ever reports them so they won't be fixed anytime soon.
> 0 votes

---
Tags: popularity-contest
---


title: IT'S CAPS LOCK DAY

text:
# Question
Title: IT'S CAPS LOCK DAY
OCTOBER 22 IS INTERNATIONAL CAPS LOCK DAY! UNFORTUNATELY, SOME DO NOT RECOGNIZE THE GLORY OF THE ALMIGHTY CAPS LOCK. THEY SAY IT SEEMS "OBNOXIOUS" OR "LIKE SHOUTING" OR SOME NONSENSE. IN ORDER TO CONFORM TO THESE OBVIOUSLY ILLOGICAL AND INANE COMPLAINTS, PLEASE WRITE ME A PROGRAM THAT TURNS NORMAL TEXT INTO "SENSIBLE" OR "REASONABLE" TEXT TO MAKE PEOPLE STOP COMPLAINING.

## Description

The input and output for your solution will both be strings that contain only printable ASCII characters.

The input string will contain zero or more *caps lock runs*. A *caps lock run* (or CLR for short) is defined as the following:

* The CLR must contain no lowercase letters (`a-z`), *except* as the first character of a *word*.

+ A *word*, for the purposes of this challenge, is a sequence of non-spaces. So, `PPCG`, `correcthorsebatterystaple`, and `jkl#@_>00()@#__f-023\f[` are all considered *word*s.
* The CLR must also contain at least one space; hence, it must be at least two *word*s.
* Each of the *word*s in the CLR must contain at least two letters (`A-Za-z`).

+ Note that this refers to the CLR taken by itself, without any surrounding characters that may not have been included in the CLR. For example, `fo**O B**ar` is *not* a CLR because the string `O B` by itself has *word*s with less than two letters.

CLRs should be parsed "greedily"—that is, you should always find the longest CLRs possible.

Once you have identified all of the CLRs in the input string, swap the case of all letters inside of the CLRs and output the resulting string.

## Test cases

The first line is input, and the second is output. Bolded portions of the input are substrings that are considered CLRs.

```
**CAPS LOCK IS THE BEST!**
caps lock is the best!
```

```
I really **LOVE pROGRAMMING pUZZLES AND cO**de Golf!
I really love Programming Puzzles and Code Golf!
```

```
This is a challenge on PPCG. This is a test **CASE. TEST**
This is a challenge on PPCG. This is a test case. test
```

```
Lor**EM iPSUM DOL**oR sIT amet, conSECTETur ADIPISci**NG eLIT. MAECENAS iD** orci
Lorem Ipsum doloR sIT amet, conSECTETur ADIPIScing Elit. maecenas Id orci
```

```
**;'>}{/[]'"A*(389971(*(#$&B#@*(% c'>#{@D#$!** :,>/;[e.[{$893F
;'>}{/[]'"a*(389971(*(#$&b#@*(% C'>#{@d#$! :,>/;[e.[{$893F
```

```
**iT'S cAPS lOCK DAY!!! cEL**ebra**TE TH**is WONDERFUL key
It's Caps Lock day!!! Celebrate this WONDERFUL key
```

```
aBc**DE fGHI**j KLm**NO pQ**rST (uVw**XY) ZZ___Z**z__Z
aBcde Fghij KLmno PqrST (uVwxy) zz___zz__Z
```

```
#aA# aA
#aA# aA
```

## Rules

* You may assume that the input will never contain two or more spaces in a row, and that it will never contain a leading or trailing space.
* 20% bonus (multiply your code length by .8) if your entire code is a CLR. ;) (mostly just for fun, since it's unlikely that the winning submission will have this bonus)
* This is , so the shortest code in bytes wins.

# Answer
# CJam, ~~100~~ ~~86~~ ~~83~~ 81 bytes

```
Ml{_,),{1$<_S/(4$!>\1f>s+_eu=*S%_{'[,_el^:Af&s,2<},!*1>},_{W=/(AA26m>er}{;(}?\s}h

```

Try this fiddle in the CJam interpreter or verify all test cases at once.

### Algorithm

1. Identify the longest possible CLR that starts with the first character.
2. If it exists, swap its case, print it, and remove it from the beginning of the string.

Else, remove a single character from the beginning of the string, and print it unmodified.
3. If there are more characters left, go back to step 1.

### How it works

```
Ml         e# Push an empty string and a line from STDIN.
{          e# Do:
  _,       e#   Copy the string on the stack and compute its length (L).
  ),       e#   Push [0 ... L].
  {        e#   Filter; for each integer I in that array:
    1$<    e#     Copy the string and keep its first I characters.
    _S/    e#     Push a copy and split at spaces.
    (      e#     Shift out the first word.
    4$!    e#     Push the logical NOT of the fifth topmost item of the stack.
           e#     This pushes 1 for the empty string on the bottom, and 0
           e#     for non-empty strings and printable characters.
    >      e#     Remove that many characters from the beginning of the first word.
           e#     This will remove the first character iff the string on the
           e#     stack is the entire input. This is to account for the fact that
           e#     the first word is not preceded by a space.
    \1f>   e#     Remove the first character of all remaining words.
    s+     e#     Concatenate all of them.
    _eu=   e#     Convert a copy to uppercase and check for equality.
    *      e#     Repeat the I characters 1 or 0 times.
    S%_    e#     Split at runs of spaces, and push a copy.
    {      e#     Filter; for each non-empty word:
      '[,  e#       Push the string of all ASCII characters up to 'Z'.
      _el  e#       Push a copy and convert to lowercase.
      ^    e#       Perform symmetric difference, pushing all letters (both cases).
      :A   e#       Store the result in A.
      f&s  e#       Intersect A with each character of the word. Cast to string.
      s    e#       This removes all non-letters from the word.
      ,2<  e#       Count the letters, and compare the result to 2.
    },     e#     If there are less than 2 letters, keep the word.
    !      e#     Push the logical NOT of the result.
           e#     This pushes 1 iff all words contain enough letters.
    *      e#     Repeat the array of words that many times.
    1>     e#     Remove the first word.
  },       e#   Keep I if there are still words left.
  _{       e#   If at least one I was kept:
    W=     e#     Select the last (highest) one.
    /      e#     Split the string on the stack into chunks of that length.
    (      e#     Shift out the first chunk.
    AA26m> e#     Push "A...Za...z" and "a...zA...Z".
    er     e#     Perform transliteration to swap cases.
  }{       e#   Else:
    ;      e#     Discard the filtered array.
    (      e#     Shift out the first character of the string on the stack.
  }?       e#
  \s       e#   Swap the shifted out chunk/character with the rest of the string.
}h         e# If the remainder of the string is non-empty, repeat.

```
> 4 votes

# Answer
## Perl, 96 82 80 bytes

```
-pe'$y=qr/[^a-z ]{2,}|\b\S[^a-z ]+/;s#$y( $y)+#join$,,map{uc eq$_?lc:uc}$&=~/./g#eg'

```

---

Passes all tests. Assumes input from `STDIN`, prints to `STDOUT`.

How it works:

* setup a regex (`$y`) that matches

+ at least two non-lowercase, non-whitespace characters **OR**
    + a word boundary, followed by a non-whitespace character, followed by one or more non-lowercase, non-whitespace characters
* match multiple instances of space-separated strings that match `$y`, use `s///` to invert case

I'm sure there's room for improvement. If there is a way to get rid of the whole `join-map-split` deal there may still be a chance to qualify for the bonus :)
> 2 votes

# Answer
# Javascript, 193

```
decapslock =

a=>a.replace(/(^[a-z][^a-z ]+|[^a-z ]{2,})( [a-z][^a-z ]+| [^a-z ]{2,})+/g,b=>b.split` `.some(f=>f.split(/[a-z]/i).length<3)?b:b.split``.map(e=>e==(E=e.toUpperCase())?e.toLowerCase():E).join``)
```

```
<!-- Snippet UI -->
<input placeholder='sAMPLE tEXT' oninput="document.getElementsByTagName('p')[0].innerText=decapslock(this.value)" />
<p></p>
```

Explanation:

```
a=>a.replace(/* giant regex */,
  b=>
    b.split` `.some(
      f=>
        f.split(/[a-z]/i).length < 3   // check for 2+ letters
    )
      ? b                              // .some() immediately returns true if it's invalid
      : b.split``.map(                 // otherwise it's valid, so flip case
          e=>
            e == (E = e.toUpperCase()) // is it uppercase?
              ? e.toLowerCase()        // change it to LC
              : E                      // change it to UC, which was already done for
                                       // the case check
            ).join``
        )

```

```
(
^[a-z][^a-z ]+ // check for a CLR starting at the beginning with LC
|
[^a-z ]{2,}    // check for a CLR that begins in the middle of a word or starts at the
               // beginning with UC
               // in both cases, 2+ letters are required
)
(
 [a-z][^a-z ]+ // check for the next word of the CLR, starting with LC
|
 [^a-z ]{2,}   // check for the next word of the CLR, starting with UC
)+             // check for 1 or more next words

```
> 2 votes

---
Tags: code-golf
---