text:
Define a function f such that f(f(n)) = -n for all non-zero integers n

This challenge was inspired by a programming blog I frequent. Please see the original post here: A Programming Puzzle

Challenge
Define a function \$f:\mathbb{Q}\to\mathbb{Q}\$ such that \$f(f(n)) = -n\$ for all non-zero integers \$n\$, and where \$\mathbb{Q}\$ is the set of rational numbers.
Details
In whatever language you prefer, please define one function or program \$f\$ that accepts as parameter one number \$n\$ and returns or outputs one number \$f(n)\$.
Input may be provided through whichever mechanism is most natural for your language: function argument, read from STDIN, command-line argument, stack position, voice input, gang signs, etc.
Output should be a return value from a function/program or printed to STDOUT.
I would like to restrict answers to functions that do not take advantage of program state or global memory/data that is visible from outside of the function \$f\$. For example, keeping a counter outside of \$f\$ that counts how many times \$f\$ was called and just doing a negation based on this count isn't very challenging or interesting for anyone. The decisions \$f\$ makes should rely only on data within \$f\$'s lexical scope.
However, this restriction is probably inappropriate for some stack-oriented languages or other types of languages that do not distinguish these types of data or scopes. Please use your best judgement to keep with the spirit of this challenge.

Scoring
Standard code golf rules apply - your score is the number of bytes in your source code.
The minimal answer requires the domain and codomain of \$f\$ to be a subset of the rationals \$\mathbb{Q}\$. If you restrict your domain and codomain of \$f\$ to the integers \$\mathbb{Z}\$, then your score is the ceiling of 90% of the number of bytes in your source code.
Tiebreak
In the event of a tie, the following will be used in order:

Fewest number of printable non-whitespace symbols in your source code
Earliest date and time of answer submission

You are not required to support arbitrarily sized numbers. Please interpret the sets \$\mathbb{Z}\$ and \$\mathbb{Q}\$ as datatypes in your chosen language (typically integer and floating point, respectively).
If your solution relies entirely on the underlying structure or bit pattern of a data type, please describe its limitations and how it is being used.

f(n) = i*n -- pure math :P

@JohannesKuhn this is why the domain and codomain are restricted to the rationals

Could you explain what f:Q->Q means?

@beary605 it means f is a function mapping members of Q (rational numbers) to other members (possibly the same) of Q. see http://en.wikipedia.org/wiki/Function_(mathematics)#Notation

What should f[6] return?: (a)  6; (b) f[6]; (c) something else?  What should f[3/4] return?: (a)  3/4; (b) f[3/4]?

@DavidCarraher that is dependent on your solution. the value of f(n) is not required to be anything other than a rational number. but the value of f(f(6)) should be -6. for your other question, 3/4 is not an integer, so it will never be input to f(f(n)).

I knew I'd seen this recently, but it took a while to remember where. A less tightly specified version on StackOverflow was recently closed. Over 100 answers.

Followup comment: you talk about "integers" and "Z": does this restrict the problem to languages with arbitrarily large integers?

@PeterTaylor oops, definitely not. i will relax that requirement

@ardnew You say: 3/4 will never be input to f[f[n]].  But 3/4 is in f's domain so it must correspond to something in the codomain (that includes 3/4 itself). It follows that f[f[3/4]] should be in the codomain of rationals.

In that case you'll also need to take into account that for languages which use twos complement, the minimum value of signed fixed width integer types is a fixpoint under negation due to overflow.

@DavidCarraher i agree 3/4 is in f's domain, and f(n) should be defined for all rational n. however, the challenge is to handle integer input values a certain way. you can do whatever you want with non-integer input.

@DavidCarraher for example, if f(f(3/4)) evaluates to 438943, and f(f(n)) evaluates to -n for all integer n, then f is correct. if f(f(3/4)) evaluates to 438943 and f(f(n)) does not evaluate to -n for all integer n, then f is not correct. does this help clarify?

Floating point numbers and Q are certainly not the same thing.

@ypercube right, and not all floating point implementations are the same thing either. in any case, i should have laid off the overly complicated specs

So just to clarify, the function needs to be able to handle any rational number (with certain size restrictions for languages without arbitrary size numbers), but only needs to satisfy the property for integers?

lambda n:n*1j almost works for python, but on the second run the output is of the form (-n+0j) which is numerically the same, but represented differently, so I'm not sure if it counts. EDIT: oops, domain restricted to rationals anyways

@HyperNeutrino it doesn't need to be able to handle any rational number -- that was a little misleading on my part. the intent was to prevent complex numbers while also allowing more than just the integers. it should, in principle, work for every integer though

Okay. Thanks for clarifying. So essentially, the domain of the function needs to be a subset or be equal to Q?

J, 9 points (10 chars)
Based on stackoverflow answer:
   (*-[*_1&^)

First idea (13 chars):
   ((-*)-2&|*+:)

   ((-*)-2&|*+:) _10 _9 _8 _7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8 9 10
_9 10 _7 8 _5 6 _3 4 _1 2 0 _2 1 _4 3 _6 5 _8 7 _10 9

   ((-*)-2&|*+:) _9 10 _7 8 _5 6 _3 4 _1 2 0 _2 1 _4 3 _6 5 _8 7 _10 9
10 9 8 7 6 5 4 3 2 1 0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _10

This works for integer input, but this produces imaginary output for floating point values (the function must produce rational output for rational input according to the spec)

@Volatility, the spec is confusing worded, but as I read it it allows restricting domain and codomain to integers.

Do you need the parentheses?

Python: 61 34 30 29 27 points
f: Q -> Q
in math:
       | 0.5-x   if x is in Q \ Z
f(x) = |
       | x+0.5   if x is in Z

in Python:
f=lambda x:.5+[x,-x][x%1>0]

tested with
filter(lambda n: n[0] != -n[1], map(lambda n:(n,f(f(n))),range(0,50)))

logic behind this:
When you take an integer n and put it into f you will get x+0.5. This is not an integer any more, so the next application will be 0.5-(x+0.5) which is -x.
Credits
Thanks to

Bakuriu for striping it down from 61 characters to 34 characters.
Volatility for further reducing code size to 30 characters.
copy for reducing code size to 29 characters (and fixing a potential floating point problem).
aditsu for mentioning an inconsistency that came with the changes above.

Notes
First I thought this would be ok
f = lambda n: 1j*n

but its f:N->C and that is not allowed :-/

Can be stripped down to: f=lambda x:x%1>0and(-x+x%1)or x+.1 which is only 34 characters long.

f=lambda x:[x+.1,x%1-x](x%1>0) is only 30

Oops, should be f=lambda x:[x+.1,x%1-x][x%1>0]

One char shorter: f=lambda x:[x+.5,.5-x][x%1>0]. Note the use of .5 instead of .1 to get around precision issues

I don't think this solution is correct: f(f(1.48))->f(-1)->-0.9

@AJMansfield 1.48 is not an integer.

But, according to the problem, f:Q->Q, meaning it must work with a floating argument.

No, that doesn't mean it. If he ment that, he should have written "all rational numbers". f:Q->Q does only mean that f maps rational number to rational numbers. Which my definition of f does.

The math part doesn't match the python part. It's 0.5-x not -floor(x).

@aditsu: Thanks. I've corrected it.

Does this work? f=lambda x:.5+x-2*x*(x%1>0)

Or even just f=lambda x:.5+[x,-x][x%1>0]

Even better: f=lambda x:.5+x-x%1*x*4

C, 41 points (41 or 45 chars)
Works using both 32- and 64-bit.
f : Z -> Z (except INT_MAX):
f(n){return (abs(n)%2*2-1)*n+n?(-n<n)*2-1:0;}

If we don't have to include 0 we can shave off some chars (41 chars):
f : Z -> Z (except 0 & INT_MAX):
f(n){return (abs(n)%2*2-1)*n+(-n<n)*2-1;}

This function works by dividing all integers into 4 groups based on their sign and parity.
So we have the 4 different combinations:
+ even, + odd, - even, - odd

As we need to switch the sign of the number, but not the parity after two passes, we get two different possible sequences:
  + even -> - odd -> - even -> + odd -\
^-------------------------------------/

  + even -> + odd -> - even -> - odd -\
^-------------------------------------/

In this example I have chosen the first one.
First we need to map all even positive integers to odd negative integers. We do this by changing the sign and incrementing the number (you could also choose to decrement the number instead):
f1(n) = -n + 1

We then need to map all odd negative integers to even negative integers. We need to make sure that f2(f1(n)) = -n:
f2(f1(n)) = -n
f2(-n + 1) = -n
f2(-n) = -n - 1
f2(n) = n - 1

Using the same methods we find f3 and f4:
f3(n) = -n - 1
f4(n) =  n + 1

To combine these functions into one single function, we observe that every time n is even we switch the sign of n and every time n is positive we increment by one and otherwise we decrement by one:
f1(n) = -n + 1 (+ even)
f2(n) =  n - 1 (- odd)
f2(n) = -n - 1 (- even)
f4(n) =  n + 1 (+ odd)

This can thus be rewritten as:
f(n) = odd(n) * n + sign(n)

where odd(n) returns 1 for odd numbers and -1 for even numbers.
There are 4 solutions total:
f(n) = odd(n) * n + sign(n)  (edge cases: f(f(0))  -> -2, f(f(INT_MAX))   -> -8)
f(n) = even(n) * n - sign(n) (edge cases: f(f(0))  -> -2, f(f(INT_MIN+1)) -> -6)
f(n) = odd(n) * n - sign(n)  (edge cases: f(f(1))  -> -3, f(f(INT_MIN))   -> -5)
f(n) = even(n) * n + sign(n) (edge cases: f(f(-1)) -> -1, f(f(INT_MIN))   -> -5)

INT_MIN might always be considered an edge case in all 4 functions as -INT_MIN == INT_MIN => f(f(INT_MIN)) = INT_MIN.

This is essentially the same as my GolfScript answer (except explained better). Does this work for 0?

@BenReich As stated in the answer it doesn't work for 0 and 3 other numbers.

@Tylio I see now.  Makes sense.  It seems like you should only take the Z bonus if you cover 0, at least.

@BenReich Removed the bonus until I get it fixed.

Here's my go at it.
long f(int i){return i;}
int f(long i){return -i;}

Live example:
int main()
{
  for(int i=-10; i<10; i=i+3)
    std::cout << f(f(i)) << "\n";
}

The input types cn be arbitrarily tailored to suit your needs. This version works for integer literals that are smaller in magnitude than 2^32-1.

The problem said f:Q->Q, not f:Z->Z.

@AJMansfield the scoring section of the spec was meant to offer bonus points for functions defined f:Z->Z, sorry for the confusing wording

the problem with this answer is it appears to define two separate functions, while the spec requires you only define one. but i don't mean to start a semantics debate, it's still a very thoughtful solution

@ardnew, oh you're right. I was pointed to this valid objection only seconds before sharing it with the Lounge<C++> on SO chat. I do wonder what the compiler makes of this (if it doesn't inline the calls), but my assembly sucks.

are 2 functions different the name is different for the machine and for me

I think you can remove the space in return -i

JavaScript, 18
f=n=>n%1?.5-n:n+.5

Using the new fat arrow notation (Firefox 22).
Other version (18):
f=n=>n%1?-.5/n:.5/n

Previous version (20):
f=n=>n-~~n?.5-n:n+.5

Example:
> [-3,-2,-1,1,2,3].map(f).map(f)
[3, 2, 1, -1, -2, -3]

Looks like JavaScript is evolving into CoffeeScript.

Mathematica 18
f=#+1/2-4#(#-⌊#⌋)&

Here ⌊...⌋ is the floor function. It uses only rational numbers (not lists, complex numbers, etc)
f[10]
f[f[10]]

21/2
-10

f[-5]
f[f[-5]]

-9/2
5

x86 assembly language (FASM). The argument and the result are in eax register.
It works properly for -2^30 < N < +2^30-1
16 bytes executable code.
        use32

f_n:
        lea     edx, [2*eax]
        xor     edx, eax
        btc     eax, 30
        shl     edx, 1
        jnc     .end
        neg     eax
.end:
        retn

Nitpicking your numbers; 2E30 would be 2 * 10^30, not 2^30 as I think you want.

@NickT My mistake. Fixed.

I'm pretty sure you are supposed to count the bytes in the source code.

Common Lisp: 35 bytes
(defun f(x)(/(if(> 1 x)-1/2 1/2)x))

Scheme (and Racket): 36 bytes
(define(f x)(/(if(> 1 x)-1/2 1/2)x))

Ungolfed with comments and explanation:
(define (f x)
  (/             ;; divide
     (if (> 1 x) ;; if x is below 1
         -1/2    ;; then -1/2 (the fraction)
         1/2)    ;; else 1/2 (the fraction)
      x))        ;; gets divided with x

For any number x in [1,->] the if will turn into the fraction 1/2 which is a real exact number in both languages.
The divide part will then become (/ 1/2 x) so the fraction will become 1/(x*2) which always is below 1. For 1 it will be 1/2, for 2 it's 1/4, etc.
For any number below 1 the if will turn in to the fraction -1/2, which makes the function do (/ -1/2 x) which is -1/(2*x) but since we can expect the value to be result of the previous run we can substitute x for 1/(x*2) making a double application -1/((1/(x*2))*2) = -x
E.g. since 1 turns into 1/2 the second application is (/ -1/2 1/2) ==> -1

