# Question
Title: Print 123454321 without if statements and using only 2 variables
The challenge: Write a function, that delivers following output: "1 2 3 4 5 4 3 2 1".

Kids stuff? Of course. But here's the point:

* You only can use: 1 for loop, 2 int variables.
* You must not use: IF terms, another function, ...
* Do not hardcode the output

There are also some more restrictions to make this harder:

* No functions like abs or sth. else are allowed! (Yep, it's possible)
* No static output like echo "1 2 3 4 5 4 3 2 1"

This is a , so the answer with the most votes wins!

# Answer
# Cobra

## Really, this is quite trivial.

```
class Program
    def main
        for i in 10, Console.write(5 - Math.abs(5 - i))

```

Or

```
class Program
    def main
        v as int = 123454321
        for i in v.toString, Console.write(i)

```

Or even simpler

```
class Program
    def main
        print 1, 2, 3, 4, 5, 4, 3, 2, 1

```

## But if you insist on following the question *exactly*:

```
class Program
    def main
        num as int = 123454321
        for i in '[num]'
            Console.write(i)
            Console.write(' ')

```

This uses only one integer variable, only one loop, and the only function explicitly called is used for output.
> 3 votes

# Answer
## Python

One for loop, one int variable (`i`), no if, no other functions (unless you consider `print` or `+-*/` as functions, haha):

```
for i in range(9):
    print i+1 - 2*(i//5)*(i-4),

```
> 10 votes

# Answer
# C

No function, no hidden IF (abs, min, etc.)

```
#include <stdio.h>

int main()
{
int sum=0;
for (int i=3; i<12; i++)
    {
    sum += 1-2*(i/8);
    printf("%d\n", sum );
    }
}

```

Explanation : The 4th bit of i is the heart of the trick : it's 0 for \[3,7\] and 1 for \[8,11\].

i/8 gives the value of the bit (just like i\>\>3) for i in \[3,11\] it gives : 0, 0, 0, 0, 0, 1, 1, 1, 1

1-2\*(i/8) is simple math to obtain 1, 1, 1, 1, 1, -1, -1, -1, -1

+= is used to sum the values
> 5 votes

# Answer
**Javascript, 32 characters**

```
+new Date(1970,0,2,11,17,34,321)

```

*edit:* **not timezone-dependant, 42 chars**

```
+new Date(Date.UTC(1970,0,2,10,17,34,321))

```
> 4 votes

# Answer
# Delphi XE3

I dont think this requires much explaining right?

```
function p:string;
var
  i:integer;
begin
  for I:=1 to 4 do
    Result:=Format('%s%d ',[Result,I]);
  Result:=Format('%s%d%s',[Result,5,ReverseString(Result)]);
end;

```

In case it does. Function loops from 1 to 4, and keeps adding the number + \[space\].
Then it adds I again which became 5 which made it quit the loop and adds the reversed string as it is now.

# Variation

```
function p:string;

```

const s='123454321' var i:integer; begin s:='123454321'; for I:=1to Length(s) do Result:=Format('%s %s',\[Result,s\[i\]\]); Exit(Trim(Result));
end; This might seem hardcoded but the constant doesnt have the spaces that are required.
Although it might seem impossible but there is a solution that is even lamer than this.

```
function p:string;
const
  s='123454321'
begin
  result:=Format('%s %s %s %s %s %s %s %s %s',[s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9]])
  {or}
  result:=Format('%s %s %s %s %s %s %s %s %s',[s[1],s[2],s[3],s[4],s[5],s[4],s[3],s[2],s[1]])
 {OR!}
  result:=Format('%d %d %d %d %d %d %d %d %d',[1,2,3,4,5,4,3,2,1])
end;

```
> 3 votes

# Answer
### Golfscript, 16 characters

```
6,(;)1$-1%++' '*

```

I assume this is meant to be a code golf?

No variables. All data (two arrays and a number) is on the stack. The only loops are implicit ones.

Online demonstration: http://golfscript.apphb.com/?c=NiwoOykxJC0xJSsrJyAnKg%3D%3D
> 3 votes

# Answer
**C++: Works finely in VC 11.0**

```
#include <iostream>
#include <cstring>
#include <vector>
#include <conio.h>
#include <algorithm>

using namespace std;

bool called = false;
int main();
int f() {
    called = true;
    typedef vector<int>::iterator _v_interate;
    int l;
    static bool d;
    vector<int> iVector;
    for(l = 1; (true); (!d) ? l++ : l--) {
        _v_interate i = find(iVector.begin(), iVector.end(), 4);
        _v_interate i2 = find(iVector.begin(), iVector.end(), 3);
        _v_interate i3 = find(iVector.begin(), iVector.end(), 2);
        _v_interate i4 = find(iVector.begin(), iVector.end(), 1);
        _v_interate i5 = find(iVector.begin(), iVector.end(), 5);
        d =  (i != iVector.end()) &&  (i2 != iVector.end()) &&  (i3 != iVector.end()) &&  (i4 != iVector.end()) ? 1 : 0;
        iVector.push_back(l);
        cout << l << " ";
        (d && (l==1) ? main() : 0);
    }
    return 0;
}

int main() {
    !called ? f() : 0;
    _getch();
    exit(0); // Removing the exit(0) causes an infinite loop; I don't know why.
    return 0;
}

```

A simple solution:

```
#include <iostream>

void main() {
  cout << "1 2 3 4 5 4 3 2 1";
}

```
> 3 votes

# Answer
# Perl

### Version 1:

```
for(1..9){
    $x = ($_%18 - 5);
    print 5 - ($x, -$x)[$x < -$x] . " ";
}

```

### Version 2:

```
for(1..9){
    $x = ($_%18 - 5);
    $x =~ s/-//;
    print 5 - $x . " ";
}

```

For both versions: 1 For loop, and 2 variables, `$_` and `$x`, and I'm not using `if` or any other function.
> 3 votes

# Answer
Ruby - **47 chars**

```
(1..4).to_a.push((1..5).to_a.reverse).join ' '

```

Edit - **33 chars**

```
[*(1..4),[*(1..5)].reverse]*' '

```
> 3 votes

# Answer
**Java**

Used one loop and the loop variable. Added a constant for the upper bound.

```
public class Test {
   private static final int BOUND = 5;
   public static void main(String[] args) {
      for (int i = 1; i < BOUND * 2; i++) {
         System.out.print(i - (2 * ((i % BOUND) * (i / BOUND))) + " ");
      }
   }
}

```
> 2 votes

# Answer
# Brainfuck, 83

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

```

Only 1 loop, no `if`s (if you don't count the loop as an `if`). No `int` variables.
> 2 votes

# Answer
# JavaScript

```
function f(){
  for ( var i=1,j=5; j>0; ++i>j&&(--i,--i,--j) )
    console.log(i);
}

```
> 2 votes

# Answer
# C

Not sure if it follows exactly the rules but my answer is below

```
int main()
{
    int x;
    for(x = 123454321; x > 10; x /= 10)
    {
        printf("%d ", x % 10);
    }
    printf("%d", x);
    return 0;
}

```

Run the code
> 2 votes

# Answer
Well, I guess the fastest and most naive solution (in Python) would be:

```
' '.join (str(x) for x in range(1,6)) + ' ' + ' '.join (str(x) for x in range(4,0,-1))

```
> 1 votes

# Answer
# Javascript

This might not be the best and fastest way to do it, but I like what I came up with.

```
z = '';
for (x = 1; x <= 5; x++) { // Don't need a loop, but hey, I like loops!
    z += x + ' '; // Creates "1 2 3 4 5 "
}
document.getElementById('result').innerHTML = z + z.split("").reverse().join("").substring(2, 10);
// "1 2 3 4 5 " + " 4 3 2 1"

```

Result:

```
1 2 3 4 5 4 3 2 1

```

You can see it in action Here!
> 1 votes

# Answer
As 2.0

```
var num:Int = 11111;
alert(num*num);

```
> 1 votes

# Answer
**C**

```
#include <stdio.h>

int main(void) {
    int i;
    for (i = 21911761; i > 0 && printf("%d", i&7); i = i>>3)
        i > 1 && printf(" ");

    return 0;
}

```
> 1 votes

# Answer
## Java, 79 chars (standalone: 131 chars)

```
int b=-1,i=1;for(;i>0&(i<5||(b=1)==1);i-=b){System.out.print(i+(b==i?"":" "));}

```

Uses two `int`s, and no other variables. No if statements, just a for loop for evaluation. This will run on its own when put in the main(String\[\] args) method in a class, or in any other function. The full code, including class declaration and method, is 131 chars.

```
public class M{public static void main(String[]a){int b=-1,i=1;for(;i>0&(i<5||(b=1)==1);i-=b){System.out.print(i+(b==i?"":" "));}}}

```

While I'm at it:

## PHP, 70 chars (standalone: 78 chars)

```
$b=-1;for($i=1;$i>0&($i<5||($b=1)==1);$i-=$b){echo$i.($b==$i?"":" ");}

```

Uses same method as Java. Standalone script is 62 chars:

```
<?php $b=-1;for($i=1;$i>0&($i<5||($b=1)==1);$i-=$b){echo$i.($b==$i?"":" ");}?>

```
> 1 votes

# Answer
# Fortran 90: 60

```
integer::j(9)=5;do i=1,4;j(i)=i;j(10-i)=i;enddo;print*,j;end

```

If you wanted it formatted slightly better, I can add a few characters to make the print statement `print'(9i2)',j`. Ungolfed & written properly, this is

```
program main
   implicit none
   integer :: i, j(9)
   j = 5
   do i=1,4
      j(i) = i
      j(10-i) = i
   enddo
   print *,j
end program main

```
> 0 votes

# Answer
# Powershell

```
((1..9)|%{
    $_ = ($_%18-5)
5 - @($_,-$_)[$_ -lt -$_]
})-join ' '

```

1 variable, no `if`, no functions (unless you were to count `-join` which is just for displaying the data...

**Explanation:** Loops from 1 to 9, then for each value calculates the reminder of the current value by 18, then subtracts 5 and assigns it to the currently used `$_` variable. After that it evaluates `$_ < -$_` (this is to handle negative values), and uses the result (`False`/`True`) to get the value from the array `@($_,-$_)`, therefore making sure we always get a positive number in this case, after that it subtracts this number to 5 and finally joins the results with space.
> 0 votes

# Answer
# Scala, 53

```
(4 to 12).foldLeft(1)((a,b)=>{print(a);a+1-2*(b/8)})

```

I stole the neat bit shifting idea from @cpri

http://scalafiddle.net/console/3b3fff6463464959dcd1b68d0320f781
> 0 votes

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


title: Fibonacci Sequenze without using loops!

text:
# Question
Title: Fibonacci Sequenze without using loops!
Here is one more "Challenge"! Today i had a meeting with a friend, and mostly we are a little bit crazy.. He bets, that it is not possible to create a Fibonacci Sequence without using loops.

No static output like:

```
return "1, 2, 3, 5, 8, 13, ..";

```

**GOAL / Requirements**

* Use only 1 int var
* Return the first 5 (or more) numbers
* Name your function "fibonacci"
* Call no other functions except "fibonacci"
* No loops are allowed
* Have fun ;)

**Scoring**

Popularity contest (Most upvotes minus downvotes)

**End Date**

June 17. 2014

**No special language required**

# Answer
> 3 votes
# Kona

```
fibonacci:{((x-1)(|+\)\1 1)[;1]}

```

Execute in shell as `fibonacci 12` to get the first 12 Fibonacci numbers.

**Explanation**:

* `1 1` is a vector
* `(|+\)\` generates a vector of vectors by summing the elements of the vector
* `(x-1)` reduces 12 to 11 (due to 0 indexing) which is applied to the summation to repeat `x-1` times
* `[;1]` returns/prints the second element of each vector in the larger vectors.

If I neglected the `[;1]` portion, you can see what happens to the vector:

```
> fib 1
,1 1
> fib 2
(1 1
 2 1)
> fib 3
(1 1
 2 1
 3 2)

```

And so on.

# Answer
> 3 votes
# Python

```
def fibonacci(n):
    if n > 1:
        return fibonacci(n-1) + [(1.618033988749895**n/2.23606797749979 + 0.2) // 1]
    else:
        return [1]

```

Call `fibonacci(n)` to generate a list up to the nth element of the Fibonacci series. Sample output of `fibonacci(20)`:

```
>>> fibonacci(20)
[1, 1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 21.0, 34.0, 55.0, 89.0, 144.0, 233.0, 377.0, 610.0, 987.0, 1597.0, 2584.0, 4181.0, 6765.0]

```

The correctness is limited by the precision of the double precision floating point.

# Answer
> 3 votes
**EXCEL / NUMBERS / $spreadsheetapp**

I think I saw this somewhere here, but I can't remember. Nevertheless, credits go to unknown author. Just Fill in the first 2 fields, do a simple addition and then it's time to drag, baby!

# Answer
> 1 votes
# JavaScript (ECMAScript 6)

```
fibonacci=n=>n<2?[0,1]:[...fibonacci(n-1),fibonacci(n-1)[n-1]+fibonacci(n-2)[n-2]]

```

or more efficiently

```
fibonacci=n=>n<2?[0,1]:(i=fibonacci(n-1),[...i,i[n-1]+i[n-2]])

```

or even more efficently (but with a loop instead of recursion)

```
fibonacci=n=>[i[m]=m<2?+m:i[m-1]+i[m-2]for(m in i=[...Array(n)])]

```

---
Tags: popularity-contest
---


# Question
Title: Cheap, Fast, Good - Common Factor (Greatest)
Inspired by Cheap, Fast, Good, we're going to implement an algorithm which has exactly two of them.

**The Math**

Given two nonzero integers *a* and *b*, the GCF *d* is the largest integer that divides both *a* and *b* without remainder. Bézout coefficients are pairs of integers *(x, y)* such that *ax + by = d*. Bézout coefficients are not unique. For example, given:

```
a = 15, b = 9

```

We have

```
d =  3
x =  2
y = -3

```

Since `15*2 + 9*(-3) = 30 - 27 = 3`.

A common way to calculate the GCF and a pair of Bézout coefficients is using Euclid's Algorithm, but it's by no means the only way.

**The Code**

Your program should take two integers as inputs. It should output/return the greatest common factor and one pair of Bézout coefficients.

Example input:

```
15 9

```

example output

```
3 (2, -3)

```

The output can be in any order and format, but it should be clear which is the GCF and which are the coefficients.

**The Underhanded**

Your program has the potential to be cheap, fast, and good. Unfortunately, it can only be two of those at once.

* When it's not *cheap*, the program should use an excessive amount of system resources.
* When it's not *fast*, the program should take an excessive amount of time.
* When it's not *good*, the program output should be wrong.

The program should be able to do (well, not do) all three. Which is does when is up to you- it could be based on the time, the compiler, which input is larger, etc. Some additional notes:

* Your program should not be obviously underhanded and should pass a cursory inspection. I'd be a little suspicious if you implemented three separate algorithms.
* In the *cheap* case, "excessive amount of system resources" is anything that would slow down other programs. It could be memory, bandwidth, etc.
* In the *fast* case, "excessive time" means relative to how it runs in the *cheap* and *good* cases. The program should still finish. The closer you can to "incredibly frustrating but not frustrating enough to stop the program" the (funnier and) better.
* In the *good* case, the output shouldn't be obviously wrong and should pass a cursory inspection. I'd be **very** suspicious if it gave me a GCF of "2 anna half".

This is a popularity contest, so most upvotes wins!

**EDIT**

To clarify, I'm looking for programs that can be "fast and cheap" *and* "cheap and good" *and* "fast and good" in different cases, not ones that just do one of them.

# Answer
# C

It's cheap and fast. You get gcd in the blink of an eye. However the guy who did it had no clue about that "Bézier co-something" so he simply divided a and b by gcd. (to make things worse, at that point a and b are pretty far from their initial value because of the algorithm he wisely chose)

```
int main(int argc, char **argv){
    unsigned int a, b, tmp;
    a = (unsigned int)atoi(argv[1]);
    b = (unsigned int)atoi(argv[2]);
    for (tmp = 0; ((a | b) & 1) == 0; ++tmp){
        a >>= 1;
        b >>= 1;
    }
    while ((a & 1) == 0)
        a >>= 1;
    do {
        while ((b & 1) == 0)
            b >>= 1;
        if (a > b){
            unsigned int t = b;
            b = a;
            a = t;
        }
        b = b - a;
    } while (b != 0);
    tmp = a << tmp;
    printf("%u, (%u,%u)", tmp, a/tmp, b/tmp);
    return 0;
}

```
> 2 votes

# Answer
## C#

This calculates the Bézout coefficients. I used the Extended Euclidean algorithm.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your first number.");
            int firstNumber = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter your second number.");
            int secondNumber = Convert.ToInt32(Console.ReadLine());

            double max = Math.Max(firstNumber, secondNumber);
            double min = Math.Min(firstNumber, secondNumber);
            double s1 = 1;
            double s2 = 0;
            double t1 = 0;
            double t2 = 1;
            double quotient = 0;
            double remainder = 0;
            double[] remainders = new double[0];

            int i = 0;
            do
            {
                quotient = (int)(max / min);
                remainder = max - quotient * min;
                if (remainder > 0)
                {
                    Array.Resize(ref remainders, remainders.Length + 1);
                    remainders[i] = remainder;

                }
                if (i % 2 == 0)
                {
                    s1 = s1 - quotient * s2;
                    t1 = t1 - quotient * t2;
                }
                else
                {
                    s2 = s2 - quotient * s1;
                    t2 = t2 - quotient * t1;
                }

                if (i == 0)
                {
                    max = min;

                }
                else if (i >= 1)
                {
                    max = remainders[i - 1];
                }

                min = remainder;
                i++;
            } while (remainder > 0);

            Console.WriteLine((remainders[remainders.Length - 1]).ToString() + " " + (i % 2 == 0 ? "(" + s1 + "," + t1 + ")" : "(" + s2 + "," + t2 + ")"));
        }

    }
}

```
> 0 votes

# Answer
# Javascript

### Not cheap

Uses a lot of system resources.

```
function gcf(a, b) {
    var result = 1;
    for (var i = 1; i < 100000000 * a && i < 100000000/* Do it a few extra times, just to make sure */ * b; i++) {
        if (a % i == 0 && b % i == 0) {
            result = i;
        }
    }
    return [result, a / result, b / result];
}

```

### Not fast

Use a callback, just as an extra failsafe.

```
function gcf(a, b) {
    setTimeout(function() {
        var result = 1;
        for (var i = 1; i < 2 * a && i < 2 * b; i++) {
            if (a % i == 0 && b % i == 0) {
                result = i;
            }
        }
        alert(result.toString() + " (" + (a / result).toString() + ", " + (b/result).toString() + ")");
    }, 10000);
}

```

### Not good

Strict limit of `gcf(10, 10)`, just to safe disk space.

```
function gcf(a, b) {
    var gcfTable = [[1,1,1,1,1,1,1,1,1,1],[1,2,1,2,1,2,1,2,1,2],[1,1,3,1,1,3,1,1,3,1],[1,2,1,4,1,2,1,4,1,2],[1,1,1,1,5,1,1,1,1,5],[1,2,3,2,1,6,1,2,3,2],[1,1,1,1,1,1,7,1,1,1],[1,2,1,4,1,2,1,8,1,2],[1,1,3,1,1,3,1,1,9,1],[1,2,1,2,5,2,1,2,1,10]];
    return [gcfTable[a - 1][b - 1], a / gcfTable[a - 1][b - 1], b / gcfTable[a - 1][b - 1]];
}

```
> 0 votes

# Answer
# Perl 5

```
#!/usr/bin/perl
use strict;
use warnings;

$SIG{__WARN__} = sub { exit };

print(<<INTRO);
Greatest Common Factor

    goodbye           -- exit the application
    [number] [number] -- compute gcf of both numbers

INTRO

main();
sub main {
    print "> ";
    chomp(local $_ = <STDIN>);

    print "Have a good one.\n" and exit if /goodbye/;

    my @nums = /(-?\d+)/g;
    print "invalid input\n" and return main() if @nums != 2;

    my ($gcf, @coeff) = gcf(@nums);
    unless (grep abs($_) > 99, $gcf, @coeff) {
        select $\,$\,$\, rand for 1..10;
    }

    local $" = ", "; #"
    print "gcf(@nums) = $gcf\n";
    print "bezout coefficients: @coeff\n";
    main();
}

sub gcf {
    my ($x, $y) = @_;

    my @r = ($x, $y);
    my @s = (1, 0);
    my @t = (0, 1);

    my $i = 1;
    while ($r[$i] != 0) {
        my $q = int($r[$i-1] / $r[$i]);
        for (\@r, \@s, \@t) {
            $_->[$i+1] = $_->[$i-1] - $q * $_->[$i];
        }
        $i++;
    }

    return map int(1.01 * $_->[$i-1]), \@r, \@s, \@t;
}

__END__

```

Not cheap: main() is called recursively (filling up the stack) until a "deep recursion" warning is fired by perl which will quit the application due to the \__WARN\__ handler.

Not fast: When the gcf() algorithms returns correct results, the code just hangs on for a few seconds (select() in main()).

Not good: All results above 99 (or below -99) are incorrect.

All in all not so creative; looking forward to more elegant answers.
> 0 votes

# Answer
Python

```
#!/usr/bin/python
def gcd(x, y):
    l = 0
    if x < y:
        l = x
    else:
        l = y
    for g in reversed(range(l + 1)):
        if x%g == 0 and y%g == 0 and g > 1:
            return g
        else:
            if g == 1:
                return 1

def bezout(x,y,g):
    c1 = 0
    c2 = 0
    k = 0
    if x < y:
        k = y
    else:
        k = x
    for _k in range(k):
        tc = (gcd(x,y) - x*_k)%y
        if tc == 0:
            c1 = _k
            c2 = (gcd(x,y) - y*_k)/x
            return (c1, c2)

gc = gcd(15,9)
be, bf = bezout(9,15,gc)
print("%d (%d, %d)" % (gc, be, bf))

```

This is cheap and fast but it is bad in the fact that the range is capped at the largest input so it may not find a pair of coefficients.

Good puzzle.
> 0 votes

---
Tags: popularity-contest, number-theory, underhanded
---


title: Implement an integer parser

text:
# Question
Title: Implement an integer parser
Implement an integer parser in the shortest code possible, with the following restrictions:

1. The function or program can only take one argument: a string (or equivalent). Assume it to be signed and always valid (don't worry about decimals, etc.). The input may optionally omit the sign, in which it is assumed to be positive.
2. The function or program must output an integer (or equivalent).
3. No pattern matching, regular expressions, etc. are allowed. This includes utilities such as `tr` for \*nix.
4. No string parsing utilities are permitted, even from the standard library. This includes, but is not limited to, `parseInt()` from JavaScript, `int()` in Python, and `Int32.parse()` from VBScript.
5. The only permitted predefined string manipulation functions, methods, etc. fall into one of the following categories:

* extract a substring (e.g. `substr()`, `slice()`)
    * get code point from character, vice versa (e.g. `toCodePoint()`, `fromCodePoint()`)
    * concatenate strings (e.g. `append()`, `concat()`, `strcpy()`)
6. No external libraries are permitted.
7. No string parsing utilities are permitted, even from the standard library.
8. Implicit conversion to string is disallowed (e.g. `1+''` in JavaScript)

Shortest code wins, so happy golfing!

**EDIT:** Sorry for the confusion, but implicit conversion is also disallowed.

# Answer
# GolfScript, 19 / 24 / 28 chars

Assuming that positive numbers are always preceded by a `+` sign (19 chars; online demo):

```
(45-~0@{48-\10*+}/*

```

Assuming that positive numbers *never* have a `+` sign (24 chars; online demo):

```
"-"/)0\{48-\10*+}/-1@,?*

```

Assuming that positive numbers may or may not have a `+` sign (28 chars; online demo):

```
"+"-"-"/)0\{48-\10*+}/-1@,?*

```

(This is the same as the 24-char solution about, but with `"+"-` prepended to strip away any `+` signs.)

All of these are based on the following 13-character program, which converts an unsigned base-10 digit string into an integer:

```
0\{48-\10*+}/

```

It works by keeping a running total on the stack and iterating over (the ASCII codes of) the characters in the string. For each character, it subtracts 48 (the ASCII code of `0`) from the ASCII code, multiplies the running total by 10, and adds the two together to give the new running total.

The rest of the code is for sign handling. The always-signed case is easiest, because we can just chop the first character off the string and test its ASCII code to see if it's `+` (43) or `-` (45). Conveniently, the ASCII codes of those two characters differ by two, so we can easily remap them to 1 and -1 via subtraction and negation. (The code happens to also give the right answer for an unsigned zero, but mostly by accident.)

For the only-negatives-signed case, we use a different strategy: we split the input string at `-` signs, take the last segment as the number, and count the number of earlier segments to determine whether to negate the number or not. The code for the maybe-signed case is exactly the same, but we first strip off any plus signs to reduce it to the previous case.

---

**Ps.** If we can cheat and use eval, the obvious GolfScript solution is just one character long:

```
~

```

It doesn't handle leading `+` signs, though, since GolfScript integer literals don't allow them.
> 4 votes

# Answer
# Python 3 (68)

```
s=input()
n=s<'0'
t=0
for c in s[n:]:t=t*10+ord(c)-48
print(t-t*2*n)

```

The Boolean `n` remembers whether the string started with a minus sign by using the lexicographic string ordering, in which `'-'` is less then the lowest digit `'0'`. The expression `s[n:]` casts n to a number (0 or 1), skipping the minus sign if it was there. The expression `t-t*2*n` is a shortening of `[t,-t][n]`.
> 5 votes

# Answer
## Python, 164 125 121 characters

```
n=raw_input()
d=[i-48for i in map(ord,n[::-1])if i!=45]
x=0
for i in range(len(d)):x+=d[i]*10**i
if'-'==n[0]:x=-x
print x

```

Prints out the value with a .0 on the end but that should be all right for the purposes of the exercise, right? Either way, it's a complete script in and of itself. Idea's pretty simple: get ASCII values of the characters passed in, convert those to numbers, multiply each digit by a relevant power of 10 and sum the lot. Test the first character passed in to see if it's negative.

It can almost certainly be shortened but since I'm really new to this whole golfing thing (2nd submission) I reckon it's not bad.

Edit: further golfed by TheRare
> 3 votes

# Answer
# GolfScript, 33 characters

I'm still pretty new to GolfScript, so I'm not sure how well this came out. I could be missing some better approaches/optimizations. If you see any, let me know so I can hopefully learn!

I believe this code works correctly for any signed integer of the form: `[-+]?[0-9]+`

Fully golfed:

```
(.45=!2*(:s;48-.0>*\{48-s*\10*+}/

```

Expanded source with C-ish pseudocode:

```
"-01234567890"  # char in[] = "-01234567890";

(               # char c0 = in[0];
.45=!2*(:s;     # int s = c0 == '-' ? -1 : 1;
48-.0>*\        # int x = c0 > '0' ? c0 - '0' : 0;
{               # for (char c : in[1-]) {
  48-s*\10*+    #   x = x * 10 + (c - '0') * s;
}/              # }
                # return x;

```
> 3 votes

# Answer
# C 75 76 80 chars

```
p(char*s){int c,r=0,m=*s-45;for(;c=*s++;)r=c<48?r:r*10+c-48;return m?r:-r;}

```

No checks for valid inputs, as by rule 1.

THX bebe for edit - Now still 1 less
> 3 votes

# Answer
# CJam - 14

```
q(',\-\'0f-Ab*

```

It assumes the input is signed, that is, it always starts with a "+" or "-".
Try it online at http://cjam.aditsu.net/

`q` reads the input
`(` takes out the first character
`',\-` subtracts it from the ',' character, resulting in 1 for '+' and -1 for '-'
`\` swaps the sign with the rest of the number
`'0f-` subtracts the character '0' from each character, obtaining an integer array
`Ab` converts this array to a number in base 10 (A=10)
`*` multiplies the number with the sign

Thanks Runer112
> 2 votes

# Answer
# Haskell - 51 ~~69~~ chars

```
p('-':n)= -p n
p n=foldl(\v->(10*v-48+).fromEnum)0n

```
> 2 votes

# Answer
# Python 3 - ~~92~~ 84

I'm pretty happy with this.

```
x=lambda n:[1,-1][n<'0']*sum(10**i*(ord(c)-48)for i,c in enumerate(n[n<'0':][::-1]))

```

Alternatively, without a lambda: (92)

```
def x(n):j=n[0]=='-';return((j*2-1)*sum(10**i*(ord(c)-48)for i,c in enumerate(n[j:][::-1])))

```

Thanks to xnor for `n<'0'`.
> 2 votes

# Answer
## Mathematica - 33 or 37

```
Fold[10#+#2&,0,ToCharacterCode@#-48]&

```

or

```
FromDigits[ToCharacterCode@#-48]&

```

if `FromDigits` is permissible. `FromDigits` takes a list of integers and interprets it as the digits of a number (in arbitrary base).

In contrast, `Fold` can be considered a fundamental part of the language (even though what is fundamental and what isn't is a bit subjective in Mathematica).
> 2 votes

# Answer
# AWK, 120 characters

```
{for(i=0;i<10;i++)o[sprintf("%c",i+48)]=i;for(i=l=length($0);i>0;i--)(c=substr($0,i,1))in o?r+=o[c]*10^(l-i):r=-r;$0=r}1

```

Usage:

```
$ echo -0123456789 | awk -f parse-int.awk
-123456789

```

AWK is a language where numbers are strings. (Perl, Tcl, and the Unix shell are also such languages.) My code is stupid because it pretends that numbers and strings are different.

AWK has no function to convert a string to a code point, so I do the inverse, using `sprintf("%c",i+48)` to convert a code point to a string. I then loop from 0 to 9, storing `o["0"] = 0` through `o["9"] = 9` in an associative array. Later, I use `o[c]` to get the number 9 from the string "9". This is stupid because 9 and "9" are already the same thing.

The usual ways to split a string into characters are with `FS=""` or `split(string,array,"")`, but these use `""` as an empty regular expression, and I can't use regular expressions. So, I use `c=substr($0,i,1)` to get each character `c` from the input line `$0`. I check if `c` is an index in array `o`. If yes, I add the product of `o[c]` and a power of 10 to the result. If no, I assume that `c` is a negative sign and negate the result.

# AWK, 1 character, no parser!

```
1

```

Usage:

```
$ echo -0123456789 | awk 1
-01234567890

```

This 1-character answer implements all the requirements except for parsing the integer, just by copying input to output.

To print the parsed integer, I must format it as a string. The input is already a valid integer formatted as a string. So I optimize my program to skip the parse!
> 1 votes

# Answer
# JavaScript (ECMAScript 6) - ~~83~~ ~~80~~ ~~71~~ 67 Characters

**Version 4:**

Since the input is always signed (i.e. has a leading `+` or `-`) then:

```
f=x=>(t=0,[(k=48-c.charCodeAt())>0?s=4-k:t=10*t+k*s for(c of x)],t)

```

However, if it can be unsigned then (+5 characters):

```
f=x=>(s=-1,t=0,[(k=48-c.charCodeAt())>0?s=4-k:t=10*t+k*s for(c of x)],t)

```

**Version 3:**

Since the input is always signed (i.e. has a leading `+` or `-`) then:

```
f=x=>[...x].reduce((p,c)=>(k=48-c.charCodeAt())>0?(s=4-k,0):10*p+k*s,0)

```

**Version 2:**

```
f=x=>[...x].reduce((p,c)=>((k=c.charCodeAt()-48)<0?p:k+10*p),0)*(x[0]=='-'?-1:1)

```

**Version 1:**

```
f=x=>[].reduce.call(x,(p,c)=>((k=c.charCodeAt()-48)<0?p:k+10*p),0)*(x[0]=='-'?-1:1)

```

# JavaScript (ECMAScript 6) - 8 Characters

JavaScript will implicitly try to convert any variable to a number if you perform an arithmetic operation on it **as part of the language** (i.e. without using any external libraries). So any of the solutions below will convert a string containing a valid number to a number.

```
f=x=>~~x
f=x=>x-0
f=x=>x*1
f=x=>x|0

```

# JavaScript (ECMAScript 6) - 7 Characters

```
f=x=>+x

```

# JavaScript (ECMAScript 6) - 5 Characters

Or as an anonymous function:

```
x=>+x

```
> 1 votes

# Answer
# Java 7 - 107

Boring and long (typical for Java), but the other Java answer is an embarrassment so I had to remedy the situation.

```
int p(String i){for(int x=1,l=i.length(),a=0;;a=a*10+i.charAt(x++)-48)if(x==l)return i.charAt(0)==45?-a:a;}

```

Ungolfed:

```
int parseInt(String input) {
  for(int index = 1,len = input.length(),accumulator=0,num;;
      num = input.charAt(index) - '0',
      accumulator = accumulator * 10 + num,index++)
    if (index == len) return input.charAt(0)=='-'?-accumulator:accumulator;
}

```
> 1 votes

# Answer
# C (82 chars)

I'm late to the party and I guess my answer is really close to edc's.

```
int i(char*s){int v=0,n=*s-'-';if(!n)s++;for(;*s;s++)v=v*10+*s-'0';return n?v:-v;}

```
> 1 votes

# Answer
# Fortran - 46 characters

```
function i(s);character(len=*)s;read(s,*)i;end

```

Call like:

```
i('100')

```
> 1 votes

# Answer
## C# - 82 characters

```
int p(string t)
{
 var n=t(0)=='-';
 var i=n?1:0;
 var v=0;
 while(i<t.length)
 {
   v=(10*v)+(t(i)-'0');
   i++;
 }
 return n ? -v : v;
}

```

I think this would also parse a string `t` into an int.

```
 var i = t.skip(t(0)=='-'?1:0).Aggregate(0,(p,c)=>(10*p)+(c-'0'))*(t(0)=='-'?-1:1);

```
> 0 votes

# Answer
# Javascript (E6) 80 ~~92~~

Edit: apply 'reduce' directly, no need to 'split'. Thanks to MTO

**Esoteric**

```
Q=S=>(m=1,[].reduce.call(S,(p,x)=>(c=48-x.charCodeAt())>0?(m=c-4)&0:p*10-c*m,0))

```

**Simple loop** stay behind at 92

```
P=S=>{for(n=i=0,m=S[0]>'/'||(S[i++]>'+'?-1:1);d=S.charCodeAt(i++);n=n*10+m*(d-48));return n}

```

Anyway, assume valid input: first letter can be '-' or '+' or digit, then digits only

... or even

```
F=S=>1*S

```

No library function used
> 0 votes

# Answer
## Scala, 115 characters

```
def p(s:String)=((0,1)/:s.reverse){case(a,'+')=>a;case(a,'-')=>(-a._1,0);case((t,n),d)=>(t+(d.toInt-48)*n,n*10)}._1

```

Ungolfed:

```
def parseInt(input: String) = ((0, 1) /: input.reverse) {
  case (acc, '+') => acc
  case (acc, '-') => (-acc._1, 0) // place never used again
  case ((total, place), digit) =>
    (total + (digit.toInt - 48) * place, place * 10)
}._1

```
> 0 votes

# Answer
# Python 2.7 - 102 bytes

```
def p(n):
 a,r,l=0,range(10),list(n);d=dict(zip(map(str,r),r))
 while l:a*=10;a+=d[l.pop(0)]
 return a

```

I believe this is valid, but I'm not 100% sure about rule 3.

Creates a dictionary where the keys are the strings `'0'`, `'1'`, `'2'`... `'9'` and the values are the int representing that key. Creates a list of the characters in the input, and assigns `a`to 0. While the list we made isn't empty, multiply `a` by 10, take off the first item of that list and use it as a key in the dictionary, adding the value to `a`. Then just return `a`.
> 0 votes

# Answer
## Java - 274 Characters

```
static int parseInt(String arg)
{
    int length = arg.length();
    String reversed = new StringBuilder(arg).reverse().toString();
    int sum = 0;
    for(int i=0; i<length-1; i++)
        sum += (reversed.charAt(i)-48) * Math.pow(10, i);
    if(arg.charAt(0) == '-')
        sum = -1*sum;
    else
        sum += (reversed.charAt(length-1)-48) * Math.pow(10, length-1);
    return sum;
}

```
> 0 votes

# Answer
## C 226

Parses positive and negative integers.

```
#include <stdio.h>
#define P(x) printf("%d",x)
char c;
int n,x,y;
int main()
{
while(((c=getchar())=='-') || ((c>='0')&&(c<='9')))
{
if(c=='-')y=1;
else{
n*=10;
x=c-'0';
n+=x;
}
}
if(y)n=-1*n;
P(n);
getchar();
return 0;
}

```
> 0 votes

# Answer
# Go - 141 characters

```
func p(s string) (t int) {
    for i, x := range s {
        y := int(x) - 48
        for j := len(s) - 1; j > i;  j-- {
            y *= 10
        }
        t += y
    }
    return
}

```

int() here is a straight conversion from a rune (a type identical to int32) to a longer int - and it has to be in the code somewhere to get the function to return an int rather than a rune. The above code is standard go formatting, but technically some of the whitespace is optional.

(If you copy/paste the above, before you count the characters, put it in play.golang.org and hit format.)
> 0 votes

# Answer
in :r4 (http://code.google.com/p/reda4/)

```
::str>int | str -- int
    0 swap ( c@+ $2f >? )(
        $39 >? ( 2drop ; )
        $30 - rot 10 * + swap )
    2drop ;

```

is in standard library http://code.google.com/p/reda4/source/browse/trunk/r4/Lib/parse.txt line 92
> 0 votes

# Answer
# C - 69 characters

```
c,r,m;p(char*s){for(m=2,r=0;c=15&*s++;r=c>9?m=r:r*10+c);return--m*r;}

```
> 0 votes

# Answer
## J - 19 characters

```
10#.'0123456789'&i.

```

No string manipulation at all. Just index each character into the vector of decimal digits, and take the base-10 representation of that array.
> 0 votes

# Answer
## J, 41 chars

Here's a J solution that should follow the spec... I'm not very fond of the sign handling; it's too verbose. I can't think of a more compact way, though.

```
(u:48+i.10)&((_1^'-'e.])*10 p.~e.~#i.)@|.

```

Sample use:

```
   atoi =: (u:48+i.10)&((_1^'-'e.])*10 p.~e.~#i.)@|.
   atoi '-1234'
_1234

```
> 0 votes

# Answer
# Python ~~116~~ ~~108~~ 146

```
O=b=0
I=list(input())
if I[0]=='-':I.pop(0);b=1
a=range(len(I))
for c in a:I[c]=ord(I[c])-48
for i in a:O+=I[i]*10**(len(I)-i-1)
if b:O=-O
print O

```
> 0 votes

# Answer
# Ruby, 43 characters

```
a=0;$*[0].each_char{|n|a=a*10+n.ord-48};p a

```

Alternate answer (also 43 characters)

```
p $*[0].chars.inject(0){|a,b|a*10+b.ord-48}

```
> -1 votes

---
Tags: code-golf, string, restricted-source, parsing
---


title: Fast Trig Calculation

text:
# Question
Title: Fast Trig Calculation
# Fast Trigonometry Calculations

Your task is to create a program which can calculate the sine, cosine and tangent of an angle in degrees.

## Rules

* No built-in trigonometry functions (not even secant, cosecant and cotangent if your language has them).
* You may use lookup tables, but their total size must not exceed 3000 members (for all of the three operations put together). Please make it read the tables from a file (e.g. `trig.lookup`) so they don't confuse the code.
* No network access.
* You must correctly round your output as explained below. Don't use floor or ceiling.
* You may use any method to calculate the values, for example continued fractions, as long as it is correct to 7 significant figures.
* Your code must be able to time itself. Exclude the file I/O operations from your time - so just time the function(s) that do(es) the trig and any rounding.
* I must be able to run your code. Please post a link to a freely available compiler/interpreter and give the instructions needed to compile/run the code (e.g. what options to pass to GCC).
* Standard loopholes apply.

## Input Format

* Read from a file called `trig.in` unless your language doesn't support file I/O.
* Angles are between 0 and 360 inclusive.
* Input will consist of angles to ten significant figures in decimal digits, separated by new lines. For example:

> 90.00000000
> 74.54390000
> 175.5000000

## Output Format

* For each angle supplied, you must output its sine, cosine and tangent to 7 significant figures, separated by spaces, on a single line. Use "scientific notation", e.g. `1.745329E-5` for `tan 0.001` or `1.000000E+0` for `sin 90`.
* Denote infinity or NaN by `n`, for example the output for `90.00000000` should be `1.000000 0.000000 n`.
* If the input is three angles separated by newlines, your output should consist of three lines, each containing the sine, cosine and tangent.
* You may not output anything else.
* Output to a file called `trig.out` unless your language does not support file I/O.

## Scoring

* . The challenge is to write a program which computes these three values as quickly as possible. Fastest time wins.
* Everyone will receive the same test input of many angles.
* Times will be recorded on my machine.
* Your score is the average of three runs on the same input (you can't save anything in between runs obviously).
* Compiling time not included. This challenge is more about the method used than the language. (If someone could point me to how I would exclude compilation time for languages such as Java, I'd be very grateful)
* My machine is an Ubuntu 14.04 install. The processor's stats are on Pastebin (obtained by running `cat /proc/cpuinfo`).
* I will edit your time into your answer when I've tested it.

# Answer
# Fortran 90

I employ the CORDIC method with a pre-tabulated array of 60 arctan values (see Wiki article for details on why that's necessary).

This code requires a file, `trig.in`, with all the values on newlines to be stored in the same folder as the Fortran executable. Compiling this is,

```
gfortran -O3 -o file file.f90

```

where `file` is whatever filename you give it (probably `SinCosTan.f90` would be easiest, though it's not necessary to match program name and file name). If you have the Intel compiler, I'd recommend using

```
ifort -O3 -xHost -o file file.f90

```

as the `-xHost` (which doesn't exist for gfortran) provides higher level optimizations available to your processor.

My test runs were giving me about 10 microseconds per calculation when testing 1000 random angles using gfortran 4.4 (4.7 or 4.8 is available in the Ubuntu repos) and around 9.5 microseconds using ifort 12.1. Testing only 10 random angles will result in an indeterminable time using Fortran routines, as the timing routine is accurate to the millisecond and simple math says it should take 0.100 milliseconds to run all 10 numbers.

---

**EDIT** Apparently I was timing IO which (a) made the timing longer than necessary and (b) is contrary to bullet #6. I've updated the code to reflect this. I've also discovered that using a `kind=8` integer with the intrinsic subroutine `system_clock` gives microsecond accuracy.

With this updated code, **I am now computing each set of values of the trigonometric functions in about 0.3 microseconds** (the significant digits in the end vary run-to-run, but it's consistently hovering near 0.31 us), a significant reduction from the previous iteration that timed IO.

---

```
program SinCosTan
   implicit none
   integer, parameter :: real64 = selected_real_kind(15,307)
   real(real64), parameter :: PI  = 3.1415926535897932384626433832795028842
   real(real64), parameter :: TAU = 6.2831853071795864769252867665590057684
   real(real64), parameter :: half = 0.500000000000000000000_real64
   real(real64), allocatable :: trigs(:,:), angles(:)
   real(real64) :: time(2), times, b
   character(len=12) :: tout
   integer :: i,j,ierr,amax
   integer(kind=8) :: cnt(2)

   open(unit=10,file='trig.out',status='replace')
   open(unit=12,file='CodeGolf/trig.in',status='old')
! check to see how many angles there are
   i=0
   do
      read(12,*,iostat=ierr) b
      if(ierr/=0) exit
      i=i+1
   enddo !-
   print '(a,i0,a)',"There are ",i," angles"
   amax = i

! allocate array
   allocate(trigs(3,amax),angles(amax))

! rewind the file then read the angles into the array
   rewind(12)
   do i=1,amax
      read(12,*) angles(i)
   enddo !- i

! compute trig functions & time it
   times = 0.0_real64
   call system_clock(cnt(1)) ! <-- system_clock with an 8-bit INT can time to us
   do i=1,amax
      call CORDIC(angles(i), trigs(:,i), 40)
   enddo !- i
   call system_clock(cnt(2))
   times = times + (cnt(2) - cnt(1))

! write the angles to the file
   do i=1,amax
      do j=1,3
         if(trigs(j,i) > 1d100) then
            write(tout,'(a1)') 'n'
         elseif(abs(trigs(j,i)) > 1.0) then
            write(tout,'(f10.6)') trigs(j,i)
         elseif(abs(trigs(j,i)) < 0.1) then
            write(tout,'(f10.8)') trigs(j,i)
         else
            write(tout,'(f9.7)') trigs(j,i)
         endif
         write(10,'(a)',advance='no') tout
      enddo !- j
      write(10,*)" "
   enddo !- i

   print *,"computation took",times/real(i,real64),"us per angle"
   close(10); close(12)
 contains
   !> @brief compute sine/cosine/tangent
   subroutine CORDIC(a,t,n)
     real(real64), intent(in) :: a
     real(real64), intent(inout) :: t(3)
     integer, intent(in) :: n
! local variables
     real(real64), parameter :: deg2rad = 1.745329252e-2
     real(real64), parameter :: angles(60) = &
       [ 7.8539816339744830962e-01_real64, 4.6364760900080611621e-01_real64, &
         2.4497866312686415417e-01_real64, 1.2435499454676143503e-01_real64, &
         6.2418809995957348474e-02_real64, 3.1239833430268276254e-02_real64, &
         1.5623728620476830803e-02_real64, 7.8123410601011112965e-03_real64, &
         3.9062301319669718276e-03_real64, 1.9531225164788186851e-03_real64, &
         9.7656218955931943040e-04_real64, 4.8828121119489827547e-04_real64, &
         2.4414062014936176402e-04_real64, 1.2207031189367020424e-04_real64, &
         6.1035156174208775022e-05_real64, 3.0517578115526096862e-05_real64, &
         1.5258789061315762107e-05_real64, 7.6293945311019702634e-06_real64, &
         3.8146972656064962829e-06_real64, 1.9073486328101870354e-06_real64, &
         9.5367431640596087942e-07_real64, 4.7683715820308885993e-07_real64, &
         2.3841857910155798249e-07_real64, 1.1920928955078068531e-07_real64, &
         5.9604644775390554414e-08_real64, 2.9802322387695303677e-08_real64, &
         1.4901161193847655147e-08_real64, 7.4505805969238279871e-09_real64, &
         3.7252902984619140453e-09_real64, 1.8626451492309570291e-09_real64, &
         9.3132257461547851536e-10_real64, 4.6566128730773925778e-10_real64, &
         2.3283064365386962890e-10_real64, 1.1641532182693481445e-10_real64, &
         5.8207660913467407226e-11_real64, 2.9103830456733703613e-11_real64, &
         1.4551915228366851807e-11_real64, 7.2759576141834259033e-12_real64, &
         3.6379788070917129517e-12_real64, 1.8189894035458564758e-12_real64, &
         9.0949470177292823792e-13_real64, 4.5474735088646411896e-13_real64, &
         2.2737367544323205948e-13_real64, 1.1368683772161602974e-13_real64, &
         5.6843418860808014870e-14_real64, 2.8421709430404007435e-14_real64, &
         1.4210854715202003717e-14_real64, 7.1054273576010018587e-15_real64, &
         3.5527136788005009294e-15_real64, 1.7763568394002504647e-15_real64, &
         8.8817841970012523234e-16_real64, 4.4408920985006261617e-16_real64, &
         2.2204460492503130808e-16_real64, 1.1102230246251565404e-16_real64, &
         5.5511151231257827021e-17_real64, 2.7755575615628913511e-17_real64, &
         1.3877787807814456755e-17_real64, 6.9388939039072283776e-18_real64, &
         3.4694469519536141888e-18_real64, 1.7347234759768070944e-18_real64]
     real(real64), parameter :: kvalues(33) = &
       [ 0.70710678118654752440e+00_real64, 0.63245553203367586640e+00_real64, &
         0.61357199107789634961e+00_real64, 0.60883391251775242102e+00_real64, &
         0.60764825625616820093e+00_real64, 0.60735177014129595905e+00_real64, &
         0.60727764409352599905e+00_real64, 0.60725911229889273006e+00_real64, &
         0.60725447933256232972e+00_real64, 0.60725332108987516334e+00_real64, &
         0.60725303152913433540e+00_real64, 0.60725295913894481363e+00_real64, &
         0.60725294104139716351e+00_real64, 0.60725293651701023413e+00_real64, &
         0.60725293538591350073e+00_real64, 0.60725293510313931731e+00_real64, &
         0.60725293503244577146e+00_real64, 0.60725293501477238499e+00_real64, &
         0.60725293501035403837e+00_real64, 0.60725293500924945172e+00_real64, &
         0.60725293500897330506e+00_real64, 0.60725293500890426839e+00_real64, &
         0.60725293500888700922e+00_real64, 0.60725293500888269443e+00_real64, &
         0.60725293500888161574e+00_real64, 0.60725293500888134606e+00_real64, &
         0.60725293500888127864e+00_real64, 0.60725293500888126179e+00_real64, &
         0.60725293500888125757e+00_real64, 0.60725293500888125652e+00_real64, &
         0.60725293500888125626e+00_real64, 0.60725293500888125619e+00_real64, &
         0.60725293500888125617e+00_real64 ]
    real(real64) :: beta, c, c2, factor, poweroftwo, s
    real(real64) :: s2, sigma, sign_factor, theta, angle
    integer :: j

! scale to radians
    beta = a*deg2rad
! ensure angle is shifted to appropriate range
    call angleShift(beta, -PI, theta)
! check for signs
    if( theta < -half*PI) then
       theta = theta + PI
       sign_factor = -1.0_real64
    else if( half*PI < theta) then
       theta = theta - PI
       sign_factor = -1.0_real64
    else
       sign_factor = +1.0_real64
    endif

! set up some initializations...
    c = 1.0_real64
    s = 0.0_real64
    poweroftwo = 1.0_real64
    angle = angles(1)

! run for 30 iterations (should be good enough, need testing)
    do j=1,n
       sigma = merge(-1.0_real64, +1.0_real64, theta <  0.0_real64)
       factor = sigma*poweroftwo

       c2 = c - factor*s
       s2 = factor*c + s
       c = c2
       s = s2
! update remaining angle
       theta = theta - sigma*angle

       poweroftwo = poweroftwo*0.5_real64
       if(j+1 > 60) then
          angle = angle * 0.5_real64
       else
          angle = angles(j+1)
       endif
    enddo !- j

    if(n > 0) then
       c = c*Kvalues(min(n,33))
       s = s*Kvalues(min(n,33))
    endif
    c = c*sign_factor
    s = s*sign_factor

    t = [s, c, s/c]
   end subroutine CORDIC

   subroutine angleShift(alpha, beta, gamma)
     real(real64), intent(in) :: alpha, beta
     real(real64), intent(out) :: gamma
     if(alpha < beta) then
        gamma = beta - mod(beta - alpha, TAU) + TAU
     else
        gamma = beta + mod(alpha - beta, TAU)
     endif
   end subroutine angleShift

end program SinCosTan

```
> 6 votes

# Answer
# Python 2.7.x or Java (Take your pick)

A free Python interpreter can be downloaded from here.
A free Java interpreter can be downloaded from here.

The program can take input both from a file named `trig.in` located in the same directory as the program file. Input is separated by newlines.

I originally did this in python because - well, I love python. But, since I wanna try to win as well, I rewrote it in java afterwards...

**Python Version:** I got about 21µs per run on my computer. I got about 32µs when running it on IDEone.

**Java version:** I get about 0.4µs per run on my computer, and 1.8µs on IDEone.

**Computer specs:**

* Windows 8.1 update 1 64-bit with intel core i7-3632QM - 2.2GHz)

**Test:**

* Time per run" is the cumulative time it takes to calculate the `sin`, `cos`, and `tan` all of the input angles.
* The test input used for both is as follows:

```
90.00000000
74.54390000
175.5000000
3600000.000

```

**About The Code:**
The premise for this program was to estimate `sin` and `cos` using their Taylor polynomials with 14 terms, which was what I calculated was necessary to have an error estimate of less than 1e-8. However I found it was faster to calculate `sin` than `cos`, so decided to instead calculate `cos` by using `cos=sqrt(1-sin^2)`

>

---

# Python Version:

```
import math
import timeit
import sys
import os
from functools import partial

#Global Variabls
pi2 = 6.28318530718
piover2 = 1.57079632679

#Global Lists
factorialList = [1.0,
                 -6.0,
                 120.0,
                 -5040.0,
                 362880.0,
                 -39916800.0,
                 6227020800.0,
                 -1307674368000.0,
                 355687428096000.0,
                 -121645100408832000.0,
                 51090942171709440000.0,
                 -25852016738884976640000.0,
                 15511210043330985984000000.0,
                 -10888869450418352160768000000.0,
                 8841761993739701954543616000000.0]

#simplifies angles and converts them to radians
def torad(x):
    rev = float(x)/360.0
    if (rev>1) or (rev<0):
        return (rev - math.floor(rev))*pi2
    return rev*pi2

def sinyield(x):
    squared = x*x
    for n in factorialList:
        yield x/n
        x*=squared

def tanfastdivide(sin, cos):
    if (cos == 0):
        return "infinity"
    return sin/cos

#start calculating sin cos and tan
def calcyield(outList):
    for angle in outList[0]:
        angle = torad(angle)
        sin = round(math.fsum(sinyield(angle)), 7)
        cos=math.copysign(math.sqrt(1-(sin*sin)),(piover2-angle))
        yield sin
        yield cos
        yield tanfastdivide(sin, cos) #tan

def calculations(IOList):
    calcyieldgen = calcyield(IOList)
    for angle in IOList[0]:
        IOList[1].append(next(calcyieldgen))
        IOList[2].append(next(calcyieldgen))
        IOList[3].append(next(calcyieldgen))
    return IOList

#Begin input from file
def ImportFile():
    try:
        infile = open("trig.in", "r")
    except:
        infile = sys.stdin
    inList = [[], [], [], []]

    #take input from file
    for line in infile:
        inList[0].extend([float(line)])
    return inList

#Begin output to file
def OutputResults(outList):
    try:
        outfile = open("trig.out", "w")
        PrintOutput(outList, outfile)
    except:
        print 'Failed to write to file. Printing to stdout instead...'
    finally:
        PrintOutput(outList, sys.stdout)

def PrintOutput(outList, outfile):
    #outList[0][i] holds original angles
    #outList[1][i] holds sin values
    #outList[2][i] holds cos values
    #outList[3][i] holds tan values
    outfile.write('-----------------------------------------------------\n')
    outfile.write('                    TRIG RESULTS                     \n')
    outfile.write('-----------------------------------------------------\n')
    for i in range(len(outList[0])):
        if (i):
            outfile.write('\n')
        outfile.write("For angle: ")
        outfile.write(str(outList[0][i]))
        outfile.write('\n    ')
        outfile.write("Sin: ")
        outfile.write(str('%.7E' % float(outList[1][i])))
        outfile.write('\n    ')
        outfile.write("Cos: ")
        outfile.write(str('%.7E' % float(outList[2][i])))
        outfile.write('\n    ')
        outfile.write("Tan: ")
        outfile.write(str('%.7E' % float(outList[3][i])))

#Run the Program first
inList = ImportFile()
OutputResults(calculations(inList))

#Begin Runtime estimation
def timeTest(IOList):
    for output in calcyield(IOList):
        pass
def baselined(inList):
    for x in inList:
        pass

totime = timeit.Timer(partial(timeTest, inList))
baseline = timeit.Timer(partial(baselined, inList))
print '\n-----------------------------------------------------'
print '                    TIME RESULTS:                    '
print '-----------------------------------------------------'
OverheadwithCalcTime =  min(totime.repeat(repeat=10, number=10000))
Overhead = min(baseline.repeat(repeat=1, number=10000))
estimatedCalcTime = (OverheadwithCalcTime - Overhead)
estimatedTimePerAngle = estimatedCalcTime/len(inList)
estimatedTimePerCalc = estimatedTimePerAngle/3
print ' Estimated CalcTime+Overhead:.....', '%.10f' % (OverheadwithCalcTime*100), 'µsec'
print ' Estimated Overhead Time:..........', '%.10f' % (Overhead*100), 'µsec'
print ''
print ' Estimated CalcTime/Run:..........', '%.10f' % (estimatedCalcTime*100), 'µsec'
print ' Estimated CalcTime/Angle:.........', '%.10f' % (estimatedTimePerAngle*100), 'µsec'
print ' Estimated CalcTime/Cacluation:....', '%.10f' % (estimatedTimePerCalc*100), 'µsec'
print '-----------------------------------------------------'
print "                   COOL, IT WORKED!                  "
print '-----------------------------------------------------'

```

# Java Version:

```
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Math;

class Trig {
   /**
    *Global Variables
    **/
    static final double pi2 = 6.28318530718;
    public long totalTime = 0L;
    static final double piover2 = 1.57079632679;
    static final double plusinfty = Double.POSITIVE_INFINITY;
    static final double minusinfty = Double.NEGATIVE_INFINITY;
    static final double factoriallist[] =
                             new double[]{
                         -6.0,120.0,-5040.0,362880.0,-39916800.0,
                         6227020800.0,-1307674368000.0,355687428096000.0,
                        -121645100408832000.0,51090942171709440000.0,
                        -25852016738884976640000.0,
                         15511210043330985984000000.0,
                        -10888869450418352160768000000.0,
                         8841761993739701954543616000000.0
                         };
//Begin Program
    public static void main(String[] args) {
        Trig mytrig = new Trig();
        double[] input = mytrig.getInput();
        double[][] output = mytrig.calculate(input);
        mytrig.OutputResults(output);
        Trig testIt = new Trig();
        testIt.timeIt(input);
    }

//Begin Timing
    public void timeIt(double[] input) {
        double overhead = 0L;
        totalTime = 0L;

        for (int i = 0; i < 1000001; i++) {
            calculate(input);
            if (i == 0) {
                overhead = totalTime;
                totalTime = 0L;
            }
        }
        double averageTime = ((Double.valueOf(totalTime-overhead))/1000000.0);
        double perAngleTime = averageTime/input.length;
        double perOpperationTime = perAngleTime/3;
        NumberFormat formatter = new DecimalFormat("0000.0000");
        System.out.println("\n-----------------------------------------------------");
        System.out.println("                    TIME RESULTS:                    ");
        System.out.println("-----------------------------------------------------");
        System.out.println("Average Total  Runtime:.......... " + formatter.format(averageTime) + " nsec");
        System.out.println("                                = " + formatter.format(averageTime/1000) + " usec\n");
        System.out.println("Average Runtime Per Angle:....... " + formatter.format(perAngleTime) + " nsec");
        System.out.println("                                = " + formatter.format(perAngleTime/1000) + " usec\n");
        System.out.println("Average Runtime Per Opperation:.. " + formatter.format(perOpperationTime) + " nsec");
        System.out.println("                                = " + formatter.format(perOpperationTime/1000) + " usec");
    }

//Begin Input
    double[] getInput() {
        Scanner in;
        ArrayList<Double> input = new ArrayList<Double>();
        try {
            in = new Scanner(new File("trig.in"));
        } catch (FileNotFoundException e) {
            new FileNotFoundException("Failed to read from file. Reading from stdin instead...").printStackTrace();
            in= new Scanner(System.in);
        }
        while (in.hasNextLine()) {
            Double toadd = Double.parseDouble(in.nextLine());
            input.add(toadd);
        }
        in.close();
        double[] returnable = new double[input.size()];
        for(int i = 0; i < input.size(); i++) {returnable[i] = input.get(i);}
        return returnable;
    }

//Begin OutputStream Choice
    void OutputResults(double[][] outList) {
        PrintStream out;
        try {
            out = new PrintStream("trig.out");
            PrintOutput(outList, out);
            PrintOutput(outList, System.out);
        } catch (FileNotFoundException e) {
            new FileNotFoundException("Failed to write to file. Printing to stdout instead...").printStackTrace();
            PrintOutput(outList, System.out);
        }
    }

//Begin Output
    static void PrintOutput(double[][] outList, PrintStream out) {
        /**
         *outList[0][i] holds original angles
         *outList[1][i] holds sin values
         *outList[2][i] holds cos values
         *outList[3][i] holds tan values
         */
        NumberFormat formatter = new DecimalFormat("0.0000000E0");
        out.println("-----------------------------------------------------");
        out.println("                    TRIG RESULTS                     ");
        out.println("-----------------------------------------------------");
        for (int i=0; i<outList[0].length; i++) {
            out.println("For Angle: " + outList[0][i]);

            out.println("      sin: " + formatter.format(outList[1][i]));
            out.println("      cos: " + formatter.format(outList[2][i]));
            if (Double.valueOf(outList[3][i]).isInfinite() || Double.valueOf(outList[3][i]).isNaN()) {
                out.println("      tan: " + outList[3][i]);
            }
            else out.println("      tan: " + formatter.format(outList[3][i]));
        }
        if (out != System.out) out.close();
    }

//Begin Calculations
    double[][] calculate(double[] IOList) {
        double[][] outList = new double[4][IOList.length];
        double sin;
        double cos;
        double tan;
        double rads;
        int i = 0;
        long calctime = 0L;
        long startTime;
        long endTime;
        for (double input : IOList) {
            startTime = System.nanoTime();
            rads = toRad(input);
            sin=sin(rads);
            cos = ((piover2-rads)>=0) ? Math.sqrt((1.0-(sin*sin))) : -Math.sqrt((1.0-(sin*sin)));
            tan = (cos!=0.0d) ? sin/cos : ((sin>0) ? plusinfty : minusinfty);
            endTime = System.nanoTime();
            calctime = calctime + endTime - startTime;
            outList[0][i] = input;
            outList[1][i] = sin;
            outList[2][i] = cos;
            outList[3][i] = tan;
            i++;
        }
        totalTime = totalTime + calctime;
        return outList;
    }

//Convert Degrees to Radians
    double toRad(double deg) {
        double rev = deg/360.0;
        return (rev>1 || rev<0) ? Math.abs(rev - ((int)rev))*pi2 : rev*pi2;
    }

//Get sin
    double sin(double angle) {
        double sqr = angle*angle;
        double value = angle;
        for (double fct : factoriallist) {
            value += ((angle*=sqr)/fct);
        }
        return ((long)((value + Math.copySign(0.0000000005d, value))*10000000.0))/10000000.0;
    }
}

```
> 2 votes

# Answer
# Cobra

```
class Trig
    const mod as float = 0.0174532925199433f #0.0174532925199432957692369076848861271344287188854172f
    var time as System.Diagnostics.Stopwatch = System.Diagnostics.Stopwatch()
    var file as String[] = File.readAllLines('trig.in')
    var sin_out as float[] = float[](1)
    var cos_out as float[] = float[](1)
    var tan_out as float[] = float[](1)
    def main
        .compute(@[1f])
        .time.reset
        input = float[](.file.length)
        for num, line in .file.numbered, input[num] = float.parse(line)
        .compute(input)
        for num in .file.length, .file[num] = (.sin_out[num].toString('0.000000E+0') + ' ' + .cos_out[num].toString('0.000000E+0') + ' ' + .tan_out[num].toString('0.000000E+0'))
        File.writeAllLines('trig.out', .file)
        print .time.elapsed
    def compute(list as float[])
        .sin_out = float[](list.length)
        .cos_out = float[](list.length)
        .tan_out = float[](list.length)
        .time.start
        for index in list.length
            degrees as float = list[index]
            #add `degrees %= 360` for numbers greater than 360
            rad as float = sin as float = degrees * .mod
            two as float = rad * rad
            sin -= (rad *= two) / 6
            sin += (rad *= two) / 120
            sin -= (rad *= two) / 5040
            sin += (rad *= two) / 362880
            sin -= (rad *= two) / 39916800
            sin += (rad *= two) / 6227020800
            sin -= (rad *= two) / 1307674368000
            sin += (rad *= two) / 355687428096000
            sin -= (rad *= two) / 121645100408832000
            sin += (rad *= two) / 51090942171709440000f
            sin -= (rad *= two) / 25852016738884976640000f
            sin += (rad *= two) / 15511210043330985984000000f
            sin -= (rad *= two) / 10888869450418352160768000000f
            sin += (rad *= two) / 8841761993739701954543616000000f
            cos as float = (1 - (sin * sin)).sqrt * ((degrees - 180).abs - 90).sign
            if cos.isNaN, cos = 0
            .tan_out[index] = Math.round((sin / cos) * 10000000) / 10000000
            .sin_out[index] = Math.round(sin * 10000000) / 10000000
            .cos_out[index] = Math.round(cos * 10000000) / 10000000
        .time.stop

```

Compile it with `cobra filename -turbo`

**Tests:** AMD FX6300 @5.1GHz

* The 360 * 10000 test used by the C answer runs in 365ms (vs 190ms)
* The 4-entry test used by the Python and Java answers runs in 0.32µs (vs 30µs, 3µs)
* The 1000 random angle test used by the Fortran answer runs at 100ns per angle (vs 10µs)
> 1 votes

# Answer
# Octave (or Matlab) & C

A bit of a complicated build process, but kind of a novel approach and the results were encouraging.

The approach is to generate approximating quadratic polynomials for each degree. So degree = \[0, 1), degree = \[1, 2), ..., degree = \[359, 360) will each have a different polynomial.

## Octave - building part

Octave is publicly available - Google `download octave`.

This determines the best fit quadratic polynomial for every degree.

Save as `build-fast-trig.m`:

```
format long;
for d = 0:359
    x = (d-1):0.1:(d+1);
    y = sin(x / 360 * 2 * pi);
    polyfit(x, y, 2)
endfor

```

## C - building part

This converts doubles in text format to native binary format on your system.

Save as `build-fast-trig.c`:

```
#include <stdio.h>

int main()
{
    double d[3];

    while (scanf("%lf %lf %lf", d, d + 1, d + 2) == 3)
        fwrite(d, sizeof(double), 3, stdout);

    return 0;
}

```

Compile:

```
gcc -o build-fast-trig build-fast-trig.c

```

## Generating the coefficients file

Run:

```
octave build-fast-trig.m | grep '^ ' | ./build-fast-trig > qcoeffs.dat

```

Now we have `qcoeffs.dat` as the data file to use for the actual program.

## C - fast-trig part

Save as `fast-trig.c`:

```
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

#define INPUT    "qcoeffs.dat"

#define DEGREES    360

typedef struct {double a, b, c;} QCOEFFS;

double normalize(double d)
{
    if (d < 0.0)
        d += ceil(d / -(double)DEGREES) * (double)DEGREES;

    if (d >= (double)DEGREES)
        d -= floor(d / (double)DEGREES) * (double)DEGREES;

    return d;
}

int main()
{
    FILE *f;
    time_t tm;
    double d;
    QCOEFFS qc[DEGREES];

    if (!(f = fopen(INPUT, "rb")) || fread(qc, sizeof(QCOEFFS), DEGREES, f) < DEGREES)
    {
        fprintf(stderr, "Problem with %s - aborting.", INPUT);
        return EXIT_FAILURE;
    }
    fclose(f);

    tm = -clock();

    while (scanf("%lf", &d) > 0)
    {
        int i;
        double e, f;

        /* sin */
        d = normalize(d);
        i = (int)d;
        e = (qc[i].a * d + qc[i].b) * d + qc[i].c;

        /* cos */
        d = normalize((double)DEGREES / 4.0 - d);
        i = (int)d;
        f = (qc[i].a * d + qc[i].b) * d + qc[i].c;

        /* tan = sin / cos */

        /* output - format closest to specs, AFAICT */
        if (d != 0.0 && d != 180.0)
            printf("%.6e %.6e %.6e\n", e, f, e / f);
        else
            printf("%.6e %.6e n\n", e, f);
    }

    tm += clock();

    fprintf(stderr, "time: %.3fs\n", (double)tm/(double)CLOCKS_PER_SEC);

    return EXIT_SUCCESS;
}

```

Compile:

```
gcc -o fast-trig fast-trig.c -lm

```

Run:

```
./fast-trig < trig.in > trig.out

```

It will read from `trig.in`, save to `trig.out` and print to console the elapsed time with millisecond precision.

Depending on the testing methods used it may fail on certain input, e.g.:

```
$ ./fast-trig
0
-6.194924e-19 1.000000e+00 -6.194924e-19

```

The correct output should be `0.000000e+00 1.000000e+00 0.000000e+00`. If the results are validated using strings, the input will fail, if they are validated using absolute error, e.g. `fabs(actual - result) < 1e-06`, the input will pass.

The maximum absolute error for `sin` and `cos` was ≤ 3e-07. For `tan`, because the result isn't limited to ± 1 and you can divide a relatively large number by a relatively small number, the absolute error could be larger. From -1 ≤ tan(x) ≤ +1, the maximum absolute error was ≤ 4e-07. For tan(x) \> 1 and tan(x) \< -1, the maximum *relative* error, e.g. `fabs((actual - result) / actual)` was usually \< 1e-06 until you get in the area of (90 ± 5) or (270 ± 5) degrees, then the error gets worse.

In testing, the average time per single input was (1.053 ± 0.007) µs, which on my machine was about 0.070 µs faster than native `sin` and `cos`, `tan` being defined the same way.
> 0 votes

# Answer
# C

Here's my attempt. It works like this:

Build a table of all values of sin(x) from 0 to 450 degrees. Equivalently this is all values of cos(x) from -90 to 360 degrees. With 2926 elements, there is enough space for a value every 1/6.5 degrees. The program unit is therefore 1/6.5 degrees, and there are 585 units in a quarter turn.

Convert input degrees into program units (multiply by `6.5==110.1 binary.`) Find the nearest values for sin and cos from the table. then convert the remaining part of the input (dx) into radians.

apply the formula `sin(x+dx) == sin x +(d(sin x)/dx)*dx.` note that `(d(sin x)/dx)==cos x,` but only if we use radians.

unfortunately that isn't accurate enough on its own, so another term is required, based on the next derivative `d2(sin x)/dx2 == -sin x.` This needs to be multiplied by `dx*dx/2` (not sure where the factor of 2 comes from, but it works.)

Follow the analogous procedure for `cos x`, then calculate `tan x == sin x / cos x`.

**Code**

There are about 17 floating point operations in here. That can be improved somewhat. The program contains table-building and test output using the native trig functions, but the algorithm does not. I will add timing and edit to comply with I/O requirements later (hopefully this weekend.) It matches the native function output except for very small values of sin x and cos x, which should be improvable to better than the native function output with some tweaking.

```
<#include <math.h>                                                 //only for table building and testing
int a;
double t[2926],                                                    //a table for sin x from 0 to 360+90=450deg every 1/6.5 degrees
x,                                                                 //input
s,c,                                                               //first guess sin and cos (from table)
sn,cs,                                                             //output sin and cos
pi1170=3.1415926535897932384626433832795/1170,                     // there are 1170 units of 1/6.5 degrees in a half circle
pi180=3.1415926535897932384626433832795/180;                       // pi/180 only used for testing

main(){
  for (a=0;a<=2925;a++)t[a]=sin(a*pi1170);                         //build table.

  scanf("%lf",&x);                                                 //input
  printf("%le %le %le\n",sin(x*pi180),cos(x*pi180),tan(x*pi180));  //native output for testing purposes

  x*=6.5;                                                          //convert from deg to program units. 6.5=110.1 in binary, a fairly round number.
  a=x+0.5;                                                         //a=round(x) add 0.5 to round, not truncate. Assigning to int, this is probably faster than the round function.
  x=(x-a)*pi1170;                                                  //(x-a)=dx in program units. Divide to get radians.

  s=t[a];                                                          //get sin(a) from table
  c=t[a+585];                                                      //cos(a)=sin(a+90degrees)=sin(a+585units)
  sn=s+c*x-s*x*x/2;                                                //sin(x+dx)=sin(x)+cos(dx)-sin(dx^2/2)
  cs=c-s*x-c*x*x/2;                                                //cos(x+dx)=cos(x)-sin(dx)-cos(dx^2/2)
  printf("%le %le %le\n",sn,cs,sn/cs);                             //print sin,cos and tan=sin/cos
}

```
> 0 votes

---
Tags: math, fastest-code, trigonometry
---


# Question
Title: Convert a program to a palindromic program
A *palindrome* is a string that is the same forwards and backwards, such as "racecar".

Write a program in some language L, that takes any program P1 in language L as input, and outputs a palindromic program P2 in language L that does the same thing as P1.

You do not need to worry about handling input programs with syntax errors.

This is **code golf**, so the solution with the fewest number of bytes wins.

# Answer
> 17 votes
# Perl, 55 54 bytes

```
undef$/;$a=<>."\n__END__\n";print$a,scalar reverse$a;

```

Reads program source from stdin and writes to stdout.

Result of running on itself:

```
undef$/;$a=<>."\n__END__\n";print$a,scalar reverse$a;

__END__

__DNE__

;a$esrever ralacs,a$tnirp;"n\__DNE__n\".><=a$;/$fednu

```

# Answer
> 11 votes
# Java, 225 bytes

```
class c{public static void main(String[]a){String s="";java.util.Scanner r=new java.util.Scanner(System.in);while(r.hasNext())s+=r.nextLine()+"\n";s=s.replace("\n","//\n");System.out.print(s+new StringBuilder(s).reverse());}}

```

Output on itself (when prettified beforehand):

```
class c {//
    public static void main(String[] a) {//
        String s = "";//
        java.util.Scanner r = new java.util.Scanner(System.in);//
        while (r.hasNext()) s += r.nextLine() + "\n";//
        s = s.replace("\n", "//\n");//
        System.out.print(s + new StringBuilder(s).reverse());//
    }//
}//

//}
//}
//;))(esrever.)s(redliuBgnirtS wen + s(tnirp.tuo.metsyS
//;)"n\//" ,"n\"(ecalper.s = s
//;"n\" + )(eniLtxen.r =+ s ))(txeNsah.r( elihw
//;)ni.metsyS(rennacS.litu.avaj wen = r rennacS.litu.avaj
//;"" = s gnirtS
//{ )a ][gnirtS(niam diov citats cilbup
//{ c ssalc

```

# Answer
> 10 votes
# Python 2, 68 bytes

```
import sys
x=''.join(l[:-1]+'#\n'for l in sys.stdin)
print x+x[::-1]

```

Doesn't work if run from IDLE, because you need to generate an EOF character to stop the program from waiting on input.

Output when run on itself:

```
import sys#
x=''.join(l[:-1]+'#\n'for l in sys.stdin)#
print(x+x[::-1])#

#)]1-::[x+x(tnirp
#)nidts.sys ni l rof'n\#'+]1-:[l(nioj.''=x
#sys tropmi

```

Thanks to Greg Hewgill for helping to hammer out problems and to golf.

# Answer
> 9 votes
# GolfScript, ~~10~~ 9 bytes

```
"
}"+.-1%

```

Quite similar to minitech's solution, but it works well with newlines. It relies on GolfScript's funny (and undocumented) behavior to ignore an unmatched (and uncommented) `}`, as well as everything that follows it.

It will fail if the input contains an unmatched `{`, but that would technically constitute a syntax error.

### How it works

```
"
}"   # Push the string "\n}".
+    # Concatenate it with the input string.
.    # Duplicate the modified string.
-1%  # Reverse the copy.

```

# Example

```
$ echo -n '1{"race{car"}
> {"foo\"bar"}
> if#' | golfscript make-palindrome.gs
1{"race{car"}
{"foo\"bar"}
if#
}}
#fi
}"rab"\oof"{
}"rac{ecar"{1
$ echo '1{"race{car"}
> {"foo\"bar"}
> if#
> }}
> #fi
> }"rab"\oof"{
> }"rac{ecar"{1' | golfscript
race{car

```

# Answer
> 5 votes
## x86 machine code on DOS (`.com` file) - 70 bytes

Dealing with .COM files, creating a palyndrome is easy - since the COM "loader" just puts the content of the file at address `100h` and jumps there, the program must already hardcode its end somehow and ignore everything after it, so we can just append the reverse of the first N-1 bytes (only caveat: if the program somehow tries to do tricks with the length of file everything breaks).

Here is the hex dump of my `.COM`-palyndromizing `.COM`:

```
00000000  31 db 8a 1e 80 00 c6 87  81 00 00 ba 82 00 b8 00  |1...............|
00000010  3d cd 21 72 30 89 c6 bf  ff ff b9 01 00 ba fe 00  |=.!r0...........|
00000020  89 f3 b4 3f cd 21 3c 01  75 18 b4 40 bb 01 00 cd  |...?.!<.u..@....|
00000030  21 85 ff 75 e5 89 f3 f7  d9 88 ee b8 01 42 cd 21  |!..u.........B.!|
00000040  eb d8 47 74 f0 c3                                 |..Gt..|

```

It takes the input file on the command line, and writes the output on stdout; the expected usage is something like `compalyn source.com > out.com`.

Commented assembly:

```
    org 100h

section .text

start:
    ; NUL-terminate the command line
    xor bx,bx
    mov bl, byte[80h]
    mov byte[81h+bx],0
    ; open the input file
    mov dx,82h
    mov ax,3d00h
    int 21h
    ; in case of error (missing file, etc.) quit
    jc end
    ; si: source file handle
    mov si,ax
    ; di: iteration flag
    ; -1 => straight pass, 0 reverse pass
    mov di,-1
loop:
    ; we read one byte at time at a bizarre memory
    ; location (so that dl is already at -2 later - we shave one byte)
    mov cx,1
    mov dx,0feh
    mov bx,si
    mov ah,3fh
    int 21h
    ; if we didn't read 1 byte it means we either got to EOF
    ; or sought before the start of file
    cmp al,1
    jne out
    ; write the byte on stdout
    mov ah,40h
    mov bx,1
    int 21h
    ; if we are at the first pass we go on normally
    test di,di
    jnz loop
back:
    ; otherwise, we have to seek back
    mov bx,si
    ; one byte shorter than mov cx,-1
    neg cx
    ; dl is already at -2, fix dh so cx:dx = -2
    mov dh,ch
    mov ax,4201h
    int 21h
    jmp loop
out:
    ; next iteration
    inc di
    ; if it's not zero we already did the reverse pass
    jz back
end:
    ret

```

Tested on itself and the solutions to a previous question seems to work fine in DosBox, some more extensive testing on "canonical" DOS executables will follow.

# Answer
> 3 votes
## GolfScript, 8

```
.-1%'#'\

```

Doesn’t handle newlines, but nobody uses those in GolfScript.

# Answer
> 2 votes
# Bash+coreutils, 39 bytes

```
f="`cat`
exit"
echo "$f"
tac<<<"$f"|rev

```

Reads from STDIN and outputs to STDOUT:

```
$ cat hello.sh
#!/bin/bash

echo 'Hello, World!'

$ ./palin.sh < hello.sh
#!/bin/bash

echo 'Hello, World!'
exit
tixe
'!dlroW ,olleH' ohce

hsab/nib/!#
$

```

# Answer
> 2 votes
# Javascript (*ES6*) Multi-line - 71

Kinda sorta stole Quincunx's comment method here:

```
alert((x=prompt().replace(/\n/g,'//\n')+'/')+[...x].reverse().join(''))

```

# Single line - 49

```
alert((x=prompt()+'/')+[...x].reverse().join(''))

```

# Answer
> 2 votes
# C++, 214 209 bytes

```
#include<cstdio>
#include<stack>
int main(){std::stack<char>s;int c;while((c=getc(stdin))>EOF){if(c=='\n')for(int i=2;i;i--)s.push(putchar('/'));s.push(putchar(c));}while(s.size()){putchar(s.top());s.pop();}}

```

Result of running on itself:

```
#include<cstdio>//
#include<stack>//
int main(){std::stack<char>s;int c;while((c=getc(stdin))>EOF){if(c=='\n')for(int i=2;i;i--)s.push(putchar('/'));s.push(putchar(c));}while(s.size()){putchar(s.top());s.pop();}}//

//}};)(pop.s;))(pot.s(rahctup{))(ezis.s(elihw};))c(rahctup(hsup.s;))'/'(rahctup(hsup.s)--i;i;2=i tni(rof)'n\'==c(fi{)FOE>))nidts(cteg=c((elihw;c tni;s>rahc<kcats::dts{)(niam tni
//>kcats<edulcni#
//>oidtsc<edulcni#

```

# Answer
> 2 votes
# C 168 ~~175~~

Correctly handles escaped newline inside source code

**Edit 1** fixed bug when last newline missing
**Edit 2** fixed bug when line inside comment ends with `*`: add a tab char before the `//` comment
(and golfed more)

```
b[999999];main(c,z){char*p,for(p=b;(*p=c=getchar())>=0;z=c,p++)c-10||(z-92?*p++=9,*p++=47,*p++=47,*p=c:(p-=2));*p=47;for(p=b;*p;)putchar(*p++);for(;p>b;)putchar(*--p);}

```

C99 Standard, valid code, many warnings

**Ungolfed**

```
b[999999]; // working buffer ~ 4M on 32 bit machine, max source size
// c is current char, z is previous char,
main(c,z) // z  start as argv pointer, will be out of char range
{
  char *p;
  for(p = b;
      (*p=c=getchar()) >= 0; // while testing EOF copy char to buffer set c variable
      z=c, p++) // at end loop increment p and set previous = current
  {
      c-'\n' || // if newline
       (z - '\\' // check if escaped
          ? *p++='\t',*p++='/',*p++='/', *p=c // if not escaped, add tab,/,/ and newline
          : (p-=2) // if escaped, drop both escape and newline
       );
  }
  *p='/'; // if last newline missing, will add a comment anyway
  for(p=b;*p;) putchar(*p++); // ouput buffer
  for(;--p>=b;) putchar(*p); // outbut buffer reversed
}

```

# Answer
> 2 votes
# Brainfuck, 749 without whitespace (not golfed)

This produces brainfuck programs which mirrored palindromes, i.e. they are are mirror images of themselves.

```
++++++++++
[->++++>+++++++++<<]>+++.>+..<.>++.
>>>>+[>,]<-[+<-]
>[
  [-<+<<+>>>]
  +<-------------------------------------------[-<+>>[-]<]>[-<<<.>>>]
  +<<-[->+>[-]<<]>>[-<<<.>>>]
  +<-[-<+>>[-]<]>[-<<<.>>>]
  +<<-[->+>[-]<<]>>[-<<<.>>>]
  +<--------------[-<+>>[-]<]>[-<<<.>>>]
  +<<--[->+>[-]<<]>>[-<<<.>>>]
  +<-----------------------------[-<+>>[-]<]>[-<<<.>>>]
  +<<--[->+>[-]<<]>>[-<<<.>>>]
  <[-]>>
]
<<<<[<]
<--.<.>++..--..<.>++.
>>[>]
<[
  [->+>>+<<<]
  +>-------------------------------------------[->+<<[-]>]<[->>>.<<<]
  +>>-[-<+<[-]>>]<<[->>>.<<<]
  +>-[->+<<[-]>]<[->>>.<<<]
  +>>-[-<+<[-]>>]<<[->>>.<<<]
  +>--------------[->+<<[-]>]<[->>>++.--<<<]
  +>>--[-<+<[-]>>]<<[->>>--.++<<<]
  +>-----------------------------[->+<<[-]>]<[->>>++.--<<<]
  +>>--[-<+<[-]>>]<<[->>>--.++<<<]
  >[-]<<
]
<--.<.>++..<.

```

Given a program it outputs

```
+[[+]PROGRAM[+]][[+]MIRROR[+]]+

```

with `PROGRAM` and `MIRROR` replaced by the program (without non-brainfuck characters) and its mirror image.

# Answer
> 1 votes
# C# - 174

```
using System;using System.Linq;class c{public static void Main(){var a="";var b="";while((a=Console.ReadLine())!="")b+=a+"//\n";Console.Write(b+string.Concat(b.Reverse()));}}

```

Test Input:

```
using System;
using System.Linq;
class c
{
    public static void Main()
    {
        var a = "";
        var b = "";
        while ((a = Console.ReadLine()) != "")
            b += a + "//\n";
        Console.Write(b+string.Concat(b.Reverse()));
    }
}

```

Test Output:

```
using System;
using System.Linq;
class c
{
    public static void Main()
    {
        var a = "";
        var b = "";
        while ((a = Console.ReadLine()) != "")
            b += a + "//\n";
        Console.Write(b+string.Concat(b.Reverse()));
    }
}

// }
// }
// ;)))(esreveR.b(tacnoC.gnirts+b(etirW.elosnoC
// ;"n\//" + a =+ b
// )"" =! ))(eniLdaeR.elosnoC = a(( elihw
// ;"" = b rav
// ;"" = a rav
// {
// )(niaM diov citats cilbup
// {
// c ssalc
// ;qniL.metsyS gnisu
// ;metsyS gnisu

```

# Answer
> 0 votes
## PHP, 96 bytes

```
function a($b){
    echo $c = "a('$b')" . strrev("a)'" . $b . "'(");
    $d = substr($c, 0, strlen($b) + 5);
    eval("$d;");
}

```

**Sample Usage:**

```
a('apple'); // echoes a('apple')('elppa')a until your bytes get exhausted

```

This is nothing clever. It's just a simple piece of code that does the job... I was in a mood for playing. I do know that this code is rife with bad programming practices!

Finally, I will gladly accept any criticism and edits to this code!

# Answer
> 0 votes
# Cobra - 134

```
class P
    def main
        i=List<of String?>(Console.readLine.split('\n'))
        print '/#\n[i.reversed.join("\n")]\n#/#\n[i.join("\n")]\n#/'

```

# Answer
> 0 votes
# Racket 133

```
(require srfi/13)(let((r read-line)(w display))(let l((i(r)))(when
(not(eq? eof i))(w i)(w";\n")(l(r))(w"\n;")(w(string-reverse i)))))

```

Ungolfed (but still very imperative):

```
(require srfi/13)
(let recurse ((instr (read-line)))
  (when (not (eof-object? instr))
    (display instr)
    (display ";\n")
    (recurse (read-line))
    (display "\n;")
    (display (string-reverse instr))))

```

Output when given the ungolfed version as input:

```
(require srfi/13);
(let recurse ((instr (read-line)));
  (when (not(eof-object? instr));
    (display instr);
    (display ";\n");
    (recurse (read-line));
    (display "\n;");
    (display (string-reverse instr))));

;))))rtsni esrever-gnirts( yalpsid(
;)";n\" yalpsid(
;))enil-daer( esrucer(
;)"n\;" yalpsid(
;)rtsni yalpsid(
;))rtsni ?tcejbo-foe(ton( nehw(
;)))enil-daer( rtsni(( esrucer tel(
;)31/ifrs eriuqer(

```

---
Tags: code-golf, palindrome
---


title: Domination problem in chess

text:
# Question
Title: Domination problem in chess
Given an `m`x`m` chess board, find a minimum number of pieces of the given kind and place them on a chess board in such a way that all squares are either occupied or attacked by at least one piece.

## Input

The input consists of two parameters: `m`, the number of squares on each side; and a letter which indicates which piece to use, according to the following key: **K**ing, **Q**ueen, **R**ook, **B**ishop, k**N**ight. For example, an input of `8 B` means that you have to find a solution for an `8`x`8` board with bishops.

The input will always consist of a positive integer and a valid letter. You may choose to implement a program which takes input either as command-line arguments or separated by a space on stdin; or to implement a named function/verb which takes two parameters.

## Output

The output should be a chess board in the following format:

```
........
.....Q..
..Q.....
....Q...
......Q.
...Q....
........
........

```

This is a solution for the input `8 Q`. Each line is separated by a newline.

Note that every valid input has a solution.

## Other points

Standard loopholes are not acceptable. In particular, since your program must handle any input, it is not sufficient to hard-code the answer for small inputs.

The particular case of this problem where Queens are used has been the subject of some investigation, and the number of Queens required for square boards is in the Online Encyclopaedia of Integer Sequences as A075324. However, that probably doesn't help you for inputs larger than `18 Q`, and doesn't give you the layout for smaller cases.

As a performance constraint to prevent pure brute-force approaches, the code should output a result for `18 Q` in a reasonable time (approximately 6 hours).

# Answer
> 2 votes
This is a fun problem, and I'm sad that it has no solution, so I made my own!

Requires arguments in the form M P where M is the size of the board and P is the code for the piece

**Java - S.java - 1359 Characters**

```
public class S{int s;String p;String e=".";String b;String t;int c;public static void main(String[]args){new S(args);}S(String[] a){s=Integer.parseInt(a[0]);p=a[1];b="";int i;if(p.equals("P")){String r="P";for(i=1;i<s;i++)r+=e;r+="\n";for(i=0;i<s;i+=3){a(r);f(p);a(r);}m(0);}if(p.equals("B")){for(i=0;i<s-1;i++){if(s/2==i)f(p);f(e);}}if(p.equals("N")){for(i=0;i<s;i+=5){f(e);f(e);f("N");f(e);f(e);}m(0);if(s%5==2|s%5==1){m(1);f(p);}}if(p.equals("R")){f(p);for(i=1;i<s;i++)f(e);}if(p.equals("K")){String k="";for(i=0;i<s;i+=3)k+=".K.";k=k.substring(0,s-1);k+=(s%3==0)?e:"K";k+="\n";for(i=0;i<s;i+=3){f(e);a(k);f(e);}m(1);if(s%3==0)f(e);else a(k);}if(p.equals("Q"))for(i=0;i<s*s;i++){try{q(i,0,new String[s][s]);}catch(Exception e){}b=t;}System.out.println(b);}void q(int d,int g,String[][] o) throws Exception{int u=0;int i;if(g==s*s|u>c){if(u<=c){c=u;t="";for(i=0;i<s;i++){for(int j=0;j<s;j++)t+=o[i][j];t+="\n";}}throw new Exception();}int r=(d/s)%s;int c=d%s;if(o[c][r]==null){for(i=0;i<s;i++){try{o[c-r+i][i]=(o[c-r+i][i]==null)?e:o[c-r+i][i];}catch(Exception e){}try{o[i][r+c-i]=(o[i][r+c-i]==null)?e:o[i][r+c-i];}catch(Exception e){}o[i][r]=(o[i][r]==null)?e:o[i][r];o[c][i]=(o[c][i]==null)?e:o[c][i];}o[c][r]="Q";u++;}q(d+1,g+1,o);}void m(int d){b=b.substring(0,(s+1)*(s-d));}void a(String d){b+=d;}void f(String f){for(int i=0;i<s;i++){b+=f;}b+="\n";}}

```

(Pawns are attacking from left to right)

I couldn't find any proof of the minimum of any domination problem, but my Queen's solver at 8 solves with 5 queens and the others don't seem to be doing too badly (18 queens at 25x25). Someone will have to beat my other solutions to disprove them as minimums. That probably won't be hard!

Here is my de-golfed solution, for anyone interested. It's a bit of a mess... My first thought for doing the Queen's solver was to use backtracking, but I got lazy.

**Java - SimpleChessSolver.java - 3496 Characters**
(There was once a version which had a whole bunch of different classes, to represent the board, squares, pieces... But it quickly got out of control and was renamed ComplicatedChessSolver.java)

```
public class SimpleChessSolver {
int size;
String piece;
String period = ".";
String board;
String bestBoard;
int bestCount;

    public static void main(String[] args) {
        new SimpleChessSolver(args);
    }

    SimpleChessSolver(String[] args){
        size = Integer.parseInt(args[0]);
        piece = args[1];
        board = "";
        int index;
        if (piece.equals("P")){
            String periods = "P";
            for (index = 1; index < size; index++){
                periods += period;
            }
            periods += "\n";
            for (index = 0; index < size; index += 3){
                addString(periods);
                fillRow(piece);
                addString(periods);
            }
            trimToSize(0);
        }
        if (piece.equals("B")){
            for (index = 0; index < size - 1; index++){
                if (size/2 == index){
                    fillRow(piece);
                }
                fillRow(period);
            }
        }
        if (piece.equals("N")){
            for (index = 0; index < size; index += 5){
                fillRow(period);
                fillRow(period);
                fillRow("N");
                fillRow(period);
                fillRow(period);
            }
            trimToSize(0);
            if (size%5 == 2 || size%5 == 1){
                trimToSize(1);
                fillRow(piece);
            }
        }
        if (piece.equals("R")){
            fillRow(piece);
            for (index = 1; index < size; index++){
                fillRow(period);
            }
        }
        if (piece.equals("K")){
            String kings = "";
            for (index = 0; index < size; index += 3){
                kings += ".K.";
            }
            kings = kings.substring(0, size - 1);
            kings += (size%3 == 0) ? period : "K";
            kings += "\n";
            for (index = 0; index < size; index += 3){
                fillRow(period);
                addString(kings);
                fillRow(period);
            }
            trimToSize(1);
            if (size%3 == 0) {
                fillRow(period);
            }
            else {
                addString(kings);
            }
        }
        if (piece.equals("Q")){
            for (index = 0; index < size*size; index++){
                System.out.println(bestBoard);
                System.out.println("BlankLine\n");
                try {
                    queenSolve(index, 0, new String[size][size]);
                }
                catch (Exception e) {}
            }
            System.out.println("Final Answer");
            board = bestBoard;
        }

        System.out.println(board);
    }

    void queenSolve(int start, int depth, String[][] board2D) throws Exception {
        int currentCount = 0;
        int index;
        if (depth == size*size || currentCount > bestCount){
            if (currentCount <= bestCount){
                bestCount = currentCount;
                bestBoard = "";
                for (index = 0; index < size; index++){
                    for (int jdex = 0; jdex < size; jdex++){
                        bestBoard += board2D[index][jdex];
                    }
                    bestBoard += "\n";
                }
            }
            throw new Exception();
        }
        int row = (start / size) % size;
        int col = start % size;
        if (board2D[col][row] == null){
            for (index = 0; index < size; index++){
                try{
                    board2D[col - row + index][index] = (board2D[col - row + index][index] == null) ? period : board2D[col - row + index][index];
                } catch (ArrayIndexOutOfBoundsException e) {}
                try{
                    board2D[index][row + col - index] = (board2D[index][row + col - index] == null) ? period : board2D[index][row + col - index];
                } catch (ArrayIndexOutOfBoundsException e) {}
                board2D[index][row] = (board2D[index][row] == null) ? period : board2D[index][row];
                board2D[col][index] = (board2D[col][index] == null) ? period : board2D[col][index];
            }
            board2D[col][row] = "Q";
            currentCount++;
        }
        queenSolve(start + 1, depth + 1, board2D);
    }

    void trimToSize(int additionalTrim){
        board = board.substring(0, (size + 1) * (size - additionalTrim));
    }

    void addString(String toAdd){
        board += toAdd;
    }

    void fillRow(String filler){
        for (int index = 0; index < size; index++){
            board += filler;
        }
        board += "\n";
    }

}

```

**How it works**
Other than the queens, the other solutions are very simple. The Knights, Rooks, and Bishops can all be solved by putting a straight line in the correct place. Rooks cover their whole rank, so it works to just put a line anywhere on the board. A row of knights will cover four parallel rows, two in each direction. If there is a row of bishops on approximately (+/- 0.5) the middle row, they can cover every square. A row of pawns covers the parallel rows to their immediate left and right except for the bottom square, so I put a pawn on that square to occupy it. Kings can only cover the 3x3 squares around them, so I just stick Kings such that their squares don't overlap, with overlapping kings added if I need to fill out a size%3 != 0 board.

Queens is a little trickier. My algorithm, which may not be the best, iterates over the board, so that it starts on every square, then puts a queen there. It fills in periods for every square that queen covers, then walks along the board until it finds a square not already occupied by a Q or a period. As I said, this produces the current minimum for a 8x8 board (5 Queens) and I couldn't find a reference for any other board size.

---
Tags: code-golf, chess
---