title: Racketeer Taxi Driver

text:
# Question
Title: Racketeer Taxi Driver
## The Scenario

You are a taxi driver in your city. You picked up a passenger from the airport and he told you the place he'd like to go.

To earn more money, you need to drive as much as you can. However, there are two problems:

* He always looks around. Therefore, you cannot pass from the same district twice.
* The passenger is not so dumb. He knows the shortest way between the airport and the destination. Therefore, while you're driving, you should pass each of those districts.

## The Input

Input is an undirected and edge weighted graph. The vertices are the districts and the edges are the ways that connect those districts. The weights of the edges indicate the distance between the districts. You can model the graph any way you want.

## The Output

Given the source and destination, among with the shortest path, find the longest path that contains each vertex in the shortest path.

## The Example

**WHOOPS** there are two different edge weights between `B` and `C`.
**Source:** `A`
**Destination:** `K`
**Shortest Path:** `A-D-F-I-K`
**Solution:** `A-B-C-D-E-F-G-H-I-J-K`

Rules

1. Your solution should be generic and can be applicable to all kinds of connected graphs.
2. No cycles are allowed. You can pass through a vertex only once
3. Brute-force is not allowed. Don't list all the possibilities and pick among them.
4. The edge weights are always positive.
5. It is a must to visit all vertices in the shortest path, however, the order is not important.

Duration: 1 week.
Tie breaker: Votes.
The code with the least run-time complexity (in terms of Big-O notation) wins!

# Answer
# Reduction to Traveling Salesman Problem, O(n^2\*2^n).

In the above, n is the number of vertices in the graph.

I will give a description of the algorithm for now. Starting with the input graph, carry out the following steps:

1. Create a new graph with edge weights equal to the negation of the input edge weights. These weights represent the value to the taxi driver of traversing those edges.
2. Let N be the sum of all of the negative weights in the (new) graph minus 1. Add N to each outgoing edge from a node on the shortest path (as given in the input). This represents the fact that the taxi driver absolutely must cross each vertex in the shortest path.
3. Now, use dynamic programming to solve the traveling salesman problem on this new graph as follows:
4. Next, create a memo table, m, with entries that are pairs, (v,S), where v is the final vertex in the (partial) path created so far, and S is a subset of the vertices in the graph. The weight associated with this entry will be the minimum sum of edge weights to reach v after having passed through the vertices in S. Also, maintain a parent pointer.
5. Initialize the memo table with the entry m\[(source,{source}\]=0, p\[(source,{source}\]=None.
6. Fill in the memo table, using the recursion that m\[(v,S)\] = min(m\[(u,S-{v})\]+w\[(u,v)\] for u in S), where w is the the edge weight dictionary. Create parent pointers accordingly.
7. Using the completed memo table, find the minimum value of m\[(destination,S)\], for all subsets S of the input vertices.
8. Trace the parent pointers from this minimum value backwards until we reach the source node. The resulting path is the solution.

I don't feel like coding that all up, but I believe it is a correct solution. It runs in `O(n^2*2^n)` time because there are n\*2^n entries in the memo table, and each is generated by taking a minimum over no more than n possibilities. All the other work takes far less than that amount of time.

This solves the problem because the traveling salesman path must go through all of the vertices on the shortest path, because skipping one of those vertices results in an increase in the traveling salesman cost of N, which cannot be offset by the negative edge weights in the graph, since N was chosen to be more negative than all of them combined.
> 4 votes

---
Tags: graph-theory, fastest-algorithm
---


title: Finding internal rate of return (IRR)

text:
# Question
Title: Finding internal rate of return (IRR)
In investing, internal rate of return (IRR), the continuously compounded rate of return economically equivalent to a specified series of cashflows, is often a valuable concept.

Your challenge is to demonstrate how to compute IRR in the language of your choice in as few bytes as possible, subject to the following conditions:

1. Your code should accept arbitrary cashflows, subject only to the condition that the initial cashflow is negative.
2. You can assume that the cashflow has already been assigned to a variable f (use some other variable name if 'f' is a command name in your language).
3. Assume cashflow is specified as a series of (date, datum) pairs, in whatever format is most convenient for your language. This challenge is about the IRR computation, not parsing the input.
4. All functions built into your language are allowed except IRR() or the equivalent, if your language has it, because that's not interesting.
5. Output should be a real number (thus, 0.14, not "14%").

The solution requires numerical root-finding, and different methods and starting conditions will find slightly different answers. For the purposes of the contest, if you're within 0.001 of the answer reached by Excel's XIRR function, you're close enough.

Example 1:

```
f={{{2001, 1, 1}, -1}, {{2002, 1, 1}, .3}, {{2005, 1, 1}, .4}, {{2005, 1, 10}, .5}};

0.0584316

```

Example 2:

```
f = {{{2011, 1, 1}, -1}, {{2012, 2, 1}, -.3}, {{2015, 3, 1}, .4}, {{2015,3,15},.01}, {{2015, 4, 10}, .8}};

-0.2455921

```

Example 3:

```
f = {{{2011, 1, 1}, -1}, {{2012, 2, 1}, 3.3}, {{2015, 3, 1}, 5.4}, {{2015,3,15}, 6.01}, {{2015, 4, 10}, 17.8}};

2.4823336

```

More information available at http://en.wikipedia.org/wiki/Internal\_rate\_of\_return

# Answer
> 2 votes
# Maxima, 149

```
load(mnewton)$y(d):=?encode\-universal\-time(0,0,0,d[4],d[3],d[2])/31536000$mnewton(f[1][1]+sum(f[i][1]*(1+r)^(y(f[1])-y(f[i])),i,2,length(f)),r,.1);

```

This code has a bug where some payments might be off by 1/24 day (1 hour). This bug happens if your local time zone moves in or out of daylight-saving time. To fix this bug, add `,0` (2 characters) after `d[2]`.

First set f to a list of lists in the form `[[flow, year, month, day], ...]`. Then paste this code at Maxima's prompt. The answer comes in the form `[[r = float]]`. If you want the float by itself, use `part(%[1][1],2);`

Example 1:

```
(%i150) f : [[-1, 2001, 1, 1], [.3, 2002, 1, 1], [.4, 2005, 1, 1],
             [.5, 2005, 1, 10]]$

(%i151) load(mnewton)$y(d):=?encode\-universal\-time(0,0,0,d[4],d[3],d[2])/31536000$mnewton(sum(f[i][1]*(1+r)^(y(f[1])-y(f[i])),i,1,length(f)),r,.1);
(%o153)                   [[r = .058394251994029284]]

```

Example 2:

```
(%i154) f : [[-1, 2011, 1, 1], [-.3, 2012, 2, 1], [.4, 2015, 3, 1],
             [.01, 2015, 3, 15], [.8, 2015, 4, 10]]$

(%i155) load(mnewton)$y(d):=?encode\-universal\-time(0,0,0,d[4],d[3],d[2])/31536000$mnewton(sum(f[i][1]*(1+r)^(y(f[1])-y(f[i])),i,1,length(f)),r,.1);
(%o157)                  [[r = - .017843072768412977]]

```

Example 3:

```
(%i158) f : [[-1, 2011, 1, 1], [3.3, 2012, 2, 1], [5.4, 2015, 3, 1],
             [6.01, 2015, 3, 15], [17.8, 2015, 4, 10]]$

(%i159) load(mnewton)$y(d):=?encode\-universal\-time(0,0,0,d[4],d[3],d[2])/31536000$mnewton(sum(f[i][1]*(1+r)^(y(f[1])-y(f[i])),i,1,length(f)),r,.1);
(%o161)                   [[r = 2.4823712861605407]]

```

My time zone is America/New\_York. Because of the daylight-saving bug, other time zones might give slightly different answers.

## Ungolfed

```
load(mnewton)$

/*
Returns the number of 365-day periods since the epoch, when called as
year([year, month, day]).
*/
year(date):=
?encode\-universal\-time(
  /* s, m, h, day, month, year, time zone */
  0, 0, 0, date[3], date[2], date[1], 0) /
31536000 /* seconds in 365 days */$

/*
Finds a numerical approximation for the internal rate of return for a
list of cash flows on a list of dates.  The dates must be a list of
lists in the form

    [[year, month, day], [year, month, day], ...]

The first date in the list is the present date for calculating the
present value of each cash flow.  Returns the rate for each 365-day
period.
*/
xirr(flows, dates):=
part(
  /* Solve for rate where net present value = 0. */
  mnewton(
    sum(
      /* present value of flows[i] on dates[i] */
      flows[i] * (1 + rate)^(year(dates[1]) - year(dates[i])),
      i, 1, length(flows)),
    rate  /* solve for rate */,
    .1    /* initial guess */)
  [1][1], /* extract 1st solution, 1st variable */
  2       /* value in variable = value */)$

```

Here `xirr(flows, dates)` is a function, but the golfed version only has an expression that looks at `f`. The golfed version also removes the `part` call and adds the daylight-saving bug.

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


# Question
Title: Find nth root of variable without using math operators/functions
Write a program which, given two positive integers *n* and *x*, will display the *n*-th root of *x* (which is also x1/n) in decimal to an accuracy of 0.00001. The program must output the resulting number in decimal, and it must work for any two numbers *n* and *x*. The variables may be defined in the program, or they may be inputted by the user, but it must work for any two positive integers.

However:

* You may not use any arithmetic operators or bitwise operators (including `+`, `*`, `^`, `>>`, etc.)
* You may not use any built-in math functions (such as `pow()`, `sqr()`, or `add()`).
* No web requests; the program must be completely independent from all outside sources.

Although I tagged this , a program with more code that can do the job more than 1 second faster is better. A winning program will be faster than all the other programs *by more than a second*. Time differences of less than 1 second will be considered negligible. If two programs complete within a second of each other, then the one with less code wins.

# Answer
# JavaScript

This answer doesn't satisfy all the rules, but I'm happy that at least it works. It's valid only for integers greater than one and there's no further precision.

Note that the `+` and `>` operators are used for string concatenation/comparison and the maths is behind the curtain. I hope that the `!` operator doesn't count as "arithmetic" as it operates over booleans.

```
function f(x,n){for(a=(c=',')+Array(x),s=r=c;a>s;r+=c)for(i='',s=r;i!=Array(n);i+=c)s=s.split(c).join(r);return r.slice(1).length}

```

And some tests:

```
> f(125,3)
5
> f(16807,5)
7
> f(4782969,7)
9

```
> 2 votes

---
Tags: code-golf, fastest-code, restricted-source, number-theory
---


# Question
Title: Compute the number of ways how you can express a number as a sum
For a given natural number `n`, compute the number of ways how one can express `n` as a sum of positive natural numbers. For example, for `n = 1` there is just one way. For `n = 4` we have 5 possible ways:

```
1 + 1 + 1 + 1
1 + 1 + 2
1 + 3
2 + 2
4

```

The ordering of terms in a sum doesn't matter, so `1 + 3` and `3 + 1` are considered the same. Your program should be effective enough to return the result for `n = 1000` in order of minutes.

The winner will the solution with most up-votes in (at least) 2 weeks.

# Answer
> 6 votes
# Haskell, 170 148

An efficient Haskell version using a generating function with Memoization. Solve instantaneously the problem for `n = 1000`. No precision issues even with large numbers:

```
time ./partitions 10000
36167251325636293988820471890953695495016030339315650422081868605887952568754066420592310556052906916435144
./partitions 10000  17.02s user 0.00s system 100% cpu 17.021 total

```

## The code

```
generalizedPentagonal = map pentagonal $ [1..] >>= \i->[i,-i]
    where pentagonal n = (3*n^2-n)`quot`2

partitions = (map partitions' [0..] !!)
    where partitions' 0 = 1
          partitions' n = sum . alternate . map partitions . takeWhile (>=0) . map (n-) $ generalizedPentagonal
          alternate = zipWith (*) (concat . repeat $ [1,1,-1,-1])

```

## Code-golf version

```
p=(map a[0..]!!)where a 0=1;a n=sum.zipWith(*)(concat.repeat$[1,1,-1,-1]).map p.takeWhile(>=0).map(n-).map(\n->(3*n^2-n)`quot`2)$[1..]>>= \i->[i,-i]

```

## Efficiency improvements

Replace the memoization with an `Array` instead of a list:

```
import Data.Array
[...]
bnd = (0,10000)
partitions = (array bnd [(i, partitions' i) | i <- range bnd] !)
[...]

```

Time for `partitions 10000` drop from `17s` to `960ms`

## Results

Interpreted:

```
partitions 1000
24061467864032622473692149727991
(0.11 secs, 21833064 bytes)

```

Compiled:

```
time ./partitions 1000
24061467864032622473692149727991
./partitions 1000  0.08s user 0.00s system 99% cpu 0.084 total

```

## Useful links

# Answer
> 4 votes
**Mathematica ~~25~~ 11**

```
PartitionsP

```

Usage

```
PartitionsP[4]
(*
5
*)

```

Calculating the result for n = 1000 is instantaneous

```
Timing[PartitionsP@1000]
(*
 {0., 24061467864032622473692149727991}
*)

```

# Answer
> 3 votes
## JavaScript

```
var partition = function(n) {
    var sigma=[], p=[1], i,j;
    for (i=1; i<=n; i++)
        for (j=i; j<=n; j+=i)
            sigma[j] = (sigma[j]||0) + i;
    for (i=1; i<=n; i++) {
        p[i] = 0;
        for (j=1; j<=i; j++)
            p[i] += p[i-j] * sigma[j];
        p[i] /= i;
    }
    return p[n];
}

```

This computes the partition function A000041 as the Euler transform of the sequence A000012 (1,1,1,...). The intermediate sequence `sigma` is A000203, the sum-of-divisors function.

For `n=1000` it takes approx 0.05 seconds in Node on my 2GHz machine, although since it's working with JS numbers it runs into precision issues. A slightly more complex version (online demo, it's a bit long to paste) adds a naïve big integer implementation and takes approx 0.5s in Node.

# Answer
> 2 votes
# JavaScript, 105 103

```
for(n=prompt(a=[b=1]);b<=n;a[b++]=s)for(s=0,k=1,j=b-1;j>-1;j-=k&1?k:k/2)s+=++k&2?a[j]:-a[j];alert(a[n])

```

Calculation takes less than 250ms for n=1000. The result isn't precise, because JS doesn't have arbitrary precision numbers, but the order of the result is correct.

# Answer
> 2 votes
## GolfScript, table recurrence

```
[[1]]\({..[[{1$,1$,-=}%0@0=+]zip{{+}*}:^%]\+}*0=^

```

Assumes input as an integer on the stack: leaves the result on the stack. Online demo counting partitions of `10`.

This isn't as efficient as the other answers (it computes the partitions of 1000 in approximately 30 seconds), but the mathematical background is much simpler.

Instead of considering just the number of partitions of `n`, consider the number of partitions of `n` into `k` parts: `p(n, k)`. Each such partition either contains a `1` or doesn't. The number of partitions which contain a `1` is easily seen to be the same as the number of partitions of `n-1` into `k-1` parts. For the partitions which don't contain a `1`, we can subtract `1` from each part without getting any zeroes, so their number is equal to the number of partitions of `n-k` into `k` parts. So we have the recurrence `p(n, k) = p(n-1, k-1) + p(n-k, k)`.

This program builds the table of `p(n, k)` starting from `p(1, 1) = 1`, and then at the end adds up the partitions of `n` into `1..n` parts to get the result.

Dissection:

```
# Initialise the table p(x,k) with the row for x=1
# Note that we will prepend new rows to the table, so it is built backwards
[[1]]
# Repeat n-1 times
\({
    # We need a couple of copies for the two parts of the sum in the recurrence
    ..
    # Collect in an array...
    [
        # Collect in an array...
        [
            # First an array of p(x-k, k) for k = 1 to x-1
            # x is the length of the current table plus one
            # We iterate over the rows of the table
            {
                # Stack: table table row
                # Row x-k is of length x-k, so k = x - length(row)
                # But because the row is indexed from 0, we want to find k - 1
                #   = length(table) - length(row)
                1$,1$,-
                =
            }%
            # Stack: table table [p(x-1,1) ... p(1,x-1)]
            # (Although actually it will be shorter, only until about p(x/2, x/2))
            0@0=+
        ]
        # Stack: table [[p(x-1,1) ... p(1,x-1)] [0 p(x-1,1) ... p(x-1,x-1)]]
        # Vector sum. Note that we store the array-sum operation in ^ for later use.
        zip{{+}*}:^%
    ]
    # Prepend to the table
    \+
}*
# Take the first row of the table and sum it
0=^

```

(NB If this were then I would save 1 char by repeating the loop `n` times and taking the second row of the table at the end).

# Answer
> 1 votes
# Python2, 110 (Bruteforce O(n^n) implementation)

A bruteforce implementation in python which takes the input of stdin:

```
from itertools import*
n=input()
print len(set(frozenset(p)for p in product(range(n+1),repeat=n)if sum(p)==n))

```

Computing the result for n=8 takes 10 seconds on my machine. Anything over that is way over a few minutes.

# Answer
> 1 votes
### GolfScript

```
2,\.,{[2+.2&(0@,{.2%!)/+}/]}%`{0\{~.4$,<*~)3$=*+}/+}+*-1=