How does this work?

@AJMansfield added some info. Just ask if there is anything unclear. Reading LISP syntax is like greek if you haven't learned it and it takes some weeks to get used to.

C, 60 (⌈66 * .9⌉)
int f(int x){if(!x&1||!~x)return ~x;if(x<0)return x-1;return x+1;}

Here is an uncondensed version:
int f(int x){
    if(!x&1 || !~x) return ~x;
    if(x<0) return x-1;
    return x+1;
}

This method works using only integers, so it gets the 90% score bonus. I was originally writing it in java, but realized that this program in particular could benefit from C-style logical operators.
As there is no integer corresponding to -INT_MIN, f(f(INT_MIN)) returns INT_MIN instead.
The underlying mapping is algebraically rather simple. Executing the statement x=f(x) replaces x with:

x+1, if x is positive and odd
-x+1, if x is positive and even
x-1, if x is negative and odd
-x-1, if x is negative and even

The result of each case will fall under the next case the next time the function is applied to x.
As you can see, composing a case with the case following it yields -x.
The code is a result of some clever simplification of the function to take advantage of the bit structure of two's compliment integers.

><>, 21 + 3 = 24 bytes, 22 points
:0)$:0($:1$2%2*-*+-n;

Use the official Python interpreter, and use the -v command line option to enter input, at a cost of 3 bytes.
I have a feeling that this could be better--I'll keep looking at it and try to golf it down.
Given input n, the program outputs
(n>0) - ((n<0) + n * (1 - 2*(n%2)))

where (n>0) and (n<0) are booleans.  This is equivalent to Gelatin's Python answer
(n>0) - (n<0) - n * (-1)**n

but ><> doesn't have a built-in exponentiation operator so we use (1 - 2*(n%2)) in place of (-1)**n.
What follows is mathematical theory -- read if (and only if) you are interested:
Given any function f: Z -> Z such that f(f(n)) = -n for all n in Z, we see immediately that f(f(f(f(n)))) = n, or in other words, f^4 is the identity function.  In particular, f is invertible, and its inverse function is f^3.  Thus f is a permutation of Z, and since f^4 = Id, it follows that every orbit (or cycle) of f has size either 1, 2, or 4.
Next, we see that f(0) = 0.  Proof: f(0) = f(-0) = f(f(f(0))) = -f(0), so f(0) = 0, as desired.  Conversely, suppose x is in a cycle of length 1 or 2, so f(f(x)) = x.  Then -x = x so x = 0.
Thus f is made up entirely of 4-cycles, except for the fixed point (1-cycle) at 0.
Further, every 4-cycle must have the form (x, y, -x, -y), and by rotating the cycle around we may assume that x and y are both positive.  Conversely, every such product of 4-cycles partitioning the nonzero integers determines a choice of f.
Thus each choice of f corresponds uniquely to a directed graph whose vertices are the positive integers, such that every vertex is incident to exactly one arrow, either entering or exiting.  More precisely, in the underlying undirected graph, every vertex has degree exactly 1.  (Each 4-cycle (x y -x -y) with x and y positive corresponds to the arrow x --> y.)
The function in this answer (and several other answers here) corresponds to the graph where 1 --> 2, 3 --> 4, and in general 2k-1 --> 2k.
Such graphs are in bijection with infinite sequences of ordered pairs (a_n, p_n), where each a_n is a positive integer and each p_n is either 0 or 1: given a sequence (a_1, p_1), (a_2, p_2), (a_3, p_3), ..., we first pair 1 with 1 + a_1, and then we form either the arrow 1 --> 1 + a_1 or the arrow 1 + a_1 --> 1 depending on whether p_1 is 0 or 1.  Essentially, the arrow is either a < sign or a > sign, depending on the parity of p_1.
Next, take the smallest unpaired positive integer k, and count up from k, exactly a_2 steps, SKIPPING any number that is already paired with something.  Pair k with the result, and set the direction of the arrow depending on p_2 as above.  Then repeat with (a_3, p_3), etc.
Each arrow will eventually be determined this way, so the process is well defined.  The function in this answer corresponds to the sequence (1,0), (1,0), (1,0), ..., since at step n the smallest unpaired integer is 2n-1 and no integers larger than 2n-1 have been paired with anything, so we get 2n-1 --> 2n for each n (arrows are oriented this way because each p_n equals 0).
The cardinality of this set is (N*2)^N = N^N, which by the last paragraph of this answer equals 2^N, the cardinality of the real numbers.

Command line options are usually a byte each.

@cat See the "Special invocations" section at this meta post.

Java, just for fun
Here's an implementation that does an actual bijection between ℤ and ℤ², which is an odd function at the same time (g(-x) == -g(x)). It treats the corresponding ℤ² element as a complex number and multiplies it by "i", then converts back to ℤ.
f(x)=g⁻¹(ig(x))
f(f(x))=g⁻¹(-g(x))=-x
The function runs in O(1).
public class Ffn {
    public static int f(int n) {
        if (n == 0) {
            return 0;
        }
        // adjust sign
        int s = n > 0 ? 1 : -1;
        int m = n * s;
        // calculate square "radius"
        int r = (int) (Math.sqrt(2 * m - 1) + 1) / 2;
        int q = r * 2;
        // starting point
        int x = r, y = r;
        int k = q * (r - 1) + 1;

        if (m - k < q) {
            // go left
            x -= m - k;
        }
        else {
            // go left
            x -= q;
            // go down
            y -= m - k - q;
        }

        // multiply by i
        int x2 = -y * s, y2 = x * s;
        // adjust sign
        s = y2 < x2 || y2 == x2 && x2 < 0 ? -1 : 1;
        x2 *= s;
        y2 *= s;

        if (y2 == r) {
            // go left
            k += r - x2;
        }
        else {
            // go left and down
            k += q + r - y2;
        }
        return k * s;
    }

    public static void main(final String... args) {
        for (int i = 0; i < 1000000; ++i) {
            if (f(f(i)) != -i || f(f(-i)) != i) {
                System.out.println(i);
            }
        }
    }
}

P.S. Happy New Year!

I believe the whitespace is unnecessary.

To fix the earlier J answer (I don't have enough reputation to comment on the original):
(*+[*1-~2*2|])

It just replaces the _1&^ with 1-~2*2|], which gives the opposite sign. So I changed the - to a + (which only matters on input of 1 and _1).
Here are the tests:
   (*+[*1-~2*2|])6 3 _9 _8 1r2 _4.6 0 1 _1
7 _2 8 _9 1 7.28 0 2 _2
   (*+[*1-~2*2|])7 _2 8 _9 1 7.28 0 2 _2
_6 _3 9 8 0 _10.3568 0 _1 1

   NB. f^:2 = f@:f
   (*+[*1-~2*2|])^:(2)6 3 _9 _8 1r2 _4.6 0 1 _1
_6 _3 9 8 2 _5.0832 0 _1 1

As you can see, the domain and range are of all real numbers, but it only works for integers (including 0).
Explanation:
(   *     + [ *  1-~    2*     2|]    )
 signum n + n * pred (twice (n mod 2))

GolfScript ceiling(26*.9)=24
Golfscript only handles integers, so apply the Z bonus for a total of 24 points:
.{..0>2*(\)2%!2*(@*+}{ }if

The special case of 0 accounts for 8 characters.  Ignoring 0, we can have a 17 point answer:
..0>2*(\)2%!2*(@*+

This code does the following to an integer x on top of the stack:

If x is 0, leave 0 on the stack and apply no more rules.
If x is even, negate x.
If x is positive, add 1.
If x is negative, subtract 1.

This logically connects sets of 4 numbers in a cycle, where f traverses elements of the cycle, and opposite corners of the cycle are negatives of each other.  Every integer is part of exactly 1 such cycle, except 0 which is special cased.  For example, for {-8, -7, 7, 8}:

7 f -> 8
8 f -> -7
-7 f -> -8
-8 f -> 7

The only relevant test cases I could think of were a negative odd, negative even, positive odd, positive even, 0, and then I threw in -1 and 1 since their proximity to 0 may have caused problems:
[-10 -5 -1 0 1 5 10]
{.{..0>2*(\)2%!2*(@*+}{ }if}:f;
{f f}%
-> [10,5,1,0,-1,-5,-10]

I'm sure the actual GolfScript can be improved somewhat.  It doesn't feel like it should take up 26 characters!  Would love to hear some suggestions.

Python 3 - 38
Similar to @moose's answer, but, f(n) == n. Works for all integer values.
f=lambda x:x*(isinstance(x,int)*2.0-1)

Perl, 33 (non-whitespace)
sub f{($=)=@_;$=-$_[0]?-$=:"$=.1"}

Edit:

$=.".1" shortened to "$=.1" (thanks ardnew).

Math:

Ungolfed:
# script.pl
sub f {
  ($=) = @_;   # short for $= = int($_[0]);
               # "int" is implicit in assignments to $=;
               # ($=) can be prepended by "local" to get
               # the function free of side effects.

  $= - $_[0] ? # short for $= != $_[0], check if input is integer
    -$=        # input is not an integer
  : $= . ".1"  # input is integer
}

# Testing
chomp;
$_ = sprintf "f(f($_)) = f(%s) = %s\n", f($_), f(f($_));

Examples:
perl -p script.pl
7
f(f(7)) = f(7.1) = -7
2
f(f(2)) = f(2.1) = -2
0
f(f(0)) = f(0.1) = 0
-1
f(f(-1)) = f(-1.1) = 1
-10
f(f(-10)) = f(-10.1) = 10
-1.23
f(f(-1.23)) = f(1) = 1.1
3.4
f(f(3.4)) = f(-3) = -3.1
1.0
f(f(1.0)) = f(1.1) = -1

robust solution- the floating point test cases you demo'd aren't required per spec (should have offered bonus points for that!). here's your same algorithm with a few cleanups coming in at 22 chars: sub f{yzxzzc?-$_:x.$_}

@ardnew: Thanks. But I disagree that your solution uses the same algorithm. The algorithm sub f{yzxzzc?-$_:x.$_} is not state free, it uses a state via the variable $_. Because of this, f is no longer a function (in the mathematical sense), because different values are possible for the same input value depending on the state (weather $_ contains a x or not). My algorithm does not use a state, The information is encoded in the output value. Integers are converted to real numbers by adding .1. And real numbers are converted back to integers with the sign switched.

interesting- no state data is used in your implementation because of the initial assignment and not because of some special property of $=?

i didn't realize i also failed my own requirement (that f be defined Q->Q) with that x char. also $=.".1" can be shortened to "$=.1"

@ardnew: The special property of $= is just that it only takes integer numbers. The same can be achieved by using an ordinary variable: $a=int$_[0]. But that costs three additional bytes because of function int.

Julia, 26
julia> f(n::Int)=n//1
f (generic function with 1 method)
julia> f(n)=int(-n)
f (generic function with 2 methods)
julia> f(f(4))
-4

Not super competitive, but very Julian since it relies on multiple dispatch. It just makes n a Rational if its an Int, or an int with a minus sign if it is anything else. One might object that this is 2 functions, but Julia considers this to be one function with two methods, and it is equivalent to defining one function with an if statment on the type of n.

It's not what a mathematician would call a function: in Julia 3==3//1 returns true but f(3//1)==f(3) returns false.

Dyalog APL, 9 points
×-⍨⊢×¯1*⊢

The source is 9 bytes long and qualifies for the bonus (which doesn't help at all). It also uses the formula from the top SO answer.

Candy, 20 18 bytes
Uses the 3 -> 4 -> -3 -> -4 -> 3 trick.
~A2%{|m}1A0>{+|-}.

To invoke it use the -i  switch on the interpreter
Example of double-invokation:
$ candy -i 7 -e '~A2%{|m}1A0>{+|-}.'
program length: 18
>>> 8
$ candy -i 8 -e '~A2%{|m}1A0>{+|-}.'
program length: 18
>>> -7
$ candy -i -7 -e '~A2%{|m}1A0>{+|-}.'
program length: 18
>>> -8
$ candy -i -8 -e '~A2%{|m}1A0>{+|-}.'
program length: 18
>>> 7

Long form:
peekA
pushA
digit2
mod          # even/odd
if
else
  negate     # negate even numbers
endif
digit1
pushA
digit0
greater      # positive/negative
if
  add        # add two numbers from stack (original stack value, and delta)
else
  sub        # diff two numbers from stack (original stack value, and delta)
endif
retSub

Updated with function supplied by Synthetica (obviously the one who should get credit for this now)
Language: Python
Number of characters: 41 including whitespace
f=lambda x:-float(x) if str(x)==x else`x`

Please provide also the name of the language that you used an provide also the character count.

I like how this also works with non-integers. Well done. :)

f=lambda x:-float(x) if str(x)==x else\x`` is quite a bit shorter: 41 including whitespace

Thanks Synthetica, I didn't even know about the backticks trick! :D

On integers f returns a string; the specification says it must return a rational number.

All that whitespace!

You don't need the f= part. Please also remove the extra whitespace.

35 bytes: lambda x:[<backtick>x<backtick>,-float(x)][str(x)==x]

Python: 32 bytes (29 points)
f: Z -> Z
f=lambda n:(n>0)-(n<0)-n*(-1)**n

Using Ben Reich's method.

In Python 2, you can replace (n>0)-(n<0) with cmp(n,0), to save a few bytes. (But not in Python 3: https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons )

GTB, 22
@S;N,"--$x?N)→N~N#~-N&

Java, 113 bytes
The approach is pretty simple. It ended up more bytes than I anticipated, but can perhaps be golfed down a bit.
public class F{public static int f(int x){if(x<0)x+=-2147483647-++x;x+=1073741824;return x<0?-2147483647-++x:x;}

It basically creates 4 different "areas" of x, utilizing the fact that Java happily lets variables wrap around. I had to do some tricky conversion for negative numbers which is the main reason this ended up bigger than anticipated.
Works for all x besides -2147483648.

Same sequence of numbers (3, 4, -3, -4, 3 ...) as the golfscript answer, but implemented in perl (42 chars after whitespace is stripped)
sub f{($_[0]%2?1:-1)*$_[0]+($_[0]<0?-1:1)}

More legibly:
sub f { ($_[0] % 2 ? $_[0] : -$_[0] ) + ( $_[0] < 0 ? -1 : 1 ) }

Or even more legibly:
sub f {
  my $n = shift;
  my $sign = $n >= 0 ? 1 : -1;
  # note that in perl $n % 2 is the same as int($n) % 2
  if( $n % 2 ) {
    # odd: add one to magnitude
    return $n + $sign
  } else {
    # even: subtract one from magnitude then invert
    return -($n - $sign)
  }
}

Output:
ski@anito:~/mysrc/.../acme$ echo 3 | perl -e 'sub f{($_[0]%2?1:-1)*$_[0] + ($_[0]<0?-1:1)}; my $x = <>; for(0..10) { print "$_: $x\n"; $x = f($x); }'
0: 3
1: 4
2: -3
3: -4
4: 3
5: 4
6: -3
7: -4
8: 3
9: 4
10: -3

The above also works for non-integers:
ski@anito:~/mysrc/.../acme$ echo 1.1234 | perl -e 'sub f{($_[0]%2?1:-1)*$_[0] + ($_[0]<0?-1:1)}; my $x = <>; for(0..4) { print "$_: $x\n"; $x = f($x); }'
0: 1.1234
1: 2.1234
2: -1.1234
3: -2.1234
4: 1.1234

Sed, 25 bytes.
|sed s/0+/0-/|sed s/^/0+/

Usage:

$ echo 1.23 |sed s/0+/0-/|sed s/^/0+/
0+1.23
$ echo 0+1.23 |sed s/0+/0-/|sed s/^/0+/
0+0-1.23

Matlab, 26 characters
f=@(n) (n<0)-(n<0)-n*(-1)^n

This is not a valid answer, as the domain and codomain of the function must not be complex.

oh, I'm sorry... I just read the title and wasn't that careful... Let's see if I can edit this somewhat

C++ - 63 55.8
This is how the code looks:
int f(int n){return (n&45056?n^45056:n|45056)*(n&45056?-1:1);}

It doesn't work on integers whose fourth byte is equal to 0xB as it uses that value to keep track of passes. Otherwise works on any member of Z, including zero.

can you explain this one? at first inspection it looks like you're keeping a counter of calls to f with a static variable. but then what's the point of the sqrt?

I seem to have misunderstood the question; thought that a static variable was okay since C++ is a stack-oriented language, but I'll fix the code. Otherwise I have no idea why I needed sqrt as it gets rounded down anyway with type casting. I'll refactor it so it works without the static variable.

I have no idea where you got the 55.8 from, but your current code is 62 bytes long. Edit: Never mind, I didn't read the question properly.

The restriction that the fourth byte cannot equal 0xB unfortunately makes this not a valid answer to the challenge, which requires it work on (at least) all integers.

Mouse-2002, 21 19 12 bytes
$A1%[1%_|1%]

Defines a function A; call it like #A,#A,?;; (which will wait for the user to enter any number). Alternatively, call it like #A,#A,n;; where n is any number.

Javascript ES6, 27 26 bytes
a=>a%1?-Math.floor(a):a+.2

Prolog, 36 bytes
Code:
X*Y:-X//1=:=X,Y is 0.5+X;Y is 0.5-X.

Explained:
Dyadic predicate which converts integers to floats and floats back to negated integers.

Example:
10*X.
X = 10.5

10*Y,Y*X.
X = -10,
Y = 10.5

Julia, 21
f(x)=(1-2(1>x>-1))/2x

Then
julia> f(f(12//1))
-12//1

p//q is julia's literal notation of rational numbers.

Forth, 37 bytes
: f 9 @ if negate 0 else 1 then 9 ! ;

Works at least in durexforth (it should at least, I couldn't type the whole line in because VICE was being stupid with my keybaord layout so I couldn't type the :). To run it in gforth you need to do variable 9 before, since it doesn't allow writing to arbitrary memory locations.
(Forth sadly doesn't work with floating point numbers.)

C, 80 bytes
#include <math.h>
double z(double x){return x==0.0?x:fabs(x)>0.5?0.5/x:-0.5/x;}

for to test
#include <stdio.h>
#define P printf
#define R return
main()
{double i, j;
 for(i=-20;i<20;i+=1)
       P("z(z(%f))=%f\n", i, z(z(i)) );
 for(i=-2;i<-1;i+=0.1)
       P("z(z(%f))=%f\n", i, z(z(i)) );
 for(i= 2;i<3;i+=0.1)
       P("z(z(%f))=%f\n", i, z(z(i)) );
 P("z(z(%f))=%f\n", 0.1245447, z(z(0.1245447)) );
 R 0;
}

results where you can see that this is for every number in double except 0
and 2 other
/*
z(z(-20.000000))=20.000000
z(z(-19.000000))=19.000000
z(z(-18.000000))=18.000000
z(z(-17.000000))=17.000000
z(z(-16.000000))=16.000000
z(z(-15.000000))=15.000000
z(z(-14.000000))=14.000000
z(z(-13.000000))=13.000000
z(z(-12.000000))=12.000000
z(z(-11.000000))=11.000000
z(z(-10.000000))=10.000000
z(z(-9.000000))=9.000000
z(z(-8.000000))=8.000000
z(z(-7.000000))=7.000000
z(z(-6.000000))=6.000000
z(z(-5.000000))=5.000000
z(z(-4.000000))=4.000000
z(z(-3.000000))=3.000000
z(z(-2.000000))=2.000000
z(z(-1.000000))=1.000000
z(z(0.000000))=0.000000
z(z(1.000000))=-1.000000
z(z(2.000000))=-2.000000
z(z(3.000000))=-3.000000
z(z(4.000000))=-4.000000
z(z(5.000000))=-5.000000
z(z(6.000000))=-6.000000
z(z(7.000000))=-7.000000
z(z(8.000000))=-8.000000
z(z(9.000000))=-9.000000
z(z(10.000000))=-10.000000
z(z(11.000000))=-11.000000
z(z(12.000000))=-12.000000
z(z(13.000000))=-13.000000
z(z(14.000000))=-14.000000
z(z(15.000000))=-15.000000
z(z(16.000000))=-16.000000
z(z(17.000000))=-17.000000
z(z(18.000000))=-18.000000
z(z(19.000000))=-19.000000
z(z(-2.000000))=2.000000
z(z(-1.900000))=1.900000
z(z(-1.800000))=1.800000
z(z(-1.700000))=1.700000
z(z(-1.600000))=1.600000
z(z(-1.500000))=1.500000
z(z(-1.400000))=1.400000
z(z(-1.300000))=1.300000
z(z(-1.200000))=1.200000
z(z(-1.100000))=1.100000
z(z(2.000000))=-2.000000
z(z(2.100000))=-2.100000
z(z(2.200000))=-2.200000
z(z(2.300000))=-2.300000
z(z(2.400000))=-2.400000
z(z(2.500000))=-2.500000
z(z(2.600000))=-2.600000
z(z(2.700000))=-2.700000
z(z(2.800000))=-2.800000
z(z(2.900000))=-2.900000
z(z(0.124545))=-0.124545
*/


text:
Reversible hex dump utility (aka `xxd`)
xxd is a utility, bundled with vim, that has been used to encode answers to code golf problems on this site. It converts a binary file into a hex dump and back again.
Implement the xxd and xxd -r commands in the programming language(s) of your choice. Scoring is based on the character/byte lengths of a) your program(s) and b) any command line argument(s) necessary to switch a combined program between modes (they need not be -r). As in golf, lower scores are better.

For two separate programs: forward code + reverse code
For a combined program: combined code + sum(forward arguments) + sum(reverse arguments) - 2

Specification of the chosen xxd subset
The forward command (e.g. xxd) accepts 0 ≤ n ≤ 216 bytes from standard input and generates ceil(n / 16) lines of standard output in the following format (all hex digits lowercase):

Offset of the first encoded byte (format string "%07x:"); ends in "0"
At most 16 hex-encoded bytes, grouped into pairs (format string " %02x" for even bytes, "%02x" for odd bytes) and right-padded with spaces to 42 characters
The encoded bytes interpreted as ASCII characters, values not between 0x20 and 0x7e ('\40' and '\176') inclusive becoming "."
A newline ("\n"; "\r\n" allowed when standard output is in binary mode)

Minimal ungolfed C implementation:
#include <stdio.h>
int main() {
    unsigned char L[16];
    int t = 0, n, i, s;

    for (; (n = fread(L, 1, 16, stdin)); t += n) {
        printf("%07x:", t);
        s = 42;
        for (i = 0; i < n; i++)
            s -= printf(i & 1 ? "%02x" : " %02x", L[i]);
        printf("%*s", s, "");
        for (i = 0; i < n; i++)
            putchar(L[i] > '\37' && L[i] < '\177' ? L[i] : '.');
        printf("\n");
    }

    return 0;
}

The reverse command (e.g. xxd -r) accepts any unmodified output of the forward command (given a valid input to that command) and produces that original input.
Example usage
$ xxd < /dev/null | wc -c
0
$ php -r 'echo join(range("\0",~"\0"));' | xxd
0000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f  ................
0000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f  ................
0000020: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f   !"#$%&'()*+,-./
0000030: 3031 3233 3435 3637 3839 3a3b 3c3d 3e3f  0123456789:;<=>?
0000040: 4041 4243 4445 4647 4849 4a4b 4c4d 4e4f  @ABCDEFGHIJKLMNO
0000050: 5051 5253 5455 5657 5859 5a5b 5c5d 5e5f  PQRSTUVWXYZ[\]^_
0000060: 6061 6263 6465 6667 6869 6a6b 6c6d 6e6f  `abcdefghijklmno
0000070: 7071 7273 7475 7677 7879 7a7b 7c7d 7e7f  pqrstuvwxyz{|}~.
0000080: 8081 8283 8485 8687 8889 8a8b 8c8d 8e8f  ................
0000090: 9091 9293 9495 9697 9899 9a9b 9c9d 9e9f  ................
00000a0: a0a1 a2a3 a4a5 a6a7 a8a9 aaab acad aeaf  ................
00000b0: b0b1 b2b3 b4b5 b6b7 b8b9 babb bcbd bebf  ................
00000c0: c0c1 c2c3 c4c5 c6c7 c8c9 cacb cccd cecf  ................
00000d0: d0d1 d2d3 d4d5 d6d7 d8d9 dadb dcdd dedf  ................
00000e0: e0e1 e2e3 e4e5 e6e7 e8e9 eaeb eced eeef  ................
00000f0: f0f1 f2f3 f4f5 f6f7 f8f9 fafb fcfd feff  ................
$ xxd <<< 'The quick brown fox jumps over the lazy dog.'
0000000: 5468 6520 7175 6963 6b20 6272 6f77 6e20  The quick brown
0000010: 666f 7820 6a75 6d70 7320 6f76 6572 2074  fox jumps over t
0000020: 6865 206c 617a 7920 646f 672e 0a         he lazy dog..
$ xxd <<< 'The quick brown fox jumps over the lazy dog.' | xxd -r
The quick brown fox jumps over the lazy dog.

Should the reverse mode ignore incorrect ASCII characters? (FWIW the actual xxd does, which is quite useful).

@PeterTaylor: The reverse mode only has to work properly with unmodified hex dumps (start at 0000000, lowercase hex digits, 16 bytes on all lines but the last, no gaps, etc.), and input validation is not required. That said, it probably makes sense to ignore the 16-character "ASCII" column on the right, because it cannot be used to distinguish "." and non-printable characters.

Perl, 122 + 54 = 176 122 + 45 = 167
The forward script:
$/=$,;for(<>=~/.{1,16}/gs){$h="";$h.=sprintf"%*s%02x",++$m%2,"",ord for/./gs;
s/[^ -~]/./g;printf"%06x0:%-42s",$n++,$h;say}

And the reverse script:
/:(.+?)  /,print map{chr hex}$1=~/\w\w/gfor<>

(This one is interesting; there are all kinds of obscure bugs that can show up in the reverse script depending on the input, if you're not careful.)

Since $1 is known only to contain hex digits and spaces, can you not use /\w\w/ instead of /[0-9a-f]{2}/?

$1 contains many things besides hex digits and spaces.

In the example, I only see hex digits and spaces between the :  and the   .

(Anyone know how to generate two monospace spaces in comment markdown?)

@Neil Never mind, I misread my own code. I don't recall now why I didn't just use /\w\w/. It seems so obvious that I feel like I must have had a reason, but I can't see one. My best guess is that it was a holdover from a version that was trying to avoid requiring the initial regex.

Fair enough, that would have made sense.

Javascript, 247 + 61 = 308 225 + 63 = 288
-20 or so thanks to ASCII-only
Forward:
b=>[...Array(b.length+15>>4)].map((_,i)=>(P=j=>i=>i.toString(x=16).padStart(j,0))(7)(i)+"0: "+(p=b.splice(0,x)).map(P(2)).join``.replace(/.{4}/g,"$& ").padEnd(42)+p.map(l=>String.fromCharCode(l>31&l<127?l:46)).join``).join`
`

Try it online!
Reverse:
d=>d.match(/[^:]{40}/g).join``.match(/\S\S/g).map(t=>+("0x"+t))

Try it online!
Might make an explanation at some point.

253
JavaScript (V8), 200 bytes
b=>{for(i=0,P=j=>i=>i.toString(16).padStart(j,0);t=b.slice(i,i+16),t+t;i+=16)print(P(7)(i)+': '+t.map(P(2)).join``.replace(/.{4}/g,"$& ").padEnd(42)+String.fromCharCode(...t.map(c=>c<32|c>126?46:c)))}

Try it online!
JavaScript (V8), 57 53 bytes
d=>d.match(/(?<=:.*)\w\w(?=.{19})/g).map(t=>"0x"+t-0)

Try it online!
optimized from Redwolf Programs's answer

C (clang), 222 + 108 = 330 189 + 105 = 294 186 + 104 = 290 bytes
Forward (-36 thanks to @ceilingcat):
#define P printf(
t,n,s;main(i){for(char z[16];n=read(i=0,z,16);t+=n){P"%07x:",t);for(s=42;i<n;)s-=P" %02x"+i%2,z[i++]);for(i=!P"%*s",s,"");i<n;i++)P"%c",isprint(z[i])?z[i]:46);P"\n");}}

Try it online!
Reverse (-4 thanks to @ceilingcat):
b;main(a){for(char z[80];gets(z);)for(a=9;z[a]-32;a+=5)b=strtol(z+a,0,16),b=b>>8?ntohs(b):b,printf(&b);}

Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Fourth of July Edition: Print lines of a file containing multiples of a specific number
Create a program which takes one command-line argument, n, which will be an integer less than 2147483648 (2^31), and then reads a file input.txt and prints the lines of input.txt which contain any substring which is a positive (non-zero) multiple of n. You may choose to ignore multiples greater than 2147483647.
Test case
If input.txt contains
1. Delaware Dec. 7, 1787
2. Pennsylvania Dec. 12, 1787   1682
3. New Jersey   Dec. 18, 1787   1660
4. Georgia  Jan. 2, 1788    1733
5. Connecticut  Jan. 9, 1788    1634
6. Massachusetts    Feb. 6, 1788    1620
7. Maryland Apr. 28, 1788   1634
8. South Carolina   May 23, 1788    1670
9. New Hampshire    June 21, 1788   1623
10. Virginia    June 25, 1788   1607
11. New York    July 26, 1788   1614
12. North Carolina  Nov. 21, 1789   1660
13. Rhode Island    May 29, 1790    1636
14. Vermont Mar. 4, 1791    1724
15. Kentucky    June 1, 1792    1774
16. Tennessee   June 1, 1796    1769
17. Ohio    Mar. 1, 1803    1788
18. Louisiana   Apr. 30, 1812   1699
19. Indiana Dec. 11, 1816   1733
20. Mississippi Dec. 10, 1817   1699
21. Illinois    Dec. 3, 1818    1720
22. Alabama Dec. 14, 1819   1702
23. Maine   Mar. 15, 1820   1624
24. Missouri    Aug. 10, 1821   1735
25. Arkansas    June 15, 1836   1686
26. Michigan    Jan. 26, 1837   1668
27. Florida Mar. 3, 1845    1565
28. Texas   Dec. 29, 1845   1682
29. Iowa    Dec. 28, 1846   1788
30. Wisconsin   May 29, 1848    1766
31. California  Sept. 9, 1850   1769
32. Minnesota   May 11, 1858    1805
33. Oregon  Feb. 14, 1859   1811
34. Kansas  Jan. 29, 1861   1727
35. West Virginia   June 20, 1863   1727
36. Nevada  Oct. 31, 1864   1849
37. Nebraska    Mar. 1, 1867    1823
38. Colorado    Aug. 1, 1876    1858
39. North Dakota    Nov. 2, 1889    1812
40. South Dakota    Nov. 2, 1889    1859
41. Montana Nov. 8, 1889    1809
42. Washington  Nov. 11, 1889   1811
43. Idaho   July 3, 1890    1842
44. Wyoming July 10, 1890   1834
45. Utah    Jan. 4, 1896    1847
46. Oklahoma    Nov. 16, 1907   1889
47. New Mexico  Jan. 6, 1912    1610
48. Arizona Feb. 14, 1912   1776
49. Alaska  Jan. 3, 1959    1784
50. Hawaii  Aug. 21, 1959   1820

then find_multiples 4 will print the entire file, and find_multiples 40 will print
10. Virginia    June 25, 1788   1607
17. Ohio    Mar. 1, 1803    1788
21. Illinois    Dec. 3, 1818    1720
32. Minnesota   May 11, 1858    1805
40. South Dakota    Nov. 2, 1889    1859
41. Montana Nov. 8, 1889    1809

Are you sure you mean 32 bytes and not 32 bits? 2. What multiple of 4 is present in the line 33. Oregon  Feb. 14, 1859   1811? Is it the 4 in 14, implying that the match is against any substring rather than any string of digits delimited by non-digits or end of line?

yes the 4 in 4 counts as a 4 because it is a substring.

Also, is this code golf or does it have some other winning criterion?

just code golf... sorry just learning here!

Perl, 67 chars
open F,"input.txt";print grep/(\d+)(?(?{!$^N+$^N%$ARGV[0]})(*F))/,<F>

Please note that the given character count is taking advantage of one of Perl's more horrific features, namely that a special variable of the form $^X can be written in two characters instead of three, by replacing the ^X with a literal ctrl-X character.
And, of course, this solution wouldn't be possible without a couple of Perl's arguably-equally-terrifying regex extensions that allows one to embed actual code inside of a regex pattern. (But at least those features are clearly documented as being potentially scary.)
[EDITED to fix bug in argument-handling due to not reading the description carefully enough.]

As I can see the solution doesn't read from file input.txt.

Hm. As I read it, the problem description states that the program takes two arguments, the name of the input file and the number to search for multiples of. I see now that this is modified at the very end of the description. Nice little trap you set for me there, Oscar Blass.

Mathematica
dates=Import["input.txt"]
f[digits_]:=FromDigits/@Flatten[Table[Partition[digits,k,1],{k,1,Length[digits]}],1]
g[oneline_]:={FromDigits[oneline[[1]]],Complement[Union[Flatten[f/@oneline]],{0}]}
h[n_,{a_,b_}]:={a,MemberQ[Mod[#,n]&/@b,0]};

w[k_]:=Column@dates[[Cases[h[k,g[#]]&/@ToExpression@(Characters /@ (StringCases[#, DigitCharacter ..] & /@ dates)),{j_,True}:>j]]]

f removes all non-digits;
g finds all the numbers that can be found in a single date line.
h checks to see whether Mod[x, n] is true for any of the numbers returned by g.
w calls the subroutines and formats the output.
Examples
n=40
w[n]

 n=51
 w[n]

 n=71
 w[n]

It returns "ToExpression::sntx:
Invalid syntax in or before "1. Delaware Dec. 7, 1787    "." to me

@belisarius I suspect that there was a problem with your "Input.txt" file.  Try directly setting dates={"1. Delaware Dec.7,1787"}  Then try w[17].  It should return the same line of information.

Ok. How should I save my input file?

First put your data into a list: dates = {"1. Delaware Dec.7,1787",...}, then Export["input.txt",dates]. You use Import["input.txt", dates] to get it back.

Ahh ... OK. Some massaging was needed. Thanks!

Ruby 2.0, 129 chars
With some help from @chron:
IO.foreach('input.txt'){$><<$_ if$_.gsub(/\d+/).any?{(0..s=$&.size).any?{|i|(1..s).any?{|j|(v=$&[i,j].to_i)%$*[0].to_i<1&&v>0}}}}

That long line broken up a bit:
IO.foreach('input.txt') {
    $> << $_ if $_.gsub(/\d+/).any? {
        (0..s=$&.size).any? { |i|
            (1..s).any? { |j|
                (v=$&[i,j].to_i) % $*[0].to_i < 1 && v>0 }}}}

Example:
$ ruby july4.rb 40
10. Virginia    June 25, 1788   1607
17. Ohio    Mar. 1, 1803    1788
21. Illinois    Dec. 3, 1818    1720
32. Minnesota   May 11, 1858    1805
40. South Dakota    Nov. 2, 1889    1859
41. Montana Nov. 8, 1889    1809

$ ruby july4.rb 71
29. Iowa    Dec. 28, 1846   1788

A few small savings for the second line: IO.foreach('input.txt'){|l|puts l if l.scan(/\d+/).any?{|a|(0..s=a.size).any?{|i|(1..s).any?{|j|(v=a[i,j].to_i)%n<1&&v>0}}}} I love #combination but it's such a long word!

Thanks chron! Yes, semantically, I think my original answer was prettier, but this is way shorter; Nice one! I managed to sqeeze out a few more chars by taking advantage of some $variables, so now it almost looks like perl!

Looks good!  Looking at the spec again, apparently n needs to be a command-line arg rather than a value read from stdin.  So you could delete your first line entirely and replace n in the second line with $*[0].to_i

Right you are! thanks.

Q, 94
-1@m(&){0|/{(x>0)&0=x mod"I"$.z.x 0}"J"$sublist[;x]'[a cross a:(!)1+(#)x]}'[m:(0:)`input.txt];

There's undoubtedly a more graceful way to find substrings in q.
$ q find_multiples.q 40 -q
10. Virginia    June 25, 1788   1607
17. Ohio    Mar. 1, 1803    1788
21. Illinois    Dec. 3, 1818    1720
32. Minnesota   May 11, 1858    1805
40. South Dakota    Nov. 2, 1889    1859
41. Montana Nov. 8, 1889    1809

.
$ q find_multiples.q 51 -q
19. Indiana Dec. 11, 1816   1733
25. Arkansas    June 15, 1836   1686
37. Nebraska    Mar. 1, 1867    1823

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Write a program with one & only if statement that
Challenge: You Are The Teacher
Everyone knows that simple task of receiving a grade, and telling if the student:

is approved,
will attend the summer school, or
failed.

In this challenge, you must write a program that does that, but using the maximum of one if statement (also ternary operators count as if).
The grade will be an integer from 0 to 10.
situation   outputs
-------------------------
grade >= 7: Approved
grade >= 3: Summer School
grade  < 3: Failed

You can do whatever you want, write in any language.
Fastest working answer wins.

What about list indexing?

@Volatility Tricky and worky, but ew... let's think of something better =P ("Unfortunately" would still count as a correct answer)

This problem is far too trivial to be assessable on speed. To be able to compare performance with any confidence, you need the programs to run for a minute, not for about ten clock cycles.

Ruby
def x(mark)
    possible_results = ['','Failed', 'Failed', 'Summer school', 'Approved']

    index = (mark + 1).to_s(2).length

    possible_results[index]
end

This uses the fact that the length of the binary representation of the numbers 0-10 is pretty close to the required classification.
Online test: http://ideone.com/y0kLqY

Ruby
Using regular expressions:
puts "Failed012Summer School3456Approved78910"[/\D*(?=\d*#{gets.chomp})/]

Plain array indexing:
puts ["Failed","Summer School","Approved"][(gets.to_i+1)/4]

Python2: 65
Bonus: it doesn't use any conditional expression.
g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]

Example output:
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
10
Approved
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
7
Approved
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
6
Summer School
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
3
Summer School
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
2
Failed

C
#include <stdio.h>
#include <stdlib.h>

int min(int a, int b)
{
    return (a < b) * a + (a >= b) * b;
}

const char *grade_to_string(int grade)
{
    const char * grades[3] = { "Failed", "Summer school", "Approved" };
    return grades[min(((grade + 1) >> 2), 2)];
}

int main(int argc, char *argv[])
{
    int grade = atoi(argv[1]);
    printf("%d = %s\n", grade, grade_to_string(grade));
    return 0;
}

Test:
$ gcc -Wall -O3 grade.c
$ time for i in $(seq -1 20) ; do ./a.out $i ; done
-1 = Failed
0 = Failed
1 = Failed
2 = Failed
3 = Summer school
4 = Summer school
5 = Summer school
6 = Summer school
7 = Approved
8 = Approved
9 = Approved
10 = Approved
11 = Approved
12 = Approved
13 = Approved
14 = Approved
15 = Approved
16 = Approved
17 = Approved
18 = Approved
19 = Approved
20 = Approved

real    0m0.120s
user    0m0.025s
sys     0m0.042s
$

I count one ternary operator and one if.

Well main is just a test harness, so I don't count the if in that - I'll remove it though if it makes you happy. ;-)

The spec asks for a program, so I think you have to count main. It would be more interesting, though, to keep that if and remove the one in min ;)

Challenge accepted !

Perl
sub f {
  my $grade = shift;
  my $result = 0;
  for (++$grade ; $grade > 1; $grade >>= 1) {
    ++$result;
  }
  return ("Failed", "Failed", "Summer school", "Approved")[$result];
}

(The for-loop test constitutes the program's one permitted "if statement".)

 R
g=function(x)cut(x,c(0,3,7,10),
                 labels=c("Failed","Summer school","Approved"),
                 right=FALSE, include=TRUE)

Usage:
> g(2)
[1] Failed
Levels: Failed Summer school Approved
> g(7)
[1] Approved
Levels: Failed Summer school Approved
> g(3)
[1] Summer school
Levels: Failed Summer school Approved

Function cut in R converts a numeric into a factor (categorical) according to the interval in which it falls. It is vectorized:
> g(0:10)
[1] Failed       Failed       Failed       Summer school Summer school Summer school Summer school
[8] Approved      Approved      Approved      Approved
Levels: Failed Summer school Approved

Awk
{
  print check($1,0,2,"Failed") check($1,3,6,"Summer School") check($1,7,10,"Approved")
}

function check(grade,lower,upper,result)
{
  if (grade>=lower && grade<=upper) return result
}

(There are enough clever solutions, so I felt the need to post a brute force one too.)
Sample run:
bash-4.1$ for i in {0..10}; do echo -n $i\ ; awk grade.awk <<< $i; done
0 Failed
1 Failed
2 Failed
3 Summer School
4 Summer School
5 Summer School
6 Summer School
7 Approved
8 Approved
9 Approved
10 Approved

APL
'Failed' 'Summer School' 'Approved'⌷⍨+/⎕≥0 3 7

Explanation:

⎕≥0 3 7: read input, see if it is bigger or equal to 0, 3 and 7 (this gives a vector of bits, i.e. if the input is 5 this gives 1 1 0)
+/: sum the vector (giving an index into the list)
⌷⍨: select the corresponding string from the list

Using Javascript, Thanks to @Bakuriu
function decision(g) {
    var d = ["Approved","Summer School","Failed"];
    return d[(g<7)+(g<3)]
}

console.log(decision(2)); ==> Failed
console.log(decision(5)); ==> Summer School
console.log(decision(9)); ==> Approved
console.log(decision(1)); ==> Failed
console.log(decision(4)); ==> Summer School

Java
public static String getFeedback(int grad) {
    String str = grad>=7? "Approved" : grad>=3 ?  "Summer School" : grad<3 ? "Failed"  : "";
    return str;
}

That in not a program, just a snippet. At least post the whole method. 2) There are 3 ternary operators while only 1 is allowed.


text:
quine-ish tic-tac-toe
Write a program in your chosen language which plays a perfect game of tic-tac-toe on a 3 * 3 board against a human player. However, every move has to be a different program, generated from the previous iteration.
How and in what form you evaluate human input, is up to you, but it has to be read from the standard input. Similarly, you are free to choose a method how you will determine which player starts (for example, you ask first, or you allow the human to enter an invalid move to signal that the computer starts, or other ideas).
Validating moves is not necessary, you can assume a fairly playing human opponent.
Basically, you have program which corresponds to a state of the board. The state is printed in any recognizable way, but at least the following level of detail is expected:
X..
00X
x..

After the human player entered his moves, your program has to generate the next iteration of itself as a source file in the same language (either to standard output or to a file) and terminate. You are not allowed to store information anywhere else outside of that source file. (it is not necessary for your program to build and run the generated program, it can be done by the user - however, it's not forbidden). When the generated program is built and run, it will behave similarly, display the state, wait for user input, etc.
At the end of the game, you have to print the result (whether you won or it's a tie) in any unambiguously identifiable way.
By perfect play I mean the program must not lose, and if there is a possibility to force a win, it should win.
Shortest code wins, winner is selected at least 10 days after the first valid entry.
You get a 10% reduction in the score if your program can handle the building and launching of its next iteration. (I know, it's most probably not worth it) Of course, the program itself must be terminated by the time the next iteration accepts the moves from the user.
If you use some strange uncommon tricks, please post a short explanation with your code.

Nice challenge, but I think I'm going to opt-out.

"Every move has to be a different program".  Do you mean, "each game has to be initiated and managed by a new, distinct instance of the original program"?

@DavidCarraher : No. Every move, not just every game. Check the description below the board example. When the computer has to make a move (so the state of the board changes), your program has to generate a source file, which when built and run, will become the next state. The original program then exits. The newly generated program, when making a move, will behave similarly: it creates a source file, which when built and run, will become the next state, and so on. As no information storage is allowed except in the generated source file, it is like a quine with differences between iterations.

Perl, 933 characters
$m=<<'';$_='         ';
sub h{/^(?:...)*(\d)\1\1/|/^.?.?(\d)..\1..\1/|/(\d)...\1...\1/|/^..(\d).\1.\1/&&$1}
sub r{substr($_,$p-1,1)=pop}sub p{my$w=pop;my@b=(0,h==$w||h&&-1);if(!$b[1]&&/ /){$b[1]=-9;
while(/ /g){local($_,$p)=($_,pos);r$w;$r=-(p($w^1))[1];@b=($p,$r)if$r>$b[1]}}@b}
if(($w=h||!/ /)||!@ARGV){$w--&&print+(nobody,X,O)[$w]," wins\n";s/(...)/$1\n/g;
tr/ 23/.XO/;print}else{$w=3;$w^=1for/\d/g;($p=pop)?r($w^1)&&!h&&(($p)=p$w)&&r$w:s/ /2/;
print"\$m=<<'';\$_='$_';\n$m\n$m"}

sub h{/^(?:...)*(\d)\1\1/|/^.?.?(\d)..\1..\1/|/(\d)...\1...\1/|/^..(\d).\1.\1/&&$1}
sub r{substr($_,$p-1,1)=pop}sub p{my$w=pop;my@b=(0,h==$w||h&&-1);if(!$b[1]&&/ /){$b[1]=-9;
while(/ /g){local($_,$p)=($_,pos);r$w;$r=-(p($w^1))[1];@b=($p,$r)if$r>$b[1]}}@b}
if(($w=h||!/ /)||!@ARGV){$w--&&print+(nobody,X,O)[$w]," wins\n";s/(...)/$1\n/g;
tr/ 23/.XO/;print}else{$w=3;$w^=1for/\d/g;($p=pop)?r($w^1)&&!h&&(($p)=p$w)&&r$w:s/ /2/;
print"\$m=<<'';\$_='$_';\n$m\n$m"}

Please note that the blank line in the middle of the script is actually required to be there. (The line breaks at the end of the long lines are not required, other than for legibility, and are not included in the character count.)
Usage: When the program is run without arguments, it displays the current game state. Since at the start the board is empty, the output will be:
...
...
...

Run the program with an argument between 1 and 9 to claim that square as your move. The program will make its own move and then output a replacement script with the new state. Thus, for example:
$ perl ./qttt 5 > ./qttt-2
$ perl ./qttt-2
O..
.X.
...

On the very first turn only, you may give a move of 0 to indicate that the computer should take the first move. Note that the first player will always be X.
When the game is over, the display output will include a note to that effect:
$ perl ./qttt-4 6 > ./qttt-5
$ perl ./qttt-5
O wins
OXX
OOX
X.O

The program works by doing a standard minimax search of the game tree. (Tic-tac-toe is a small enough game that a full game tree can be generated on every run.) The exception to this is when the computer moves first -- in this case the initial move to the upper left corner is hard-coded.
Note that this program works in the fashion of a proper quine -- at no point does the script access its own source file in order to produce its output.

That is beautiful! I didn't realize I was staring at a huge here-doc for the longest time, then did a double-take.


text:
The centers of a triangle
Circles and squares have a single, definite center point. However, the notion of the center of a triangle has long been discussed. Four different centers were known to the Ancient Greeks:

Incenter: The intersection of the angle bisectors of the triangle
Centroid: The intersection of the lines from each vertex of the triangle to the middle of its opposite side
Circumcenter: The intersection of the perpendicular bisectors of the sides
Orthocenter: The intersection of the altitudes of the triangle

Euler later proved that the centroid, circumcenter and orthocenter are collinear in any triangle. The line that these three points are on in a triangle is called the Euler Line. It is defined for every triangle except an equilateral triangle, where all the points coincide.
Your challenge is to create the shortest program or function that, when given two inputs, outputs a specific center or the Euler Line of the triangle. The first specifies the coordinates of each vertex of a triangle. The second is an integer from 1 to 5, determining what to output.
1 - Incenter
2 - Centroid
3 - Circumcenter
4 - Orthocenter
5 - Equation of Euler Line
    (if the Euler Line is vertical, output the `x` value of the line
      (e.g. output `5` if the equation of the line is `x = 5`))

You may assume that the given vertices will never be collinear, and that they will always be integer coordinates (this also excludes the possibility of having an equilateral triangle as an input, as per @R.Kap's comment).
The input array should be a valid nested array in your language, and input should be in any reasonable format. Any float values should be displayed to at least 3 decimal places, but no less. An outputted point should be a valid array in your language, matching with the input format.

Test cases:
Input: [(-2, 0), (1, 0), (0, 1)] 1
Output: (-0.089, 0.451)

Input: [(-2, 0), (1, 0), (0, 1)] 2
Output: (-0.333, 0.333)

Input: [(-2, 0), (1, 0), (0, 1)] 3
Output: (-0.5, -0.5)

Input: [(-2, 0), (1, 0), (0, 1)] 4
Output: (0, 2)

Input: [(-2, 0), (1, 0), (0, 1)] 5
Output: 5x + 2

Clarification: The input can either be from stdin, either space or new-line separated, or as the arguments to a function. The output, however, must be written to stdout.

I'm afraid explicit formulas for the circumcenter and orthocenter in cartesian coordinates are pretty ugly. If I go the way of creating a general trilinear/barycentric => carthesian coordinates, the incenter drops out almost free. See http://en.wikipedia.org/wiki/Trilinear_coordinates#Examples. Do I get extra points for implementing it?

What are the valid output formats for the Euler line? If it is vertical, it cannot be expressed as y=f(x).

(please comment if you disagree) Please use the sandbox if you are not sure if a challenge is ok or not. There you can ask for comments and refine the question until it fits. Once posted here it shouldn't be changed with regards to content. Several people might already work on it - and don't like moving targets.

@Howard fixed now, apparently I didn't realise there was a simple formula for it [the incenter].

@JanDvorak No. Also, I've edited the challenge details - see them.

"When outputting a point, the coordinates must be... surrounded in round brackets (())".  Why this requirement? In some languages, points are represented in curly brackets.  And something like (12, -2) can only be represented as a string, in which case the elements themselves are interpreted as strings rather than numbers.

@DavidCarraher I have changed the output format to be a little more lax. Do note though that I have said that "The input array should be a valid nested array in your language".

I'm unclear - do you expect the input to be read from a textual input (stdin, say), and parsed by the program? Or is the program a function that takes "valid nested array", but prints the result rather than returns a result?

@MtnViewMark either is fine; see the edit.

Can you please tell me how you can possibly create an equilateral triangle with only integer coordinates?

You may either want to make it that the input can be floating point coordinates, or completely get rid of (if the triangle is equilateral, output the point at which the centers meet) as it is not possible to create an equilateral triangle on the coordinate plane using only integer coordinates.

@R.Kap thanks for pointing that out. Edited.

You forgot one(or should I say 3?). Excenters.

Python - 908 870
Newlines were added to reduce scrolling. This could probably be golfed further.
from math import*;t=eval(input());p=int(input())-1;
r=[];A,B,C=t[0],t[1],t[2];
a,b,c=hypot(B[0]-C[0],B[1]-C[1]),hypot(A[0]-C[0],A[1]-C[1]),hypot(A[0]-B[0],A[1]-B[1]);
r.append(((a*A[0]+b*B[0]+c*C[0])/(a+b+c),(a*A[1]+b*B[1]+c*C[1])/(a+b+c)));
r.append(((A[0]+B[0]+C[0])/3,(A[1]+B[1]+C[1])/3));d,e,f=(0,0),(B[0]-A[0],B[1]-A[1]),(C[0]-A[0],C[1]-A[1]);g=2*(e[0]*f[1]-e[1]*f[0]);
r.append(((f[1]*(e[0]**2+e[1]**2)-e[1]*(f[0]**2+f[1]**2))/g+A[0],(e[0]*(f[0]**2+f[1]**2)- f[0]*(e[0]**2+e[1]**2))/g+A[1]));
h=acos((b*b+c*c-a*a)/(2*b*c));i=acos((a*a+c*c-b*b)/(2*a*c));j=acos((a*a+b*b- c*c)/(2*a*b));k=cos(i)*cos(j);
l=cos(h)*cos(j);m=cos(h)*cos(i);r.append(((a*k*A[0]+b*l*B[0]+c*m*C[0])/(a*k+b*l+c*m),(a*k*A[1]+b*l*B[1]+c*m*C[1])/(a*k+b*l+c*m)));
n,o=r[1][0]-r[2][0],r[1][1]-r[2][1];q=r[1][1]-o/n*r[1][0]if n!=0 else 0;
r.append(r[1]if a==b==c else("x="+str(r[1][0])if n==0 else"".join([str(o/n),"x+(",str(q),")"])));print(r[p])

Test cases (annotated):
Input: [(-2, 0), (1, 0), (0, 1)]
1
Output: (-0.08907279243665268, 0.45110872103880023) --> More digits than in question

Input: [(-2, 0), (1, 0), (0, 1)]
2
Output: (-0.3333333333333333, 0.3333333333333333) --> More digits than in question

Input: [(-2, 0), (1, 0), (0, 1)]
3
Output: (-0.5, -0.5)

Input: [(-2, 0), (1, 0), (0, 1)]
4
Output: (-1.1702778228588997e-16, 1.9999999999999984) --> More digits than shown in question

Input: [(-2, 0), (1, 0), (0, 1)]
5
Output: 4.999999999999999x+(1.9999999999999996) --> More digits than in question

As you can see, there are possibly errors caused by using floating point.

Further golfing:
Based on suggestions in the comments below, I've managed to make this smaller.
from math import*;I=input;t=eval(I());p=int(I())-1;r=[];A,B,C=t[0],t[1],t[2];R,H,D,S,T=r.append,hypot,cos,acos,str;a,b,c=H(B[0]-C[0],B[1]-C[1]),H(A[0]-C[0],A[1]-C[1]),H(A[0]-B[0],A[1]-B[1]);R(((a*A[0]+b*B[0]+c*C[0])/(a+b+c),(a*A[1]+b*B[1]+c*C[1])/(a+b+c)));R(((A[0]+B[0]+C[0])/3,(A[1]+B[1]+C[1])/3));d,e,f=(0,0),(B[0]-A[0],B[1]-A[1]),(C[0]-A[0],C[1]-A[1]);g=2*(e[0]*f[1]-e[1]*f[0]);R(((f[1]*(e[0]**2+e[1]**2)-e[1]*(f[0]**2+f[1]**2))/g+A[0],(e[0]*(f[0]**2+f[1]**2)-f[0]*(e[0]**2+e[1]**2))/g+A[1]));h=S((b*b+c*c-a*a)/(2*b*c));i=S((a*a+c*c-b*b)/(2*a*c));j=S((a*a+b*b-c*c)/(2*a*b));k=D(i)*D(j);l=D(h)*D(j);m=D(h)*D(i);R(((a*k*A[0]+b*l*B[0]+c*m*C[0])/(a*k+b*l+c*m),(a*k*A[1]+b*l*B[1]+c*m*C[1])/(a*k+b*l+c*m)));n,o=r[1][0]-r[2][0],r[1][1]-r[2][1];q=r[1][1]-o/n*r[1][0]if n!=0else 0;R(r[1]if a==b==c else("x="+T(r[1][0])if n==0else"".join([T(o/n),"x+(",T(q),")"])));print(r[p])

I think it's actually 907 bytes. (URL shortened).

Could you do something like R=r.append and then use that throughout to save bytes?

AutoHotkey - 731
f(z, r:=1){
static 1:="i",2:="m",3:="c",4:="o"
r := %r%,mx :=(z.1.1+z.2.1+z.3.1)/3,my:=(z.1.2+z.2.2+z.3.2)/3
s:=(c:=sqrt((z.2.1-z.1.1)**2+(z.2.2-z.1.2)**2))+(a:=sqrt((z.3.1-z.2.1)**2+(z.3.2-z.2.2)**2))+(b:=sqrt((z.3.1-z.1.1)**2+(z.3.2-z.1.2)**2))
ix:=(a*z.1.1+b*z.2.1+c*z.3.1)/s,iy:=(a*z.1.2+b*z.2.2+c*z.3.2)/s
midx_a:=(z.3.1+z.2.1)/2,midy_a:=(z.3.2+z.2.2)/2,m:=-1*(z.3.1-z.2.1)/(z.3.2-z.2.2),cc_a:=midy_a-(m*midx_a)
midx_b:=(z.3.1+z.1.1)/2,midy_b:=(z.3.2+z.1.2)/2,n:=-1*(z.3.1-z.1.1)/(z.3.2-z.1.2),cc_b:=midy_b-(n*midx_b)
cx:=(cc_b-cc_a)/(m-n),cy:=cc_a+(m*cx),oc_a:=z.1.2-(m*z.1.1),oc_b:=z.2.2-(n*z.2.1),ox:=(oc_a-oc_b)/(n-m),oy:=oc_a+(m*ox)
if r in m,i,c,o
return [%r%x, %r%y]
else return "y=" (m:=(oy-cy)/(ox-cx)) "x+" oy-m*ox
}

The function can be more minified (to about 600 chars OR less) by shortening the variable names like midx_a, midx_b and so.
Calling the function
d:=f([[-2, 0], [1, 0], [0, 1]], 1)
for k,v in d
    msgbox % k "`n" v

Python 3.5, 851 772 bytes:
def H(z,a,b,l):c=complex;T=lambda A,B:abs(c(*A)-c(*B));d=T(z,a);e=T(z,b);f=T(a,b);g=[((a[0]+b[0])/2,(a[1]+b[1])/2)for a,b in[[a,b],[z,a],[b,z]]];E=(z[0]+a[0]+b[0])/3;F=(z[1]+a[1]+b[1])/3;m=lambda f:[(a,0)if(b[1][0]-b[0][0])==0else(a,-1/((b[1][1]-b[0][1])/(b[1][0]-b[0][0])))if(b[1][1]-b[0][1])else''for a,b in zip(f,[[a,b],[z,a],[b,z]])];i=[u for u in m(g)if u!=''];C=i[0][1];D=i[0][0][1]-(C*i[0][0][0]);A=i[1][1];B=i[1][0][1]-(A*i[1][0][0]);G=(B-D)/(C-A);H=C*G+D;j=[u for u in m([z,b,a])if u!=''];C=j[0][1];D=j[0][0][1]-(C*j[0][0][0]);A=j[1][1];B=j[1][0][1]-(A*j[1][0][0]);I=(B-D)/(C-A);J=C*I+D;K,L=[((d*b[o])+(e*a[o])+(f*z[o]))/sum([d,e,f])for o in[0,1]];a=(H-J)/(G-I)if(G-I)else'';b=H-(a*G)if a!=''else G;print(['',(K,L),(E,F),(G,H),(I,J),[b,'%sx+%s'%(a,b)][a!='']][l])

Takes input as a sequence of comma separated coordinates followed by an integer conveying what to output. For instance, if the input coordinates are (1,0),(2,1),(1,4) and you want the orthocenter of the triangle corresponding to those coordinates you would simply call the function like so:
H((1,0),(2,1),(1,4),4)

Outputs in the format of a tuple if a specific point is needed, in the format of a string with the equation in the form y=mx+b if the Euler line is needed and the line is not vertical, or simply the x value of the line if the Euler line is needed but the line is vertical.
So, using the triangle with vertices (1,0),(2,1),(1,4), the outputs would be:
1. Incenter: (1.4663911961440428, 1.125967951102358)
2. Centroid: (1.3333333333333333, 1.6666666666666667)
3. Circumcenter: (0.0, 2.0)
4. Orthocenter: (4.0, 1.0)
5. Euler Line: -0.25x+2.0

I will try to golf this more over time where and when I can.
Try It Online! (Ideone)


text:
Writing firewall rules
Congratulations, you're now a network administrator! As your first task you will need to configure a firewall to stop any traffic to some blacklisted addresses.
Unfortunately, the only firewall at your disposal only takes in rules in this format:
x.y.z.t/m ALLOW
There's no DENY keyword. If you want to exclude a specific address, you'll have to write a lot of rules to allow everything except that address. If you want to exclude more than one address or a whole range, then you're in luck because these ALLOW rules will overlap to some degree.
The challenge
You are given a list of blacklisted IPs. Write a program that will print out rules for our firewall. Also, be sensible when writing rules: don't just enumerate all 256^4 and don't print out duplicates.
Code golf rules apply: shortest code wins
*this problem is inspired by a real life assignment; a friend actually needed this done
Example
To block address 0.1.2.3 you could write the following ALLOW rules (this is not the only solution possible, and it's certainly not the shortest):
0.1.2.0 ALLOW
0.1.2.1 ALLOW
0.1.2.2 ALLOW
0.1.2.4 ALLOW
...
0.1.2.255 ALLOW

0.1.0.0/24 ALLOW
0.1.1.0/24 ALLOW
0.1.4.0/24 ALLOW
...
0.1.255.0/24 ALLOW

0.0.0.0/16 ALLOW
0.2.0.0/16 ALLOW
...
0.255.0.0/16 ALLOW

1.0.0.0/8 ALLOW
...
255.0.0.0/8 ALLOW

Could you add some test cases?

"shortest code" conflicts with "be sensible". Are there any hard requirements for "being sensible"? Note there is always exactly one optimal solution and it's fairly easy to find and verify optimality. You could require that.

Python3 - 325 chars
import sys
r=[(0,32)]
for b in (int('%02x'*4%tuple(int(x) for x in y.split('.')),16) for y in sys.stdin):
 i=0
 while i<len(r):l,q=r[i];o=2**q//2;m=l+o;h=m+o;k=l<=b<h;r[i:i+1]=[(l,q-k),(m,q-k)][0:k+1*(not l==h==b)];i+=1-k
for n,m in r:print('%s/%d ALLOW'%('.'.join(str(int(('%08x'%n)[i:i+2],16)) for i in range(0,8,2)),32-m))

Python 3: 253 characters
Yay, Python!
from ipaddress import *
import sys
def e(x,a):
 b=[]
 for i in a:
  try: b+=i.address_exclude(ip_network(x))
  except ValueError: b+=[i]
 return b
a=[ip_network('0.0.0.0/0')]
for h in sys.stdin:
 for i in h.split(): a=e(i,a)
for i in a: print(i,'ALLOW')

It accepts a list of addresses on stdin, separated by any (ASCII) whitespace you like (no commas, though).
You can save 12 characters by replacing the stdin loop with for i in sys.stdin: a=e(i.strip(),a). The strip() is necessary to get rid of a trailing newline anyway, though, so I figured I'd use split() and another for loop and allow any whitespace.
You can probably save a few more characters by moving the code out of that pesky function. I didn't because I figured I was already confusing myself enough.
You can also make it work for IPv6 instead by changing only one line.
Ungolfed version:
#!/usr/bin/env python3

import ipaddress
import sys

def exclude(address, networks):
    new_networks = []
    for network in networks:
        try:
            new_networks.extend(network.address_exclude(ipaddress.ip_network(address)))
        except ValueError:
            new_networks.append(network)
        except TypeError:
            pass
    return new_networks

networks = [ipaddress.IPv6Network('::/0'), ipaddress.IPv4Network('0.0.0.0/0')]
for line in sys.stdin:
    for address in line.split():
        networks = exclude(line, networks)

for network in networks:
    print(network)

This one has the added benefit of working for IPv4 and IPv6, no tweaking necessary. :)

You could still remove unnecessary spaces, such as the ones after :s and before the first *. Great first answer on this site! :) +1

PHP 5.3, 465 characters
$r=array_map(function($v){return explode('.',$v);},$w);$l=256;$n=" ALLOW\r\n";$o='';$a=$b=$c=$d=range(0,$l-1);foreach($r as$i){unset($a[$i[0]],$b[$i[1]],$c[$i[2]],$d[$i[3]]);}for($x=0;$x<$l;$x++){for($y=0;$y<$l;$y++){for($z=0;$z<$l;$z++){for($t=0;$t<$l;$t++){$k="$x.$y.$z.$t";if(isset($a[$x])){$o.="$k/8$n";break 3;}elseif(isset($b[$y])){$o.="$k/16$n";break 2;}elseif(isset($c[$z])){$o.="$k/24$n";break;}else$o.=isset($d[$t])?"$k$n":'';}}}}file_put_contents($p,$o);

Usage:
$w = array('2.5.5.4', '1.2.3.4');
$p = 'data.txt';
$r=array_map(function($v){return explode('.',$v);},$w);$l=256;$n=" ALLOW\r\n";$o='';$a=$b=$c=$d=range(0,$l-1);foreach($r as$i){unset($a[$i[0]],$b[$i[1]],$c[$i[2]],$d[$i[3]]);}for($x=0;$x<$l;$x++){for($y=0;$y<$l;$y++){for($z=0;$z<$l;$z++){for($t=0;$t<$l;$t++){$k="$x.$y.$z.$t";if(isset($a[$x])){$o.="$k/8$n";break 3;}elseif(isset($b[$y])){$o.="$k/16$n";break 2;}elseif(isset($c[$z])){$o.="$k/24$n";break;}else$o.=isset($d[$t])?"$k$n":'';}}}}file_put_contents($p,$o);

This will write to data.txt
Uncompressed:
$deny = array('2.5.5.4', '1.2.3.4');
$file = 'data.txt';

$list = array_map(function($v){return explode('.', $v);}, $deny);
$l = 256;
$n = " ALLOW\r\n";$o = '';

$first = $second = $third = $fourth = range(0,$l-1);
foreach($list as $ip){unset($first[$ip[0]], $second[$ip[1]], $third[$ip[2]], $fourth[$ip[3]]);}

for($x=0;$x<$l;$x++){
    for($y=0;$y<$l;$y++){
        for($z=0;$z<$l;$z++){
            for($t=0;$t<$l;$t++){
                if(isset($first[$x])){
                    $o .= "$x.0.0.0/8$n";break 3;
                }else{
                    if(isset($second[$y])){
                        $o.="$x.$y.0.0/16$n";break 2;
                    }else{
                        if(isset($third[$z])){
                            $o.="$x.$y.$z.0/24$n";break 1;
                        }else{
                            if(isset($fourth[$t])){
                                $o.="$x.$y.$z.$t$n";
                            }
                        }
                    }
                }
            }
        }
    }
}

file_put_contents($file, $o);

Won't this solution only consider the subnets /8, /16 and /24?

@jarnbjo correct, but it will write the rest without /x. For examlpe in this case it will write 1.2.3.0 ALLOW\r\n1.2.3.1 ALLOW\r\n 1.2.3.2 ALLOW\r\n1.2.3.3 ALLOW\r\n1.2.3.5 ALLOW ....

The shortest rule list to block only 0.1.2.3 would require the rule "0.1.2.0/31 ALLOW" instead of allowing the IP addresses 0.1.2.0 and 0.1.2.1 separately.

@jarnbjo I know, but if I would take that into consideration the code will be too huge, I'm already using PHP so I'm suffering enough from the code length. Besides it isn't specified by the OP :)

I assumed that returning the shortest rule list is part of the "being sensible" requirement. Otherwise you could shorten your code a lot and simply output each allowed IP address, but that's obviously not what's asked for either.


text:
Floating points: Make Gaussian elimination go wrong
You know that some decimal numbers can't be expressed as IEEE 754 floating points. You also know that arithmetic with floating points can give results that seem to be wrong:

System.out.print(4.0-3.1); (source)
0.2 + 0.04 = 0.24000000000000002 (source)

While one wrong number with an error that is this small might not be significant, more of those error might be.
Task
Find a system of linear equations in form of a matrix A \in R^{n \times n} and b \in R^n, such that the result vector is as wrong as possible. Reference is the script below, executed with Python 2.7.
Points
#!/usr/bin/env python
# -*- coding: utf-8 -*-

def pprint(A):
    n = len(A)
    for i in range(0, n):
        line = ""
        for j in range(0, n+1):
            line += str(A[i][j]) + "\t"
            if j == n-1:
                line +=  "| "
        print(line)
    print("")

def gauss(A):
    n = len(A)

    for i in range(0,n):
        # Search for maximum in this column
        maxEl = abs(A[i][i])
        maxRow = i
        for k in range(i+1,n):
            if abs(A[k][i]) > maxEl:
                maxEl = A[k][i]
                maxRow = k

        # Swap maximum row with current row (column by column)
        for k in range(i,n+1):
            tmp = A[maxRow][k]
            A[maxRow][k] = A[i][k]
            A[i][k] = tmp

        # Make all rows below this one 0 in current column
        for k in range(i+1,n):
            c = -A[k][i]/A[i][i]
            for j in range(i,n+1):
                if i==j:
                    A[k][j] = 0
                else:
                    A[k][j] += c * A[i][j]

    # Solve equation Ax=b for an upper triangular matrix A
    x=[0 for i in range(n)]
    for i in range(n-1,-1,-1):
        x[i] = A[i][n]/A[i][i]
        for k in range(i-1,-1,-1):
            A[k][n] -= A[k][i] * x[i]
    return x;

if __name__ == "__main__":
    from fractions import Fraction
    datatype = float # Fraction
    n = input()

    A = [[0 for j in range(n+1)] for i in range(n)]

    # Read input data
    for i in range(0,n):
        line = map(datatype, raw_input().split(" "))
        for j, el in enumerate(line):
            A[i][j] = el
    raw_input()

    line = raw_input().split(" ")
    lastLine = map(datatype, line)
    for i in range(0,n):
        A[i][n] = lastLine[i]

    # Print input
    pprint(A)

    # Calculate solution
    x = gauss(A)

    # Print result
    line = "Result:\t"
    for i in range(0,n):
       line += str(x[i]) + "\t"
    print(line)

Let x be the correct answer and x' the answer that the script above gives.
Your points are (||x-x'||^2)/n, where || . || is the euclidean distance.
Your solution gets 0 points if it gives nan as result.
Example
bad.in:
2
1 4
2 3.1

1 1

The first line is n, the next n lines describe the matrix A and the last line describes b.
$ python gauss.py < bad.in
1.0 4.0 | 1.0
2.0 3.1 | 1.0

Result: 0.183673469388  0.204081632653

The answer should be:
Result: 9/49    10/49

So the score would be:
((0.183673469388-9/49)^2+(0.204081632653-10/49)^2)/2
= 3.186172428154... × 10^-26

The last step was calculated with Wolfram|Alpha.

Hooray! Now there's a geeky comic we can link to whenever this question comes up!

Ok, this feels kind of cheating.
Tcl, score 1234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234569876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876543209876544
gets stdin a
puts $a
for {set i 0} {$i<$a} {incr i} {
    set r {}
    for {set j 0} {$j<$a} {incr j} {
        lappend r [expr {$i==$j?1:0}]
    }
    puts $r
}
puts ""
puts [join [lrepeat $a [string repeat 8 308]]]

let us continue this discussion in chat

Ok, seems to be correct: http://pastebin.com/JgKrhLe1 I didn't think it was so easy to get such a high number of points. Congratulations. I will wait until tomorrow, but I think you've won this challenge.

Actually it is 1.2345*10^588

It is kind of cheating. You're not exploiting any instability of Gaussian elimination at all, but merely the fact that Python will parse arbitrary bigints and convert them to doubles.

@PeterTaylor Yeah, it feels that way. This question asks for the biggest difference, not a relative difference. So using high numbers almost win the challenge. Relative error would be better for this challenge.

@JohannesKuhn, that's not my point (although it is a point I've also made in my answer). You could remove the Gaussian elimination step entirely and it wouldn't affect the error calculation. It's not making Gaussian elimination go wrong at all, which is what the title asks for.

Taking this as a question about numerical inaccuracy in calculations rather than in conversion from numbers which can't be exactly represented in 64 bits to 64-bit representations, we're interested in nearly singular matrices.
Let's take the simplest possible case:
[a b] [x] = [p]
[c d] [y]   [q]

has solution
[x] = [(dp - bq) / (ad - bc)]
[y]   [(aq - cp) / (ad - bc)]

so that if ad - bc is very small we find that errors in dp - bq and aq - cp are magnified.
We also find that scaling p and q scales the absolute error linearly, which points out a massive flaw in the scoring system of this question.
How can we get a nearly singular matrix? In order of ill-conditionedness:

a=1+e, b=c=d=1 gives ad - bc = e. This allows us to get a determinant of 1 ulp (which for IEEE 64-bit is on the order of 10^-16).
a=1+e, d=1-e, b=c=1 gives ad - bc = -e^2. This allows us to get a determinant on the order of 10^-32.
2
1.000000000000001 1
1 0.999999999999999

1 1

gives output:
1.0 1.0 | 1.0
1.0 1.0 | 1.0

Result: -9.0    10.0

rather than x = 100000000000000, y = -100000000000000
Similarly,
2
1.000000000000001 1
1 0.999999999999999

1E307 1E307

gives
1.0 1.0 | 1e+307
1.0 1.0 | 1e+307

Result: -9.1120238836e+307  1.01120238836e+308

rather than x = 1E321, y = -1E321. This seems to roundly beat Johannes' solution (it gives a score on the order of 10^642 vs 10^588), and moreover it would continue to generate about the same score even if the input numbers were tweaked to be exactly representable in IEEE 64-bit, whereas his would then score 0.
a=d=e, bc=0 gives ad - bc = e^2 but this time we can choose e to be a very small number rather than 1 ULP. In principle this allows us to get a determinant on the order of 10^-600 (i.e. underflowing IEEE 64-bit). However, so far I haven't managed to get a decent score without an infinity in the answer, and I gather from your chat with Johannes that even though the question doesn't rule out infinite scores, in practice you do.

I've wanted this challenge to be a numerical one, so you've answered what I wanted to (but failed to) ask. Thanks!

+1 Good work. I just used a flaw in the question, but you actually solved it.


text:
Save money with price rounding
In Canada, the penny is no longer circulated.  Cash payments are rounded to the nearest 5 cents.
Money can be saved by splitting purchases.  For example, two $1.02 items cost $2.04 which rounds up to $2.05, but when buying the items in separate purchases, each price rounds to $1.00 for a total of $2.00.  However, when buying two items at $1.03 each, it is better to buy them in a single purchase.
Another way to save money is using a credit card when rounding is unfavourable, because credit payments are not rounded.  If we want two $1.04 items, the total price will round up to $2.10 regardless of how we split the purchases.  Therefore, we should pay for these items with a credit card.
Write a function or program which accepts a list of prices of items as integers in cents and outputs the lowest possible total price (in cents) for those items which can be achieved through a sequence of purchases, each either by cash or by credit.
Shortest code wins.
Test cases
[] : 0
[48] : 48
[92, 20] : 110
[47, 56, 45] : 145
[55, 6, 98, 69] : 225
[6, 39, 85, 84, 7] : 218
[95, 14, 28, 49, 41, 39] : 263
[92, 6, 28, 30, 39, 93, 53] : 335
[83, 33, 62, 12, 34, 29, 18, 12] : 273
[23, 46, 54, 69, 64, 73, 58, 92, 26] : 495
[19, 56, 84, 23, 20, 53, 96, 92, 91, 58] : 583
[3, 3, 19, 56, 3, 84, 3, 23, 20, 53, 96, 92, 91, 58, 3, 3] : 598
[2, 3, 4, 4, 4, 4, 4] : 19

Ruby, 119 105 characters (93 body)
def f s
a,b,c,d=(1..4).map{|i|s.count{|x|x%5==i}}
s.reduce(0,:+)-a-(c-m=c>d ?d:c)/2-2*(b+m+(d-m)/3)
end

Two characters may be saved if the algorithm is allowed to crash when fed an empty shopping list.

You may change to s.reduce(:+) (normally you even don't need parantheses, but in your case...) and inline m for additional 2 chars.

And of course a,b,c,d=(1..4).map{|i|s.count{|x|x%5==i}}.

@Howard if I remove 0, from the reduce call, the code breaks for the empty input. I did mention that in the answer. Inlining m doesn't seem to help. Thanks for the last suggestion - that was stupid from me.

You can write (c-m=c>d ?d:c) which gives you two chars.

@Howard I thought that would break because - has higher priority than =. Is it that the assignment has a high priority on its left side (as in, to ensure the left operand is an lvalue)?

I didn't think about that before - and actually I can't find anything in the lang spec about this situation. Anyway, it works ;-) and is interesting.

@cardboard_box tested with all supplied test cases and works

GolfScript (54 chars)
~]4,{){\5%=}+1$\,,}%~.2$>$:m- 3/m+@+2*@@m- 2/++~)+{+}*

This is a program which takes input from stdin as space-separated values. One character could be saved by forcing the input format to instead be as GolfScript arrays.
Test cases online
The most interesting trick is .2$>$ for a  non-destructive min operator.

My analysis of the maths is essentially the same as Jan's and Ray's: considering values mod 5, the only saving is on transactions worth 1 or 2. The credit card option means that we never round up. So an item which costs 5n+2 cents can't benefit from bundling; nor can an item worth 5n+1 cents (because combining two 1-cent savings into a 2-cent saving doesn't give any benefit). 0 is the additive identity, so the only interesting cases involve values of 3 and 4. 3+3 = 1 and 3+4 = 4+4+4 = 2; if we have mixed 3s and 4s then we optimise by preferring 3+4 over 3+3 (strictly better) or 4+4+4 (equivalent).

+1 - although those spaces look so lavishly ;-) You might remove them by saving -m (~):m) unfortunately with no reduction in char count.

@Howard, I know, I tried it too. :D

C++: 126 character
int P(int*m,int i){int t=0,h=0,d;while(i>-1){d=m[i]%5;t+=m[i--];d<3?t-=d:d==4?h++,t-=2:h--;}h<0?t+=h/2:t+=(h-h/3)*2;return t;}

Welcome to give guidance to put this program becomes shorter.Here is the test program,compile with tdm-gcc 4.7.1 compiler and run normally.
#include<iostream>
using namespace std;

//m[i]表示单个商品的价格,t表示所有商品总价格,
//d为单个商品价格取模后的值,h为单个商品价格取模后值为3的个数,
//f为单个商品价格取模后值为4的个数
int P(int*m,int i){int t=0,h=0,d;while(i>-1){d=m[i]%5;t+=m[i--];d<3?t-=d:d==4?h++,t-=2:h--;}h<0?t+=h/2:t+=(h-h/3)*2;return t;}

int main() {
int p1[1]={48};
int p2[2]={92,20};
int p3[3]={47,56,45};
int p4[4]={55,6,98,69};
int p5[5]={6,39,85,84,7};
int p6[6]={95,14,28,49,41,39};
int p7[7]={92,6,28,30,39,93,53};
int p8[8]={83,33,62,12,34,29,18,12};
int p9[9]={23,46,54,69,64,73,58,92,26};
int p10[10]={19,56,84,23,20,53,96,92,91,58};
int p11[10]={1,2,3,4,5,6,7,8,9,10};
cout<<P(p1,0)<<endl
    <<P(p2,1)<<endl
    <<P(p3,2)<<endl
    <<P(p4,3)<<endl
    <<P(p5,4)<<endl
    <<P(p6,5)<<endl
    <<P(p7,6)<<endl
    <<P(p8,7)<<endl
    <<P(p9,8)<<endl
    <<P(p10,9)<<endl
    <<P(p11,9)<<endl;

return 0;
}

Python 3 (115 chars)
m=eval(input());t=a=b=0
for v in m:d=v%5;t+=v-d*(d<3);a+=d==3;b+=d==4
d=min(a,b);a-=d;b-=d;print(t-d*2-a//2-b//3*2)

Python 2 (106 chars)
m=input();t=a=b=0
for v in m:d=v%5;t+=v-d*(d<3);a+=d==3;b+=d==4
d=min(a,b);a-=d;b-=d;print t-d*2-a/2-b/3*2

The question asks for the total price, so there should be one output for the entire list.  For example, the input [3,4,9] should give 14, because you can combine the 3 and 4 cent items to get a 7 cent purchase which you pay in cash with 5 cents, and the remaining 9 cent item you pay with credit because it would otherwise round up.

Given 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, this gives 0.0, 0.0, 2.5, 3.33, 5.0, 5.0, 5.0, 7.5, 8.33, 10.0, which sums to 46.66.  However, the correct answer is 45, so the sum of the numbers you print is not the correct answer, and therefore this solution is incorrect.

This answer was wroted when job not contain "total" yet

I'm afraid I have to recommend deletion. Asker didn't change the requirements - he clarified them. If the price for each item separately were desired, then why the mention of a "sequence of purchases / single purchase" and the discussion of which one is favourable?

I delete wrong answers. Now It's shortest Python answers

R 143
function(x)min(sapply(rapply(partitions::listParts(length(x)),
                             function(i)min(sum(x[i]),5*round(sum(x[i])/5)),h="l"),
                      function(x)sum(unlist(x))))

Tests (where P is an alias for the code above)
> P(c(48))
[1] 48
> P(c(92, 20))
[1] 110
> P(c(47, 56, 45))
[1] 145
> P(c(55, 6, 98, 69))
[1] 225
> P(c(6, 39, 85, 84, 7))
[1] 218
> P(c(95, 14, 28, 49, 41, 39))
[1] 263
> P(c(92, 6, 28, 30, 39, 93, 53))
[1] 335
> P(c(83, 33, 62, 12, 34, 29, 18, 12))
[1] 273
> P(c(23, 46, 54, 69, 64, 73, 58, 92, 26))
[1] 495
> P(c(19, 56, 84, 23, 20, 53, 96, 92, 91, 58))
[1] 583

Mathematica 112 126 167 157
Edit: Cases of {3, 3} and {4,4,4} now handled thanks to Peter Taylor and cardboard_box.
n_~g~o_ := {a___, Sequence @@ n, b___} :> {a, b, o};
f@s_ := Tr@Join[#[[2]], Sort@#[[1]] //. {1 -> 0, 2 -> 0, g[{3, 4}, 5], g[{3, 3}, 5],
   g[{4, 4, 4}, 10]}] &[Transpose[{m = Mod[#, 5], # - m} & /@ s]]

Note: Non-purchases (test case #1) are entered as f[{0}].
How it works

For each item, the greatest multiple of 5 less than the respective price will be paid  regardless of form of payment.  (No getting around that.)
The remainders of Mod[n, 5] are then processed:  1's and 2's become 0's.  Zeros stay unchanged.
Each pair {3, 4} -> {5}; afterwards each pair {3, 3} -> {5}; then the triple, {4,4,4}-> {10}, if applicable.
The remaining 4's, if any, remain unchanged (paid by credit card).
Original multiples of 5 summed with remainders that were tweaked (or not) in steps (2) to (4).

Testing
a12 adjusts for {3,3}
a13 adjusts for {4,4,4}
a1={0};
a2={48};
a3={92,20};
a4={47,56,45};
a5={55,6,98,69} ;
a6={6,39,85,84,7};
a7={95,14,28,49,41,39};
a8={92,6,28,30,39,93,53};
a9={83,33,62,12,34,29,18,12};
a10={23,46,54,69,64,73,58,92,26};
a11={19,56,84,23,20,53,96,92,91,58};
a12={3,3,19,56,3,84,3,23,20,53,96,92,91,58,3,3};
a13={2,3,4,4,4,4,4};

f /@ {a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13}

{0, 48, 110, 145, 225, 218, 263, 335, 273, 495, 583, 598, 19}

What about {3,3}?

@PeterTaylor.  Good point. It slipped by.

What about {4,4,4}?  I think with {3,4} -> {5}, {3,3} -> {5} and {4,4,4} -> {10} (in that order) it should give optimal answers.

@cardboard_box You are right! See update.

I added your additional test cases to the question.  The ones I had were generated randomly so those corner cases didn't show up.

APL, 58 characters
{a b c d←+/(⍳4)∘.=5|⍵⋄(+/⍵)-a-(⌊2÷⍨c-m)-2×b+m+⌊3÷⍨d-m←c⌊d}

The program is essentially a direct translation of Jan Dvorak's Ruby solution.

      {a b c d←+/(⍳4)∘.=5|⍵⋄(+/⍵)-a-(⌊2÷⍨c-m)-2×b+m+⌊3÷⍨d-m←c⌊d}⍬
0
      {a b c d←+/(⍳4)∘.=5|⍵⋄(+/⍵)-a-(⌊2÷⍨c-m)-2×b+m+⌊3÷⍨d-m←c⌊d}95 14 28 49 41 39
263
      {a b c d←+/(⍳4)∘.=5|⍵⋄(+/⍵)-a-(⌊2÷⍨c-m)-2×b+m+⌊3÷⍨d-m←c⌊d}19 56 84 23 20 53 96 92 91 58
583

⍬ is the empty vector.

Julia 83C
C=L->let
w,z,x,y=map(i->[i==x%5for x=L]|sum,1:4)
L|sum-(x+2w+3min(x,y)+4z)>>1
end

Explaination:
In one purchase, you can save 2 cent at most. So if you have a combination that can save you 2 cents, just buy it that way and it will be optimial. For example, if you have x items with price 3(mod 5) and y items with price 4(mod 5), you can make min(x, y) number of (3, 4) pairs, which save you 2 min(x, y) cents. Then you use the rest 3's, if any, to save you max(0, x-min(x,y)) / 2 cents. This can also be calculated by (max(x,y)-y)/2
w = sum(1 for p in prices if p % 5 == 1)
z = sum(1 for p in prices if p % 5 == 2)
x = sum(1 for p in prices if p % 5 == 3)
y = sum(1 for p in prices if p % 5 == 4)

ans = sum(prices) - (w + 2 z + 2 min(x, y) + div(max(x, y) - y, 2))
    = sum(prices) - (2w + 4z + 4 min(x, y) + x + y - min(x, y) - y) `div` 2
    = sum(prices) - (2w + 4z + 3 min(x, y) + x) `div` 2

Edit
This solution is wrong.

+1 for using a relatively unknown language that might be interesting to learn

It's a new language under active development. It combines many strengh from different languages. Hope that more people can known it.

The analysis isn't quite complete, because if you have 4 4 4 3 3 then 4 4 4 is a combination which can save 2 cents, but buying it that way isn't optimal. (In fact, you don't seem to be taking 4 4 4 into account at all. Doesn't this code fail the last test case?)


text:
Delete those pesky ".DS_Store" files
If you use OS X then you might be familiar with the infamous hidden ".DS_Store" files that are produced as a result of using Finder.
The challenge is to write code that will go through the entire file system and delete any file named ".DS_Store".
Classic code golf - shortest code wins.

Clarifications:

The code does not need to delete any .DS_Store files that require superuser; assume no such files exist.
The code should only delete the relevant .DS_Store files and nothing else.

And again a chameleon question.

@JohannesKuhn The latest edit should have been self-evident, I would assume. I added it for the sake of completeness. But I appreciate the clever answer, nonetheless!

@Joey — Transpose the question into the military domain — for example, hmm… the military of the USA, at random ^^ . And replace “file named ".DS_Store"” with “person to kill”. And you will see that the requirement “only” is far from being evident.

I’m voting to close this question because questions which ask for malicious code are off topic and the described task counts as malicious per our guidelines.

zsh, 19
rm -f /**/.DS_Store

(Make that 16 if it's ok to leave out -f.)

Bash*, 40 30
find / -name .DS_Store -delete

find / -name .DS_Store -exec rm -f {} \;

This should handle it (not very golfed, not.to.mention marvelously slow).
Bash seems right because we don't have to deal with any "import system" nonsense. If you want to require execution in any environment, add 4 chars for bash and 1 for a line feed.
*any shell I guess, just can't get out of the habit assuming the bourne again shell is the only one.

Bash is exactly the right tool for that.

What kind of find has OS X? With GNU find is even shorter: find / -name .DS_Store -delete.

Umm, find does have -delete yes. I guess that I assumed it wouldn't act as the -f option does with rm. After a test, it is most satisfactory--Cheers.

Subject to “Argument list too long” error and requires either bash 4 or newer with globstar shell option turned on, or zsh: rm /**/.DS_Store.

GNU bash, version 3.2.48 is what I am currently using courtesy of osx.6

You're not doing anything bash-specific, so it could as well be sh.

It removed my .DS_Store directory where I had important stuff.

@KonradBorowski Why would you name a directory .DS_Store, and expect a program explicitly designed to delete things named .DS_Store to not delete that directory?

Ruby: 38 33 characters
File.delete *Dir['/**/.DS_Store']

Dir[...] is a shortcut for Dir.glob(...), this will save you 5 chars.

Argh! I knew there is a shorter way, but I searched for it in Kernel. Thank you, @padde.

fish, 16
rm /**/.DS_Store

(Make that 19 if -f is required to delete .DS_Store in read-only directories.)

Shell, 25
locate .DS_Store|xargs rm

Requires working locate database.

Also requires paths without whitespace characters.

Python 3, 80 bytes
import os
d='.DS_Store'
for r,_,f in os.walk('/'):
 if d in f:os.remove(r+'/'+d)

Try it online!
By no means competable, but just for the sake of it :)

CMD, 17
del/s "/.DS_Store

Pretty straight-forward.
/s is required for searching within subdirectories as well.
" is used to escape the / char which would otherwise be interpreted as an (invalid) argument.

find, 38
The previus find solution is plain wrong: it's mean to delete everything named .DS_Store including directory, links, special file etc.
But:
find / -type f -name .DS_Store -delete

it's the minimal solution using find.
DISCLAMER: I strongly advice against really using this solution on a real *nix box: trying to delete something recursively from / is a very bad idea. You are warned.
EDIT :
If the differences among files, directorys, links (hard and symbolic), named pipes, sockets, special files, pseudo-file systems is not clear to you, I suggest to google some of this unknown terms. You'll be surprise, wiser, and less prone to (catstrofic) errors.
EDIT2 :
Even more relevant : the OP wrote "The code should only delete the relevant .DS_Store files and nothing else." : so, if someone care to read the boring requirements, all solutions that remove more than this files hare funny, smart, ect. but wrong.

The previous find solution is correct. The question says “delete any file named ".DS_Store"”. So no special requirement based on file type.

@ manatwork : nonsense: a file is a different thing from a directory. Along your twisted line, the best solution is still rm -rf /

and thanks for downvote me: you guys do it because you dont know the difference between a file and a directory or it's just because I'm unpleasant to you ?

@DavAlPi: Your solution won't delete named pipes, sockets, directories, and other special files. .DS_Store files are normally normal files though, so here's a +1 from me.

@ Evan: In a unix filesystem everthing is a file except directories, named pipe, sockets, and other special files that are NOT files. Try to google some of this unknown terms, you'll be surprise (and wiser).

oh, I forgot to mention file system links (hard and symbolic). But certainly by now you have googled etc. etc. :)

Ohh, you did not google: http://en.wikipedia.org/wiki/Everything_is_a_file

Ohh, and an other thing: In code golf the goal is to get the shortest solution, so if you can save a few chars by trating the requirements in your favor, well, so be it. You could save 8 chars by treating everything as file, like unix does. PS: where was the surprise? The fact that some people deny the basic UNIX principe?

Dear Johannes, the OP wrote "The code should only delete the relevant .DS_Store files and nothing else." : The requirements rules.

johannes, have a nice day :-)

Now I got a better answer , something that everyone here can understand.