title: What? No error?

text:
# Question
Title: What? No error?
Your task is simple. Write a program that should obviously produce an error on first glance either when compiled or run, but either doesn't or produces some other unrelated error. This is a popularity contest, so be creative.

# Answer
# C++

Make sure you compile the following code in standard conforming mode (for example, for g++ use the -ansi flag):

```
int main()
{
  // why doesn't the following line give a type mismatch error??/
  return "success!";
}

```

How it works:

> The ??/ is a trigraph sequence that is translated into a backslash which escapes the following newline, so the next line is still part of the comment and therefore won't generate a syntax error. Note that in C++, omitting the return in `main` is well defined and equivalent to returning 0, indicating a successful run.
> 278 votes

# Answer
# Ruby

Always a fan of this one.

```
x = x

```

No `NameError`. x is now `nil`.

> This is just a "feature" of Ruby :-)

Here's a more mundane one that's gotten me before:

```
x = 42

if x < 0
  raise Exception, "no negatives please"
elseif x == 42
  raise Exception, "ah! the meaning of life"
else
  p 'nothing to see here...'
end

```

Prints "nothing to see here."

> It's **elsif**, not **elseif**. (and it's certainly not **elif** \- woe to the wayward python programmer (me)!) So to the interpreter **elseif** looks like a normal method call, and since we don't enter the x\<0 block, we go straight on to **else** and don't raise an exception. This bug is incredibly obvious in any syntax-highlighting environment, thankfully (?) code golf is not such an environment.
> 85 votes

# Answer
# C?

Pretty normal code here...

```
void main() = main--;

```

> It's Haskell, not C. It defines a function named "void" that takes two arguments. The first is named "main" and if the second (unnamed) is an empty tuple, it returns the "main" variable. "--" starts a comment in Haskell, so the ";" is commented out.
> 77 votes

# Answer
# JavaScript

```
var а = 100;
if (typeof a !== 'undefined') throw 'This should always throw, right?';
console.log('How am I still alive?');

```

Here's how it works:

> The first `a` is actually an `а` (that is, Cryllic Unicode "a").
> 72 votes

# Answer
# JavaScript

When I was providing the following code I was told many times *"It must be a typo! How can it work?"*.

```
console.log( 42..toString(2) );

```

The description below was copied exactly from one the recent cases.

> As you probably know, in JavaScript everything except literals is an object. Numbers are objects as well. So theoretically (and practically) you may get properties or call methods of any non-literal via dot notation, as you do `'string'.length` or `[1,2,3].pop()`. In case of numbers you may do the same but you should keep in mind that after a single dot the parser will look for a fractional part of the number expecting a float value (as in `123.45`). If you use an integer you should "tell" the parser that a fractional part is empty, setting an extra dot before addressing a property: `123..method()`.
> 70 votes

# Answer
# bash

```
#!/bin/bash

[ 1 < 2 ] && exit

for i in `seq 1 $[2 ** 64]`
    do "$0" | "$0"
done

while [[ false ]]
    do :
done

if maybe
    do [: [: [: [: [; [; [; [; ;] ;] ;] ;] :] :] :] :]
fi

```

### Results

* You might expect the script not to produce any errors at all, since it exits after the first command. It doesn't.
* You might expect the typical error messages caused by an ongoing fork bomb due to the `for` loop. There's no fork bomb.
* You might expect bash to complain about the missing `maybe` command or the whole bunch of syntax error inside the `if` block. It won't.
* The only error message the script *might* produce ends in `2: No such file or directory`.

### Explanation

* > `[` isn't special to bash, so `< 2` performs, as usual, redirection. Unless there is a file with name `2` in the current directory, this will cause an error.
* > Due to that error above, the command before `&&` will have a non-zero exit status and `exit` will not be executed.
* > The `for` loop isn't infinite. In fact, there's no loop at all. Since bash cannot compute the 64th power of 2, the arithmetic expression's result is `0`.
* > `[[ false ]]` tests if `false` is a null string. It isn't, so this `while` loop is infinite.
* > Because of the above, the `if` statement never gets executed, so no errors get detected.
> 62 votes

# Answer
## Perl

```
use strict;
use warnings;
Syntax error!
exit 0;

```

Source and explanation: https://stackoverflow.com/questions/11695110
> 54 votes

# Answer
# Java

```
class Gotcha {
    public static void main(String... args) {
        try  {
            main();
        } finally {
            main();
        }
    }
}

```

No stack overflows here; move along.

> At first glance, this should produce a `StackOverflowError`, but it doesn't! It actually just runs forever (for all practical purposes at least; technically it would terminate after a time many orders of magnitude longer than the age of the universe). If you want to know how/why this works, see this. Also, if you happen to be wondering why we can call `main()` without arguments when the main method generally would need a `String[]` argument: it's because we've declared it to be variable-argument here, which is perfectly valid.
> 46 votes

# Answer
# CoffeeScript

```
What? No error? Yep, this code does not have any bugs, why would it?

```

> `?` followed by a space is operator that calls a function, but only if it exists. JavaScript doesn't have a function called `What`, therefore the function isn't called, and its arguments are simply ignored. The other words in the code are function calls that actually aren't called, because `What` function doesn't exist. At end, `?` is existence operator, as it is not used in call function. Other sentence enders, such as `.` or `!` would not work, as `.` is for methods, and `!` is not operator (which cannot be used after an identifier). To read how CoffeeScript converted this to JavaScript, visit http://coffeescript.org/#try:What%3F%20No%20error%3F%20Yep%2C%20this%20code%20does%20not%20have%20any%20bugs%2C%20why%20it%20would%3F.
> 42 votes

# Answer
# VBScript

The `&` operator in VBScript is string concatenation but what on earth are the `&&` and `&&&` operators? (Recall that the "and" operator in VBScript is `And`, not `&&`.)

```
x = 10&987&&654&&&321

```

That program fragment is legal VBScript. Why? And what is the value of `x`?

> The lexer breaks this down as `x = 10 & 987 & &654& & &321`. An integer literal which begins with `&` is, bizarrely enough, an octal literal. An octal literal which ends with `&` is, even more bizarrely, a long integer. So the value of x is the concatenation of the decimal values of those four integers: `10987428209`.
> 36 votes

# Answer
# Objective-C

Not a big deal, but it has surprised me while trying to put a link inside a comment:

```
http://www.google.com
        return 42;

```

> http is a code label here, such labels are used in goto instructions
> 27 votes

# Answer
# C#

```
class Foo
{
    static void Main(string[] args)
    {
        Bar();
    }

    static IEnumerable<object> Bar()
    {
        throw new Exception("I am invincible!");
        yield break;
    }
}

```

> Because the `Bar` method does a `yield`, the method doesn't actually run when called, it returns an enumerator which, when iterated,s runs the method.
> 25 votes

# Answer
## C

```
main=195;

```

> Works on x86 platforms, where 195 is the opcode for ret. Does nothing,
> 22 votes

# Answer
# Java

Probably too obvious.

```
public static void main(String[] varargs) throws Exception{
    char a, b = (char)Integer.parseInt("000d",16);
    // Chars have \u000d as value, so they're equal
    if(a == b){
        throw new Exception("This should be thrown");
    }
}

```

What?

> Throws a syntax error after `\u000d`. `\u000d` is the unicode for a new line. Even though it is commented out, the Java compiler treats what is after this as code since it isn't commented out anymore.
> 21 votes

# Answer
# C++

```
#include <iostream>

int succ(int x)
{
  return x + 1;
}

int succ(double x)
{
  return int(x + 1.0);
}

int succ(int *p)
{
  return *p + 1;
}

int main()
{
  std::cout << succ(NULL) << '\n';
}

```

Why?

> `NULL` is an intergal constant, so it matches the `int` overload strictly better than the `int*` one. Still, most programmers have `NULL` associated with pointers, so a null pointer dereference can be expected.
> 19 votes

# Answer
## Python

```
print """""quintuple-quoted strings!"""""

```

> Perfectly valid, but the output is hard to guess. The first 3 " characters start a multiline string and the next two are part of the string. At the end, the first three "s terminate the string and the last two are an empty string literal that gets concatenated by the parser to the multiline string.
> 16 votes

# Answer
## **JavaScript**

```
if (1/0 === -1/0) {
  throw "Surely there's an error in here somewhere...";
}

```

How it works:

> There's positive and negative infinity in JS, and no error for dividing by zero.
> 15 votes

# Answer
## C++

Mixing trigraphs and space-less lambdas can be quite confusing and definitely look erroneous to people who are not aware of trigraphs:

```
int main()
{
    return??-??(??)()??<return"??/x00FF";??>()??(0??);
}

```

How it works:

> Some sequences consisting of 3 symbols, beginning with ??, are called trigraphs and will be substituted by a fully-compliant preprocessor. Preprocessed, the line in question looks as follows: **return ~\[\] (){ return "\x00FF"; }()\[0\];** As one can see, this is nothing but a superfluous lambda function returning a string consisting of the 0xFFth character. The **\[0\]** just extracts that character and **~** NOTs it, so 0 is returned.
> 14 votes

# Answer
## VBA/VB6

```
Private Sub DivByZero()

    Dim x() As String
    x = Split(vbNullString, ",")

    Debug.Print 1 / UBound(x)

End Sub

```

Splitting an empty comma delimited string should give an empty array. Should be an obvious division by zero error, right?

> Nope. Surprisingly, when any zero length string is split the runtime gives you an array with a lower bound of 0 and an upper bound of -1. The code above will output -1.
> 13 votes

# Answer
# Javascript

```
5..toString();
5 .toString();

```

Gives: 5

Whereas:

```
5.toString();

```

Gives SyntaxError

How it works:

> JavaScript tries to parse dot on a number as a floating point literal
> 12 votes

# Answer
# HTML

First post here, I'm not sure I get this or not, but here goes.

```
<html>
    <head></head>
    <body>
        <?php $_POST['non-existant'] = $idontexisteither ?>
    </body>
</html>

```

---

> It's a `.html` file...
> 12 votes

# Answer
# VBScript

Visual Basic 6 users will know that

```
If Blah Then Foo Bar

```

is legal, as is

```
If Blah Then
    Foo Bar
End If

```

But what about

```
If Blah Then Foo Bar End If

```

? Turns out that is legal in VBScript but not in VB6. Why?

> It's a bug in the parser; the intention was to reject this. The code which detects the `End If` was supposed to also check whether it was a multi-line `If` statement, and it did not. When I tried to fix it and sent out a beta with the fix, a certain influential industry news organization discovered that they had this line of code in one of their VBScript programs and said they would give the new version a low rating unless we un-fixed the bug, because they didn't want to change their source code.
> 9 votes

# Answer
# C

This reminded me of an error I ran into when I learned C. Sadly the original variant doesn't seem to work with a current GCC, but this one still does:

```
#define ARR_SIZE 1234
int main() {
    int i = ARR_SIZE;
    int arr[ARR_SIZE];
    while(i >= 0) {
        (--i)[arr] = 0;
    }
    i = *(int*)0;
}

```

This obviously segfaults because we dereference a null pointer, right?

> Wrong - actually, it's an infinite loop as our loop condition is off by one. Due to the prefix decrement, `i` runs from 1023 to -1. This means the assignment overwrites not only all elements in `arr`, but also the memory location directly before it - which happens to be the place where `i` is stored. On reaching `-1`, `i` overwrites itself with `0` and thus the loop condition is fulfilled again...

This was the original variant I which I can't reproduce anymore:

> The same thing worked with `i` going upwards from 0 and being off by one. The latest GCC always stores `i` before `arr` in memory; this must have been different in older versions (maybe depending on declaration order). It was an actual error I produced in one of my first toy programs dealing with arrays.

Also, this one's obvious if you know how pointers work in C, but can be surprising if you don't:

> You might think that the assignment to `(--i)[arr]` throws an error, but it's valid and equivalent to `arr[--i]`. An expression `a[x]` is just syntactic sugar for `*(a + x)` which computes and dereferences the pointer to the indexed element; the addition is of course commutative and thus equivalent to `*(x + a)`.
> 9 votes

# Answer
## Java