```

Just because we need a GolfScript entry. Thanks to Peter for several ideas.

*Example:*

```
1000 2,\.,{[2+.2&(0@,{.2%!)/+}/]}%`{0\{~.4$,<*~)3$=*+}/+}+*-1=
# => 24061467864032622473692149727991

```

# Answer
> 1 votes
## JavaScript Hardy-Ramanujan-Rademacher

This depends on a BigNumber implementation which supports the following functions: `plus`, `minus`, `times`, `div`, `sqrt`, `isZero`, `lt`, `gt`, `round`). It also uses `config` to control the precision used in divisions and to set the rounding mode.

```
var partition = function(n) {
    // Hardy-Ramanujan estimate to set the precision with appropriate margin
    BigNumber.config((5 + 1.115 * Math.sqrt(n) + Math.log(n) / Math.log(100))|0, 6);

    // Hardy-Ramanujan-Rademacher
    var zero = new BigNumber(0),
        one = new BigNumber(1),
        // \sum_{i=0}^\infty 2^{i+1} i!^2 / {2i+1}!
        PI = function(){ var t = new BigNumber(2), s=t, i=1; while (!t.isZero()) s = s.plus(t = t.times(i).div((i+ ++i))); return s }(),
        A = new BigNumber(n).minus(one.div(24)),
        B = A.times(2).div(3).sqrt().times(PI),
        ABsqrt12 = A.times(B).times(new BigNumber(12).sqrt()),
        gcd = function(x, y) { return y ? gcd(y, x % y) : x },
        genexp = function(x, a, b, c, d) {
            // \sum_{i=0}^\infty ax^{4i}/(4i)! + bx^{4i+1}/(4i+1)! + cx^{4i+2}/(4i+2)! + dx^{4i+3}/(4i+3)!
            var res = zero, z = one, i;
            for (i=0; !z.isZero(); i+=4) {
                res = res.plus(z.times(a)); z = z.times(x).div(i+1);
                res = res.plus(z.times(b)); z = z.times(x).div(i+2);
                res = res.plus(z.times(c)); z = z.times(x).div(i+3);
                res = res.plus(z.times(d)); z = z.times(x).div(i+4);
            }
            return res;
        },
        p = zero, q = 0, C, L, Psi_, h, k, s, max_L = zero;
    for (;;) {
        // Adaptive precision calculation for performance
        if (++q > 1) BigNumber.config((5 + 1.115 * Math.sqrt(n) / q + Math.log(n) / Math.log(100))|0);

        L = zero;
        for (h = 0; h < q; h++) {
            if (gcd(h,q) > 1) continue;
            for (k=s=0; k < q; k++) s+= (2*(h*k %q) - q) * k - 4*h*n;
            // NB The %(4*q*q) is critical for performance
            L = L.plus(genexp(new BigNumber(s % (4*q*q)).div(2*q*q).times(PI),1,0,-1,0));
        }
        if (L.gt(max_L)) max_L = L;

        C = B.div(q);
        Psi_ = genexp(C,C,-1,C,-1).times(new BigNumber(q).sqrt());
        p = p.plus(L.times(Psi_));
        if (Psi_.times(max_L).abs().lt(ABsqrt12)) break;
    }
    return p.div(ABsqrt12).round();
};

```

It computes `partition(10000)` in about 0.67 seconds using Node on a 3.5GHz PC.

---
Tags: popularity-contest, number, combinatorics, integer-partitions
---


title: Print the relative path

text:
# Question
Title: Print the relative path
**Description**

Given a source path and a destination path, output the relative path to the destination with respect to the source.

**Rules**

1. The input can come from stdin or as arguments to the program/function.
2. Both Windows and Unix style paths must be supported.
3. The output path can use `/` and/or `\` for the path separator (your choice and combination of both is OK).
4. You can assume a relative path is possible.
5. The use of external programs, built-in or library functions made for computing relative paths is prohibited (e.g. Python's `os.path.relpath`)
6. This is

*Edit:* New rule from comments.
7. The relative path must be the shortest relative path possible.
8. Assume the destination path is different from the source path.

**Example 1**

```
# In
/usr/share/geany/colorschemes
/usr/share/vim/vim73/ftplugin

# Out
../../vim/vim73/ftplugin

```

**Example 2**

```
# In
C:\Windows\System32\drivers
C:\Windows\System32\WindowsPowerShell\v1.0

# Out
..\WindowsPowerShell\v1.0

```

# Answer
> 2 votes
# CJam, 46 bytes

```
ll]{'\/'/f/:~}/W{)__3$=4$@==}g@,1$-"../"*o>'/*

```

Try it online.

### Examples

```
$ echo '/usr/share/geany/colorschemes
> /usr/share/vim/vim73/ftplugin' | cjam path.cjam; echo
../../vim/vim73/ftplugin
$ echo 'C:\Windows\System32\drivers
> C:\Windows\System32\WindowsPowerShell\v1.0' | cjam path.cjam; echo
../WindowsPowerShell/v1.0

```

### How it works

```
ll]         " Read two lines from STDIN and wrap them in an array.                       ";
{           " For each line:                                                             ";
  '\/       " Split by “\”.                                                              ";
  '/f/      " Split each chunk by “/”.                                                   ";
  :~        " Flatten the array of chunks.                                               ";
}/          "                                                                            ";
W           " Push -1 (accumulator).                                                     ";
{           "                                                                            ";
  )__       " Increment and duplicate twice.                                             ";
  3$=       " Extract the corresponding chunk from the first line.                       ";
  4$@=      " Extract the corresponding chunk from the second line.                      ";
  =         " If the are equal,                                                          ";
}g          " repeat the loop.                                                           ";
@,          " Rotate the array of chunks of the first line on top and get its length.    ";
1$-         " Subtract the value of the accumulator.                                     ";
"../"*o     " Print the string “../” repeated that many times.                           ";
>           " Remove all chunks with index less than the accumulator of the second line. ";
'/*         " Join the chunks with “/”.                                                  ";

```

# Answer
> 2 votes
# Bash + coreutils, 116

Here's a shell script to get the ball rolling. Pretty sure there'll be shorter answers:

```
n=`cmp <(echo $1) <(echo $2)|grep -Po "\d+(?=,)"`
printf -vs %`grep -o /<<<${1:n-1}|wc -l`s
echo ${s// /../}${2:n-1}

```

Output:

```
$ ./rel.sh /usr/share/geany/colorschemes /usr/share/vim/vim73/ftplugin
../vim/vim73/ftplugin
$ ./rel.sh /usr/share/geany/colorschemes/ /usr/share/vim/vim73/ftplugin/
../../vim/vim73/ftplugin/
$ ./rel.sh /usr/share/vim/vim73/ftplugin /usr/share/geany/colorschemes
../../geany/colorschemes
$

```

Note there is no way for the script to tell if the string `ftplugin` is a file or a directory. You may explicitly provide a directory by appending it with an `/` as in the example above.

Won't handle paths containing whitespace or other funny characters. Not sure if that is a requirement or not. Just a few extra quotes would be needed.

# Answer
> 2 votes
## Ruby \>= 1.9, 89 ~~94~~ characters

```
$;=/\\|\//
a,b=$*.map &:split
puts"../"*(a.size-r=a.index{a[$.+=1]!=b[$.]}+1)+b[r..-1]*?/

```

Input via command line arguments. Works for both UNIX- and Windows-style paths, including paths with repeated folder names:

```
$ ruby relpath.rb /usr/share/geany/colorschemes /usr/share/vim/vim73/ftplugin
../../vim/vim73/ftplugin
$ ruby relpath.rb 'C:\Windows\System32\drivers' 'C:\Windows\System32\WindowsPowerShell\v1.0'
../WindowsPowerShell/v1.0
$ ruby relpath.rb /foo/bar/foo/bar /foo/qux/foo/bar
../../../qux/foo/bar

```

# Answer
> 2 votes
# Javascript (E6) 104

*Edit* Added alert for output

```
R=(s,d)=>alert(s.split(x=/\/|\\/).map(a=>a==d[0]?d.shift()&&'':'../',d=d.split(x)).join('')+d.join('/'))

```

**Ungolfed**

```
R (s,d) => // a single espression is returned, no {} or () needed
  s.split(x=/\/|\\/) // split string at / or \, save regexp in X for later
  .map( // create a new array from s
     a => a == d[0] // check if current of s and d equals
          ? d.shift() && '' // map to '' and cut 1 element of d
          : '../', // else map to '../'
     d=d.split(x)) // second param of map is useless, so split d here
  .join('')+d.join('/') // join map and concat to rest of d adding separators

```

**Test**

```
R('C:\\Windows\\System32\\drivers','C:\\Windows\\System32\\WindowsPowerShell\\v1.0')

```

> ../WindowsPowerShell/v1.0

```
R('/usr/share/geany/colorschemes','/usr/share/vim/vim73/ftplugin')

```

> ../../vim/vim73/ftplugin

# Answer
> 2 votes
# Bash, 69 66

I didn't post this one because I thought someone must be able to do it much better. But apparently it is not that easy.

```
sed -r 'N;s/(.*[/\])(.*)\n\1/\2\n/'|sed '1s/[^/\]*/../g;N;s!\n!/!'

```

`N` makes `sed` match two lines together. The first expression removes the common prefix ending with `/` or `\`. The second expression replaces directory names with `..` in the first line. Finally it concatenates the two lines with the separator.

Thanks to Hasturkun for 3 characters.

# Answer
> 2 votes
# J - 63 char

A function taking the old path on the left and the new path on the right.

```
}.@;@(c=.c&}.`(,~(<'/..')"0)@.(~:&{.))&('/'<;.1@,'\/'&charsub)~

```