```
public class WhatTheHeckException extends RuntimeException {
    private static double d;        // Uninitialized variable
    public static void main(String... args) {
        if (d/d==d/d) throw new WhatTheHeckException();
        // Well that should always be true right? == is reflexive!

        System.out.println("Nothing to see here...");
    }
}

```

Why this works:

> Unitialized fields have default values. In this case **d** is just **0**. **0/0 = NaN** in double division, and **NaN** never equals itself, so the **if** returns false. Note this would not work if you had **0/0==0/0**, as at would be integer **0/0** division would WOULD throw an **ArithmeticException**.
> 9 votes

# Answer
# PHP (40 bytes)

```
<?for(;;$e.=$e++)foreach($e::$e()as&$e);

```

This was the answer I gave in this question: Insanity Check Program

The idea was to make a code that produced errors.

The 1st error that we will think of, is a syntax error.

There are no syntax errors...

Other would be that the class/function doesn't exist.

It doesn't run that far...

Other would be a time-out or a memory overflow, but, again, it doesn't reach that far...

Test the code here: http://writecodeonline.com/php/ (remove the `<?` on the beginning to test).
> 8 votes

# Answer
# VBScript

```
function[:(](["):"]):[:(]=["):"]:
end function
msgbox getref(":(")(":)")

'Output: :)

```

What it does:

> Function, Sub and Variable Names in VBScript can be anything if you use square brackets. This script makes a function called `:(` and one argument `"):"` but because they do not follow normal naming convention they are surrounded by square brackets. The return value is set to the parameter value. An additional colon is used to get everything on one line. The Msgbox statement gets a reference to the function (but does not need the brackets) and calls it with a smiley `:)` as parameter.
> 8 votes

# Answer
# C++11

```
struct comp {
    comp operator compl () { return comp { }; }
    operator comp () { return comp { }; }
    compl comp () { return; comp { }; }
};

int main() {
    comp com;
    compl com;
}

```

Compiles and runs without any warnings with `g++ -pedantic-errors -std=c++11`.

> `compl` is a standard alternative spelling for `~`, just like `not` is an alternative for `!`. `compl` is used here to first override `operator~` and then define a destructor. Another trick is that `operator comp` is a conversion function from the type `comp` to itself. Surprisingly the standard does not forbid such a conversion function - but it does say that such a function is never used.
> 8 votes

# Answer
## C#

Actually I caught myself on mistakenly doing just that :)

```
public static object Crash(int i)
{
    if (i > 0)
        return i + 1;
    else
        return new ArgumentOutOfRangeException("i");
}

public static void Main()
{
    Crash(-1);
}

```

> **throw**, not **return**.
> 8 votes

# Answer
# Java

```
enum derp
{

    public static void main(String[] a)
    {
        System.out.println(new org.yaml.snakeyaml.Yaml().dump(new java.awt.Point()));
    }
}

```

And how that one works:

> Firs you think the Enum is not valid but its valid; then you think it will print a standard Point objects attributes but Gotcha! due to how Snakeyaml serializes you get a smooth StackOverFLow error

And another one:

```
enum derp
{

    ;public static void main(String[] a)
    {
        main(a);
    }
    static int x = 1;

    static
    {
        System.exit(x);
    }
}

```

> you think a Stackoverflow will happen due to the obvious recursion but the program abuses the fact that when you run it the `static{} block` will be executed first and due to that it exits before the main() loads

```
enum derp
{

    ;
        public static void main(
            String[] a)
    {
        int aa=1;
        int ab=0x000d;
        //setting integer ab to \u000d  /*)
        ab=0;

        /*Error!*/
        aa/=ab;
    }
    static int x = 1;
}

```

> this one relies on that `/*Error*/`-commented out code as closing point for the comment opened before the ab=0; the explain about the integer ab to 0x000d hides the newline to activate the commentout of the next line
> 7 votes

# Answer
# C

Strings and arrays in c can be pretty confusing

```
main(){
  int i=0;
  char string[64]="Hello world;H%s";
  while(strlen(&i++[string])){
    i[' '+string]=string[i]-' ';
  }
  5[string]=44;
  return printf(string,'!'+string);
}

```
> 6 votes

# Answer
# Java

```
  public static void main(String[] args) throws Exception {
        Integer a = 1, b = 1;
        Integer c = 200, d = 200;
        if ( a != b || c == d) {
            throw new Exception("This should be thrown");
        }
    }

```

> The Integers from the range of -127 .. 127 are cached so Integer.valueOf(127) == Integer.valueOf(127) is true but Integer.valueOf(128) == Integer.valueOf(128) is false.
> 6 votes

# Answer
# JavaScript

```
/21 + 21     // SyntaxError in this

```

SyntaxError could be expected, but this expression works and even returns true.
> 5 votes

# Answer
# python

```
 = 3

```

You expect

```
SyntaxError: unexpected indent

```

Instead you get

```
SyntaxError: invalid character in identifier

```

Also this:

```
" " == " "
False

```

> Unicode spaces
> 4 votes

# Answer
## APL

```
table ← {
  ⍵⍴⍳×/⍵
  [{(]}) ⍝ obviously a syntax error right?
}

```

Result:

```
      table 6 8
 1  2  3  4  5  6  7  8
 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48

```

This *does* fail:

```
table ← {
  [{(]})
  ⍵⍴⍳×/⍵
}

```

But this runs fine again:

```
table ← {
  0:[{(]})
  ⍵⍴⍳×/⍵
}

```

> APL parsing is lazy. At least in Dyalog APL. (Really!) Also, a d-fn returns the value of the *first* line that gets a result. `⍵⍴⍳×/⍵` always returns a value (it's not an assignment and it doesn't have a guard), so, `⍵⍴⍳×/⍵` is run and returns a value, and the second line is never even parsed, thus, no error. In the second example, the line `[{(]})` is run first, so it fails. But the third example works, because it has a guard (`0:`), and `0` is false so it's skipped.
> 4 votes

# Answer
# C

I don't belive that nobody posted this yet (sorry for archaeology):

```
const int main[] = {};

```

> C use the same namespace for function names and variable names. So this will compile and link as valid executable but will return `SIGSEGV` at runtime.
> 4 votes

# Answer
# Java (java.util.regex.Pattern)

This post's effectiveness depends on how much you know about `Pattern` class documentation. The behavior shown below also depends on the quirks in **OpenJDK's Java Class Library (JCL) implementation** of `Pattern` class.

1. Inline flags (valid ones as shown in documentation `(?idmsuxU-idmsuxU)`)

```
Pattern.compile("(?t)"); // Throws PatternSyntaxException. Nothing surprising here

Pattern.compile("(?c)"); // Compiles normally (!)

```

`c` flag was intended to be used as inline flag for `CANON_EQ`, but it currently has absolutely no effect, due to the way `CANON_EQ` is handled.

There is absolutely no reason to use this in your code.
2. Character class intersection (shown in documentation as `[\p{L}&&[^\p{Lu}]]` or `[a-z&&[def]]`, i.e. nesting seems to be required from the example)

```
Pattern.compile("[\\p{IsAlphabetic}&&\\pM]"); // Compiled normally (!)

```

And the compiled `Pattern` also works when matching against `"\u0345"`.

However, it is still recommended that you follow the documentation's way of writing regex.
3. Character class in `\p` notation (shown in documentation to specify a POSIX character class, a `java.lang.Character` class, or for Unicode script/block/category/binary property)

```
Pattern.compile("\\p{Letter}"); // Throws PatternSyntaxException. Nothing surprising here

Pattern.compile("\\p{all}"); // Both compiles normally (!)
Pattern.compile("\\p{L1}");

```

`all` and `L1` are hidden names usable by `\p`:

* `\p{all}` is equivalent to `(?s:.)`.
    * `\p{L1}` is equivalent to `[\x00-\xFF]`.

However, since this is not specified in the documentation, **I strongly advise you against** using them even if you know you can use them.
> 3 votes

# Answer
# C++

How many times have you been told to be careful to avoid `index out of bounds` errors with your `for` loops?

```
#include<iostream>
#include<string>
using namespace std;

int main() {
    string s="text here";
    for(int i=0;i<=s.size();i++)
        cout<<s[i];
    return 0;
}

```

> In C++ (and most other languages), strings are just special char-arrays. In C++, a `string` always has a buffer of a space at the end, which isn't usually noticed because all the functions, etc. account for it. Here I am just accessing the space directly, so it just prints a space instead of crashing with and `index out of bounds` error.
> 3 votes

# Answer
# PHP

Some slightly non-standard syntax here:

```
<html>
<body>
<p>Error?</p>
<?php

echo beach, far away in time;

?>
<p>What error??</p>

```

What's going on?

> There's a three-per-em space after the opening **\<?php** tag. The PHP parser treats this as part of the tag name, and therefore fails to recognise this code block as PHP. Instead it passes it straight to your web browser. Your browser doesn't understand it either, so all you see is the HTML text that surrounds it. (An ordinary non-breaking space would have worked too, but Markdown converts those to regular spaces so we need to use something different.)
> 3 votes

# Answer
# Python 2

```
isSorted = lambda a: all(x>y for x,y in zip(a[1:],a[:-1]))
print isSorted( [(1+3j),(1+2j,),(2+1j)] )

```

> The surplus comma after `1+2j` does not raise a syntax error, because this is Python’s way of creating a tuple with one element. But most importantly, this avoids that in `isSorted` complex numbers are compared and thus a `TypeError` is raised. This is because apart from two complex numbers you can almost compare everything in Python, including complex numbers and tuples.
> 3 votes

# Answer
# Perl

```
if (false) {
    # Shouldn't happen
}
else {
    die "Huge error";
}

```

> In Perl, `false` is not a keyword, and it's parsed a bareword (`"false"`). As `"false"` is true, the program exits without any exception (`die` keyword). Both `strict` and `warnings` would notice this problem, which shows why using `use strict; use warnings;` in Perl is a good idea.
> 3 votes

# Answer
## Java

It is more convoluted than I would like, but here it goes.

```
package misc;

import java.io.FileWriter;

public class HelloWorld
{
    public static String writeFile(String fileName)
    {
        try {
            FileWriter fw = null;
            try {
                if( fileName==null ) return "bad parameter!";

                fw = new FileWriter(fileName);
                fw.write("Hello, World!\n");
            } finally {
                fw.close();
            }
        } catch( Exception ex ){
        }

        return "OK";
    }

    public static void main(String[] args)
    {
        String result = writeFile("hello.txt"); // returns OK
        System.out.println(result);

        result = writeFile(null); // should return "bad parameter!", right?
        System.out.println(result);
    }
}

```

The second call to writeFile should complain, right? It doesn't. Both calls return "OK".

If fileName is null, the very first thing the method does is to return an error message. So how can it return "OK"?

> The return "bad parameter!"; is executed. But before returning, it has to execute the final section. At that time, fw is null. It throws a NullPointerException and, well, forgets it was supposed to return. The exception is caught and ignored. The procedure returns "OK".
> 3 votes

# Answer
## XML

And you thought you knew XML...

```
Lo§”“@¥…™¢‰–•~}ñKð}@on%L”…¢¢‡…nÈ…““–k@æ–™“„ZLa”…¢¢‡…n

```

copy the above in hello.xml and open with IE.

> It is encoded in EBCDIC. The XML processor is supposed to detect it. It does in IE. But when you view it, it is usually displayed in UTF or latin, so it is all garbled.
> 3 votes

# Answer
## Ruby

```
1 / 0.0

```

This does not result in a ZeroDivisionError, but in

```
# => Infinity

```
> 3 votes

# Answer
## C#

```
using System;
class DivideByZero
{
   static int \u004F = Convert.ToInt16('\u0031');

   static void Main(string[] args)
   {
      Console.WriteLine(1 / O);  // Divide by Zero
   }
}

```

> This code is actually dividing by O(the letter) and not 0(the number). If you know your hexadecimal ASCII characters well, then you might notice that I am setting the value of O(the letter) to '1' converted to an int16. Perhaps even weirder to some people, the output of this program is (the number): 0
> 3 votes

# Answer
# Casio Calculator

It's quite hard to count bytes/tokens in this "language" - I've given the number of keypresses required, excluding Shift, Alpha (the second shift key) and `=` at the end - this certainly fits into 1 byte per keypress.

Tested on the fx-85GT PLUS model, which is a standard, non-graphing, "non-programmable" scientific calculator. Other models will work.

These calculators have two possible input/output formats: MathIO, which is default, and displays expressions as they are written on paper (e.g. fractions display properly), and LineIO, which uses the more conventional method of representing expressions as a single string of characters without vertical dimension - e.g. square root is `√(...)`, fractions are `1⎦2` (that's meant to be like an underscore with a vertical bar of equal length attached to the right, like `_|` but as a single character).

## Code

You'd think that this monstrosity would give many syntax errors. How to enter it:

`(``(``.``!``%``Power``Negative``-``.``Degree``Right (close-paren if in linear mode)``%``Degree`

Press `=` to evaluate it.

What it looks like in linear mode:

```
((.!%^(--.°)%°

```

Decimal points without numbers, multiple percent signs, multiple degree signs, too many minuses, unclosed parentheses...

## Output

```
0°0'36"

```

> `.` evaluates to `0`, just as `.5` is `0.5` and `5.` is `5`.
> Parentheses are automatically closed at the end of the expression.
> `((.!%^(--.°)` on its own evaluates to `1` \- the degree symbol disappears.
> Although the calculator uses different symbols for negation and subtraction, the latter can be used for both, while the first only negates. `--.` is just `0`.
> Multiple percent symbols can be used in a single number - `1%%` evaluates to `0.0001`.
> Without the final `°`, the expression evaluates to `0.01`.
> 3 votes

# Answer
## REBOL

```
do not run "this"

```

---

How it works:

> `do`: execute the following code.
> `not`: negate.
> `run`: runs the following thing as a bash command.
> `"this"`: an illegal bash command, does nothing.
> 3 votes

# Answer
# Ruby

```
class Foo

  def self.get_bar
    self.bar
  end

  private

  def self.bar
    1 + 1
  end

end

p Foo.bar

```

> Prints 2. Yeah, Ruby just doesn't apply the `private` modifier to class methods if you declare them this way. If you instead do this in a `class << self` block it works fine.
> 2 votes

# Answer
# Clojure

```
  (defn check-nil [v] {:pre [nil? v]} v)

  (check-nil nil)

  (defn check-keyword [v] {:pre [keyword? v]} v)

  (check-keyword “sdf”)

```

> First one throwing exception but second one does not throw any exception. First one v itself is null that way it throw exception. The form should be {:pre \[(nil? v)\]} and {:pre \[(keyword? v)\]}
> 2 votes

# Answer
## Haskell

```
main=print (0/0, 1/0)

```

> It is funny because Haskell is such a mathematical language, but this won't produce a zero-division error. Instead it outputs `(NaN,Infinity)`. This is because division isn't defined on integer anyways, so it just assumes they are floats, which can be NaN and Infinity.
> 2 votes

# Answer
# C

```
#include <stdio.h>
#include <string.h>

int main(void)
{
    if(1 != 0)
        perror("Error?");

    return 0;
}

```

> perror() produces a message describing the last error encountered during a call to a system or library function - In the absence of an error it will print "Success". As such the output of the program is: "Error?: Success"
> 2 votes

# Answer
This isn't anything new, but still, the syntax of C/C++ in `gcc` has always amazed me ;-) Of course, it compiles without any errors by `gcc -Wall -pedantic-errors`.

```
#include <ctype.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
    char p = '!';

    switch (argc) {
        while (!isdigit(p))
    case 1:
        p += 1;
        do { break;
    case 2:
        p = '1';
        continue;
    default:
        p = *1[argv];
        } while (false);
    }

    printf("%c\n", p);

    return 0;
}

```

> `a[b]` is just `*(a+b)` and cases in `switch` are just labels. As a bonus, `continue` works like `break` here, because the loop checks the condition before jumping. Also, it's nice trick to spell `default` as `defau1t` while using a font where `1` and `l` are hard to distinguish.

:-)
> 2 votes

# Answer
```
#include <stdio.h>

int main(void) {
    if ("hello"=="hello") {
        printf("Same!\n");
    } else {
        printf("Different!\n");
    }
    return 0;
}

```

---

Hint:

> Oh ho! This is classic CS 101 stuff. Strings should not be compared directly, because they're pointers!

---

Answer:

> . . . except that in this case, since they're the *same literal*, the compiler has optimized the literals to point to the same location in memory. Hence the output: "Same!\n".
> 2 votes

# Answer
## Python

Looks like this should produce an indentation error:

```
def a():
 print "start"
 if True:
                    for x in range(2):
                     print x
 if False:
            print "do not print this"

 a()

```

but it doesn't. And it prints "start" and then 0 and 1.

> In fact, Python interpreter doesn't care about the size of indentation, and it is relative to the current block.
> 2 votes

# Answer
## Haskell

```
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}

import Control.Monad

main = 0 -- just bogus value so we can compile and see if the below definitions make sense...
         -- will be an error if you actually try to run this as a program.

data Complex a = Complex { realPart :: a, imagPart :: a }

instance Monad Complex where  -- to get convenience functions `liftM` etc..
  return x = Complex x x
  Complex r i >>= f = f r

instance (Monad complex, Num a) => Num (complex a) where
                            -- allow `Complex` to be used with numerical operators
  fromInteger = return . fromInteger
  (+) = liftM2(+)
  (*) = liftM2(*)
  abs = liftM abs
  signum = liftM signum

instance (Monad Complex, Fractional a) => Fractional (Complex a) where
  fromRational = return . fromRational
  (/) = liftM2(/)

```

> Indeed, it's normally not possible to define an effectful action such as **main** by simply writing **= number**. If you try to run **main = 0** alone, it'll sure enough give an error (indeed at compile time already).
> However, I made a mistake further down in the code: the **Num (complex a)** instance should have **Complex** in uppercase like everywhere else. But it's lowercase, so the compiler will interpret this as a *type variable* and define a **Num** instance not only for **Complex**, but for *all* **Monad** types. This includes particularly the **IO** monad, so all of the sudden the definition of **main** on top makes sense: **0** is now an acceptable value, and will simply be wrapped up and returned.
> 2 votes

# Answer
JavaScript

```
var bSum = function (result, current, index, source) {
    return  result + (current << ( soucre.length - index - 1))
}
[1,0,1,0,1,0].reduce (bSum,0) //42

```

This obviously fails with a `ReferenceError: soucre is not defined` right?

> Nope,
> because of the function expression, there is no ASI, and the ArrayLiteral becomes a Property Accesor. Since the function has no property 0. The above fails even before, throwing a
> TypeError: Cannot call method 'reduce' of undefined
> 2 votes

# Answer
Bit late on this one, but whatever.

# PHP

```
<?='this ';</script>is some<%echo('code');

```

outputs "this is some code" (at least on my system)