This solution comes in three parts, looking like `post@loop&pre~`. Explained by explosion:

```
post @ loop & pre ~   NB. the full golf
                  ~   NB. swap the arguments: new on left, old on right
            & pre     NB. apply pre to each argument
       loop           NB. run the recursive loop on both
post @                NB. apply post to the final result

'/'<;.1@,'\/'&charsub  NB. pre
         '\/'&charsub  NB. replace every \ char with /
'/'     ,              NB. prepend a / char
   <;.1@               NB. split string on the first char (/)

c=.c&}.`(,~(<'/..')"0)@.(~:&{.)  NB. loop
                      @.(~:&{.)  NB. if the top folders match:
    &}.                          NB.   chop off the top folders
   c                             NB.   recurse
       `                         NB. else:
           (<'/..')"0            NB.   change remaining old folders to /..
         ,~                      NB.   append to front of remaining new folders
c=.                              NB. call this loop c to recurse later

}.@;  NB. post
   ;  NB. turn the list of folders into a string
}.@   NB. chop off the / in the front

```

Note that we add a leading `/` to each path before splitting, so that we handle Windows-style paths by making `C:` into a "folder". This results in an empty folder at the start of Unix-style paths, but that always gets removed by the loop.

See it in action:

```
   NB. you can use it without a name if you want, we will for brevity
   relpath =. }.@;@(c=.c&}.`(,~(<'/..')"0)@.(~:&{.))&('/'<;.1@,'\/'&charsub)~
   '/usr/share/geany/colorschemes' relpath '/usr/share/vim/vim73/ftplugin'
../../vim/vim73/ftplugin
   'C:\Windows\System32\drivers' relpath 'C:\Windows\System32\WindowsPowerShell\v1.0'
../WindowsPowerShell/v1.0

```

You can also try it yourself at tryj.tk.

# Answer
> 1 votes
# Ruby - 89

```
r=/\/|\\/
s = ARGV[0].split r
d = ARGV[1].split r
puts ("../"*(s-d).size)+((d-s).join"/")

```

Usage:

```
ruby relative.rb working/directory destination/directory

```

# Answer
> 1 votes
## Python 3, 120

```
a,b=(i.split('\\/'['/'in i])for i in map(input,'  '))
while[]<a[:1]==b[:1]:del a[0],b[0]
print('../'*len(a)+'/'.join(b))

```

Example:

```
$ python3 path.py
 /usr/share/geany/colorschemes
/usr/share/vim/vim73/ftplugin
../../vim/vim73/ftplugin

```

# Answer
> 1 votes
# C, 119 106

```
void p(char*s,char* d){while(*s==*d){s++;d++;}s--;while(*s){if(*s==47||*s==92)printf("../");s++;}puts(d);}

```

# Answer
> 0 votes
# JavaScript - 155

```
function p(s,d){s=s.split(/\\|\//g);d=d.split(/\\|\//g);o=[];for(i=0;s[i]==d[i];i++);for(j=s.length-i;j--;)o[j]="..";return o.concat(d.slice(i)).join("/")}

```

Parses either path format but outputs with `/` separator.

```
console.log(p("/usr/share/geany/colorschemes","/usr/share/vim/vim73/ftplugin"));
../../vim/vim73/ftplugin
console.log(p("/usr/share/geany/colorschemes/test/this","/usr/share/vim/vim73/ftplugin/this/is/a/test"));
../../../../vim/vim73/ftplugin/this/is/a/test
console.log(p("c:\\windows\\system32\\drivers\\etc\\host","c:\\windows\\system\\drivers\\etc\host"));
../../../../system/drivers/etchost

```

# Answer
> 0 votes
# PHP, 158 151

```
function r($a,$b){$a=explode('/',$a);$b=explode('/',$b);foreach($a as $k=>$v){if($v==$b[$k])$b[$k]='..';else break;}unset($b[0]);echo implode('/',$b);}

```

Ungolfed:

```
function r($a,$b){
    $a=explode('/',$a);
    $b=explode('/',$b);
    foreach($a as $k=>$v){
        if($v==$b[$k])$b[$k]='..';
        else break;
    }
    unset($b[0]);
    echo implode('/',$b);
}
// these lines are not included in count:
r('/test/test2/abc','/test/test3/abcd'); // ../test3/abcd
r('/test/test2/abc','/test/test2/abcd'); // ../../abcd

```

# Answer
> 0 votes
## Groovy - 144 chars

One solution:

```
x=args[0][1]!=':'?'/':'\\'
f={args[it].tokenize x}
s=f 0
d=f 1
n=0
while(s[n]==d[n++]);
u="..$x"*(s.size-(--n))
println "$u${d.drop(n).join x}"

```

example output:

```
bash$ groovy P.groovy C:\\Windows\\System32\\drivers C:\\Windows\\System32\\WindowsPowerShell\\v1.0
..\WindowsPowerShell\v1.0

bash$ groovy P.groovy /usr/share/geany/colorschemes /usr/share/vim/vim73/ftplugin
../../vim/vim73/ftplugin

bash$ groovy P.groovy /foo/bar/foo/bar /foo/qux/foo/bar
../../../qux/foo/bar

```

ungolfed:

```
// fs = file seperator, / or \
fs = args[0][1]!=':'?'/':'\\'

s = args[0].tokenize fs
d = args[1].tokenize fs

// n = # of matching dirs from root + 1
n = 0
while (s[n] == d[n++]) ;

// up = the up-prefix. e.g. "../../..", for instance
n--
up = "..${fs}" * (s.size-n)

println "$up${d.drop(n).join fs}"

```

---
Tags: code-golf
---


# Question
Title: Detect the newest file and pass it to a process
# Challenge

Detect the newest file in a specific folder and pass it as an argument to another process. The first argument to your program will be the folder, and the second argument will be the full path to the process.

Please specify the platform(s) your code works on.

# Examples

## Windows

```
newestfile "C:\Public_domain_movies\" "C:\Mplayer\mplayer.exe"

```

## Linux

```
./newestfile /home/user /bin/ls

```

# Answer
# Zsh - 15

Only tested on Linux, but it should work on other platforms too.

```
$2 $1/*(.om[1])

```
> 5 votes

# Answer
## Windows, PowerShell, 35

```
&$args[1](ls $args[0]|sort *w*)[-1]

```
> 3 votes

# Answer
## Linux, Ruby, 52 characters

```
exec$*[1],Dir[$*[0]+"/*"].sort_by{|a|test(?M,a)}[-1]

```

I'm not sure if I undestood the specifications correctly, so if this doesn't work as intended, please let me know. I only tested this on Linux, but *in theory* it should run on Windows, too.
> 2 votes

# Answer
## linux - bash+sed - 18 bytes

```
$2 `ls -t $1|sed q`

```

Does not work if the arguments contain blanks.
> 2 votes

# Answer
## Windows, cmd, 54

```
for /f "delims=" %%A in ('dir/b/o-d %1')do %2 %%A&exit

```

Caveats:

* Closes the current shell session
* Will consider directories (as do most other solutions)
> 1 votes

---
Tags: code-golf
---


title: Rotate 2D Array

text:
# Question
Title: Rotate 2D Array
Given an input of a 2 dimensional array of integers, rotate the array 90 degrees clockwise.

It should work for rectangular arrays of all sizes and proportions.

The rotated array should be printed at the end of the program.

**Example:**

Input:

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

 [6,7,8,9,0,1],

 [2,3,4,5,6,7],

 [8,9,0,1,2,3]]

```

Output:

```
[[8,2,6,0],
 [9,3,7,1],
 [0,4,8,2],
 [1,5,9,3],
 [2,6,0,4],
 [3,7,1,5]]

```

Do not rely on the patterns in the arrays above, they were used just for explanation purposes. Expect the arrays to be randomly generated.

**Scoring**

Every character in the program counts as **1 point**.

The first line of the program can store the array as a variable for **0 points**. The array must be stored as-is without any changes made to it until after this first line.

If your code can rotate other multiples of 90 degrees, **-15 points** from your score. If this value must be stored, it can be done so at the beginning of the program for **0 points**. It can be supplied in the same way that the array is supplied.

Lowest score wins!

# Answer
## Python 2 (17=32-15) (19)

No input (19):

```
s = [[0,1,2,3,4,5],
     [6,7,8,9,0,1],
     [2,3,4,5,6,7],
     [8,9,0,1,2,3]]
print zip(*s[::-1])

```

Taking input in `t`, the number of rotations (17=32-15)

```
s = [[0,1,2,3,4,5],
     [6,7,8,9,0,1],
     [2,3,4,5,6,7],
     [8,9,0,1,2,3]]
t=3
exec"s=zip(*s[::-1]);"*t
print s

```
> 5 votes

# Answer
# J 11 9 7 -10 = -3

```
|:&|.^:

```

*Edit:* Changing argument order gets rid of the parentheses.

*Edit 2:* Reducing by 2 characters by swapping rows instead of columns, and inverting the order of operations.

Adverb taking the multiple of 90 degrees, then the array to rotate.

```
NB. needs assigning to a variable or parentheses to separate from the arguments.
rot =: |:&|.^:
]a =: i. 4 4
 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

    |:&|.^: 1 a
12  8 4 0
13  9 5 1
14 10 6 2
15 11 7 3
   |:&|.^: 2 a
15 14 13 12
11 10  9  8
 7  6  5  4
 3  2  1  0
   |:&|.^: 3 a
3 7 11 15
2 6 10 14
1 5  9 13
0 4  8 12
   |:&|.^: 4 a
 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

```

Try it yourself at tryj.tk

As a little extra, this extends to any rank at the cost of 1 char, when slightly changed to

```
rot =: (|:|.)^:

```

This way it takes the permutation order for the transpose to the left, and the number of flips and the array to the right. Depending on the axis permutation requested, you get back after a number of flips: flipping two axis makes you come back after 4 turns, shifting the axis makes you come back after 2 times the rank of the array.

```
       ]b=:i.2 3 4
 0  1  2  3
 4  5  6  7
 8  9 10 11

12 13 14 15
16 17 18 19
20 21 22 23
   0 2 1 (|:|.)^: 1 b
12 16 20
13 17 21
14 18 22
15 19 23

 0  4  8
 1  5  9
 2  6 10
 3  7 11
   1 2 0 (|:|.)^: 6 b
 0  1  2  3
 4  5  6  7
 8  9 10 11

12 13 14 15
16 17 18 19
20 21 22 23

```
> 5 votes

# Answer
# Javascript (*ES6*) 51 48 45

Alerts each row of the new rotated array in sequence.

```
a = [[0,1,2,3,4,5],
     [6,7,8,9,0,1],
     [2,3,4,5,6,7],
     [8,9,0,1,2,3]]

for(i in a[0])alert(a.map(j=>j[i]).reverse())

```
> 2 votes

# Answer
### Ruby — 34 - 15 = 19

```
m = [[0,1,2,3,4,5],
     [6,7,8,9,0,1],
     [2,3,4,5,6,7],
     [8,9,0,1,2,3]]
n = 1

n.times{m=m.reverse.transpose};p m

```

### Haskell — 55 - 15 = 40

```
let m = [[0,1,2,3,4,5],[6,7,8,9,0,1],[2,3,4,5,6,7],[8,9,0,1,2,3]]
let n = 1 :: Int

import Data.List
print$(iterate(transpose.reverse)m)!!n

```
> 2 votes

---
Tags: code-challenge, array
---


title: A Most Excellent Code Golf Adventure

text:
# Question
Title: A Most Excellent Code Golf Adventure
You dudes, the Most Excellent Adventure is a home brew roleplaying game system based on the Bill & Ted Films, *plays gnarly air guitar riff*.

In this game system, when you draw from your dice pool (you have between 1 and 12 ten-sided dice, with faces labelled 0-9) you need to connect the results as a phone number on your phone pad:

Here one person has rolled 4, 2, 8, 3, 8, and 2, dialling 3-2-2-4-8-8. The other 7, 4, 6, 3, 9, and 4, only dialling 4-4-7 or 3-6-9. And the longest number wins.

Bill and Ted want to play this game on their telephone kiosk, but haven't the first clue about programming. As Station isn't around, they want you to program it. The kiosk had access to all programming languages and OSs past and future (causality forbids you using any future technology... No imaginary python 7 !)

Your input is two numbers between 1 and 12, representing the number of dice player 1 and player 2 have respectively. The output is the result for each player, and the length of the largest number they could dial.

Input: `8 10`
Output:

```
Player 1 rolled 1 2 3 4 5 6 7 8 with longest dialable number of 8.
Player 2 rolled 8 8 8 2 3 1 4 0 3 3 with longest dialable number of 10.

```

Numbers can be reordered and pressing the same key twice counts as two digits (which is why the above sequence `8 8 8 2 3 1 4 10 3 3` makes a six digit number not a 4 digit number)

Also, as you're programming this in a telephone kiosk you can only access 0-9, a-z, the `*` and a `#` keys in your code. Letters are accessed by repeated typing, much like on a mobile phone. *Every other key must be input in the kiosk as its ASCII code in hex like so: `#0a` **the upshot is when scoring your submission, these keys "cost" three times as many***.<sup>\[Unclear / Incorrect?\]</sup>

For instance to type `~` you press the hash key once, the `7` and then `3` three times to cycle through the digits `3de`. This gives the code `#7e` which corresponds to `~`. When you upload you code here you can just type the `~`, and count it as five characters.

The keypad looks a little like this:

For instance If your code had `print()` that would cost 15 for the `print` (`7p 7pqr 4ghi 6mn 8t`) plus 6 for the `()` (`#28 #29`).

This is code golf as Bill and Ted will get bored otherwise. Let the coding commence *plays gnarly air guitar riff*.

# Answer
> 3 votes
# VBScript - 1668 telephone keypresses (was 1708)

My entry is golfed a bit more - I realized (doh!) that the variable names should be characters that require less telephone keypresses (a,d,g,j,etc).

This program produces the output exactly as shown and takes the input as command line parameters. If line endings are 1 byte there is no advantage to using `:` to put it all on one line (#0a vs #3a). Run it with `cscript script.vbs 8 10` replacing 8 and 10 with whatever values you want - it tries every combination in order to get the maximum string so it is SLOW.

I just have one question: if you needed a two numbers beside each other that were both on the same key isn't it a bit ambiguous. Wouldn't the text a=e (22#333333) be the same keypresses as a\>d (22#333333)? How do you differentiate where the character boundaries are? I didn't specifically check for every possible occurance of where things on the same key are beside themselves and I don't know what I would have done if I did notice it...

```
sub b(d,m)
p=true
a=len(m)
for g=1to a-1
p=p and instr(split("7890*1245*123456*2356*124578*123456789*235689*45780*4567890*56890","*")(mid(m,g,1)),mid(m,g+1,1))>0
next
if p and t<a then t=a
if d=""then exit sub
a=len(d)
for g=1to a
w=""
if g>1then w=left(d,g-1)
p=""
if g<a then p=mid(d,g+1)
b w+p,m+mid(d,g,1)
next
end sub
randomize
set m=wscript.arguments
for e=1to 2
d=""
j="Player "+cstr(e)+" rolled"
for t=1to mid(10000+m.item(0)*100+m.item(1),e*2,2)
w=cstr(int(rnd()*10))
j=j+" "+w
d=d+w
next
j=j+" with longest dialable number of"
t=0
b d,""
wscript.echo j+" "+cstr(t)
next

```

Ok, I am finally ready to score my entry - that of course means no more changes to it because of how long it takes to transform it to a score. The transformed phone input is:

```
77777888222#20222#2833#2222266#29#02277#333887777888333#02222#3335555333666#2866#29#02233336666777
7#2044#3331886666#2022#2331#02277#33377#202266633#20444466677777887777#2877777775555444488#28#2278
90*1245*123456*2356*124578*123456789*235689*45780*4567890*56890#22#22222#22*#22#29#2866444433#2866
#2222244#222221#29#29#2222266444433#2866#2222244#22221#222221#29#29#33330#02266633399988#022444433
33#2077#202266633#2088#3222222#2088444333666#2088#33322#02244443333#2033#333#22#2288444333666#2033
3999444488#2077777888222#02222#3335555333666#2833#29#022333366667777#2044#3331886666#2022#02299#33
3#22#22#02244443333#2044#3333188444333666#2099#3335555333333388#2833#2222244#2331#29#02277#333#22#
22#02244443333#2044#3222222#2088444333666#2077#33366444433#2833#2222244#22221#29#022222#2099#22227
7#2222266#222266444433#2833#2222244#222221#29#02266633399988#02233366633#2077777888222#02277772266
633666666444499999333#0227777733388#2066#33399777772222777744447788#233322777744888663336668877777
#022333366667777#20333#3331886666#202#02233#333#22#22#02255#333#22#5055552299993337777#20#22#22222
22277777887777#28333#29#2222#22#20777766665555555533333#22#022333366667777#2088#3331886666#2066444
433#2810000#222266#233344448833366#280#29*100#222266#233344448833366#281#29#22222333*2#222222#29#0
2299#333222277777887777#28444466688#28777766633#28#29*10#29#29#02255#33355#2222#22#20#22#222299#02
233#33333#222299#02266633399988#02255#33355#2222#22#2099444488444#2055556666666443337777788#203344
44225555222225555333#20666888662223337777#2066663333#22#02288#3330#022222#2033#22222#22#22#0229977
7772222777744447788#233333322224446666#2055#2222#22#20#22#2222222277777887777#2888#29#022666333999
88

```

---
Tags: code-golf, number, game, restricted-source
---


title: Council Majority

text:
# Question
Title: Council Majority
**Introduction**

You belong to a council which oversees the destruction of corrupted worlds. When the council assembles, a single vote is taken. The ballot lists all nominated worlds. One is ultimately destroyed each time the council meets.

Due to a bug in user12345's code, the council recently flooded and then sent pirate zombies to the wrong planet. We need a more reliable system for counting votes.

**Problem**

A vote is described by a series of integers on a single line. The first integer is `m`, and the worlds nominated for destruction are uniquely numbered from 1 to `m`. The remaining integers each represent the world each council member voted on.

Somehow, without any collusion, one world always receives more than half of the vote. This *always* occurs, regardless of how many worlds are present.

Given an input, write a program that outputs the world elected for destruction.

**Example Input**

Remember, the first `3` is the number of worlds, `m`. It is not a vote.

`3 1 1 2 3 1 3 1 1 3`

**Example Output**

The majority of the council voted for planet 1, so we output that.

`1`

**Assumptions**

* The exact number of votes is not given
* The number of votes is between 1 and 100 (inclusive)
* Each vote is between 1 and m (inclusive)
* Every vote contains a majority
* Input must be provided through stdin, read from a file, or accepted as a sole argument to the program

The answer with the fewest characters wins!

# Answer
## GolfScript (10 9 chars)

```
~]$.,(2/=

```

Explanation:

```
~]     # Parse input into array
$      # Sort; note that the extra element giving the number of worlds will end up last
.,(2/= # Take the middle element (not counting the last one)

```

Thanks to Dennis for 10-\>9.
> 8 votes

# Answer
## APL (21)

```
∪v/⍨c=⌈/c←+/∘.=⍨v←1↓⎕

```
> 6 votes

# Answer
# Python (50)

```
l=raw_input().split()[1:];print max(l,key=l.count)

```

This approach doesn't need sorting. It finds the element which appears the most times is list `l`, using the `max` function and different ordering function.
> 3 votes

# Answer
# Python, ~~61~~ 60

```
l=map(int,raw_input().split())[1:];print sorted(l)[len(l)/2]

```

22 characters are spent parsing the input with spaces; if I could do comma separated, my score would drop to **39**.

Does the same thing as the other answers: drops the first element, then prints the element at halfway through the list when it is sorted.

Explanation:

```
          raw_input().split()                                # Get the line of input, split on spaces
  map(int,raw_input().split())                               # Convert list of strings into list of ints
  map(int,raw_input().split())[1:]                           # Drop the first element
l=map(int,raw_input().split())[1:];                          # Assign list to variable `l`
                                         sorted(l)           # Sort l in ascending order
                                         sorted(l)[len(l)/2] # Get the element halfway through the list.
                                   print sorted(l)[len(l)/2] # Print it
l=map(int,raw_input().split())[1:];print sorted(l)[len(l)/2] # Combine statements

```
> 2 votes

# Answer
# Mathematica (19)

```
g=Commonest@Rest@#&

```

Input as follows:

```
g[{3, 1, 1, 2, 3, 1, 3, 1, 1, 3}]

```

Output:

```
{1}

```
> 2 votes

# Answer
# Pyth 1.0.5, 10

```
JPwd;ocJNJ

```

Unlike almost every solution above, this code doesn't just take the middlemost element.

Explanation:

```
JPwd    J = input, split on spaces
;       Print last element of
ocJN    Order by count in J of N,
J       For N in J

```

---

Bonus solution:

# Council Plurality, 11

If you want pluralities to be correctly judged as well, that's one more character:

```
JtPwd;ocJNJ

```

This judges correctly the only case where the above fails for pluralities: When the last planet has one less vote than the plurality winner, the 10 character code will mistakenly select the last planet, because it counts the statement of the number of worlds as a vote.

This code corrects that error by using the tail function, `t`, to ignore the first number.
> 2 votes

# Answer
# J (33 characters)

33 characters in J: `(>:@i.>./)@:(+/"1)@(>:@i.@{.=/}.)`

Use it as:

```
(>:@i.>./)@:(+/"1)@(>:@i.@{.=/}.) 3 1 1 2 3 1 3 1 1 3

```
> 1 votes

# Answer
# J - 18 char

```
({~<.@-:@#)@/:~@}.

```

Explained by explosion:

```
({~<.@-:@#)@/:~@}.  NB. find the majority vote!
                }.  NB. remove the head of the list
            /:~     NB. sort the list
(        #)         NB. take the length
   <.@-:            NB. halve it and round down
 {~                 NB. select from the beheaded list

```

Usage:

```
   ({~<.@-:@#)@/:~@}. 3 1 1 2 3 1 3 1 1 3
1
   ({~<.@-:@#)@/:~@}. 20 3 2 2 1 1 1 1 7 7 7 7 7 7 7 7 7
7

```
> 1 votes

# Answer
## Groovy - 99 Chars

Using drop-sort-get-midway technique:

```
l=(System.in.text as List).findAll{!it.allWhitespace}.drop(1).sort()
println l.get((int)l.size()/2)

```

Ungolfed, somewhat:

```
list = System.in.text as List
s = list.findAll{ ! it.isAllWhitespace() }.drop(1).sort()
i = (int) s.size() / 2
println s.get(i)

```
> 1 votes

# Answer
# Python (78):

I swear I didn't see Quincunx's answer before I posted this...

```
from collections import*;print Counter(raw_input().split()[0:]).most_common(1)

```
> 1 votes

# Answer
# C# 133 chars

Because it's totally worth it to go into an old question and add an answer massively longer than any other. c# is tough to golf.

```
namespace System.Linq{class P{static void Main(){Console.Write(Console.ReadLine().GroupBy(x=>x).OrderBy(x=>x.Count()).Last().Key);}}}

```
> 1 votes

# Answer
# Python, ~~88~~ 83

```
from collections import*;print Counter(map(int,raw_input().split())).most_common(1)

```

This works even if one world gets only one more vote than another, because it uses modes.

The output for the example: `[(1, 5)]`. The first number is the world to destroy, and the second is the number of votes it got. This output is valid according to your rules:

> write a program that outputs the world elected for destruction.

And you gave an **Example output**, not a **Corresponding output**.

But if I really need the single number, then this works for **6** more characters:

```
from collections import*;print Counter(map(eval,raw_input().split())).most_common(1)[0][0]

```

Explanation:

```
from collections import*                                                            # import everything from the `collections` module
                                               raw_input().split()                  # Get the line of input, split on spaces
                                       map(int,raw_input().split())                 # Convert the list of strings to a list of ints
                               Counter(map(int,raw_input().split()))                # Create a Counter object (from collections) to get the mode
                               Counter(map(int,raw_input().split())).most_common(1) # Get the most common element of the Counter object
                         print Counter(map(int,raw_input().split())).most_common(1) # Print it
from collections import*;print Counter(map(int,raw_input().split())).most_common(1) # Combined statements

```
> 0 votes

# Answer
## J 21

```
(~.(#~(=>./))#/.~)@}.

```

Explanation from right to left:

1. `}.` drop first number
2. fork:
    1. `#/.~`: Count per unique element the number of occurences
    2. Hook:
        1. `#~` copy from left
        2. `(=>./)` hook: where right is maximum of right
    3. `~.` : take unique elements, in order

Examples

```
   (~.(#~(=>./))#/.~)@}. 3 1 1 2 3 1 3 1 1 3
1
   (~.(#~(=>./))#/.~)@}. 10 1 2 1 7 1 2 2 7 7 7
7

```
> 0 votes

# Answer
# PHP - 66

```
<?=!preg_filter(~‹ﬂ—‹ö,~€û§€ñ‘‘¢¬€œ,$argv[1]).sort($a)?:$a[$i/2];

```

Without the special chars:

```
<?=!preg_filter("# .#e",'$a[$i++]=$0',$argv[1]).sort($a)?:$a[$i/2];

```
> 0 votes

# Answer
# JavaScript (60)

```
a=prompt().split(" ").slice(1).sort();alert(a[a.length/2-1])

```
> -1 votes

---
Tags: code-golf
---


title: Calculate cell-phone keypresses

text:
# Question
Title: Calculate cell-phone keypresses
Your task is to calculate the total number of key-presses required to enter a given text on an old cellphone.

The keymaps are:

```
1:1
2:abcABC2
3:defDEF3
4:ghiGHI4
5:jklJKL5
6:mnoMNO6
7:pqrsPQRS7
8:tuvTUV8
9:wxyzWXYZ9
0:<space><newline>0

```

To type `exaMPle TExt 01` , you would press `33 99 2 6666 77777 555 33 0 8888 33333 99 8 0 <a 1-sec pause here in real life but we'll ignore it>000 1` for a total of 37 keypresses.

The `*` key brings up a map of special characters:

```
.,'?!
"-()@
/:_;+
&%*=<
>£€$¥
¤[]{}
\~^¡¿
§#|`

```

with the first one (`.`) highlighted. You can move to highlight the required character using rectangular navigation keys and it takes another keypress to select.

So to insert `$`, you would press `*↓↓↓↓→→→<select>` i.e. a total of 9 key-presses.

* Input will be from a file called `source` placed in the current directory/directory of your program. **EDIT:** Per requests in comments, I'm adding `STDIN` as a valid input method.  Apologies for changing the spec after receiving answers.
* You must output `Total key presses <total_keypresses>`
* If the input file contains any character not in the given keymap, then your program must output `Invalid character <character> in source` and exit.

In short, the input and output of your program must resemble that of this(ungolfed) python script:

```
# This Python file uses the following encoding: utf-8
from __future__ import print_function
import sys

general_dict = { '1':1,
                 'a':1, 'b':2, 'c':3, 'A':4, 'B':5, 'C':6, '2':7,
                 'd':1, 'e':2, 'f':3, 'D':4, 'E':5, 'F':6, '3':7,
                 'g':1, 'h':2, 'i':3, 'G':4, 'H':5, 'I':6, '4':7,
                 'j':1, 'k':2, 'l':3, 'J':4, 'K':5, 'L':6, '5':7,
                 'm':1, 'n':2, 'o':3, 'M':4, 'N':5, 'O':6, '6':7,
                 'p':1, 'q':2, 'r':3, 's':4, 'P':5, 'Q':6, 'R':7, 'S':8, '7':9,
                 't':1, 'u':2, 'v':3, 'T':4, 'U':5, 'V':6, '8':7,
                 'w':1, 'x':2, 'y':3, 'z':4, 'W':5, 'X':6, 'Y':7, 'Z':8, '9':9,
                 ' ':1, '\n':2, '0':3
                }

special_chars = ['.',',',"'",'?','!','"','-','(',')','@','/',':','_',';','+','&','%','*','=','<','>','£','€','$','¥','¤','[',']','{','}','\\','~','^','¡','¿','§','#','|','`']
for x in special_chars:
    general_dict[x]=(special_chars.index(x)/5) + (special_chars.index(x)%5) + 2

key_press_total = 0
with open('source') as f: # or # with sys.stdin as f:
    for line in f:
        for character in line:
            if character in general_dict:
                key_press_total+=general_dict[character]
            else:
                print('Invalid character',character,'in source')
                sys.exit(1)

print('Total key presses',key_press_total)

```

This is code-golf, shortest program in bytes wins.

---

Shameless disclaimer: I made this challenge to have translations of the above python script in different languages which will be used to score this challenge in the sandbox.

# Answer
### GolfScript, 219 characters

Basic approach using a lookup table:

```
"Total key presses "0@1/{"1adgjmptw °behknqux\n.°cfilorvy0,\"°ADGJMsTz'-/°BEHKNPUW?(:&°CFILOQVX!)_%>°23456R8Y@;*£¤°SZ+=€[~°79<$]^§°¥{¡#°}¿|°`°".2$?)\1$<"°"/,{"Invalid character  in source"18/*puts'"#{''exit}"'+~}if\;+}/

```

Try here.
> 4 votes

# Answer
## Ruby 2.0, 232

```
$.-=~(%W[1adgjmptw\s
behknqux.\n
cfilorvy0,"
ADGJMsTz-'/
BEHKNPUW?(:&
CFILOQVX!)_%>
23456R8Y@;*£¤
SZ+=€[\\
79<$]~§
¥{^{#
}¡|
¿`].index{|s|s[$c]}||$><<"Invalid character #$c in source"&exit)while$c=$<.getc
puts"Total key presses #$."

```

Very simple encoding scheme so far: over 75% of the characters are used for string/array literals ...
> 3 votes

# Answer
### PHP, 711 708 676 characters (reading from STDIN now)

```
<?php $message=iconv("UTF-8","CP1252",fread(STDIN,1024));@$s=str_split;$special=iconv("UTF-8","CP1252",'.,\'?!"-()@/:_;+&%*=<>£€$¥¤[]{}\~^¡¿§#|`');$z=0;foreach($s($message)as$l){$a=ord($l);$b=$a;if($a==13)continue;($a>114||($a>82&&$a<91))&&$a--;$w=$a<58?($a-48):($a<91?($a-64):($a-96));$y=($a<58?1:($w%3?$w%3:3));$a<91&&$y+=3;$a<58&&$y=7;if($a==55||$a==57)$y=9;if($b==115||$b==122)$y=4;if($b==90||$b==83)$y=8;if(($b>79&&$b<83)||($a>85&&$a<89))$y++;($a==32||$a==49)&&$y=1;$a==10&&$y=2;$a==48&&$y=3;$u=array_search($l,$s($special));if($u!==false){$y=2+floor($u/5)+$u%5;}$z+=$y;if(($a<32||$a>127)&&$a!=10){echo"Invalid character $l in source";exit();}}echo"Total key presses $z";

```

*My first golf so far :)*

Wanted to try a rather unconventional approach. Instead of having a list of every character and how many clicks are needed to create it, I am using the character's ASCII values and calculate their required keypresses. **Thought it would spare me some characters first, now I think it's even longer than an array-approach.**

My main problem are the keys 7 and 9, which have 4 letters, instead of 3. Therefore I needed to create a couple of fallbacks, which blew my code up by almost 200 characters.

**Ungolfed version**

```
<?php
@$source = source;
$h = fopen($source, @r);
$message = iconv("UTF-8", "CP1252", fread($h, filesize($source)));
@$split = str_split;
$special = iconv("UTF-8", "CP1252", '.,\'?!"-()@/:_;+&%*=<>£€$¥¤[]{}\~^¡¿§#|`');
$count = 0;
foreach ($split ($message) as $character) {
    $ascii = ord($character);
    $helper = $ascii;
    if ($a == 13) continue;
    ($a > 114 || ($a > 82 && $a < 91)) && $ascii--;
    $key = $ascii < 58 ? ($a - 48) : ($a < 91 ? ($a - 64) : ($a - 96));

    $presses = ($a < 58 ? 1 : ($key % 3 ? $key % 3 : 3));

    // This part uses a lot of (probably unnecessary or still optimizable) fallbacks
    // for those characters, that are on "4-letter-keys"
    $ascii < 91 && $presses += 3;
    $ascii < 58 && $presses = 7;
    if ($a == 55 || $a == 57) $presses = 9;
    if ($helper == 115 || $helper == 122) $presses = 4;
    if ($helper == 90 || $helper == 83) $presses = 8;
    if (($helper > 79 && $helper < 83) || ($a > 85 && $a < 89)) $presses++;
    $ascii == 32 && $presses = 1;
    $ascii == 10 && $presses = 2;
    $ascii == 48 && $presses = 3;
    $ascii == 49 && $presses = 1;

    $key = array_search($l, $split($special));
    if ($key !== false){
        $presses = 2 + floor($key/5) + $key % 5;
    }

    $count += $presses;
    if ($a < 32 && $a > 127 && $a != 10) {
        echo "Invalid character $l in source";
        exit();
    }
}
echo "Total key presses $count";

```

I assume there's still a lot of room for improvement, but I'm pretty happy with this.

Another bad thing is the required use of `iconv()` for the list of special characters. Some of these (, `¥`, ...) are not natively supported by PHP.
> 2 votes

# Answer
## Python 3, 239 characters

```
s='1adgjmptw 1behknqux\n.1cfilorvy0,"1ADGJMsTz\'-/1BEHKNPUW?(:&1CFILOQVX!)_%>123456R8Y@;*£¤1SZ+=€[\\179<$]~§1¥{^#1}¡|1¿`'
print('Total key presses',sum(s[:s.find(c)+1].count('1')or exit('Invalid character %c in source'%c)for c in input()))

```
> 2 votes

# Answer
# CJam, 207 bytes

```
q:Q{" dptgwj1am hxk
.bnequ  ,0flco\"rviy    DT'/GsJz-AM (HP?KW&:BNEU    LXCO_>FV!%)IQ   48@3;*26R¤£5Y   €\+S[Z= $<§7~9] #{^¥ |¡}    `¿"'    /{1$#W>\}%1#)}%_0#){"Invalid character "Q@0#=" in source"}{:+"Total key presses "\}?

```

This program has 207 characters. With the appropriate encoding (Windows-1252), it fits in 207 bytes.

Note that Stack Exchange converts tabs (which I use as delimiter in the lookup table) into spaces, so you can't copy and paste the above code.

### Usage

Windows-1252 encoding

```
$ base64 -d > keys.cjam <<< cTpReyIgZHB0Z3dqMWFtCWh4awouYm5lcXUJLDBmbGNvXCJydml5CURUJy9Hc0p6LUFNCShIUD9LVyY6Qk5FVQlMWENPXz5GViElKUlRCTQ4QDM7KjI2UqSjNVkJgFwrU1taPQkkPKc3fjldCSN7XqUgfKF9CWC/IicJL3sxJCNXPlx9JTEjKX0lXzAjKXsiSW52YWxpZCBjaGFyYWN0ZXIgIlFAMCM9IiBpbiBzb3VyY2UifXs6KyJUb3RhbCBrZXkgcHJlc3NlcyAiXH0/
$ wc -c keys.cjam
207 keys.cjam
$ echo 'Hello, world!' | LANG=en_US.CP1252 cjam keys.cjam; echo
Total key presses 39
$ echo 'á' | LANG=en_US.CP1252 cjam keys.cjam; echo
Invalid character á in source

```

UTF-8 encoding

```
$ base64 -d > keys.cjam <<< cTpRezpDIiBkcHRnd2oxYW0JaHhrCi5ibmVxdQksMGZsY29cInJ2aXkJRFQnL0dzSnotQU0JKEhQP0tXJjpCTkVVCUxYQ09fPkZWISUpSVEJNDhAMzsqMjZSwqTCozVZCeKCrFwrU1taPQkkPMKnN345XQkje17CpSB8wqF9CWDCvyInCS97MSQjVz5cfSUxIyl9JV8wIyl7IkludmFsaWQgY2hhcmFjdGVyICJRQDAjPSIgaW4gc291cmNlIn17OisiVG90YWwga2V5IHByZXNzZXMgIlx9Pw==
$ wc -cm keys.cjam
209 217 keys.cjam
$ echo 'Hello, world!' | LANG=en_US.UTF8 cjam keys.cjam; echo
Total key presses 39
$ echo 'á' | LANG=en_US.UTF8 cjam keys.cjam; echo
Invalid character á in source

```
> 2 votes

# Answer
# JavaScript (E6) 291

**Edit**

Shell version, using spydermonkey shell. Read from a 'source' file, write to sdtout

```
z=t=0,[...read('source')].map(c=>t-=~((i=".\"/&>Â¤\\Â§,-:%Â£[~#'(_*â‚¬]^|?);=${Â¡`!@+<Â¥}Â¿".indexOf(c))<0?(p="0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])?p.search(/\d/):z="Invalid character "+c+" in source":i%8-~(i>>3))),print(z||"Total key presses "+t)

```

First try, works in FireFox console using popup for input and output

```
P=m=>(z=t=0,[...m].map(c=>t-=~((i=".\"/&>¤\\§,-:%£[~#'(_*€]^|?);=${¡`!@+<¥}¿".indexOf(c))<0
?(p="0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])
?p.search(/\d/):z="Invalid character "+c+" in source":i%8-~(i>>3))),z||"Total key presses "+t);
alert(P(prompt()))

```

**Readable**

```
P=m=>(
  z=t=0,
  [...m].map(
    c=>t-=~(
      (i = ".\"/&>¤\\§,-:%£[~#'(_*€]^|?);=${¡`!@+<¥}¿".indexOf(c)) < 0
      ? (p = "0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])
        ? p.search(/\d/)
        : z="Invalid character "+c+" in source"
      : i%8 - ~(i>>3)
    )
  ),
  z||"Total key presses "+t
);

```
> 1 votes

# Answer
## VBScript 435

Does not support non-ASCII chars. I was pretty far along with my code so I thought I'd post it for reference. I don't think anyone else used this approach.

```
i=inputbox(i)
a=SPLIT("1 abcABC2 defDEF3 ghiGHI4 jklJKL5 mnoMNO6 pqrsPQRS7 tuvTUV8 wxyzWXYZ9 0")
a(9)=" "+vbLf+"0"
b=SPLIT(".,'?! ""-()@ /:_;+ &%*=< >£€$¥ ¤[]{} \~^¡¿ §#|` x x")

for o=1 to len(i)
n=0
    for x=0 to 9
        for c=1 to 10
            d=mid(i,o,1)
            IF n=0 AND mid(b(x),c,1)=d THEN n=c+x
            IF mid(a(x),c,1)=d THEN n=c
        next
    next
    z=n+z
    IF n=0 THEN EXIT FOR
next
o="Total key presses "+cstr(z)
IF n=0 THEN o="Invalid character "+d+" in source"
msgbox o

```
> 0 votes

---
Tags: code-golf
---


title: Control Your Computer's Fan Speed

text:
# Question
Title: Control Your Computer's Fan Speed
The objective of this question is to create a program that pushes your computer's internal fan speed to its maximum RPM. Upon exiting the program, your fan should return to the normal operating RPM.

**Rules:**

1. You may not perform a CPU intensive task in order to modify the fan's speed.
2. Exiting the program may be via user input, a timeout period, or a response to a `SIGTERM` or `SIGEXIT` signal.
3. Avoid the standard loopholes.

# Answer
# OSX + Bash + smcFanControl, 91 bytes

This relies on the third-party smcFanControl suite to do the hard work **and is therefore more of a proof-of-concept** than a serious answer. **Real** answers could pick apart the smcFanControl source code and do this without third-party help.

smcFanControl.app is assumed to be installed in `/Applications`.

```
p=/Ap*/smcFan*/C*/R*/smc\ -k # Path to CLI utility
f()($p'FS! ' -w000$1)        # function to set fan mode
f 3                          # Set fan speeds to "forced" mode
eval $p\ F{0,1}"Tg -w5DC0;"  # Set fan 1 and 2 to 6000 RPM target speed
read                         # wait for keyboard input
f 0                          # Return fans to "auto" mode

```

Comments added for explanation, but not included in score.
> 5 votes

# Answer
# GLXGEARS - 8bytes

First thing I thought of was `yes`, or `yes` in parallel. As we are not allowed to use the CPU to control the speed, let's use the GPU:

```
glxgears

```
> 5 votes

# Answer
# Reboot, 6 bytes

```
reboot

```

Just after a boot, the fans start spinning at max rpm because the power is turned on to the fan, before the BIOS loads any real time controllers that will base the speed of the fan on the temperature of the processor. This also keeps the processor from getting excessively hot if you were to try the alternative... which would be to keep the fan off until those controllers were loaded and basing the fan speed on processor temp. More of a safeguard than anything. The processor is starting to work the moment you turn the computer on, but the BIOS still needs time to load. https://superuser.com/a/427723/246895

(Does not work on every pc, but is confirm the OP)
> 4 votes

---
Tags: code-golf
---


title: Golfed sort by debian version number

text:
# Question
Title: Golfed sort by debian version number
I wrote some perl to sort by debian package version number (specification here). Whilst readable, it was disappointingly long (114 lines, 2042 characters) - shocking. So this challenge is to produce the shortest program (in perl or otherwise) which takes debian package version numbers on `STDIN` separated by `\n`, sorts them, and puts the output on `STDOUT` separated by `\n`.

You can produce an dataset of debian versions numbers on a debian/ubuntu box by:

```
apt-cache madison . | perl -n -e 'print "$1\n" if /^\S+\s+\|\s+(\S+)\s+/;'

```

For those not on Debian / Ubuntu I've put a random selection of 1000 here. The sorted version of this sample is here. The `md5sum` of the unsorted and sorted versions (check they each end with a `\n`) are:

```
5ffd12d3f59b06619a712e92791c0dfd  input.sample
e6b2d03ddfd9491c5bdf2594a5aa82e5  output.sample

```

*(note as Ventero points out in the comments, there are certain equivalent version numbers, e.g. lines 135-138 out of the output, where 08 and 8 are equivalent and thus the sort order is arbitrary)*

For the purposes of verifying your input, you can install `Debian::Dpkg::Version` from CPAN and use the following to test:

```
#!/usr/bin/perl

use strict;
use warnings;
use Debian::Dpkg::Version;

my @input;

while (<>)
{
    chomp;
    push @input, $_;
}

my @output = sort version_compare (@input);
print join("\n", @output)."\n";

```

The following test data is thus sorted in the correct order, and (I believe) only contains lines complying with the Debian spec above, with each version being distinct:

```
0~~-~~
0~~-~
0~-~~
0~-~
0~-0
0-0
0-1
0-02
3-0
04-0
04a-0
5-0
04:3-0
5:3-0
06:3-0
06:3a-0
06:3a-01
06:3a-3~
06:3a-3
6:3a-04
06:3a-05
06:3.-0
06:3:a
06:3:a-01
06:3:a-05

```

The rules are:

* Package name sorting must be exactly per the Debian spec
* No inclusion of external modules written to perform Debian packages sorting, as that would make it rather easy. Therefore golfing the above test program will not produce a legal answer, as it includes `Debian::Dpkg::Version`. You may of course look to the source of that module for inspiration if you lack imagination, but I believe there are shorter ways to do this.
* You may assume that any input line whose format is invalid (i.e. does not constitute a version number conforming to the debian spec) must be retained, but may be sorted arbitrarily.
* Equivalent version numbers may be sorted arbitrarily, e.g. `0.08-1` is equivalent to `0.8-1` as the numeric components `08` and `8` are compared as integers.
* Save in respect of the arbitrary sort order of any lines not constituting version numbers conforming to the debian spec, and equivalent version numbers, your output should be identical to the test program above.

# Answer
## Ruby 2.0, 145 ~~179~~ characters

```
puts$<.sort_by{|a|(1..3).map{|i|"#{a[/^(\d+:)?(.+?)(-[^-]+)?
/,i]}".scan(/(\D*)(\d*)/).map{|w,n|w.bytes.map{|c|c<126?c>58?c:c+99:-1}+[0,n.hex]}}}

```

Correctly sorts both the linked reference input (though it generates a slightly different output order due to different sorting of equivalent version numbers, e.g. `1.06-2` vs `1.6-2`) and the included test data.
> 2 votes

---
Tags: code-golf
---


title: Hide your hash function

text:
# Question
Title: Hide your hash function
So you are tasked with creating an open source password authentication system but you want to reveal as little about the implementation of the hash function as possible. Can you write a function that takes in a password string and a salt string and outputs a salted hash string without revealing the hashing function?

End date: 6th of July

Popularity contest: So whoever is voted as hardest to figure out the hashing method.

Restriction: Must use an accepted as secure hashing function

# Answer
> 3 votes
# Python 3

Uninspired solution - hide your hash function with hash-looking code

```
import base64

a = b'66726F6D20686173686C696220696D706F72742A3B7072696E74287368613235'
b = b'3628627974657328696E70757428292B696E70757428292C277574662D382729'
c = b'292E686578646967657374282929232048656C6C6F2074686572652021402324'

exec(base64.b16decode(a+b+c))

```

# Answer
> 3 votes
# Ruby

Need a way to obfuscate your choice of hashing function? Why not use a hashing function?

```
require 'digest'

three_card_monte = %w[SHA1 MD5 RMD160]

part1, part2 = three_card_monte.repeated_permutation(2).find{|x,y|Digest(x).base64digest(y)[/tada!?/i]}

part2.send( ('mode'..$&).find{|x|Digest(part1).base64digest(x)[/\d\dSXQ/]}<<$&.to_i.chr)

puts Digest(part2).base64digest(gets+gets)

```

# Answer
> -1 votes
# Python

This one is not a hashing function, takes no salt, and is completely insecure, but can you tell what it is?

```
def f(x):
    a,b=ord(x),ord(x)+13
    if not (97<=a<=122 or 65<=a<=90):return x
    if (65<=a<=90 and b>90) or b>122: b-=26
    return chr(b)
print(''.join(f(i) for i in input()))

```

> It's rot13

Here is an actual hashing function.

```
import hashlib
salt = b'cHJpbnQoaGFzaGxpYi5zaGEyNTYoYnl0ZXMoaW5wdXQoKStpbnB1dCgpLCd1dGYtOCcpKS5oZXhkaWdlc3QoKSkKZXhpdCgp';import base64;exec(base64.b64decode(salt))
print(hashlib.md5(bytes(input(), 'utf-8') + salt).hexdigest())

```

Note that it is not md5 and it does not use a hard coded salt. Based on qwr's solution.

---
Tags: popularity-contest, obfuscation, hashing
---


title: Fake infinite loop

text:
# Question
Title: Fake infinite loop
The challenge is to write a fake infinite loop in any imperative programming language.

At first sight, the code should seem not to halt at all.

As a naive example:

```
int f(int x)
{
    return f(4.0);
}

int f(double x)
{
    return 0;
}

```

**But remember**
You're not allowed to use overflows:

```
int f(int x)
{
    if(x < 0) return -1;
    return f(x*x);
}

```

is illegal. When the number exceeds the integer limit, the function will stop. It's a good trick. But not good enough :)

The answer with the highest votes wins! Duration is 1 week.

# Answer
> 5 votes
# Bash

```
trap 'exec "$0"' exit

```

It re-execs itself when it should exit. So it will never really exit.

> It doesn't have the shebang. So you must run it like `bash a.sh`. And `$0` will probably not be something executable.

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


title: Make a finky syntax checker

text:
# Question
Title: Make a finky syntax checker
You are to make a program that can check the syntax of programs of its same language. For example, if you do it in python, it checks python syntax. Your program will receive a program on standard input, and verify whether or not its syntax is correct. If it is correct, output just "true" on standard output. If not, output just "false" on standard output.

Your program must be incorrect in one instance though. If fed its own source code, it will just output "false" on standard output. This is code golf, so shortest program wins!

Note: Although this isn't technically a quine, you must follow the quine rules, meaning you can't access your source code through the file system or whatever.

Note: You can't claim a program that could not be run due to a syntax error solves this challenge, since it needs to be runnable.

# Answer
> 9 votes
## Ruby 2.0, 65 ~~76 164~~ characters

```
eval r="gets p;$<.pos=0;`ruby -c 2>&0`;p$?==0&&$_!='eval r=%p'%r"

```

This uses Ruby's built-in syntax checker (`ruby -c`) to check the input's syntax, which means the code won't be evaluated.

Basic usage example:

```
ruby syntax.rb <<< foo
true
ruby syntax.rb <<< "'"
false
ruby syntax.rb < synxtax.rb # assumes the file was saved without trailing newline
false

```

### Explanation

This solution is (was) based on the standard Ruby quine:

```
q="q=%p;puts q%%q";puts q%q

```

`%p` is the format specifier for `arg.inspect`, which can be compared to `uneval`: when `eval`ing the string returned by `arg.inspect`, you (usually) get the original value again. Thus, when formatting the `q` string with itself as argument, the `%p` inside the string will be replaced with the quoted string itself (i.e. we get something like `"q=\"q=%p;puts q%%q\";puts q%q"`).

Generalizing this type of quine leads to something like the following:

```
prelude;q="prelude;q=%p;postlude";postlude

```

This approach has one huge drawback though (at least in ): All code needs to be duplicated. Luckily, `eval` can be used to get around this:

```
eval r="some code;'eval r=%p'%r"

```

What happens here is that the code passed to eval is stored inside `r` *before* `eval` is called. As a result, the full source code of the `eval` statement can be obtained with `'eval r=%p'%r`. If we do this inside the `eval`d code and ensure that the top level of our consists only of the one `eval` statement, that expression actually gives us the full source code of our program, since any additional code passed to `eval` is already stored inside `r`.

Side note: This approach actually allows us to write a Ruby quine in 26 characters: `eval r="puts'eval r=%p'%r"`

Now, in this solution the additional code executed inside `eval` consists of four statements:

```
gets p

```

First, we read all input from STDIN and implicitly save it into `$_`.

```
$<.pos=0

```

Then, we rewind STDIN so the input is available again for the subprocess we start in the next step.

```
`ruby -c 2>&0`

```

This starts Ruby in its built-in syntax checking mode, reading the source code from stdin. If the syntax of the supplied script (filename or stdin) is ok, it prints `Syntax OK` to its stdout (which is captured by the parent process), but in case of a syntax error, a description of the error is printed to *stderr* \- which would be visible, so we redirect that into nirvana (`2>&0`) instead.

```
p$?==0&&$_!='eval r=%p'%r

```

Afterwards, we check the subprocess's exit code `$?`, which is 0 if the syntax was ok. Lastly, the input we read earlier (`$_`) is compared against our own source code (which, as I described earlier, can be obtained with `'eval r=%p'%r`).

Edit: Saved 14 characters thanks to @histocrat!

# Answer
> 6 votes
# Rebol - 69 or 74~~75~~ fully compliant with all rules

New working versions thanks to @rgchris! Not sure if the first fails the "don't access the source" requirement as the interpreter holds the loaded and parsed code it has been passed as a cmd line parameter in the system object (`system/options/do-arg`) which is used to recognise itself.

```
probe not any[error? i: try[load/all input]i = system/options/do-arg]

```

This one follows all of the rules:

```
do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]]]

```

**Example usage:**

First printing a valid integer, the second printing an invalid integer.

```
echo "rebol [] print 123" | rebol --do "probe not any[error? i: try[load/all input]i = system/options/do-arg]"
true
echo "rebol [] print 1w3" | rebol --do "probe not any[error? i: try[load/all input]i = system/options/do-arg]"
false
echo "probe not any[error? i: try[load/all input]i = system/options/do-arg]" | rebol --do "probe not any[error? i: try[load/all input]i = system/options/do-arg]"
false

```

Fully compliant version:

```
echo 'rebol [] 123' |r3 --do 'do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]]
true
echo 'rebol [] 123a' |r3 --do 'do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]]]'
false
echo 'do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]]]' |r3 --do 'do b:[i: input prin block? if i <> join "do b:" mold b [try [load/all i]]
false

```

**Explanation:**

*First version*

This uses Rebols built-in `load` function to parse and load the code from stdin but it does not execute it.

The `try` block catches any syntax errors and the `error?` function converts the error to a simple boolean.

The `i = system/options/do-arg` compares the input from stdin (assigned to `i`) with the code passed on the `do-arg` argument (sneaky but very golf :).

`any` is a great function which returns `true` if `any`-thing in the block evaluates to `true` (for example, `any [ false false true ]` would return `true`).

`not` then just inverts the boolean to give us the correct answer and `probe` displays the contents of the returned value.

*Fully compliant version*

Let's go through this in order ...

Assign the word `b` to the block \[\] that follows.

Use the `do` function to interpret the `do` dialect in the `b` block.

Inside the `b` block ...

Set the word `i` to refer to the contents of stdin (`input`).

Now, `if` we `join` the string "do b:" to the `mold`'ed block `b` and it is not equal (`<>`) to the stdin input `i` then we try to `load` the input `i`.

If the result is a `block` then we have `load`'ed the passed data correctly otherwise we would receive a `none` from the failed `if`.

Use `prin` to display the result of `block?` which returns true if the result is a block. Using `prin` as opposed to `print` does not display a carriage return after the output (and it saves us another char).

# Answer
> 2 votes
I think this follows the rules:

**JS** (✖╭╮✖)

`function f(s){if(s==f.toString())return false;try{eval(s)}catch(e){return false}return true}`

The code will be evaluated if it's correct.

Need to take a look at arrow notation to see if it can't be shortened more.

`!function f(){try{s=prompt();return"!"+f+"()"!=s?eval(s):1}catch(e){return 0}}()`

After a couple failed attempts and reverts - new version!

`!function f(){try{s=prompt();"!"+f+"()"!=s?eval(s):o}catch(e){return 1}}()`

And I'm back!

`!function f(){try{s=prompt();"!"+f+"()"!=s?eval(s):o}catch(e){return !(e instanceof SyntaxError)}}()`

And I'm gone! Unfortunately due to nature of eval and thanks to @scragar (damn you @scragar!) this approach will not work (seeing as `throw new SyntaxError` is valid JS code, which ticks this method of) - as such, I'd say it's impossible to create a syntax checker (at least using eval or any variation thereof)

(\*see the comments!)

# Answer
> 2 votes
# Javascript - 86 82

```
!function $(){b=(a=prompt())=='!'+$+'()';try{Function(a)}catch(e){b=1}alert(!b)}()

```

Paste into your browser's Javascript console to test.
Explanation:

```
// Declare a function and negate it to call it immediately
// <http://2ality.com/2012/09/javascript-quine.html>
!function $ () {
  // Concatenating $ with strings accesses the function source
  invalid = (input = prompt()) == '!' + $ + '()';
  try {
    // Use the Function constructor to only catch syntax errors
    Function(input)
  }
  catch (e) {
    invalid = 1
  }
  alert(!invalid)
// Call function immediately
}()

```

**Note:** @m.buettner brought up the point that the program returns `true` for a naked return statement, such as `return 0;`. Because Javascript doesn't throw a syntax error for an illegal return statement until it actually runs (meaning code like `if (0) { return 0; }` doesn't throw a syntax error), I don't think there's any way to fix this short of writing a Javascript parser in Javascript. For example, consider the code:

```
while (1) {}
return 0;

```

If the code is executed, it will hang because of the loop. If the code is not executed, no error will be thrown for the illegal return statement. Therefore, this is as good as Javascript can get for this challenge. Feel free to disqualify Javascript if you feel that this doesn't fulfill the challenge sufficiently.

# Answer
> 2 votes
# Haskell - 222 bytes

Note that this uses a true parser. It does not depend on `eval` like functions of dynamic languages.

```
import Language.Haskell.Parser
main=interact(\s->case parseModule s of ParseOk _->if take 89s=="import Language.Haskell.Parser\nmain=interact(\\s->case parseModule s of ParseOk _->if take"then"False"else"True";_->"False")

```

This solution is not particularly pretty but does work.

# Answer
> 1 votes
# Python (95)

```
c=raw_input()
try:compile('"'if sum(map(ord,c))==7860 else c,'n','exec');print 1
except:print 0

```

# Answer
> 1 votes
# PHP - 140

```
<?exec("echo ".escapeshellarg($argv[1])." | php -l",$A,$o);echo$o|(array_sum(array_map(ord,str_split($argv[1])))==77*150)?"false":"true";//Q

```

Comment necessary to keep the 'hash' (a shameless copy of s,ɐɔıʇǝɥʇuʎs). Using php -l / lint to check for errors.

```
$ php finky_syntax_check.php '<?php echo "good php code"; ?>'
true
$ php finky_syntax_check.php '<?php echo bad--php.code.; ?>'
false
$ php finky_syntax_check.php '<?exec("echo ".escapeshellarg($argv[1])." | php -l",$A,$o);echo$o|(array_sum(array_map(ord,str_split($argv[1])))==77*150)?"false":"true";//Q'
false
$ php finky_syntax_check.php '<?exec("echo ".escapeshellarg($argv[1])." | php -l",$A,$o);echo$o|(array_sum(array_map(ord,str_split($argv[1])))==77*150)?"false":"true";//D'
true // note that the last character was changed

```

# Answer
> 0 votes
## C 174

Explanation -Wall needed to produce system error while still being compilable. The syntax error is no `return 0;` To enter via stdin in Windows console type Ctrl-Z after pasting and press enter.

Golfed

```
char c[256];int i;int main(){FILE *f=fopen("a.c","w");while(fgets(c,256,stdin)!=NULL){fputs(c,f);}fclose(f);i=system("gcc a.c -o -Wall a.exe");printf("%s",i?"false":"true");}

```

Ungolfed:

```
#include <stdio.h>
#include <stdlib.h>
char c[256];int i;
int main()
{
FILE *f=fopen("a.c","w");
while(fgets(c,256,stdin)!=NULL)
{
fputs(c,f);
}
fclose(f);
i=system("gcc a.c -o -Wall a.exe");
printf("%s",i?"false":"true");
}

```

# Answer
> 0 votes
**T-SQL - 110**

Fairly simple, I've been wanting to try a challenge on here for a while, finally got round to doing it. This is not the fanciest code, but I had fun nontheless.

The 'golfed' version.

```
BEGIN TRY DECLARE @ VARCHAR(MAX)='SET NOEXEC ON'+'//CODE GOES HERE//'EXEC(@)PRINT'TRUE'END TRY BEGIN CATCH PRINT'FALSE'END CATCH

```

A better formatted version.

```
BEGIN TRY
    DECLARE @SQL VARCHAR(MAX)='SET NOEXEC ON'+'//CODE GOES HERE//'
    EXEC(@SQL)
    PRINT'TRUE'
END TRY

BEGIN CATCH
    PRINT'FALSE'
END CATCH

```

It's fairly self explanatory, it uses SET NOEXEC on which makes it just parse the query instead of returning any results. the rest is mostly the try/catch that I use to determine what I need to print.

EDIT: I should have added that this will technically fail for itself. because it uses dynamic SQL any single quotes in the input have to be doubled ' -\> ''

---
Tags: code-golf, syntax
---


# Question
Title: Determine number of connected components
You are given a graph represented through an adjacency list. For example, the input

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

```

would correspond to the graph with nodes *1*, *2*, *3* and *4*, where *1* is connected to *2*, *2* is connected to *3*, *3* is connected to *4*, and *4* is connected to *1* (forming a square).

The task is to determine the number of of connected components of the graph represented by an inputted adjacency list. A "connected component" is a set of nodes from which there is no path to any other node that is not in the set.

Example:

> Intput: `1-2 2-3 4-5`
> Output: `2`

---

Language of your choice - shortest code possible.

# Answer
### Ruby, 77 characters

```
gets;0while$_.sub!(/\b(\d+)\b(.*) (\1-\d+|\d+-\1)\b/,'\3\2');p$_.count(" ")+1

```

A first plain attempt in Ruby. It collects the sub-graphs using a regular expression until no more connections can be made.

Examples:

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

> 1-2 2-3 4-5
2

> 1-2 3-4 8-9 1-6 5-7 7-4 10-9
3

```
> 2 votes

# Answer
# Mathematica 126

With `x` holding the input string,

```
t = ToExpression;
Length@ConnectedComponents@Graph[Characters /@ ImportString[x, "Table"][[1]] /.
{a_, "-", b_} :>   UndirectedEdge[t@a, t@b]]

```

---

If `x` is input instead as a list of undirected edges, in standard Mathematica format, the solution can be reduced to 34 chars:

```
Length@ConnectedComponents@Graph@i

```

Example:
> 1 votes

# Answer
## Sage, 77

```
len(Graph([t.split('-')for t in raw_input().split()]).connected_components())

```
> 1 votes

# Answer
# Golfscript, ~~67~~ 62 characters

This can probably be golfed down a little more but...

~~`" "/{"-"/{~}%}%0\{.}{(:^;{.{^&},.{+}*}{.@\-\{+}*:^;}while\)\}while;`~~

```
'-'%{~}%2/0\{.}{(:^;{.{^&},.{+}*}{.@\-\{+}*:^;}while\)\}while;

```

Important note: this ONLY works on the ruby interpreter for golfscript (from golfscript.com), NOT on the online golfscript app, because the online app incorrectly handles nested while loops. Here's the commented code:

~~`" "/{"-"/{~}%}% # parse into array of number pairs`~~

```
'-'%{~}%2/        # parse into array of number pairs
0\                # push the counter under the current set
{.}               # copy top for the condition pop
{
    (:^;          # grab leftmost pair
  {
    .{^&},        # grab any matching the left pair, make a copy for the
    .{+}*         # condition, and merge the copy's elements together
  }{
    .@\-\         # remove the matches from remaining set
    {+}*:^;       # merge matches together & assign to '^'
  }while
  \)\             # update the counter underneath
}while;

```
> 0 votes

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


title: Output a non-Context-Free Language

text:
# Question
Title: Output a non-Context-Free Language
Your challenge is to write a program which will output a non-context-free language.

A Context-free Grammar is a series of replacement rules, describing which symbols can be replaced by which other symbols. It defines set of strings, known as a language, which is generated by performing all possible replacement rules on an initial symbol until no more replacements can be made.

Any language which can be generated this way is known as a **context-free language**.

Your challenge is to write a program which will output a language which *cannot* be generated this way.

**Details**:

* Output your language in increasing order of length. Ordering between strings of a given length is up to you.
* As all CSLs are infinite, your program must not halt.
* The strings must be separated from each other. However, you may choose the separation.
* Please include in your answer a description of the language you generate and an explanation of why it is not context-free.
* One possible way to prove this is by using the pumping lemma.
* Example context-sensitive language: \[abc, aabbcc, aaabbbccc, aaaabbbbcccc, ...\]

**Scoring**: For all programs which can be encoded in ASCII or another 7 bit or less character set, scoring is by character. For all other programs, scoring is (# of bits in binary encoding)/7.

Feel free to ask questions.

# Answer
# Pyth, 6

I didn't find the Pyth documentation. But it works.

```
W1~ddd

```
> 1 votes

# Answer
# Python 2 (24) (26)

```
s="1"
while 1:print s;s+=s

```

Prints the language of strings in the symbol `1` whose length is a power of 2, i.e `{"1"*(2**n) | n>=0}`. The `s+=s` is equivalent to `s*=2`; it doubles the string each time.

Since unary (one-symbol) CFG's are regular, and unary regular CFG's are periodic past a point, this cannot be regular and thus is not a CFG. Alternatively, use the pumping lemma to see that the possible lengths of words in a CFL must have finite density and can't have arbitrarily large gaps.

Unfortunately, Python doesn't have a short way to produce an infinite counter. I'm sure some language can do `for i in Naturals:print("1"*i*i)` shorter (squares suffice just as well).

**Edit:** Can shorten to

```
s=2
while 1:print s;s*=s

```

which prints numbers of the form `2**(2**n)`, which can be taken as strings over `0123456789`. Because the decimal length doubles at each step, this can't be context-free because the length gaps cannot satisfy the pumping lemma.
> 1 votes

# Answer
# CJam, 8 7

```
{]`_p}h

```

It is not context-free because there are only at most 4 strings between length `n` and `7n` for any `n`.

It is context-sensitive because the memory usage is always growing, and it prints almost everything in the memory.
> 1 votes

---
Tags: code-golf, string
---


title: mathpack numeric literals

text:
# Question
Title: mathpack numeric literals
# preface

In a very heated situation you have to go even further with golfing.
(e.g. in a challenge where your answer is 100 characters long and it is just embarrassing that you couldn't make it 99)
In that case, from now on you use the winner's algorithm of this challenge :)

# goal

You have to write a program that takes an uint32 and returns the most compressed form.

```
$ mathpack 147456
9<<14

```
* There will be multiple solutions for a number. Pick the shortest one
* If the compressed form is longer or equal to the original number, return the original number

# rules

* write in any language - output in any language
* i'm aware of that in C `'abc'` is `6382179` and you can achieve pretty good results with this conversion. but languages are separated in this challenge so don't lose heart
* it is prohibited to use external variables. only operators and literals and math related functions!

# scoring

here are the test cases: pastebin.com/0bYPzUhX
your score (percent) will be the ratio of
`byte_size_of_your_output / byte_size_of_the_list` **without line breaks**.
(you have to do this by yourself as i'll just verify the best codes just in case)
winners will be chosen by score and **language of output**!

**examples:**

```
$ mathpack 147456 | mathpack 97787584 |  mathpack 387420489
            9<<14 |           9e7^9e6 |            pow(9,9)

```

# Answer
> 1 votes
## Code: Mathematica, Output: C, ~62.1518% (12674/20392)

I thought I'd also give C a try because of those funny character literals. Currently this is the only thing this answer is trying, and it's working quite well.

```
mathpack[n_] := Module[{versions, charLiteral},
   charLiteral = "'" <> StringReplace[Map[
        Switch[#,
          (*d_ /; d < 32,
          "\\" <> IntegerString[#, 8],*)
          10,
          "\\n",
          13,
          "\\r"
          39,
          "\\'",
          92 ,
          "\\\\",
          _,
          FromCharacterCode@#] &,
        FromDigits[#,
           2] & /@ (Partition[PadLeft[IntegerDigits[n, 2], 32],
            8] //. {{0 ..} .., x__} :> {x})
        ] <> "",
      {(*"\\10" -> "\\b",
       "\\11" -> "\\t",
       "\\13" -> "\\v",
       "\\14" -> "\\f",*)
       RegularExpression["(?!<=\?)\?\?(?=[=/()!<>-]|$)"] -> "?\\?"
       }
      ] <> "'";
   versions = {ToString@n, charLiteral};
   SortBy[versions, StringLength][[1]]
 ];

```

I hope I didn't miss anything, but this answer makes sure to escape backslashes, single quotation marks as well as trigraphs. There is some commented out code that uses octal or other escape sequences for non-printable characters, but I don't think that's actually necessary, because C should be able to deal with any bytes in character literals, afaik (please correct me if I'm wrong).

As with the other submission, test this with

```
input = StringSplit[Import["path/to/benchmark.txt"]];
numbers = ToExpression /@ input;
output = mathpack /@ numbers;
N[StringLength[output <> ""]/StringLength[input <> ""]]

```

# Answer
> 3 votes
# Code: Mathematica, Output: Julia, ~98.9457% (20177/20392 bytes)

```
optimise[n_] :=
  Module[{bits, trimmedBits, shift, unshifted, nString, versions,
    inverted, factorised, digits, trimmedDigits, exponent, base,
    xored, ored, anded},
   nString = ToString@n;
   versions = {nString};

   (* Try bitshifting *)
   bits = IntegerDigits[n, 2];
   trimmedBits = bits /. {x___, 1, 0 ..} :> {x, 1};
   shift = ToString[Length[bits] - Length[trimmedBits]];
   unshifted = ToString@FromDigits[trimmedBits, 2];
   AppendTo[versions, unshifted <> "<<" <> shift];

   (* Try inverting *)
   inverted = ToString@FromDigits[1 - PadLeft[bits, 32], 2];
   AppendTo[versions, "~" <> inverted];

   (* Try invert/shift/invert *)
   trimmedBits = bits /. {x___, 0, 1 ..} :> {x, 1};
   shift = ToString[Length[bits] - Length[trimmedBits]];
   unshifted = ToString@FromDigits[trimmedBits, 2];
   AppendTo[versions, "~(~" <> unshifted <> "<<" <> shift <> ")"];

   (* Try factoring *)
   factorised = Riffle[
      FactorInteger[n]
        /. {a_, 1} :> ToString@a
       /. {a_Integer, b_Integer} :> ToString[a] <> "^" <> ToString[b]
      , "+"] <> "";
   AppendTo[versions, factorised];

   (* Try scientific notation *)
   digits = IntegerDigits[n, 10];
   trimmedDigits = digits /. {x___, d_ /; d > 0, 0 ..} :> {x, d};
   exponent = ToString[Length[digits] - Length[trimmedDigits]];
   base = ToString@FromDigits[trimmedDigits, 10];
   AppendTo[versions, base <> "e" <> exponent];

   (* Don't try hexadecimal notation. It's never shorter for 32-bit uints. *)
   (* Don't try base-36 or base-62, because parsing those requires 12 characters for
      parseint("...") *)

   SortBy[versions, StringLength][[1]]
  ];

mathpack[n_] :=
 Module[{versions, increments},
  increments = Range@9;
  versions = Join[
    optimise[#2] <> "+" <> ToString@# & @@@ ({#, n - #} &) /@
      Reverse@increments,
    {optimise@n},
    optimise[#2] <> "-" <> ToString@# & @@@ ({#, n + #} &) /@
      increments,
    optimise[#2] <> "*" <> ToString@# & @@@
      Cases[({#, n / #} &) /@ increments, {_, _Integer}],
    optimise[#2] <> "/" <> ToString@# & @@@ ({#, n * #} &) /@
      increments
    ];
  SortBy[versions, StringLength][[1]]
 ];

```

The function takes a *number* and returns the shortest *string* it finds. Currently it applies four simple optimisations (I might add more tomorrow).

You can apply it to the entire file (to measure its score) as follows:

```
input = StringSplit[Import["path/to/benchmark.txt"]];
numbers = ToExpression /@ input;
output = mathpack /@ numbers;
N[StringLength[output <> ""]/StringLength[input <> ""]]

```

Note that some of these optimisations assume that you're on a 64-bit Julia, such that integer literals give you an `int64` by default. Otherwise, you'll be overflowing anyway for integers greater than 231. Using that assumption we can apply a few optimisations whose intermediate steps are actually even larger than 232.

**EDIT:** I added the optimisation suggested in the OP's examples to bitwise *xor* two large numbers in scientific notation (actually, for all of *xor*, *or* and *and*). Note that extending the `xormap`, `ormap` and `andmap` to include operands beyond 232 might help finding additional optimisations, but it doesn't work for the given test cases and only increases run time by something like a factor of 10.

**EDIT:** I shaved off another 16 bytes, by checking all `n-9, n-8, ..., n+8, n+9` for whether any of *those* can be shortened, in which case I represented the number based on that, adding or subtracting the difference. There are a few cases, where one of those 18 numbers can be represented with 3 or more characters less than `n` itself, in which case I can make some extra savings. It takes about 30 seconds now to run it on all test cases, but of course, if someone actually "used" this function, he'd only run it on a single number, so it's still well under a second.

**EDIT:** Another incredible 4 bytes by doing the same for multiplication and division. 50 seconds now (the divided ones don't take as long, because I'm only checking these if the number is actually divisible by the factor of interest).

**EDIT:** Another optimisation that doesn't actually help with the given test set. This one could save a byte for things like 230 or 231. If we had uint64s instead, there'd be a lot of numbers where this could be a huge saving (basically, whenever the bit representation ends in a lot of 1s).

**EDIT:** Removed the *xor*, *or*, *and* optimisations altogether. I just noticed they don't even work in Julia, because (quite obviously) scientific notation gives you a float where bit-wise operators are not even defined. Interestingly, one or more of the newer optimisations seem to catch all of the cases that were shortened by these optimisations, because the score didn't change at all.

# Answer
> 1 votes
# J to C (untested, but works in most cases, kind of a baseline answer.)

```
    f=:(,~ (($&0) @: (8&-) @: (8&|) @: #)) @: #:
    g=:($~ ((,&8) @: (%&8) @: #))@:f
    toCString=:({&a.)@:#.@:g
    toCString 6382179
abc

```

Outputs an string literal that, if entered in C, represents the number (as mentioned in the OP). This is not a serious submission, but rather something to strengthen my J skills, that I thought I'd share.

Alternative one-liner:

```
toCString=:({&a.) @: #. @: ($~ ((,&8) @: (%&8) @: #))@: (,~ (($&0) @: (8&-) @: (8&|) @: #)) @: #:

```

What J tries to make of this when you input it:

```
{&a.@:#.@:($~ ,&8@:(%&8)@:#)@:(,~ $&0@:(8&-)@:(8&|)@:#)@:#:

```

Thanks a bunch, J. Also, for those in 'the know' about J, visio rocks for creating more complex functions:

---
Tags: code-challenge
---