> PHP allows `<script>...</script>` and `<%...%>` alongside `<?php...?>`, `<?...?>`, and `<?=...?>` for enclosing tags for reasons nobody quite understands, allows mixing of these tags in a single script (in this example, `<?=...</script>` for reasons nobody quite understands, and doesn't actually require a closing tag for reasons nobody quite understands. As such, this is actually two separate code segments (`<?='this ';</script>` and `<%echo('code');`), with `is some` just being garbage.
> 2 votes

# Answer
# C++

Two plus two is minus four.

```
#include <cassert>

int main() {
  struct {
    int two : 2;
  } _;
  _.two = 2;

  assert(_.two + _.two == -4);

  return 0;
}

```

Returns successfully; there is no error. http://ideone.com/eHQcJQ

> This is actually quite a useful (but dangerous) feature - controlled overflow of a limited size bitfield struct member.
> 2 votes

# Answer
# JavaScript

As you've seen, using `99999.toString()` gives an error, where `99999..toString()` works.

Now, have a look at this code:

```
0322323022302343534534535043.toString()

```

> The number here is an octal (base-8) number. The octal notation does not have decimals in JavaScript.
> 2 votes

# Answer
**Javascript**

```
a = 1
a+++1

```

*Javascript now has a triple plus operator*
> 2 votes

# Answer
# Go

```
package main insofaras
import "fmt" notwithstanding
func whereas main() {
    fmt despiteallobjections.Println(
        thetruthofthematter "Hello, world!")
}

```

> http://golang.org/src/cmd/gc/lex.c defines some strange keywords like `despiteallobjections`, which are ignored by the language.
> 2 votes

# Answer
# Python

I made this mistake when I started coding in python. So, I guess its worth telling

```
a=b=[1,2,3]
b.append(1)
print(a[3])

```

It seems like it will produce `IndexError: list index out of range` right?

> But, It won't! actually a,b both points to the same list so whatever we do with b will change the list. So we will see 1 as output

Having said that, lets see another example:

```
a=b=[1,2,3]
b=[1,2,3,1]
print(a[3])

```

> You might expect to see 1 as output. But, you won't! Here things are different. Now, after b=\[1,2,3,1\] , b points to a completely different list. So, the first list remain unchanged and thus we get the IndexError: list index out of range
> 1 votes

# Answer
# JavaScript:

```
function isInputValid(value) {
    return +value === 0;
}

if (!isInputValid(' \n')) throw 'Invalid input';

```

> What happens is that the `+` unary operator tries to convert the operand to a number - and for some bizarre reason, any string containing only white-space is converted to `0`.

---

```
if ('Test' === new String('Test')) throw 'The strings are equal';

```

> The `===` operator compares the references, and the primitive string `'Test'` is **not** equal to an instance of a `String` object; therefore, it doesn't throw any error.
> 1 votes

# Answer
# JavaScript

* Code 1:

```
(function() {
    return
    {
        error: undeclaredVariable
    };
})();

```
* Code 2:

```
(function() {
    return
    {
        error: undeclaredVariable,
        foo: 'bar'
    };
})();

```

It seems both should throw `ReferenceError: undeclaredVariable is not defined`, but:

* The first one doesn't throw any error
* The second one throws `SyntaxError: missing ; before statement`

That's because JavaScript doesn't require `;` at the end of lines, so a `return` followed by line break exits function without returning following object.
> 1 votes

# Answer
# Python:

```
@type
@type
def f(x):
    return 0/0
f(0)(0)

```

`f(anything)(object)` returns `type(object)`.

People tend to forget that decoraters don't always do what they seem to do ;)
> 1 votes

# Answer
# Java

No error for any input, and the curly brackets don't even match

```
public class ShouldFail {

    public static void main(String[] args) {
        String secret = "v#19!e/\u0022;}/*sd@x";
        if (!secret.equals(args[0]))
            throw new RuntimeException("Invalid argument");
        }
        System.out.println("***/// argument is valid ///***");

}

```

> `\u0022` ends the string, the rest of the program is enclosed in /\* comments \*/
> 1 votes

# Answer
# HTML/PHP

```
 <?php

   echo '<pre>';
   print_r($_POST);
   echo '</pre>';

    ?>
        <form action="dummy.php" method="post">
        <dl>
            <dd>select months</dd>
            <dt><select id="month" name="month" size="6" multiple="multiple">
                <option>January</option>
                <option>February</option>
                <option>March</option>
                <option>April</option>
                <option>May</option>
                <option>June</option>
                <option>July</option>
                <option>August</option>
                <option>September</option>
                <option>October</option>
                <option>November</option>
                <option>December</option>
            </select>
            </dt>

            <dd></dd>
            <dt><input name="submit" id="submit" type="submit" value="submit"/>
        </dl>
        </form>

```

You can select multiple months by holding down the shift key or ctrl key. You'd expect all selected options to arrive in $\_POST after hitting the submit button.
Well...
Only one, no matter how many you pick.
NO error message, neither PHP nor HTML.

> `select id="month" name="month" size="6" multiple="multiple"`
> is the problem – PHP assigns them all into the same variable, so only the last of them survives.
> `name="month[]" instead of name="month"` does the trick (now they become all entries in an array).
> 1 votes

# Answer
## Emacs Lisp

It looks like there should be a divide by 0 error but there is not! (evals to 0)

```
(when (= 0 (- ? ? ))
  (print "(- ? ? ) does equal zero!")
  ;; look! no divide by 0 error!
  (/ 1 (- ? ? )))

```

> chars in emacs lisp are written: '?{character}' so ?a in emacs lisp == 'a' in C. The bad part about this is that a ? followed by a space character is a valid way of writing ' '. This works with anywhite space character though. In the first (- ? ? ) I am doing space minus space which is 32 - 32 == 0. In the second (- ? ? ), the second whitespace character is actually the unicode char #x2001. so it is not 0
> 1 votes

# Answer
```
    public static void main(String[] args) {
    try{
        int a[] = new int[2];
        System.out.println("Accessing out of bounds :" + a[3]);
    }catch(NullPointerException e){
        System.out.println("But we dont catch out of bounds exceptions  :" + e);
    } finally {
        return;
    }
}

```

> finally is always guaranteed to run
> 1 votes

# Answer
# C

Here's another one:

```
#include <stdio.h>

int main()
{
  int a[2] = { 2, 6 };
  int typo = 2;

  /* Calculate a[1]/a[0] + typo
     to save a character (code golf!), write *a instead of a[0] */
  int r = a[1]/*a + tipo;
  /* the above should trigger an error because I wrote tipo instead
     of typo; why does it compile correctly? */

  -1; /* statement with no effect, but no warning about this? */

  printf("%d\n", r); /* and this even prints the correct value! */
  return 0;
}

```

Explanation:

> The `/` from the intended division and the `*` from the intended pointer dereference together form the comment starter `/*`. Note that inside the comment, further `/*` are not parsed, so the comment continues until the end of the intended statement. Of course, due to thwe unintentionally long comment, the `-0;` is no longer a separate statement, but gets part of the previous definition, to form the complete definition `int r = a[1] - 1`. Due to the carefully chosen constants, this gives the same result as `a[1]/a[0] + typo`. However, when compiling using gcc with warnings on, you do get a warning of the nested `/*` (and another one about the unused `typo` variable).
> 1 votes

# Answer
### Brainfuck

Of course, this varies by interpreter, but it fails to run on mine:

```
Author: Darkgamma (contact: darkgamma@email(dot)com)

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

```

> In Brainfuck, all text (save for the eight commands) is taken as a comment. So what's at play here? The trick's in the fact that some interpreters take "@" as end-of-source and stop interpreting after that point. Doesn't work on all interpreters but stumped me on mine until I figured out what was going on.
> 1 votes

# Answer
```
static void Main(string[] args)
    {
        object foo = 10;
        object bar = 10;

        if (foo == bar)
            throw new Exception("They're equal!");

        Console.WriteLine("Why am I here? Obviously {0} == {1}, right?", foo, bar);
        Console.ReadLine();
    }

```

Output:

```
Why am I here? Obviously 10 == 10, right?

```

> The == operator compares the references of the two objects, not the unboxed value. The code above would throw an exception if it was "if (foo.Equals(bar))" instead
> 1 votes

# Answer
## T-SQL

```
select CustomerID
from NorthWind.dbo.Customers
where not exists (select DivideByZero=1/0
                    ,BadConversion=convert(int,'xxx')
                    ,InvalidParameter=left('abc',-ShipVia)
                    ,DateOverflow=dateadd(year,9999,getdate())
                    ,ArithmeticOverflow=cast(1e308 as tinyint)
                    ,InvalidCursorRef=cursor_status('junk','junk')
                    ,BadSubquery=(select top (-OrderID) EmployeeID
                                  from NorthWind.dbo.Employees)
              from NorthWind.dbo.Orders
              where CustomerID=Customers.CustomerID)

```

This should have a lot of errors (named in the query), but because it's a subquery in an exists clause, it runs without error. Taken from http://bradsruminations.blogspot.com/2009/09/age-old-select-vs-select-1-debate.html.
> 1 votes

# Answer
# **JavaScript**

Disturbing string to boolean conversion

```
booleanValue = Boolean("false");
if(!booleanValue){
    throw "I threw an error!"
}

```
> 1 votes

# Answer
Whoops! I'm such a n00b, I thought I could just paste a url right into the source code ..

```
int main()
{
  http://codegolf.stackexchange.com/
  printf("My first C program\n");
  return 0;
}

```
> 0 votes

# Answer
# Java

```
public static void main(String[] args) {
     http://codegolf.stackexchange.com/questions/23250/what-no-error
}

```

> `http:` is a label, the rest of the line is commented out
> 0 votes

# Answer
## Python

```
#i don't think theres a module called antigravity..../
import antigravity

```

> There's an easter egg in python.. im not going to tell u what it does
> 0 votes

# Answer
**C**

```
#include <stdio.h>

int g(int a) {
    return a + 1;
}

int f(int a) {
    g(a);
    return;
}

int main() {
    printf("%d\n", f(13));
}

```

`f` has to return an `int`, but returns `void`. This actually is an error and undefined behaviour, but with GCC on linux, this will work, since the return value of `g` will still be in place when control returns from `f`. This may - however - not be the case on any system.
> 0 votes

# Answer
**In AppleScript**

```
item -1 of {1,2}

```

→ Expected error : AppleScript error : Impossible to get item -1 of {1, 2}.

→ Actual result : 2

The negative number -1 has a special handling. This trick works even further :

```
item -2 of {1,2}

```

→ Actual result : 1

But :

```
item 0 of {1,2}

```

→ Actual result : AppleScript error : Impossible to get item 0 of {1, 2}.
> 0 votes

# Answer
# AWK

This program works like cat utility in UNIX.

```
AWK! Run a program that works exactly like cat

```

Running (in shell):

```
awk 'AWK! Run a program that works exactly like cat' list of files (or nothing for STDIN)

```

> Nothing in AWK is a concatentation operator, accessing unknown variables returns empty string, `!` operator when seeing nothing returns `1`. Contatenation of "AWK" variable and boolean inverse of concatenation of lots of strings gives `1` (think, `$AWK + !($Run + $a + $program + ...)`). AWK is line based, so `1` is taken as a condition in `condition { code }` block. Code block is optional, and when not specified, it prints the input line.
> 0 votes

# Answer
**C or C++**

Based on celtschk's answer:-

```
int main (int argc, char *argv [])
{
  return argc ["success!"];
}

```

(yes, I have done that in production code, mainly to ensure people had read the code)
> 0 votes

---
Tags: popularity-contest, underhanded
---


title: The Swift Make-It-Compile Challenge #4

text:
# Question
Title: The Swift Make-It-Compile Challenge #4
This is a challenge for the people using **Swift 2.0 beta 6**, it's not code golf, but it's a programming puzzle so I'm pretty sure this belongs here. The basic idea is: Make it compile. There are more details and a very nicely formatted playground at the Github project. Previous challenges are there as well, all set up to tinker. Solutions are included for the previous challenges, as they all have been solved.

## Rules

* You can't modify the given lines
* You can't insert anything between the given lines
* You can't provide custom functions for ones that are in the standard library, according to the syntax-hightlighed picture. This applies to the inverse as well.
* The given lines are not allowed to produce a warning (on default warning settings). However the code you append is allowed to produce warnings.
* The code may or may not crash at runtime, it only has to compile

## The Code

```
func doIt(inout s: D) {
    if case self = isUniquelyReferenced(&s),
        self.`self` = true where self {
        self.`self` = { [unowned x = [self, 7] as Self] n in
            print(x + n)
        } as () -> ()
    }
}

```

## The Picture

## Winner

The first one posting an answer that compiles and conforms to all the rules above wins and gets an entry in the projects Hall of Fame.

## EDIT: Hint

Upon submission of Chris Goldsby's 99% solution, he received the following hint:

> The syntax highlighting of

```
protocol P {
    typealias P
    var p : P { get }
}

```

# Answer
I'm posting this answer on behalf of Chris Goldsby who managed to submit a

# 99% Solution (Gist):

```
typealias D = NonObjectiveCBase

func ~=(left: Any, right: Bool) -> BooleanType {
    return true
}

func +(left: Any, right: Any) -> String {
    return ""
}

protocol 🐢: class, BooleanType, ArrayLiteralConvertible {

    var `self` : () -> () { get set }
}

extension 🐢 {

    typealias Element = Any

    internal init(arrayLiteral elements: Any...) {
        self.init()
    }

    //

    func doIt(inout s: D) {
        if case self = isUniquelyReferenced(&s),
            self.`self` = true where self {
            self.`self` = { [unowned x = [self, 7] as Self] n in
                print(x + n)
            } as () -> ()
        }
    }

    //

}

```

Only the snytax highlighting of `D` doesn't match. That's remarkable as it is!

# 100% Solution

EDIT: Two days later he submitted the following full solution, congrats!:

```
private func ~=(left: Any, right: Bool) -> BooleanType {
    return true
}

private func +(left: Any, right: Any) -> String {
    return ""
}

protocol Challenge4: class, BooleanType, ArrayLiteralConvertible {

    typealias D

    var `self` : () -> () { get set }

    func doIt(inout s: D)
}

private extension Challenge4 where D == NonObjectiveCBase {

    typealias Element = Any

    init(arrayLiteral elements: Any...) {
        self.init()
    }

    //

    func doIt(inout s: D) {
        if case self = isUniquelyReferenced(&s),
            self.`self` = true where self {
            self.`self` = { [unowned x = [self, 7] as Self] n in
                print(x + n)
            } as () -> ()
        }
    }

    //

}

```
> 2 votes

---
Tags: programming-puzzle, swift
---


title: Calculate A(N) / B(N) with C(N) digits

text:
# Question
Title: Calculate A(N) / B(N) with C(N) digits
Consider three number sequences, \\$A\\$, \\$B\\$ and \\$C\\$:

* \\$A\\$: A sequence based on recurrence relations, \\$f(n) = f(n-1)+f(n-2)\\$, starting with \\$f(1) = 3, f(2) = 4\\$. So, the sequence begins like this: \\$3, 4, 7, 11, 18, 29, 47, 76, ...\\$
* \\$B\\$: The composite numbers, that is all integers that aren't primes (or 1): \\$4, 6, 8, 9, 10, 12, 14, 15, 16, ...\\$
* \\$C\\$: The digits of \\$\pi\\$: \\$3, 1, 4, 1, 5, 9, 2, 6, 5, ...\\$

Given a positive integer \\$N \< 50\\$, either as function argument or STDIN, return the decimal value of the fraction \\$\frac{A(N)}{B(N)}\\$ with \\$C(N)\\$ digits after the decimal point. Normal rules for rounding applies (round up if the \\$N+1\\$'th digit is 5 or higher). If the Nth digit of \\$\pi\\$ is zero, an integer should be printed. scientific notation / Standard form is accepted for numbers higher than 1000.

This is code golf, so the shortest answer in bytes wins.

Some examples:

```
N = 1: 0.750
N = 2: 0.7
N = 3: 0.8750
N = 4: 1.2
N = 6: 2.416666667
N = 10: 11.056
N = 20: 764.8750

```

Of course, standard code golf rules applies.

The function must terminate in less than two minutes on any modern laptop.

# Answer
> 9 votes
# Pyth, ~~60~~ ~~57~~ 58 bytes

```
.[K`.Rchu,eGsGQjT7e.ftPZQ)Je/u+/*GHhyHy^TQr^T3ZZT\0+xK\.hJ

```

Test harness

It's pretty straightforward - calculate pi, the fibonacci series and the composites, round to C(n) digits, pad to C(n) digits plus the location of the decimal point digits, done.

A(n): `hu,eGsGQjT7`

B(n): `e.ftPZQ)`

C(n): `e/u+/*GHhyHy^TQr99ZZT`

60 -\> 57: Cleaned up the n = 1 special case in the pi calculation.

57 -\> 58: Wasn't using high enough precsion for pi for the entire input range - increased 99 iterations to 1000 iterations.

**Note on rounding:** This uses Python's "nearest even" rounding system, rather than the OP specified "towards infinity" system. However, the difference only matters if the digits immediately following the rounding point are `5000...`, e.g. 1.25 rounded to 1 digit. I checked the input range, and this never happens, so the correct result is alway returned.

# Answer
> 2 votes
# PowerShell, 420 Bytes (ayyyyyyyy) 378 Bytes

```
param($n);[int[]]$p="03141592653589793238462643383279502884197169399375"-Split'';$a=@(0,3,4);for($i=3;$i-lt50;$i++){$a+=$a[$i-1]+$a[$i-2]};$c=[char[]]"00001010111010111010111011111010111110111010111011111011111010111110111";$b=@(0);for($i=4;$i-le70;$i++){if($c[$i]-eq'1'){$b+=$i}};[double]$r=$a[$n]/$b[$n];$q=$p[$n+1];$s="";(0..($q-1))|%{$s+="0"};([math]::Round($r,$q,[MidpointRounding]::AwayFromZero)).ToString("0.$s")

```

Thanks to isaacg for saving 41 bytes, for calculating how the question does rounding. Means I didn't have to include the horrendous `[MidpointRounding]::AwayFromZero` and didn't need to explicitly cast as a `[double]`.

This one was great fun!

### Expanded:

```
# Take input N
param($n)

# First digits of pi, stored as integer array
[int[]]$p="03141592653589793238462643383279502884197169399375"-Split''

# Fibonacci sequence A(N)
$a=@(0,3,4)
for($i=3;$i-lt50;$i++){
  $a+=$a[$i-1]+$a[$i-2]
}

# Zero-indexed bitmask for if the n-th integer is composite (1) or not (0)
$c=[char[]]"00001010111010111010111011111010111110111010111011111011111010111110111"

# Populate B(N) as an array using the $c mask
$b=@(0)
for($i=4;$i-le70;$i++){
  if($c[$i]-eq'1'){
    $b+=$i
  }
}

# Calculation Time!
$r=(a($n))/$b[$n]

# A small golf, as $p[$n+1] gets used a couple times
$q=$p[$n+1]

# Need to generate a string of zeroes for padding
$s=""
(0..($q-1))|%{$s+="0"}

# Round the number, then send it to a string so we get the necessary number of zeroes
([math]::Round($r,$q)).ToString("0.$s")

```

Recursion in PowerShell is ... slow, shall we say, so we have to build `A(N)` the other direction and store it into an array, then index it.

---

### OLD

Also, holy cow, did the output requirements kill this. PowerShell defaults to rounding-to-nearest a/k/a banker's rounding, which necessitates utilizing the extraordinarily verbose `[MidpointRounding]::AwayFromZero` to switch rounding styles. On top of that, we then needing to pad trailing zeroes, if any. Those two requirements combined to turn the last couple of lines from **20 Bytes** `[math]::Round($r,$q)` to **102 Bytes** (from the `$s=""` to `+$s)`) ... wow.

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

One word: Unfinished.

```
x=>{a=[0,3,4],b=[0],c='03141592653589793238462643383279502884197169399375';for(i=1;i<x;a[i+2]=a[i]+a[++i]);for(i=1,p=[];++i<70;v=p.every(x=>i%x),(v?p:b).push(i));r=''+Math.round(a[x]/b[x]*(l=Math.pow(10,c[x])))/l;if(x==33)return r;r.indexOf`.`<0&&(r+='.');while(!r[r.indexOf`.`+ +c[x]])r+='0';return r}

```

The first 49 digits of pi are stored in a string, and the other two sequences are auto-generated. This has been golfed about halfway; I'm (almost) sure I could squeeze another 50 bytes out of it.

Works for all the test cases, and should work for the rest. Crashes on anything more than 49 or less than 0 (it should never encounter these situations anyway). I especially like its result for 0:

```
NaN.

```

# Answer
> 1 votes
# Octave, ~~276~~ 236 Bytes

First of all I thought it would be cool to make use of some unlimited accuracy in these mathematical tools (and to refresh some knowledge about it) so I started writing some algorithms and then ended finally found out that the `pi` value is not so accurate that I will have to use the array again. So again, no great success:

```
function c(A)p="3141592653589793238462643383279502884197169399375";f=ones (1,50);f(1)=3;f(2)=4;for i=3:53f(i)=f(i-1)+f(i-2);end
i=0;x=1;while i<A
x++;for j=2:x/2
if mod(x,j)==0 i++;break;end end end
printf(["%." p(A) "f\n"],f(A)/x);end

```

Still quite readable, isn't it?

## Usage

copy-paste function into octave, call function `c` with argument of required value:

```
>>> c(1)
0.750
>>> c(49)
407880480.04348

```

Optimizations:

* Substitute `endif`, `endfor` and similar with `end` which works the same way
* decreasing variable `i` by one save one byte
* remove `num2str(str2num(p(A)))` nonsense :)

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


# Question
Title: Convert a string representation of a number to int[] in C#
What is the shortest C# statement that will convert a string representation of a number to an `int[]` that contains each digit?

```
string number = "1234";
number.Array.ConvertAll(line.ToCharArray(), c => Int32.Parse(c.ToString()));
number.ToCharArray().Select(i => Convert.ToInt32(i.ToString())).ToArray();
number.Select(i => Int32.Parse(i.ToString())).ToArray();
number.Select(i => i - '0').ToArray();

```

Can anyone beat my last approach?

# Answer
> 10 votes
# 28 bytes

You can make your last approach a bit shorter by replacing the `'0'` by `48`. You can also strip all unnecessary spaces and use 1-char variable names (for example, `number` -\> `n`):

```
n.Select(i=>i-48).ToArray();

```

# Answer
> 3 votes
## C# without LINQ, *97* *86* 82 bytes

```
var n=Console.ReadLine();int i=n.Length;var o=new int[i];while(i>0)o[--i]=n[i]-48;

```

I've been hanging in the shadows for a while and wanted to try this out. I'm no golfer, or even that experienced with C#, but I wanted to see how small I could get it on my own, without using LINQ. It's nothing special, but at least I had my fun.

I wasn't planning on posting this at first, since it's much longer than any good LINQ solution and doesn't really belong here, but I'm kinda curious if there is a shorter way to do it without LINQ.

**Edit 1**: Instead of int.Parse it now substracts 48 from the char's ASCII code. Well, that's already much better. **2**: Now with var instead of string and int\[\].

# Answer
> 3 votes
## 76 bytes

```
number.ToCharArray().Select(var=>Convert.ToInt32(var.ToString())).ToArray();

```

---
Tags: code-golf, tips, c#
---


title: Splitting up ASCII

text:
# Question
Title: Splitting up ASCII
Given the 95 printable characters in ASCII plus newline, break it apart into two *equal, 48 character* groups (hereafter called group A and group B). Create a one-to-one mapping *of your choice* (you have total discretion) between the two groups. In other words, `A` might map to `a`, and vice versa, but `A` might also map to `>` and vice versa, if that's what you need for your program.

Once you've broken up ASCII into two groups, write two programs and/or functions, using only the characters in each group, respectively. In other words, write one program / function that only uses the characters in group A, and another program / function that only uses the characters in group B.

These programs must be able to receive one character as input. The program written with the characters in Group A should output / return the same character if the input was a group A character, and the mapped group A character if it received a group B character; the Group A program should always output a group A character. Similarly, the Group B program should output the same character if it's a group B character, and the mapped group B character if the input is a group A character.

That might not be so clear, so here's an example. If you assume that all capital letters are in group A, and all lowercase letters are in group B, and you've chosen that your one-to-one mapping for these letters are from one to the other, then: then here are some sample input/outputs:

### Program A:

```
Input    Output
A        A
D        D
a        A
q        Q

```

### Program B:

```
Input    Output
A        a
D        d
a        a
q        q

```

Other rules:

* The two programs do not need to be in the same language.
* They don't need to be both programs or both functions; one could be a program, the other a function, that is fine.
* They don't need to work the same way, be of similar length, anything like that; they simply must meet the the other rules above.
* Yes, only one of your programs may use newlines, and only one can use spaces (this could be the same, or a different program).
* You do not need to use all 48 characters in each program.

Standard loopholes are banned, as normal. All programs must be self contained, no files containing the mapping you choose.

Scoring criteria: . Specifically, the sum of the bytes of the text of the two programs.

Please post your answer like this:

> # Language - # bytes + Language - # bytes = # bytes

An unambiguous description of your mapping. If it's complicated, use a chart like this:

> ```
> ABCDEFGHIJKLMNOPQRSTUVWXYZ (etc.)
> zyxwvutsrpqonmlkjihgfedcba (etc.)
>
> ```

Or, you can just explain it (first 48 maps to last 48 in sequence), followed by your answer as normal.

# Answer
# CJam - 11 bytes + CJam - 25 bytes = 36 bytes

Characters are selected in alternating groups of 16:

```
 !"#$%&'()*+,-./@ABCDEFGHIJKLMNO`abcdefghijklmno
0123456789:;<=>?PQRSTUVWXYZ[\]^_pqrstuvwxyz{|}~\n

```

It's cool that a few of the mappings can be obtained with the shift key :)

## Program A:

```
lL,H-f&'o+c

```

Try it online

## Program B:

```
q_S<\_0=16|_127<\S0=42^??

```

Try it online

**Explanation:**

Program A:

```
l      read a line from the input, this is a 1-character string
        or the empty string if the input was a newline
L,     get the length of an empty string/array (0)
H-     subtract 17, obtaining -17 (~16)
f&     bitwise-"and" each character (based on the ASCII code) with -17
'o+    append the 'o' character
c      convert to (first) character
        the result is the "and"-ed character, or 'o' for newline

```

Program B:

```
q_       read the whole input and duplicate it
S<\      compare with " " and move the result before the input
_0=      duplicate the input again, and get the first (only) character
16|      bitwise-"or" with 16 (based on the ASCII code)
_127<    duplicate and compare (its ASCII code) with 127
\        move the result before the "or"-ed character
S0=      get the space character (first character of the space string)
42^      xor with 42, obtaining a newline character
          stack: (input<" ") (input) ("or"-ed char<127) ("or"-ed char) (newline)
?        if the "or"-ed character is less than 127, use the "or"-ed character
          else use the newline character
?        if the input was smaller than space (i.e. it was a newline),
          use the input, else use the character from the previous step

```
> 6 votes

# Answer
# CJam - ~~46~~ ~~44~~ ~~26~~ 11 bytes + GolfScript - ~~142~~ ~~125~~ ~~115~~ ~~93~~ ~~68~~ ~~47~~ ~~40~~ 36 bytes = 47 bytes

*Thanks to Peter Taylor for golfing 6 bytes off the GolfScript program (and paving the way for many more.)*

*Thanks to Dennis for golfing 15 bytes off the CJam program and 4 bytes off the GolfScript program.*

Group A: all characters with even character code.
Group B: all characters with odd character code, plus newline.

I'm using the obvious mapping between the two, i.e. pair those characters which only differ in the least significant bit, as well as `~` and `\n`. Here is the complete map (the columns):

```
 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}\n

```

Program A (CJam, test it here):

```
lX~f&"~"|X<

```

Program B (GolfScript, test it here):

```
{1}'{-'{)}%'115)%11-[9)ie'9/{))}%++%

```

## Explanation

**Program A**

*(Outdated, will update tomorrow.)*

This program should turn odd character codes into even ones, i.e. set the least significant bit to 0. The obvious way to do this is bitwise AND with 126 (or 254 etc), but it's shorter to set it to 1 (via bitwise OR with 1) instead and then decrement the result. Finally, we need to fix newlines manually:

```
"r"(  e# Push the string "r" and pull out the character.
(~    e# Decrement to q and eval to read input.
(     e# Pull out the character from the input string.
2(|(  e# (input OR (2-1))-1 == input AND 126
0$    e# Copy the result.
N&    e# Set intersection with a string containing a newline.
"~"   e# Push "~".
"@@"( e# Push "@@" and pull out one @.
(|    e# Decrement to ?, set union with the other string to give "@?".
~     e# Eval to select either the computed character or "~" if it was a newline.

```

**Program B**

*(Outdated, will update tomorrow.)*

This program can simply set the least significant bit to 1 via bitwise OR with 1 now. But it has to check for both `\v` (character code 0x0B) and `<DEL>` (character code 0xFF) manually and set them to `~` instead. In GolfScript I didn't have access to eval, but instead you can add a string to a block (which then becomes part of the code in that block), which I could map onto the input with `%`:

```
{1}    # Push this block without executing it.
'{--'  # Push this string.
{)}%   # Increment each character to get '|..'.
')1)7?=[11=+9)?ie'
       # Push another string...
7/     # Split it into chunks of 7: [')1)7?=[' '11=+9)?' 'ie']
{))}%  # For each chunk, split off the last character and increment it.
+      # Add the array to the string, flattening the array: '|..)1)7?=\11=+9)@if'
+      # Add it to the block: {1|..)1)7?=\11=+9)@if}
%      # Map the block onto the input, i.e. apply it to the single character.

```

And as for the generated code in the block:

```
1|..   # Bitwise OR with 1, make two copies.
)1)7?= # Check if the result is one less than 2^7 == 128 (i.e. if it's <DEL>).
\11=   # Check with the other copy if it's equal to 11 (i.e. if it's \v).
+      # Add them to get something truthy either way.
9)     # Push a 10 (i.e. \n).
@      # Pull up the original value.
if     # Select the correct result.

```
> 16 votes

# Answer
## Java - 1088 bytes + Java - 1144 bytes = 2232 bytes

Thanks to @durron597 for helping to golf 1090 bytes from the first program.

Proof that it is possible to do in one language (and a non-esolang at that).

Use the unicode trick to convert the first one to all unicode characters. The second one uses reflection to get access to System.out in order to print to std. out. It couldn't use the u because that was used in the first program. I know this can be golfed more, but I wanted to post a valid solution first.

The groups are fairly arbitrarily mapped, but basically, the first one required only u,\\, and the hexadecimal digits (in any case).

The groups:

```
!#7$&89'0123456>fB@UXZ\^AKCDEGH_JL`NOkQRxzVWYu~\n
 "%()*+,-./:;<=?FIMPST[]abcdeghijlmnopqrstvwy{|}

```

First program:

```
\u0076\u006F\u0069\u0064
k\u0028\u0069\u006E\u0074
x\u0029\u007B\u0069\u006E\u0074\u005B\u005Du\u003D\u007B33\u002C33\u002C35\u002C35\u002C36\u002C55\u002C38\u002C39\u002C36\u002C38\u002C56\u002C57\u002C39\u002C48\u002C49\u002C50\u002C48\u002C49\u002C50\u002C51\u002C52\u002C53\u002C54\u002C55\u002C56\u002C57\u002C51\u002C52\u002C53\u002C54\u002C62\u002C62\u002C64\u002C65\u002C66\u002C67\u002C68\u002C69\u002C102\u002C71\u002C72\u002C66\u002C74\u002C75\u002C76\u002C64\u002C78\u002C79\u002C85\u002C81\u002C82\u002C88\u002C90\u002C85\u002C86\u002C87\u002C88\u002C89\u002C90\u002C92\u002C92\u002C94\u002C94\u002C95\u002C96\u002C65\u002C75\u002C67\u002C68\u002C69\u002C102\u002C71\u002C72\u002C95\u002C74\u002C107\u002C76\u002C96\u002C78\u002C79\u002C107\u002C81\u002C82\u002C120\u002C122\u002C117\u002C86\u002C87\u002C120\u002C89\u002C122\u002C117\u002C126\u002C10\u002C126\u007D\u003B\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006Fu\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u0028x>10\u003F\u0028\u0063\u0068\u0061\u0072\u0029u\u005Bx\u002D32\u005D\u003A'\u005C\u006E'\u0029\u003B\u007D

```

Equivalent to

```
void
k(int
x){int[]u={33,33,35,35,36,55,38,39,36,38,56,57,39,48,49,50,48,49,50,51,52,53,54,55,56,57,51,52,53,54,62,62,64,65,66,67,68,69,102,71,72,66,74,75,76,64,78,79,85,81,82,88,90,85,86,87,88,89,90,92,92,94,94,95,96,65,75,67,68,69,102,71,72,95,74,107,76,96,78,79,107,81,82,120,122,117,86,87,120,89,122,117,126,10,126};System.out.print(x>10?(char)u[x-32]:'\n');}

```

Second program:

```
void n(int r)throws Throwable{int p=(int)Math.PI;int q=p/p;int t=p*p+q;int w=q+q;int[]g={t*p+w,t*p+w,t*p+q+p,t*p+q+p,t*(q+p),t*p+t-p,t*(q+p)+q,t*(q+p)+q+p,t*(q+p),t*(q+p)+q,t*(q+p)+w,t*(q+p)+p,t*(q+p)+q+p,t*(q+p)+p+w,t*(q+p)+p+p,t*(q+p)+t-p,t*(q+p)+p+w,t*(q+p)+p+p,t*(q+p)+t-p,t*(p+w)+t-w,t*(p+w)+t-q,t*(p+p),t*(p+p)+q,t*p+t-p,t*(q+p)+w,t*(q+p)+p,t*(p+w)+t-w,t*(p+w)+t-q,t*(p+p),t*(p+p)+q,t*(p+p)+p,t*(p+p)+p,t*(t-p)+t-p,t*(t-q)+t-p,t*(t-p)+p,t*(t-q)+t-q,t*t,t*t+q,t*(t-p),t*t+p,t*t+q+p,t*(t-p)+p,t*t+p+p,t*(t-q)+t-w,t*t+t-w,t*(t-p)+t-p,t*(t+q),t*(t+q)+q,t*(t-w),t*(t+q)+p,t*(t+q)+q+p,t*(t-w)+p,t*(t-w)+q+p,t*(t-w),t*(t+q)+t-w,t*(t+q)+t-q,t*(t-w)+p,t*(t+w)+q,t*(t-w)+q+p,t*(t-q)+q,t*(t-q)+q,t*(t-q)+p,t*(t-q)+p,t*t+p+w,t*t+t-q,t*(t-q)+t-p,t*(t-q)+t-w,t*(t-q)+t-q,t*t,t*t+q,t*(t-p),t*t+p,t*t+q+p,t*t+p+w,t*t+p+p,t*(t+q)+w,t*t+t-w,t*t+t-q,t*(t+q),t*(t+q)+q,t*(t+q)+w,t*(t+q)+p,t*(t+q)+q+p,t*(t+q)+p+w,t*(t+q)+p+p,t*(t+w)+p,t*(t+q)+t-w,t*(t+q)+t-q,t*(t+q)+p+w,t*(t+w)+q,t*(t+q)+p+p,t*(t+w)+p,t*(t+w)+q+p,t*(t+w)+p+w,t*(t+w)+q+p};java.io.PrintStream o=(java.io.PrintStream)System.class.getFields()[p/p].get(p);o.print((r<=t)?"}":(char)g[r-t*p-w]);}

```

Try them out here: https://ideone.com/Q3gqmQ
> 15 votes

# Answer
# FIXED! Pyth - 23 bytes + Pyth - 30 bytes = 53 bytes

~~*oops Fixing error --- please be patient*~~

same ASCII split as Martin's:

```
1: "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~
2:!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}\n

```

Prog#1: Test Online

```
.xhft<zT.Dr\¡b:Z140 2\~

```

Prog#2: Test Online

```
C?%KCwy1K?qy5Ky5?qy+1y31Ky5+1K

```
> 5 votes

---
Tags: code-golf, restricted-source, printable-ascii
---


title: Count the trees

text:
# Question
Title: Count the trees
A tree is a connected, undirected graph with no cycles. Your task is to count how many distinct trees there are with a given number of vertices.

Two trees are considered distinct if they are not isomorphic. Two graphs are isomorphic if their respective vertices can be paired up in such a way that there is an edge between two vertices in one graph if and only if there is an edge between the vertices paired to those vertices in the other graph. For a more complete description, see the link above.

To see what all of the distinct trees of sizes 1 to 6 look like, take a look here.

The series you are trying to output is A000055 at the OEIS.

**Restriction**: Your solution must take in the range of minutes or less to run on the input `6`. This is not intended to eliminate exponential time algorithms, but it is intended to eliminate doubly-exponential time algorithms, such as brute forcing over all edge sets.

**Input:** Any non-negative integer.

Input may be by any standard means, including STDIN, command line parameter, function input, etc.

**Output:** The number of distinct trees with as many vertices as the input.

Output may be by any standard means, including STDOUT, function return, etc.

**Examples:** `0, 1, 2, 3, 4, 5, 6, 7` should return `1, 1, 1, 1, 2, 3, 6, 11`.

**Scoring:** Code golf, by bytes. May the shortest code win!

Standard loopholes forbidden.

# Answer
# Pyth, 35 bytes

```
l{m`SmSSMcXdUQk2.pQusm+L,dhHGhHtQ]Y

```

Demonstration.

This program can be divided into two parts: First, we generate all possible trees, then we remove duplicates.

This code generates the trees: `usm+L,dhHGhHtQ]Y`. Trees are represented as a concatenated list of edges, something like this:

`[0, 1, 0, 2, 2, 3, 1, 4]`

Each number stands for a vertex, and every two numbers is an edge. It is built by repeatedly adding an edge beteen each possible vertex that already exists and one which is newly created, and adding this on to each possible tree from the previous step. This generates all possible trees, since all trees can be generated by repeatedly adding one vertex and an edge from it to the existing tree. However, isomorphic trees will be created.

Next, for each tree, we perform every possible relabeling. This is done by mapping over all possible permutations of the vertices (`m ... .pQ`), and then transating the tree from the standard ordering to that ordering, with `XdUQk`. `d` is the tree, `k` is the permutation.

Then, we separate the edges into separate lists with `c ... 2`, sort the vertices within each edge with `SM`, sort the edges within the tree with `S`, giving a cannonical representation of each tree. These two steps are the code `mSSMcXdUQk2.pQ`.

Now, we have a list of lists composed of every possible relabeling of each tree. We sort these lists with `S`. Any two isomorphic trees must be able to be relabelled into the group of trees. Using this fact, we convert each list to a string with ```, then form the set of those lists with `{`, and output its length with `l`.
> 1 votes

# Answer
## CJam (69 bytes)

```
]qi:X,{1e|,:):N{N\f{1$%!*}W$.*:+}%1$W%.*:+N,/+}/W\+_1,*X=\_W%.*:+-Y/z

```

Online demo

### Explanation

The basic idea is to implement the generating function described in OEIS. The input \\$0\\$ is a nasty special case, but the final tweaks I made ended up producing \\$-1\\$ for that case, so the \\$z\\$ (for absolute value) tidies it up. That's the weirdest trick in here.

`.*:+` is repeated three times, and looks like it could save a byte if extracted as `{.*:+}:F~`. However, this breaks with the special case \\$0\\$, because it doesn't execute the outer loop at all.

---

We use the auxiliary generating function for A000081, whose terms have the recurrence

```
a[0] = 0
a[1] = 1
For n >= 1, a[n+1] = (sum_{k=1}^n a[n-k+1] * sum_{d|k} d * a[d]) / n

```

I'm sure some languages have built-ins for the inverse Möbius transform \\$\sum\_{d\mid k} d \times a\[d\]\\$, but CJam doesn't; the best approach I've found is to build an array mapping \\$d\\$ to `k % d == 0 ? d : 0` and then do a pointwise multiplication with \\$a\\$ using `.*`. Note that here it is convenient to have built up \\$a\\$ starting at index 1, because we want to avoid division by zero when setting up the weights. Note also that if the two arrays supplied to the pointwise operation are not the same length then the values from the longer one are left untouched: therefore we have to either take the first \\$k\\$ terms of \\$a\\$ or make the array of weights go up to \\$n\\$. The latter seems shorter. So this inverse Möbius transform accounts for `N\f{1$%!*}W$.*:+`

If we call the result of the inverse Möbius transform `M`, we now have $$a\[n+1\] = \frac{1}{n} \sum\_{k=1}^n a\[n-k+1\] \times M\[k\]$$

The numerator is obviously a term from a convolution, so we can handle it by reversing either a copy of \\$a\\$ or \\$M\\$ and then taking a pointwise multiplication and summing. Again, our index varies from \\$1\\$ to \\$n\\$, and in addition we want to pair up indices which sum to \\$n + 1\\$, so it's again convenient to index \\$a\\$ from 1 rather than 0. We've now accounted for

```
 qi:X,{   ,:):N{N\f{1$%!*}W$.*:+}%1$W%.*:+N,/+}/

```

The point of the auxiliary generating function is given by the formula section of A000055:

> ```
> G.f.: A(x) = 1 + T(x) - T^2(x)/2 + T(x^2)/2,
> where T(x) = x + x^2 + 2*x^3 + ... is the g.f. for A000081.
>
> ```

In terms of \\$a\\$, this means that the output we seek is $$\[x = 0\] + a\[x\] + \frac{1}{2}\left(a\[x/2\] - \sum\_{i=0}^n a\[i\] \times a\[n-i\]\right)$$

where for \\$a\[x/2\]\\$ with odd \\$x\\$ we get 0. The shortest way I've found to do that is to inflate with zeroes (`1,*`) and then take the Xth element (`X=`).

Note that the sum is yet another convolution, but this time it's convenient to index from 0. The obvious solution is `0\+`, but there is a nice little optimisation here. Since \\$a\[0\] = 0\\$, two terms of the convolution are guaranteed to be zero. We could take this as an opportunity to index from 1, but the special case \\$X = 0\\$ gets ugly. If we instead do `W\+`, the convolution gives us \\$-2a\[x\] + \sum\_{i=0}^n a\[i\] \times a\[n-i\]\\$ and after subtraction and division by \\$2\\$ we've handled the \\$a\[x\]\\$ term outside the sum as well.

So we've explained

```
 qi:X,{   ,:):N{N\f{1$%!*}W$.*:+}%1$W%.*:+N,/+}/W\+_1,*X=\_W%.*:+-Y/

```

The remaining details relate to the special case. I originally followed the recurrence more strictly by starting out with `1]` and iterating from \\$N = 1\\$ with

```
1]qi:X,1>{ ... }/

```

The result when \\$X = 0\\$ is that we compute \\$a\\$ as `[-1 1]`: one term more than we need. The inflation and convolution wind up giving a result of \\$0\\$. (Perhaps better than we deserve - it's what we should have, because we haven't done anything about the term \\$\[x = 0\]\\$). So we fix it up for three chars either as a final `X!+` or using the standard "fallback" technique as `1e|`.

To get the "right" length of \\$a\\$ we need to avoid supplying that initial \\$1\\$, and instead to produce it from the main loop with \\$N = 0\\$. A completely straightforward

```
]qi:X,{ ... /+}/

```

obviously gives division by zero. But if we try

```
]qi:X,{1e| ... /+}/

```

then it works. We get

```
             e# Stack: [] 0
1e|          e# Stack: [] 1
,:):N        e# Stack: [] [1]
{            e# We only execute this loop once
  N\f{1$%!*} e#   1 divides 1, so stack: [] [1]
  W$.*       e#   Remember: if the two arrays supplied to the pointwise operation
             e#   are not the same length then the values from the longer one are
             e#   left untouched. Stack: [] [1]
  :+         e#   Fold over a singleton. Stack: [] 1
}%           e# And that was a map, so stack: [] [1]
1$W%.*:+     e# Another [1] [] .*:+, giving the same result: 1
N,/          e# 1 / 1 = 1
+            e# And we append 1 to a giving [1]

```

which produces exactly the value we require.

Now if \\$X = 0\\$ that main loop never executes, so after we hack in a \\$-1\\$ at the bottom we get `[-1]`. We end up computing \\$(-1 - \frac12(-1 \times -1)) = -1\\$, which isn't correct. But whereas correcting \\$0\\$ to \\$1\\$ took three chars, correcting \\$-1\\$ to \\$1\\$ only takes one: `z` gives the absolute value.
> 3 votes

---
Tags: code-golf, combinatorics, sequence, graph-theory
---


title: Dynamic ASCII Encoder!

text:
# Question
Title: Dynamic ASCII Encoder!
## Introduction

Some ASCII characters are just so expensive these days...

To save money you've decided to write a program that encodes expensive characters using inexpensive ones.

However, character prices change frequently and you don't want to modify your program every time you need to encode or decode a different character! You'll need a more dynamic solution.

## Challenge

Your task is to write two programs: an ***encoder*** and a ***decoder***.

The ***encoder*** should accept a list of five inexpensive characters, and a single expensive character.

It should output a single string made up of the inexpensive characters, that encodes the expensive character.

*This string* ***may not be longer than 4 characters****, to remain inexpensive. However, it does not have to use all of the inexpensive characters in the encoding and encodings may be of different lengths.*

The ***decoder*** should accept the string outputted by the encoder, and output the expensive character.

*The decoder shall accept no input other than the encoded string. It must work, unmodified, from the encoder's output for any (valid) combination of inputs. In other words, your decoder program* ***doesn't know which characters are expensive or inexpensive.***

## Scoring

Shortest combined code wins!

## Notes

* All characters will be either uppercase letters `[A-Z]`, lowercase letters `[a-z]`, or numbers `[0-9]`.
* The list of inexpensive characters won't contain duplicates. No character will be both inexpensive and expensive.
* The encoder and decoder don't have to be written in the same language, but they can be. You may write a program or a function.
* Input and output may be in any reasonable format for your language.
* The two programs may not share any variables or data.

## Summary

* Input of some inexpensive characters and an expensive character is given to encoder.
* Encoder outputs a string of inexpensive characters, encoding the expensive character.
* Decoder is given the encoder's output, and outputs the expensive character.

## Examples

*Input:* `a, b, c, d, e` `f`

*Encoder Possibilities:* `a` `eeee` `caec`

*Decoder:* `f`

*Input:* `a, b, c, d, e` `h`

*Encoder Possibilities:* `bc` `cea` `eeaa`

*Decoder:* `h`

*Input:* `q, P, G, 7, C` `f`

*Encoder Possibilities:* `777` `P7` `PPCG`

*Decoder:* `f`

# Answer
> 5 votes
# Pyth, 46 bytes

## Encoder, 22 bytes

```
@smfql{Td^<Szd4S4-Cw48

```

## Decoder, 24 bytes

```
C+48xsmfql{Td^<sS{zd4S4z

```

# Answer
> 7 votes
# CJam, ~~55~~ ~~50~~ ~~48~~ 47 bytes

### Encoder, ~~24~~ ~~22~~ 21 bytes

```
l$:L4m*{$L|L=},rc'0-=

```

Try it online.

### Decoder, ~~31~~ ~~28~~ ~~27~~ 26 bytes

```
4_m*{$4,|4,=},l_$_|f#a#'0+

```

Try it online.

# Answer
> 4 votes
## gawk, 163 + 165 = 328

Tested with gawk 4.1.1, but should work in older gawk versions as well. Needs to be slightly modified (lengthened) to work with mawk.

**encoder** (163):

```
{for(gsub(", ",_);sprintf("%c",++r)!=$NF;asort(a))split($1,a,_);r-=r>64?53:46;for(k=4^5;r-=_~i;j=_)for(i=++k;gsub(++j,_,i);)split(k,b,_);for(j in b)printf a[b[j]]}

```

**decoder** (165):

```
{split($1,a,_);for(i in a)d[a[i]]=a[i];asort(d);for(k=4^5;c!~$1;x+=_~i){i=++k;for(c=j=_;gsub(++j,_,i);split(k,b,_));for(g in b)c=c d[b[g]]}printf"%c",x+(x>10?54:47)}

```

Well, it works, but I'm aware that this might not be the best approach for this. I have no idea what the fifth inexpensive letter is for, because I use only four.

These are for single use only. If you want to enter a second code you have to restart them. The spaces after the commas are required in the input to encode.

## What I thought about

My first question was "What could a decoder get from these 4 characters?" (I'll call them a, b, c and d), and my initial idea was to get 6 bits of Information from following relations:

```
a>b
a>c
a>d
b>c
b>d
c>d

```

Wow, 6 bit, that's perfect! I thought it was genius, but testing showed this would not work. There are only 24 possible combinations. Damn.

The next step was trying to count, based on what I already knew. So the first letter appearing in the string would become 0, then the second letter introduced in the string would become 1 and so on. But it wouldn't bring me all the way to the 62 combinations needed.

```
0000
0001
0010
0011
0012
0100
0101
0102
0110
0111
0112
0120
0121
0122
0123

```

But I like the idea anyhow.

Well, then it struck me, that I could combine these two, because the characters in the input already have relations, and I wouldn't have to wait until they were introduced to give them a value.

## How it works

*Note: This is no longer exactly how the golfed versions work, but the principle stayed the same.*

For the decoder:

An array is constructed, whose index contains all the four digit numbers whose largest digit isn't greater than the number of distinct digits in that number. There are 75 different four digit numbers meeting that condition. I brute force them, because so far I couldn't figure out a way to construct them, and I'm not sure this would be shorter to do in awk anyway. While I find these I assign them the expensive characters in asciibetical order.

Then I replace every character from the input string with a digit. The smallest (for instance is 'B' smaller than 'a') becomes 1, the second smallest becomes 2, and so on up to 4. Of course it depends on how many different characters are in the input, what the highest digit in the resulting string will be.

Then I simply print the array element, which has that string as an index.

The encoder works accordingly.

## How to use

Either copy the code directly in an awk bash line command or make two files "encode.awk" and "decode.awk" and paste the code accordingly. Or even better use the following code, which exits automatically after en/decoding, or can be used multiple times by removing the exit command at the end.

*encode.awk*

```
{
    if(!x) # only do first time
        for(i=1e3;i++<5e3;delete a)
        {
            for(m=j=0;p=substr(i,++j,1);p>m?m=p:0)++a[p];
            length(a)>=m&&i!~0?c[(x>9?55:48)+x++]=i:_
        }
    r=u=_; # clear reused variables
    for(gsub(",",FS);sprintf("%c",++r)!=$NF;); # more flexible concerning
    --NF;                                      # spaces in input
    split($0,b);
    asort(b);
    split(c[r],a,_);
    for(j in a)u=u b[a[j]]; # prettier printing than golfed version
    print u
    exit # <=== remove to encode input file
}

```

*decode.awk*

```
{
    if(!x) # only do first time
        for(i=1e3;i++<5e3;delete a)
        {
            for(m=j=0;p=substr(i,++j,1);p>m?m=p:_)++a[p];
            length(a)>=m&&i!~0?c[i]=sprintf("%c",(x>9?55:48)+x++):_
        }
    delete t; delete d; o=_; # clear reused variables
    split($1,a,_);
    for(i in a)t[a[i]]=1;
    for(i in t)d[++y]=i;
    asort(d);
    for(i in a)for(j in d)if(d[j]~a[i])o=o j;
    print c[o]
    exit # <=== remove to encode input file
}

```

Here is a usage example:

```
me@home:~/$ awk -f encode.awk
w, 0, R, 1, d X
10R1
me@home:~/$ awk -f decode.awk
10R1
X

```

Remember that the space after each comma is required, if you use the golfed versions.

If you want, you can use this short and dirty script to generate some sample data

```
BEGIN{
    for(srand();i++<1000;)
    {
        erg="";
        for(j=0;j++<5;)
        {
            while(erg~(a[j]=substr(c="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",rand()*62+1,1)));
            erg=erg a[j]
        }
        print a[1]", "a[2]", "a[3]", "a[4]", "a[5](rand()>.5?" ":rand()>.5?"  ":"   ")substr(c,rand()*62+1,1)
    }
}

```

and do something funny like

```
me@home:~/$ awk -f gen.awk|awk -f encode.awk|awk -f decode.awk|sort -u|wc -l
62

```

I've seen this more as a programming puzzle. I think it's a little sad, that almost everything on here is golfed, because you can learn a lot more from well documented, readable code, but that's just my opinion. And I golfed it like requested ;)

---
Tags: code-golf
---


title: Cut a pizza into identical slices

text:
# Question
Title: Cut a pizza into identical slices
#

This is what I thought this question was going to be, before I fully read it.

A group of code golfers walk into The Nineteenth Bite Pizzeria and order a pizza. It comes in an irregular shape, made of unit squares. Your task is to help them cut it into identical slices. That is, the slices must have the exact same shape and size; they can be rotated but not flipped/mirrored. For example, if they are Tetris pieces, they must be the same kind, you can't use both an L piece and a J piece.

## Input

You will be given the number of people in the group on the first line (always an integer from 2 to 10, inclusive), followed by a rectangular matrix of ' ' (space) and '#' characters, representing the pizza. All the '#' characters are connected through their edges. The number of '#' characters is guaranteed to be a multiple of the number of people.

## Output

You should print the same matrix, with each '#' character replaced with a digit from 0 to n-1 (n being the number of people). Each digit should mark a slice. The slice shape must be connected through the square edges. The slice numbering doesn't need to be in any particular order. If there are multiple ways of cutting the pizza, any of them is acceptable.
If it's not possible to cut the pizza as required, you should print the string "No pizza for you!" instead.

## Scoring

This is code golf. Your score will be the number of bytes in the program. Characters will be counted through their UTF-8 encoding. Lowest score wins.

## Examples

Input:

```
3
 #
###
####
   #

```

Output:

```
 0
100
1122
   2

```

---

Input:

```
4
###
# #
###

```

Output:

```
001
2 1
233

```

---

Input:

```
2
#    #
######

```

Output:

```
No pizza for you!

```

---

Input:

```
5
    #
   ####
  #####
 #####
#####
####
  #

```

Output:

```
    0
   1000
  21110
 32221
43332
4443
  4

```

---

Input:

```
4
   #
 ####
######
  #####
  ####

```

Output:

```
   0
 1000
111203
  12233
  2233

```

## Requirements

* You should write a full program that reads from the standard input and writes to the standard output.
* The program must be runnable in Linux using freely available software.
* Your program should finish each of the above examples in less than 1 minute on a modern computer.
* No standard loopholes.

# Answer
## PHP code, ~~1808~~ 971 bytes

Quick and dirty implementation in PHP. First brute-force all possible slice shapes, next brute-force all positions and orientations of the slices.

Usage: `cat pizza.txt | php pizza.php`

Edit: reduced code size by more than 45% by rewring algorithm using recursion rather than nested loops. However, this eats memory (and pizza's ;-)). Pizza's larger than 8x8 will probably run out of memory. The nested loop variant can easily handle any size, but is twice the code size.

```
<?php define('A',98);$n=fgets(STDIN);$d=array();$m=$u=str_pad('',A,'+');$s=0;while($g=fgets(STDIN)){$g=rtrim($g);assert(strlen($g)<=A-2);$s++;$m.='+'.str_pad(rtrim($g),A-2,' ').'+';for($l=0;$l<strlen($g);$l++)if($g[$l]=='#')$d[]=$s*A+$l+1;}$m.=$u;$r=count($d)/$n;x(reset($d),array(array()),0,0,0,0);die('No pizza for you!');function x($e,$c,$b,$a,$q,$t){global$r,$m,$d;$h=$a*A+$b;if(!in_array($e+$h,$d))return;if(in_array($h,$c[0]))return;$c[0][]=$h;$c[1][]=$b*A-$a;$c[2][]=-$a*A-$b;$c[3][]=-$b*A+$a;if(count($c[0])<$r)do{x($e,$c,$b+1,$a,$b,$a);x($e,$c,$b,$a+1,$b,$a);x($e,$c,$b-1,$a,$b,$a);x($e,$c,$b,$a-1,$b,$a);$v=($b!=$q||$a!=$t);$b=$q;$a=$t;}while($v);else w($c,$m,0,reset($d),0);}function w(&$p,$f,$o,$e,$i){global$n,$d;foreach($p[$i]as$h){$j=$e+$h;if(!isset($f[$j])||$f[$j]!='#')return;$f[$j]=chr(ord('0')+$o);}if(++$o==$n){for($k=A;$k<strlen($f)-A;$k++)if($k%A==A-1)echo PHP_EOL;else if($k%A)echo$f[$k];exit;}foreach($d as$j)for($i=0;$i<4;$i++)w($p,$f,$o,$j,$i);}

```

**Ungolfed, documented code**

Below is the documented, original code. To keep my sanity, I worked with the full source code, and wrote a simple minifier script to strip statements like `assert()` and `error_reporting()`, remove unnecessary brackets, rename variables, functions and constants to generate the golfed code above.

```
<?php
error_reporting(E_ALL) ;

// Width of each line of pizza shape.
// Constant will be reduced to single character by minifier,
// so the extra cost of the define() will be gained back.
define('WIDTH', 98) ;

// Read number of slices
$nrSlices = fgets(STDIN) ;

// Read pizza shape definition and
// convert to individual $positionList[]=$y*width+$x and
// linear (1D) $pizzaShape[$y*WIDTH+$x] with protective border around it.
//
// WARNING: assumes maximum pizza width of WIDTH-2 characters!
$positionList = array() ;
$pizzaShape = $headerFooter = str_pad('', WIDTH, '+') ;
$y = 0 ;
while ($line = fgets(STDIN))
{  $line = rtrim($line) ;
   assert(strlen($line) <= WIDTH-2) ;
   $y++ ;
   $pizzaShape .= '+'.str_pad(rtrim($line), WIDTH-2, ' ').'+' ;
   for ($x = 0 ; $x < strlen($line) ; $x++)
   {  if ($line[$x] == '#') $positionList[] = $y*WIDTH + $x+1 ;
   }
}
$pizzaShape .= $headerFooter ;

// Determine size of a slice
$sliceSize = count($positionList)/$nrSlices ;

// Build all possible slice shapes. All shapes start with their first part at
// the top of the pizza, and "grow" new parts in all directions next to the
// existing parts. This continues until the slice has the full size. This way
// we end up with all shapes that fit at the top of the pizza.
//
// The shape is defined as the offsets of the parts relative to the base
// position at the top of the pizza. Offsets are defined as linear offsets in
// the 1-D $pizzaShape string.
//
// For efficiency, we keep track of all four possible rotations while building
// the slice shape.
//
growSlice(reset($positionList), array(array()), 0, 0, 0, 0) ;
die('No pizza for you!') ;

function growSlice($basePosition, $shapeDeltas, $dx, $dy, $prevDx, $prevDy)
{  global $sliceSize, $pizzaShape, $positionList ;

   // Check validity of new position
   // Abort if position is not part of pizza, or
   // if position is already part of slice
   $delta = $dy*WIDTH + $dx ;
   if (!in_array($basePosition+$delta, $positionList)) return ;
   if (in_array($delta, $shapeDeltas[0])) return ;

   // Add all four rotations to shapeDeltas[]
   $shapeDeltas[0][] = $delta ;
   $shapeDeltas[1][] = $dx*WIDTH - $dy ;
   $shapeDeltas[2][] = -$dy*WIDTH - $dx ;
   $shapeDeltas[3][] = -$dx*WIDTH + $dy ;

   // Have we built a full slice shape?
   if (count($shapeDeltas[0]) < $sliceSize)
   {  // Grow shape either at current position or at previous position
      do
      {  growSlice($basePosition, $shapeDeltas, $dx+1, $dy,   $dx, $dy) ;
         growSlice($basePosition, $shapeDeltas, $dx,   $dy+1, $dx, $dy) ;
         growSlice($basePosition, $shapeDeltas, $dx-1, $dy,   $dx, $dy) ;
         growSlice($basePosition, $shapeDeltas, $dx,   $dy-1, $dx, $dy) ;
         $retry = ($dx != $prevDx || $dy != $prevDy) ;
         $dx = $prevDx ;
         $dy = $prevDy ;
      } while ($retry) ;
   } else
   {  // Try to cover the entire pizza by translated and rotated instances of
      // the slice shape.
      fitSlice($shapeDeltas, $pizzaShape, 0, reset($positionList), 0) ;
   }
}

function fitSlice(&$shape, $pizza, $id, $basePosition, $rotation)
{  global $nrSlices, $positionList ;

   // Try to fit each part of the slice onto the pizza. If the part falls
   // outsize the pizza, or overlays another slice we reject this position
   // and rotation. If it fits, we mark the $pizza[] with the slice $id.
   foreach ($shape[$rotation] as $delta)
   {  $position = $basePosition + $delta ;
      if (!isset($pizza[$position]) || $pizza[$position] != '#') return ;
      $pizza[$position] = chr(ord('0')+$id) ;
   }

   // If $nrSlices slices have been fitted, we have found a valid solution!
   // In that case, we display the solution and quit.
   if (++$id == $nrSlices)
   {  for ($pos = WIDTH ; $pos < strlen($pizza)-WIDTH ; $pos++)
      {  if ($pos % WIDTH == WIDTH-1) echo PHP_EOL ;
         else if ($pos % WIDTH) echo $pizza[$pos] ;
      }
      exit ;
   }

   // The current slice did fit, but we have still more slices to fit.
   // Try all positions and rotations for the next slice.
   foreach ($positionList as $position)
   {  for ($rotation = 0 ; $rotation < 4 ; $rotation++)
      {  fitSlice($shape, $pizza, $id, $position, $rotation) ;
      }
   }
}

```
> 3 votes

---
Tags: code-golf, geometry, grid, set-partitions
---


# Question
Title: Write code to determine the accepted answer
Post an answer to this question that evaluates any answer to this question and determines whether it wins.

**Who wins:**

* Winner is the answer that wins according to the most answers at 1700 UTC, Sunday, March 2nd.
* You are welcome to and encouraged to change your own answer as the contest progresses. Please do not change others'.
* Ties are determined by the shortest code.
* Regardless of how much sockpuppeting you might normally do, if something's fishy, I'm gonna disqualify you.
* I will not accept my own answer, but I will use it to evaluate yours.

**Rules:**

* Your calculation must provide a numeric score for any arbitrary answer (to make it easy, the input to your algorithm is either the id of the answer or the markdown of the answer on the page).
* Your score must have at least one winner, and it must be possible for an answer besides yours to win.
* Your algorithm cannot use something very specific to your answer, nor can username or timestamps be used at all. I will be the final judge of what "very specific" means, but I encourage community policing and public shaming.
* Your code must compile, run, and give a score given any answer.
* Please include a link to a way to execute your code if it is not listed on Ideone. See below.

# Answer
## R, 1 char

```
1

```

You can supply the id of an answer as a command line argument if you wish. :) Link to ideone.

## Further elaboration

Since it is not practical for an answers to execute other answers (different languages, etc.) and evaluate them based on their result the only remaining way I can see for them to give a score is to use some code metric.

I have noticed that all other answers so far give a higher score to shorter programs. I believe this is the shortest code possible so it should rank high in the result of other answers.

How and what answer my code gives for other answers seams to be less relevant. The only important aspect is that others rank my answer high.
> 6 votes

# Answer
# R, 1 char

```
0

```

Following up on @Andris's answer, there are now two codes that have a single character: Andris's and mine. Since we tie in the eyes of the other answers, neither of us have "won" outright, so my answer won't "win". :-)
> 3 votes

# Answer
## Ruby, 368 char

```
require 'json'
require 'open-uri'
v='body';w="#{v}_markdown";s='comments'
x=if(d=JSON.parse(open("http://api.stackexchange.com/2.2/answers/#{ARGV[0]}?site=codegolf&filter=!%29r%28UkmOhmCPjXru-TDty").read)['items'][0]).include?(s) then d[s].map{|c|c[w].length*[1,c[w].index('`')||1,c[w].index('\n')||1].max}.reduce(:+) else -2 end
puts d['score']*150+5*(d[v].match(/<(..).*?\1.*?\1/m))[0].ord+x-$~.end(0)

```

Good luck!
> 2 votes

# Answer
## JavaScript- 190 char

Assumption: The first code block is the answer.

```
var ans=$('.answer'),s=999,sa;
for(i=0;i<ans.length;i++){
    var x =  ans[i].getElementsByTagName('code');
    var z = x[0].innerHTML.replace(/\s/g,'').length;
    if(s>z){
        s=z;
        sa=ans[i];
        }
}
console.log(sa);

```

Can be tested in browser console. It assumes the shortest answer to be the correct answer.

How to execute- On Chrome/Firefox open console while on this page and paste code and execute.
> 2 votes

---
Tags: code-challenge, stack-exchange-api
---