text:
Write a program to print squares of integers up to 25 in java without using variables?
I asked this question  on programmers 10 days back but wasn't able to get the answer that I wanted.
Write program in java to print the squares of first 25 integers(1-25) without using any variables.
I am not looking for any theory explaining concepts about java or functional programming. I just want to know if its possible in java, the way the author has described in the original context.
--------Edit--------------------
Actually making it mutable variable makes it quite easy. The original context was

(take 25 (squares-of (integers)))
  Notice that it has no variables. Indeed, it has nothing more than three functions and one constant. Try writing the squares of integers in Java without using a variable. Oh, there’s probably a way to do it, but it certainly isn’t natural, and it wouldn’t read as nicely as my program above.

So try writing same program without using any variables.

Isn't it just a simple recursion? I don't know much Java, so I don't want to write a real solution, but something like printsq(from, to) { print(from*from); if (from < to) printsq(from+1, to); }

Strongly related to Implement a sorting algorithm with no change, and I continue to think the whole business displays a lack of deep understanding about what your computer is doing. Furthermore, you got answers on programmers that are completely equivalent to what a pure functional language does under the hood.

@dmckee: disagree. this is about code golf. you do it because it's fun and challenge. this is not about good design, but about creativity finding a solution to a problem that might or might not be useful to solve.

Ugly hack in 216 characters, this does not even use method args:
class M{static void m(){System.out.println((Thread.currentThread().getStackTrace().length-2)*(Thread.currentThread().getStackTrace().length-2));if(Thread.currentThread().getStackTrace().length-2<25)m();}static {m();}}

Formatted, this looks like:
class M {
    static void m()
    {
        System.out.println((Thread.currentThread().getStackTrace().length-2)*(Thread.currentThread().getStackTrace().length-2));
        if (Thread.currentThread().getStackTrace().length-2 < 25) m();
    }
    public static void main(String[] a)
    {
        m();
    }
    // We can comply fully with the question (no variables),
    // but then cannot avoid the "java.lang.NoSuchMethodError: main":
    static
    {
        m();
    }
}

For those who don't understand: It takes the stacks length squares it. This works because I'm recursively calling m(), always increasing the stack by 1. Maybe this could be written even shorter.

great job. finally a no variable answer !!

Obligatory cheat:
public class PrintTwentyFiveSquares {

    public static void main() {
        System.out.println("1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625");
    }

}

Haha nice one :)

How about this?
public class Squares {
    public static void printSquares(final int n) {
        if (n > 1) {
            printSquares(n - 1);
        }
        System.out.println(n * n);
    }

    public static void main(final String... args) {
        printSquares(25);
    }
}

Now that you completely changed the question, my solution depends on whether you consider function arguments to be variables or not. I'd say it still stands.
I should add that the Closure solution depends on the pre-availability of several functions in the standard library. The same functions could be written in Java, leading to a nearly identical main program:
import java.util.AbstractList;
import java.util.List;

public class Squares2 {
    public static List<Integer> integers() {
        return new AbstractList<Integer>() {
            @Override
            public Integer get(final int index) {
                return index + 1;
            }

            @Override
            public int size() {
                return Integer.MAX_VALUE;
            }
        };
    }

    public static List<Integer> squaresOf(final List<Integer> l) {
        return new AbstractList<Integer>() {
            @Override
            public Integer get(final int index) {
                return l.get(index) * l.get(index);
            }

            @Override
            public int size() {
                return l.size();
            }
        };
    }

    public static List<Integer> take(final int n, final List<Integer> l) {
        return l.subList(0, n);
    }

    public static void main(final String... args) {
        System.out.println(take(25, squaresOf(integers())));
    }
}

Besides, it looks like you already received plenty of good answers on "programmers", discussing all the aspects of the problem. Not sure what else you are looking for.

I am only interested in knowing if its remotely possible to do so without using variables as it is claimed by the author. Maybe be some kind of hack or cheat or maybe something else. I never thought it was possible to write a java program without using main method. Its possible actually.

Well, you have 3 different solutions here (so far), all without using variables. Take your pick.


text:
Output code-sized Lorem Ipsum
Output the same length of Lorem ipsum your code is!
Rules:

Code can't be identical to output
No compression libraries
Shortest program in two weeks wins
No network usage, file reading and other tricks which with one could easily solve any code golf problem (with eval, exec, etc)

Example
Your code with length 25.

Output
Lorem ipsum dolor sit ame

I don't think the lorem ipsum placeholder text is standardized.  What if our program is longer than the provided example?  Should it simply repeat from the beginning again?

@GigaWatt I provided an 1000+ character long text as link. If that's not enough then repeat.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer nunc augue, feugiat non, egestas ut, rutrum eu, purus. Vestibulum condimentum commodo pede. Nam in metus eu justo commodo posuere. Nunc varius dui id nulla. Fusce porttitor pretium leo. Quisque in diam. Nulla pellentesque. Donec vitae urna et arcu lobortis varius. Aenean velit eros, varius ac, semper sit amet, lacinia eget, sem. Phasellus mollis nunc a pede cursus fermentum. Proin et odio. Nullam turpis. Fusce eget arcu. Mauris placerat ultricies lectus. Nullam pede nisl, ullamcorper ullamcorper, hendrerit sit amet, molestie

If we're not allowed to use network/language built-ins/compression, how are we supposed to generate information that's at least as long as the program?  That's almost like pulling info out of thin air.

@GigaWatt compression (assuming it doesn't have to be dynamic in length)

@GigaWat Self made compression would be the desired way. Dynamic length doesn't need.

Is it ok to output extra characters, as long as the first n are correct? (n = source size)

@aditsu No, you can't output extra characters.

GolfScript (122 or 138 bytes)
There seems to be a very small ambiguity in the rules: what precisely does "output" mean? Many programs assume that the "output" of a program doesn't include a final newline, which is there to ensure that the next line of the shell input begins on a separate line.
00000000  27 80 38 6e df 07 55 f7  a7 8f c0 42 9d dc 1e e7  |'.8n..U....B....|
00000010  7d 48 9a 88 79 03 92 c1  fb ed 8a af 51 92 52 24  |}H..y.......Q.R$|
00000020  2c b7 0b 17 d4 eb dc b0  d8 ce 8c 82 0f 94 0d 18  |,...............|
00000030  42 71 58 8a dd e6 b9 70  9b 48 74 f5 f0 70 c2 bb  |BqX....p.Ht..p..|
00000040  e0 5b 1d e1 f2 a7 29 3e  87 b4 f0 4d 3a 22 5c 71  |.[....)>...M:"\q|
00000050  55 3d d1 fd 77 12 e2 52  73 24 89 00 9b c3 e5 47  |U=..w..Rs$.....G|
00000060  0c b4 17 1a 27 32 35 36  62 61 73 65 20 39 30 62  |....'256base 90b|
00000070  61 73 65 7b 33 32 2b 7d  25 2b                    |ase{32+}%+|
0000007a

is 122 bytes and outputs 122 bytes of lorum ipsum and a trailing newline.
00000000  27 75 24 b6 ac 4e 36 10  aa 62 7f 2b 35 67 cc ee  |'u$..N6..b.+5g..|
00000010  c2 fa d4 9a 7a 54 96 e9  f0 0b 38 58 63 79 97 f8  |....zT....8Xcy..|
00000020  d5 7e 8a bc 4e e6 9b ee  88 ed f0 87 b5 9e 78 8c  |.~..N.........x.|
00000030  ff 4e ac 59 49 d5 71 f1  94 51 f5 4e 6a 58 57 24  |.N.YI.q..Q.NjXW$|
00000040  f6 4a 07 40 d6 06 bb a3  34 55 8d 83 aa ce d4 41  |.J.@....4U.....A|
00000050  46 04 26 c7 ef e2 f7 00  a2 61 a9 d2 40 8c 00 d9  |F.&......a..@...|
00000060  78 9a a7 53 d6 ea 85 16  23 fd c6 2c 8d a6 cb 09  |x..S....#..,....|
00000070  0a 27 32 35 36 62 61 73  65 20 39 30 62 61 73 65  |.'256base 90base|
00000080  7b 33 32 2b 7d 25 2b 3a  6e 3b                    |{32+}%+:n;|
0000008a

is 138 bytes and produces 138 bytes of lorum ipsum with no trailing newline.

Or.. you could count the newline as part of the output, and print 1 less byte of lorem ipsum

@aditsu, I considered that possibility too and reckoned it was fairly unambiguous that it would count as cheating.

rot13 (1)
i'm surprised nobody came up with this before :)
Y

and as a bonus, a very simple perl solution
Perl (252)
s//LoremIpsumDolorSitAmet,ConsectetuerAdipiscingElit,SedDiamNonummyNibhEuismodTinciduntUtLaoreetDoloreMagnaAliquamEratVolutpat. UtWisiEnimAdMinimVeniam,QuisNostrudExerciTationUllamcorperSuscipitLobortisNislUtAliquipExE/;s,([^ ])([A-Z]),$1$"\l$2,g;print

Nice perl solution. A trivial 49 byte improvement: ...ExerciTationU/;s,\S\K[A-Z], \l$&,g;print

Better still for 196 bytes: print'LoremIpsumDolor...NostrudExerciT'=~s,\S\K[A-Z], \l$&,gr

Is rot13 a programming language? :)
Also based on this idea I modify the minimum codelength to be positive...

Well, code length of 1 is positive :)

I don't think it's a very simple perl solution any longer.

Golfscript - 161
Edit: python solution output a different length than its own, so I did a better one with golfscript.  This is also my first golfscript answer.
[' ,.LUabcdeghilmnopqrstuvwy''zä{~4ú›Úˆ2©JfÖØélq¤öäpDÎ;bÐô(;ÆXÔZo´dZ]e§B¥×ûba(šX†Cf½ÇUÃ0~3i‰d<Ú{¡º¯ŠÛ„å4B9W}˜$ûã–'{1-}%255base{.26%@.@=\@26/.}do;;]''+

I'm not sure how this is encoded here, so here is a link to the file.

I'm getting 363 bytes code, 362 bytes output

Fixed.  Also switched languages.

I'd ask you to post it separately, but instead I might use your ideas to improve my python solution :)

Mathematica, 8
I make the assumption that visually identical output is acceptable.  I therefore use this character in place of ASCII "i" which causes the two Symbols to be automatically sorted in the correct order:
іp*Lorem

Lorem іp

Don't make assumptions. I don't think this is valid.

Python 2 - 332
print''.join([x,'tmoi eiidoqa  ua  lde  rsernponutsatmnci  '[ord(x)%21::21]]['.'<x<'D']for x in'LAe@1su@2lA6i?9et,;3sectetu/7d1Bc0gC<t,6e=di9:3ummy:ibhCuBmo=t0cidun?8 laAee?2lA>magna7<49Cr5 vol8p5. U?wBiCni@a=m0i@veni9, 4B:ostru=ex/ci t5i3 ull9cAp/6usc1i?lobAtB:Bl 87<41CxCa;ommo2;3se45. DuB78e@velCu@iriur>2lA 0 hendr/i?0 vulp85>')

If anybody cares, here's a partial list of improvements:
1181 -> 630 -> 549 -> 510 -> 456 -> 416 -> 381 -> 332

Bash, 156
Because using a real "compression library" is forbidden, I'll abuse base64 from coreutils instead. (xxd -r to decode submission)
0000000: 7461 696c 202d 3120 2430 7c62 6173 6536  tail -1 $0|base6
0000010: 3420 2d77 307c 7472 2058 595a 205c 202c  4 -w0|tr XYZ \ ,
0000020: 2e0a 6578 6974 0a2e 8ade 9978 a9b2 e997  ..exit.....x....
0000030: 7689 68ad 7b22 b576 a67a d617 7289 ec79  v.h.{".v.z..r..y
0000040: cb5e b6e7 ab5d a762 a62b 1c8a 7817 7a58  .^...].b.+..x.zX
0000050: ad61 7b1e 7577 626a 65e7 a27b a69b 25e7  .a{.uwbje..{..%.
0000060: 89b8 577a e8ac 9a87 57b6 29dc 89db a7b5  ..Wz....W.).....
0000070: 7bad 5e56 a8ad e7ad 5dda 25a2 b797 99a8  {.^V....].%.....
0000080: 2769 76a5 8aab 9a99 77ab 6ad5 efa2 5bad  'iv.....w.j...[.
0000090: a5ab 595d 4b57 c22b 225d e9e2            ..Y]KW.+"]..

I generated the above code using this PHP program:
<?php

$lorem = '<text here>';

$enclorem = base64_decode( strtr( $lorem, ' ,.', 'XYZ' ) );

$prog = "tail -\$3 \$0|base64 -w0|tr XYZ \\ ,.\nexit\n$1";

for ( $i = 0, $n = strlen( $lorem ); $i < $n; $i++ ) {
    $cutlorem = substr( $lorem, 0, $i );
    for ( $j = 0, $o = strlen( $enclorem ); $j < $o; $j++ ) {
        $cutenclorem = substr( $enclorem, 0, $j );
        if ( substr( strtr( base64_encode( $cutenclorem ), 'XYZ', ' ,.' ), 0, $i )  === $cutlorem ) {
            break;
        }
    }
    $out = strtr( $prog, array(
        '$1' => $cutenclorem,
        '$2' => $i,
        '$3' => substr_count( $cutenclorem, "\n" ) + 1,
    ) );
    echo "\$i=$i strlen(\$out)=" . strlen( $out ) . "\n";
    if ( $i === strlen( $out ) ) {
        break;
    }
}

echo "\nHexdump:\n";
$p = popen( 'xxd', 'w' );
fwrite( $p, $out );
pclose( $p );

echo "\nFinal output check: ";
$tmp = tmpfile();
fwrite( $tmp, $out );
$md = stream_get_meta_data( $tmp );
ob_start();
passthru( 'bash ' . escapeshellarg( $md['uri'] ) );
$buf = rtrim( ob_get_clean() );
echo $buf === substr( $lorem, 0, strlen( $out ) ) ? 'PASS' : 'FAIL', "\n$buf\n";

Isn't base64 some sort of compression utility? Also, I think you violate "no file reading" - you ceratainly read a file (the program itself), similarly to the "quine" cat $0.

Mathematica 47 46 44
With 2 bytes saved thanks to Imanton1
Not sure if this is fair play. Mathematica has the 'full' text of Lorem ipsum in its example data. The following simply tells Mathematica to take a string of a particular length from the built-in example of Lorem Ipsum.
#@#["Text"][[19]]&@ExampleData~StringTake~44

"Lorem ipsum dolor sit amet, consectetuer adi"

Windows batch, 878 720
Tested on Windows XP and Windows 7, but should work for every cmd with extensions (IIRC, Windows NT and later).
Has to be run using CMD /V:ON /C batchfile to turn on delayed variable extension, but I prefer that to having non codegolf friendly SETLOCAL EnableDelayedExpansion inside the batch file.
@ECHO OFF
SET A=Lore2ipsu21 si0amet,6ctetu7 adip3cing4lit, sed dia2nonummy nibh4u3mod tincidun0u0laoree018magna aliqua27a0volutpat. U0w3i4ni2ad mini2veniam, qu3 nostrud4x7ci tation ullamcorp7 suscipi0lobort3 n3l u0aliquip4x4a commodo6quat. Du3 aute2vel4u2iriur81 in hendr7i0in vulputat8veli0ess8molestie6quat, vel illu21e4u feugia53 a0v7o4ros40accumsan40iusto odio dign3si2qui blandi0praesen0luptatu2zzril deleni0augu8du3 18t8feugai5i. Na2lib7 tempor cu2soluta nob34leifend option congu8nihil imp7die0doming id quod mazi2plac7a0fac7 possi2assum. Typi non haben0claritate2insitam;4s0usus legent3
FOR %%I IN ("8=e ","7=er","6= conse","5=0nulla facil3","4= e","3=is","2=m ","1=dolor","0=t ") do SET "A=!A:%%~I!"
ECHO %A%

J (144)
Would've been 128 if I hadn't needed to make it a proper script so you can measure the output.
exit[stdout'utsrponmligfedcbaVLI., '{~#._5>\,#:a.i.'�F��$f����`kg�c������$NI�f!!��`�L�:����l���5l�0A����Fـ���T�X ��@g�I�`��'

How it works: there are only 23 unique characters in the text, so this can be represented in a 5-byte encoding. The characters in the encoded string are converted to their ASCII numbers (a.i.), then each of the numbers is turned into their base-2 representation (#:), then the bits are grouped in groups of five (_5>\,), then each of these groups is converted to its value (#.), and these are used as an index into the lookup table. ({~).
The lookup table actually needed some tinkering, because a J string literal cannot contain \n, \r or \0.
Hexdump:

0000000: 7865 7469 735b 6474 756f 2774 7475 7273
0000010: 6f70 6d6e 696c 6667 6465 6263 5661 494c
0000020: 2c2e 2720 7e7b 2e23 355f 5c3e 232c 613a
0000030: 692e 272e 4691 d9c3 1024 660f 0595 841d
0000040: da90 6007 676b c214 8263 81c0 b483 921a
0000050: 4e24 9549 2166 a521 60a6 4cb1 8c1d 3a03
0000060: 02d0 ca80 6cd9 9302 d800 35c5 c56c 4130
0000070: ac80 d600 00c3 0346 80d9 88ad 8001 b454
0000080: 2058 e0a5 0f40 1467 49cd 60d8 e080 0a27

You can compress the lookup table e.g. ('VLI., ',97}.a.) in some way it doesn't mess up the other literal.

05AB1E, 12 bytes
.•ÿ₆∊ÃÌ¦R•.ª

Try it online!
.•ÿ₆∊ÃÌ¦R•.ª  # full program
.•ÿ₆∊ÃÌ¦R•    # "lorem ipsum "...
          .ª  # in sentence case
              # implicit output

LaTeX + lipsum, 125 bytes
\documentclass[12pt]{article}
\usepackage{lipsum}
\pagenumbering{gobble}
\begin{document}
    \lipsum[1][1-2]
\end{document}

Output:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis.

FEU, 545 bytes
a/Lorem ipsum dolor sit amet!consectetuer adipiscing elit. Integer nunc augue!feugiat non!egestas ut!rutrum eu!purus. Vestibulum condimentum commodo pede. Nam in metus eu justo commodo posuere. Nunc varius dui id nulla. Fusce porttitor pretium leo. Quisque in diam. Nulla pellentesque. Donec vitae urna et arcu lobortis varius. Aenean velit eros!varius ac!semper sit amet!lacinia eget!sem. Phasellus mollis nunc a pede cursus fermentum. Proin et odio. Nullam turpis. Fusce eget arcu. Mauris placerat ultricies lectus. Nullam pede nisl!u
s/!/, /g

Try it online!
It just so happened to work.

Vyxal, 5 bytes
`Lo≥›

Try it Online!

Perl 5 + -M5.10.0, 35 bytes
If anything that starts Lorem ipsum is acceptable this should work:
say"\u@{[<'{,do}lor{em ipsum,}'>]}"
Try it online!

Perl 5 + -M5.10.0, 42 bytes
However if it needs to start Lorem ipsum dolor sit amet, you'll need this:
$}=" dolor sit ame";say"Lorem ipsum$}t,$}"
Try it online!

Perl 5 + -M5.10.0, 72 bytes
But, if it needs to start Lorem ipsum dolor sit amet, consectetur adipiscing elit., then I think this is the shortest I can manage:
$}="Lorem ipsum do";say"$}lor sit amet, consectetur adipiscing elit. $}"
Try it online!

source: Stack Exchange

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

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

sort: votes


text:
Generate a number by using a given list of numbers and arithmetic operators
You are given a list of numbers L = [17, 5, 9, 17, 59, 14], a bag of operators O = {+:7, -:3, *:5, /:1} and a number N = 569.
Task
Output an equation that uses all numbers in L on the left-hand side and only the number N on the right-hand side. If this is not possible, output False.  Example solution:
59*(17-5)-9*17+14 = 569

Limitations and Clarification

You may not concatenate numbers ([13,37] may not be used as 1337)
Only natural numbers and zero will appear in L.
The order in L doesn't matter.
You must use all numbers in L.
Only the operators +,-,*,/ will appear in O.
O can have more operators than you need, but at least |L|-1 operators
You may use each operator any number of times up to the value in O.
All four operations in O are the standard mathematical operations; in particular, / is normal division with exact fractions.

Points

The less points, the better
Every character of your code gives you one point

You have to provide an un-golfed version that is easy to read.
Background
A similar question was asked on Stack Overflow. I thought it might be an interesting code-golf challenge.
Computational Complexity
As Peter Taylor said in the comments, you can solve subset sum with this:

You have an instance of subset sum (hence a set S of integers and a number x)
L := S + [0, ..., 0] (|S| times a zero), N := x, O := {+:|S|-1, *: |S| - 1, /:0, -: 0}
Now solve this instance of my problem
The solution for subset sum is the numbers of S that don't get multiplied with zero.

If you find an Algorithm that is better than O(2^n), you prove that P=NP. As P vs NP is a Millennium Prize Problem and hence worth 1,000,000 US-Dollar, it is very unlikely that somebody finds a solution for this. So I removed this part of the ranking.
Test cases
The following are not the only valid answers, other solutions exist, and are permitted:

([17,5,9,17,59,14], {+:7, -:3, *:5, /:1}, 569)
=> 59 * (17-5)- 9 * 17 + 14 = 569
([2,2], {'+':3, '-':3, '*':3, '/':3}, 1)
=> 2/2 = 1
([2,3,5,7,10,0,0,0,0,0,0,0], {'+':20, '-':20, '*':20, '/':20}, 16)
=> 5+10-2*3+7+0+0+0+0+0+0+0 = 16
([2,3,5,7,10,0,0,0,0,0,0,0], {'+':20, '-':20, '*':20, '/':20}, 15)
=> 5+10+0*(2+3+7)+0+0+0+0+0+0 = 15

Is m = |L|?  If yes, how can you expect the runtime to not depend on the size of that list?  For example, [2,2],[+,+,...,+,/],1.  In fact, since n is O(m), you might just write it all in terms of m.

What kind of arithmetic is this to use – exact fractionals, integer (/ ≡ div), just floating-point and hope-for-no-rounding-errors, ...?

Why the complicated scoring rules for computational complexity? There's an easy reduction from subset-sum, so anything better than O(2^n) is worth a million USD.

@moose, I mistyped -- I meant "Is m = |O|?".  As you affirm, my example (m-1 useless operators followed by one useful operator) shows that the problem is at least O(m): you can fix n and still make the runtime go off to infinity.

@PeterTaylor: Thanks, I didn't see it. I've removed this part of the ranking and added an explanation.

Though I'd imagine this could actually be done in subexponential time with extra constraints to prevent "degenerate" cases like || times a zero. But that would probably be really complicated, so...

Related: http://stackoverflow.com/questions/3947937/algorithm-for-permutations-of-operators-and-operands/3948113#3948113

@belisarius  Why don't you adapt your prior solution to the challenge at hand?  At the very least it will provide an instructive look at how to avoid parentheses (through reverse Polish notation).

@DavidCarraher I'll try. Need some spare time to do it :(

3rd test case is not False... 5+10+2*3+7*0+0...

It looks like the combination of 0,2,3,5,7,10 (with no practical restriction on operators) can actually generate quite a few numbers (pretty sure every whole number below 30, though I've only been doing the math in my head)

@DavidCarraher I found that any short enough answer is too inefficient to be used with the  OP's testcases.

Python 2.7 / 478 chars
L=[17,5,9,17,59,14]
O={'+':7,'-':3,'*':5,'/':1}
N=569
P=eval("{'+l+y,'-l-y,'*l*y,'/l/y}".replace('l',"':lambda x,y:x"))
def S(R,T):
 if len(T)>1:
  c,d=y=T.pop();a,b=x=T.pop()
  for o in O:
   if O[o]>0 and(o!='/'or y[0]):
    T+=[(P[o](a, c),'('+b+o+d+')')];O[o]-=1
    if S(R,T):return 1
    O[o]+=1;T.pop()
  T+=[x,y]
 elif not R:
  v,r=T[0]
  if v==N:print r
  return v==N
 for x in R[:]:
  R.remove(x);T+=[x]
  if S(R,T):return 1
  T.pop();R+=[x]
S([(x,`x`)for x in L],[])

The main idea is to use postfix form of an expression to search. For example, 2*(3+4) in postfix form will be 234+*. So the problem become finding a partly permutation of L+O that evalates to N.
The following version is the ungolfed version. The stack stk looks like [(5, '5'), (2, '5-3', (10, ((4+2)+(2*(4/2))))].
L = [17, 5, 9, 17, 59, 14]
O = {'+':7, '-':3, '*':5, '/':1}
N = 569

P = {'+':lambda x,y:x+y,
     '-':lambda x,y:x-y,
     '*':lambda x,y:x*y,
     '/':lambda x,y:x/y}

def postfix_search(rest, stk):
    if len(stk) >= 2:
        y = (v2, r2) = stk.pop()
        x = (v1, r1) = stk.pop()
        for opr in O:
            if O[opr] > 0 and not (opr == '/' and v2 == 0):
                stk += [(P[opr](v1, v2), '('+r1+opr+r2+')')]
                O[opr] -= 1
                if postfix_search(rest, stk): return 1
                O[opr] += 1
                stk.pop()
        stk += [x, y]
    elif not rest:
        v, r = stk[0]
        if v == N: print(r)
        return v == N
    for x in list(rest):
        rest.remove(x)
        stk += [x]
        if postfix_search(rest, stk):
            return True
        stk.pop()
        rest += [x]
postfix_search(list(zip(L, map(str, L))), [])

Wow, that's shorter than I've expected. I have scribbled an algorithm which included a conversion postfix<=>infix, but my scribble wasn't much shorter than your implementation. Impressing. And thanks for the construction P[opr](v1, v2). I never thought of combining lambdas and dictionaries like this, although it seems obvious now.

I've tried to test your solution with my 4rd testcase. After 2h, I stopped the execution.

@moose I'll try to add some heuristic to make it faster. But after that the code length may double.

Using Fraction like I did here fixes a problem in your answer. Just try it for the given instance on the link I've provided. Your current code doesn't find an answer, but when you use fraction it does.

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


text:
Group adjacent values
The task is to group adjacent values from collection and output it as a new aggregated collection.
Consider we have following input:

Sequence
Number      Value
========    =====
1           9
2           9
3           15
4           15
5           15
6           30
7           9

The aim is to enumerate over Sequence Numbers and check if the next element has the same value. If yes, values are aggregated and so, desired output is as following:

Sequence    Sequence
Number      Number
From        To          Value
========    ========    =====
1           2           9
3           5           15
6           6           30
7           7           9

Build a code with following assumptions:

Sequence Numbers are already ordered in input table.
There can be gaps in Sequence Numbers. If input contains gaps, output should contain gaps too. For example input 1 99\n2 99\n4 99\n6 99, output will be 1 2 99\n4 4 99\n6 6 99.
Assume Value is type of integer.
It can be a full program or just a function.
This cruft (Sequence Sequence\n ... ======== ======== =====\n) is not a part of output. Output format is not defined; there should be a delimeter between values and between rows, so anyone can distinguish values and rows.

It's an extend of my StackOverflow question: https://stackoverflow.com/questions/14879197/linq-query-data-aggregation.

Should it be a full program with input/output or just a function?

Is all that cruft at the top (Sequence    Sequence\n ... ========    ========    =====\n) part of the expected input and output? If not, can you please specify the expected formats?

@grc: I precised rules, thank you.

@dmckee: As above, I precised question, thx.

Regarding possible gaps in the sequence numbers: should the output also contain gaps? What would the desired output for "1 99\n2 99\n4 99\n6 99" be?

@Howard: Yes, output should also contain gaps as there must be continuity on Sequence Number; so for your input it will be: 1 2 99\n4 4 99\n6 6 99.

What is the format of the input? If we're talking about a function, then can it take a data structure directly (in languages where that is applicable)? Can it also return a data structure?

@aditsu: There are no restrictions oninput/output format

K, 43 38
{d:(x;0N,x;y)@\:&~~':y;d[1]:(1_d 1),*|x;+d}
{a::*|x;+@[(x;{x,a};y)@\:&~~':y;1;1_]}

.
k){a::*|x;+@[(x;{x,a};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9
3 5 15
6 6 30
7 7 9

Explanation
The function takes two vectors, x and y, as input
a::*|x takes the last value of x and assigns it to a.
&~~':y returns a list of indices where the y vector changes:
k){&~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
0 2 5 6

(x;{x,a};y) creates a three element list containing
1) the x vector,
2) the function {x,a} which takes an input variable x(not to be confused with the x vector which was input into the original function) and appends a, and
3) the y vector
(x;{x,a};y)@\:&~~':y takes this three element list and applies the indices to each element
so that we return the x vector at those indices, the indices with a appended, and the y vector at those indices
k){b::*|x;(x;{x,b};y)@\:&~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3 6 7
0 2 5 6 7
9 15 30 9

@[(x;{x,a};y)@\:&~~':y;1;1_] takes the matrix we've created and drops the first element of the second row.
k){b::*|x;@[(x;{x,b};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3  6  7
2 5  6  7
9 15 30 9

+ then transposes the result
k){b::*|x;+@[(x;{x,b};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9
3 5 15
6 6 30
7 7 9

Would you kindly explain how it works?

Mathematica, 40 47 / 40
Updated to handle the new rules:
#~Riffle~{##}[[-1,1]]&@@@Split[#,#2-#=={1,0}&]&

Example of use:
#~Riffle~{##}[[-1,1]]&@@@Split[#,#2-#=={1,0}&]& @
  {{1, 9}, {2, 9}, {3, 9}, {4, 15}, {5, 15}, {6, 30}, {7, 9}, {12, 9}}

{{1, 3, 9}, {4, 5, 15}, {6, 6, 30}, {7, 7, 9}, {12, 12, 9}}

Or, since "There are no restrictions on input/output format":
#[[1,1]]|Last@#&/@Split[#,#2-#=={1,0}&]&

Which when used as above outputs:

{1 | {3, 9}, 4 | {5, 15}, 6 | {6, 30}, 7 | {7, 9}, 12 | {12, 9}}

Perhaps you can explain the magic of the left hand side, #~Riffle~{##}[[-1, 1]] & @@@.  (I already explained what SplitBy does.)

Does it consider the gaps as required? Try d = {{1, 9}, {3, 9}, {4, 15}, {5, 15}, {6, 30}, {7, 9}}

@belisarius there, now it does.

Ok, +1 then. Nice hack

J, 53 48 43
Explicit version (43 chars):
f=.4 :'|:(#&y,{.@:#&x)(1&,,:,&1)2(-.@=/\)x'

Tacit version (48 chars):
(|:@((#{.)~,{.@]#{:@[)[:(1&,,:,&1)2&(-.@=/\)@{:)

Ungolfed version:
(|:@(({.@[#~]),{:@[#~{.@])((1&,),:,&1)@(-.@(0&=)@(2&(-/\)@{:)))

Maybe not the best way, but had a lot of fun golfing it down.
   1 2 3 4 5 6 7 f 9 9 15 15 15 30 9
   or
   (...) 1 2 3 4 5 6 7,:9 9 15 15 15 30 9
1 2  9
3 5 15
6 6 30
7 7  9

JavaScript, 106
function(c){for(var n={f:1,t:1,v:c[0]},r=[n],i=1,t;t=c[i++];)t^n.v?r.push(n={f:i,t:i,v:t}):n.t++;return r}

If input as a global called c is okay, then 101:
eval.bind(0,'for(var n={f:1,t:1,v:c[0]},r=[n],i=1,t;t=c[i++];)t^n.v?r.push(n={f:i,t:i,v:t}):n.t++;r')

Python, 86
n=input()
for s,v in n:
 i=1
 while[s+i,v]in n:n.remove([s+i,v]);i+=1
 print s,s+i-1,v

SyntaxError: unexpected EOF while parsing

Nevermind, I figured out how to run it (same as my answer)

APL 39
(p/n),((1⌽p)/n←⍎⍞),[1.1](p←1,2≠/v)/v←⍎⍞

The above takes screen input as the function runs via ←⍎⍞. If the vectors n and v are allowed to be predefined globals then the count reduces to 33:
(p/n),((1⌽p)/n),[1.1](p←1,2≠/v)/v

For n←1 2 3 4 5 6 7 and v←9 9 15 15 15 30 9
1 2  9
3 5 15
6 6 30
7 7  9

Python 2 - 82
r=p=[]
for x,y in input():
 if[x-1,y]==p[1:]:p[1]=x
 else:p=[x,x,y];r+=[p]
print r

Example usage:
echo "[[1,9],[2,9],[3,15],[4,15],[5,15],[6,30],[7,9]]"|python2 values.py
[[1, 2, 9], [3, 5, 15], [6, 6, 30], [7, 7, 9]]
echo "[[1,99],[2,99],[4,99],[6,99]]"|python2 values.py
[[1, 2, 99], [4, 4, 99], [6, 6, 99]]

Golfscript - 42
~(~@@.@{.~5$=\3$)=&{;)}{:*;@]p*~\.}if}/@]p

Examples:
echo "[[1 9][2 9][3 15][4 15][5 15][6 30][7 9]]"|ruby golfscript.rb values.gs
[1 2 9]
[3 5 15]
[6 6 30]
[7 7 9]

echo "[[1 99][2 99][4 99][6 99]]"|ruby golfscript.rb values.gs
[1 2 99]
[4 4 99]
[6 6 99]

Explanation:
It takes the first pair [a b], and puts b, a, a1=a and the rest of the array on the stack. Then for each pair [x y] it compares y with b and x with a1+1. If equal then discards [x y] and increments a1, else pops and remembers [x y], prints [a a1 b] and pushes y, x, x1=x. At the end it prints the last [x x1 y].

GolfScript, 49/44 characters
~]2/{\.@.@~@~@=@@-)!&!{n\}*}*][n]%{.0=0=\-1=~]p}%

The solution takes input from STDIN and prints to STDOUT. If you transform the code into an expression working on lists it reduces to 44 characters.
{\.@.@~@~@=@@-)!&!{n\}*}*][n]%{.0=0=\-1=~]}%

Example:
1 9
2 9
3 15
4 15
5 15
6 30
7 9

[1 2 9]
[3 5 15]
[6 6 30]
[7 7 9]

This version does also work with gaps as required.
1 9
3 9
4 15
6 15
7 15

[1 1 9]
[3 3 9]
[4 4 15]
[6 7 15]


text:
Implement an IEEE 754 64-bit binary floating point number through integer manipulation
(I've tagged the question "C" for the time being, but if you're aware of another language that supports unions, you can also use that.)
Your task is to build the four standard mathematical operators + - * / for the following struct:
union intfloat{
    double f;
    uint8_t h[8];
    uint16_t i[4];
    uint32_t j[2];
    uint64_t k;
    intfloat(double g){f = g;}
    intfloat(){k = 0;}
}

such that the operations themselves only ever manipulate or access the integer part (so no comparing with the double anytime during the operation either), and the result is exactly the same (or functionally equivalent, in the case of non-numeric results such as NaN) as if the corresponding mathematical operation had been applied straight to the double instead.
You may choose which integer part to manipulate, perhaps even using different ones among different operators. (You can also choose to remove the "unsigned" from any of the fields in the union, although I'm not sure whether you'd want to do that.)
Your score is the sum of the length of code in characters for each of the four operators. Lowest score wins.
For those of us unfamiliar with the IEEE 754 specification, here is an article about it on Wikipedia.

Edits:
03-06 08:47 Added constructors to the intfloat struct. You are allowed to use them for testing, rather than manually setting the double / etc.

Yikes! Tell me you have a solution.

I'll come up with one eventually. It'll be ungolfed and act as a last-place example entry.

Hmmm...perhaps it would be better to define intstruct in terms of uint8_8, uint16_t and so on as the absolute sizes of short, int and so on are not defined by the standard (each type has a minimum size and there is a strict ordering in size, but that's it).

I guess that this a great (and challenging) practice even if ungolfed

This question could use documentation of how rounding is handled and a good test suite.

Do we need full IEEE-754 compliance, e.g. proper handling of INF, NAN, denormals, etc ?

@dmckee: Noted. I'll change them to their fixed bit sizes.

@PeterTaylor Rounding documentation is probably in IEEE 754 (I believe most computers will round half to even). As for a test suite, that's a good question. I'm not sure how I'd go about writing that.

@PaulR Yes, if the C/C++ compiler will do the same.

I'm sure it is in the spec, but the real spec is going to cost a few hundred USD. There are probably descriptions which are available for free, but IMO the onus should be on the question-asker to include that kind of details (or at least a link to a site which is likely to still be around in a couple of years) within the question rather than on the answerers to go searching themselves for the necessary materials to know what the question actually wants.

Understood. In that case, you'll have to wait a while because I need to go looking for a spec. I've been relying on the Wikipedia article.

I'm currently creating the reference implementation. It's harder than it looks :S

C++, ~1500 chars
Expands the floats into an 8000-binary-digit fixed-point representation, does the operations on that, then converts back.
// an "expanded" float.
// n is nan, i is infinity, z is zero, s is sign.
// nan overrides inf, inf overrides zero, zero overrides digits.
// sign is valid unless nan.
// We store the number in fixed-point, little-endian.  Binary point is
// at N/2.  So 1.0 is N/2 zeros, one, N/2-1 zeros.
#define N 8000
struct E {
  int n;
  int i;
  int z;
  long s;
  long d[N];
};
#define V if(r.n|r.i|r.z)return r
// Converts a regular floating-point number to an expanded one.
E R(F x){
  long i,e=x.k<<1>>53,m=x.k<<12>>12;
  E r={e==2047&&m!=0,e==2047,e+m==0,x.k>>63};
  if(e)m+=1L<<52;else e++;
  for(i=0;i<53;i++)r.d[2925+e+i]=m>>i&1;
  return r;
}
E A(E x,E y){
  int i,c,v;
  if(x.s>y.s)return A(y,x);
  E r={x.n|y.n|x.i&y.i&(x.s^y.s),x.i|y.i,x.z&y.z,x.i&x.s|y.i&y.s|~x.i&~y.i&x.s&y.s};V;
  if(x.s^y.s){
    c=0;
    r.z=1;
    for(i=0;i<N;i++){
      v=x.d[i]-y.d[i]-c;
      r.d[i]=v&1;c=v<0;
      r.z&=~v&1;
    }
    if(c){x.s=1;y.s=0;r=A(y,x);r.s=1;}
  }else{
    c=0;
    for(i=0;i<N;i++){
      v=x.d[i]+y.d[i]+c;
      r.d[i]=v&1;c=v>1;
    }
  }
  return r;
}
E M(E x, E y){
  int i;
  E r={x.n|y.n|x.i&y.z|x.z&y.i,x.i|y.i,x.z|y.z,x.s^y.s};V;
  E s={0,0,1};
  for(i=0;i<6000;i++)y.d[i]=y.d[i+2000];
  for(i=0;i<4000;i++){
    if(x.d[i+2000])s=A(s,y);
    y=A(y,y);
  }
  s.s^=x.s;
  return s;
}
// 1/d using Newton-Raphson:
// x <- x * (2 - d*x)
E I(E d){
  int i;
  E r={d.n,d.z,d.i,d.s};V;
  E t={};t.d[4001]=1;
  for(i=N-1;i>0;i--)if(d.d[i])break;
  E x={0,0,0,d.s};x.d[N-i]=1;
  d.s^=1;
  for(i=0;i<10;i++)x=M(x,A(t,M(d,x)));
  return x;
}
// Convert expanded number back to regular floating point.
F C(E x){
  long i,j,e,m=0;
  for(i=N-1;i>=0;i--)if(x.d[i])break;
  for(j=0;j<N;j++)if(x.d[j])break;
  if(i>0&x.d[i-53]&(j<i-53|x.d[i-52])){E y={0,0,0,x.s};y.d[i-53]=1;return C(A(x,y));}
  if(i<2978){e=0;for(j=0;j<52;j++)m+=x.d[j+2926]<<j;}
  else if(i<5024){e=i-2977;for(j=0;j<52;j++)m+=x.d[i+j-52]<<j;}
  else x.i=1;
  if(x.z)e=m=0;
  if(x.i){e=2047;m=0;}
  if(x.n)e=m=2047;
  F y;y.k=x.s<<63|e<<52|m;return y;
}
// expand, do op, unexpand
F A(F x,F y){return C(A(R(x),R(y)));}
F S(F x,F y){y.k^=1L<<63;return A(x,y);}
F M(F x,F y){return C(M(R(x),R(y)));}
F D(F x,F y){return C(M(R(x),I(R(y))));}

I'm too lazy to remove all the spaces and newlines to get an exact golfed count, but it is about 1500 characters.


text:
solve puzzle with a tweet? javascript (fun challenge)
the question is "complete this subtraction by replacing the asterisks with digits so the numbers 1-9 only appear once each"
 9**
-*4*
____
 **1

my code tries random numbers until it works, and displays the answer.  here is the entire html app.  I want one to fit in a tweet at 140 characters  (not counting  tags)
<script>
function r(){return Math.random()*9+1^0}
do{a=900+r()*10+r(),b=r()*100+40+r(),c=a-b,s=''+a+b+c
}while(c%10!=1||eval('for(i=0;i++<9;)if(s.indexOf(i)<0)1'))alert(s)
</script>

Is there any way to make this shorter, including with a different solution?
SOLVED!:
Thanks Peter, Shmiddty and copy, currently I have 91 chars!
for(x=1;++x<999;)for(y=1;y<x;)/(?!.*0|.*(.).*\1)9...4...1/.test(s=''+x+y+(x-y++))&&alert(s)

I'm thinking there must be a better way to check if it has each of the numbers 1-9

JavaScript (118 110 102 96 95 99 98 93 chars)
for(x=1;x;x++)for(y=1;y<x;)/(?!.*0|.*(.).*\1)9...4...1/.test(s=''+x+y+(x-y++))&&alert(s,x=-1)

This will give the lexicographically smallest solution. Thanks to copy for 98->93.
You can enumerate all of them for 91 chars:
for(x=1;++x<999;)for(y=1;y<x;)/(?!.*0|.*(.).*\1)9...4...1/.test(s=''+x+y+(x-y++))&&alert(s)

Thanks to Shmiddty for pointing out a standard optimisation which slipped straight past me.
Allowing 0 as well, in <2.5 tweets, here's the analysis:
9ab-c4d=ef1; b-d in {1,-9}; 2nd => d=9 so bd in {32,65,76,87}, no carry. a-f in {4,*-6} so af in {62,73,*06,*28}. 9-c=e or *8-c=e so ce in
{27,36,63,72} or *{08,26,35,53,62,80}. af in {62,73} => no ce. af in {06,28} => ce in {35,53}; 06 => bd=87; 28 => bd=76. So four solutions:
927-346=581; 927-546=381; 908-347=561; 908-547=361

Removing 0 shrinks the analysis to fit in two tweets:
9ab-c4d=ef1; b-d in {1,-9}; 2nd => d=9 so bd in {32,65,76,87}, no carry. a-f in {4,*-6} so af in {62,73,*28}. 9-c=e or *8-c=e so ce in
{27,36,63,72} or *{26,35,53,62}. af in {62,73} => no ce. af=28 => ce in {35,53} => bd=76. So 927-346=581; 927-546=381.

/re/.test is a bit smaller than .match. You can also use && instead of if then

97!  superb.  regex's are so awesome. I need to work on them.

@copy - so in this case how would I use that syntax?

for(x=0;++x<999;)...

@Shmiddty yes! good catch.

@AwokeKnowing Yeah, I realized that and removed my comment.

@Peter Taylor - Thanks for the maths.  I'm new here, so I don't know if I'm supposed to follow certain cultural protocols to thank you for the analysis.  I do appreciate it.

k (116 chars)
It's possible in k... Returns all possible solutions. (Count ignores unnecessary whitespace).
{a:"9",','[;"1"]i@&:6=#:'i:?:'{,/x,/:\:y}/7#,:"8765320";
 b:"I"$0N 3#/:a[;i],'"4",'a[;4+i:!4];
 b@&:b[;2]='(-).'b[;0 1]}

wow! never had heard of K. That's fantastic. If no one figures out a js solution I'll accept yours.


text:
Branch differently in x86 / x86-64 using only printable visible ASCII characters in the machine code
The task is simple: write a program that branches differently in x86 (32-bit) and x86-64 (64-bit) using only printable visible ASCII characters 0x21...0x7e (space and del are not allowed) in the machine code.

Conditional assembly is not allowed.
Using API calls in not allowed.
Using kernel-mode (ring 0) code is not allowed.
The code must run without causing exceptions in both IA-32 and x86-64 in Linux or in some other protected mode OS.
The functioning must not depend on command line parameters.
All instructions must be encoded in machine code using only ASCII characters in the range 0x21...0x7e (33...126 decimal). So eg. cpuid is out of limits (it's 0f a2), unless you use self-modifying code.
The same binary code must run in x86 and x86-64, but as file headers (ELF/ELF64/etc.) may be different, you may need to assemble and link it again. However, the binary code must not change.
Solutions should work on all processors between i386...Core i7, but I'm interested also in more limited solutions.
The code must branch in 32-bit x86 but not in x86-64, or vice versa, but using conditional jumps is not a requirement (indirect jump or call is also accepted). The branch target address must be such that there is space for some code, at least 2 bytes of space in which a short jump (jmp rel8) fits in.

The winning answer is the one that uses least bytes in the machine code. The bytes in the file header (ELF/ELF64 for example) are not counted, and any bytes of code after the branch (for testing purposes etc.) aren't counted neither.
Please present your answer as ASCII, as hexadecimal bytes and as commented code.
My solution, 39 bytes:
ASCII: fhotfhatfhitfhutfhotfhatfhitfhut_H3<$t!
hexadecimal: 66 68 6F 74  66 68 61 74 66 68 69 74  66 68 75 74 66 68 6F 74  66 68 61 74 66 68 69 74  66 68 75 74 5F 48 33 3C 24 74 21.
Code:
; can be compiled eg. with yasm.
; yasm & ld:
; yasm -f elf64 -m amd64 -g dwarf2 x86_x86_64_branch.asm -o x86_x86_64_branch.o; ld x86_x86_64_branch.o -o x86_x86_64_branch
; yasm & gcc:
; yasm -f elf64 -m amd64 -g dwarf2 x86_x86_64_branch.asm -o x86_x86_64_branch.o; gcc -o x86_x86_64_branch x86_x86_64_branch.o

section .text
global main
extern printf

main:
    push    word 0x746f     ; 66 68 6f 74 (x86, x86-64)
    push    word 0x7461     ; 66 68 61 74 (x86, x86-64)
    push    word 0x7469     ; 66 68 69 74 (x86, x86-64)
    push    word 0x7475     ; 66 68 75 74 (x86, x86-64)

    push    word 0x746f     ; 66 68 6f 74 (x86, x86-64)
    push    word 0x7461     ; 66 68 61 74 (x86, x86-64)
    push    word 0x7469     ; 66 68 69 74 (x86, x86-64)
    push    word 0x7475     ; 66 68 75 74 (x86, x86-64)

    db      0x5f            ; x86:    pop edi
                            ; x86-64: pop rdi

    db      0x48, 0x33, 0x3c, 0x24
                            ; x86:
                            ; 48          dec eax
                            ; 33 3c 24    xor edi,[esp]

                            ; x86-64:
                            ; 48 33 3c 24 xor rdi,[rsp]

    jz      @bits_64        ; 0x74 0x21
                            ; branch only if running in 64-bit mode.

; the code golf part ends here, 39 bytes so far.

; the rest is for testing only, and does not affect the answer.

    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop

    jmp     @bits_32

@bits_64:
    db      0x55                    ; push rbp

    db      0x48, 0x89, 0xe5        ; mov rbp,rsp
    db      0x48, 0x8d, 0x3c, 0x25  ; lea rdi,
    dd      printf_msg              ; [printf_msg]
    xor     eax,eax
    mov     esi,64

    call    printf
    db      0x5d                    ; pop rbp

    NR_exit equ 60

    xor     edi,edi
    mov     eax,NR_exit     ; number of syscall (60)
    syscall

@bits_32:
    lea     edi,[printf_msg]
    mov     esi,32
    call    printf

    mov     eax,NR_exit
    int     0x80

section .data

printf_msg: db "running in %d-bit system", 0x0a, 0

You really hit the hot hat in the hut :)

Nice. Odd, but nice. Since you are setting the winning condition as "shortest" I'm going to change the tag to [code-golf] and add a some new descriptive tags. If you don't like them, let me know.

7 bytes
0000000: 6641 2521 2173 21                        fA%!!s!

As 32 bit
00000000  6641              inc cx
00000002  2521217321        and eax,0x21732121

As 64 bit
00000000  6641252121        and ax,0x2121
00000005  7321              jnc 0x28

and clears the carry flag so the 64 bit version always jumps. For 64-bit the 6641 is the operand size override followed by rex.b so the operand size for the and comes out as 16 bit. On 32-bit the 6641 is a complete instruction so the and has no prefix and has a 32-bit operand size. This changes the number of immediate bytes consumed by the and giving two bytes of instructions that are only executed in 64-bit mode.

Congrats on reaching 1k.

this behaviour is CPU specific.  Some 64-bit systems will ignore the 66 prefix in 64-bit mode.

@peterferrie Do you have a reference for that? My reading is that a 66h prefix is ignored when REX.W is set but this only has REX.B

excuse me, I'm wrong.  It's only transfer-of-control that's affected that way (e.g. 66 e8 doesn't switch to 16-bit IP on Intel).

11 bytes
ascii: j6Xj3AX,3t!
hex: 6a 36 58 6a 33 41 58 2c 33 74 21

Uses the fact that in 32-bit, 0x41 is just inc %ecx, whereas in 64-bit it is the rax prefix that modifies the target register of the following pop instruction.
        .globl _check64
_check64:
        .byte   0x6a, 0x36      # push $0x36
        .byte   0x58            # pop %rax
        .byte   0x6a, 0x33      # push $0x33

        # this is either "inc %ecx; pop %eax" in 32-bit, or "pop %r8" in 64-bit.
        # so in 32-bit it sets eax to 0x33, in 64-bit it leaves rax unchanged at 0x36.
        .byte   0x41            # 32: "inc %ecx", 64: "rax prefix"
        .byte   0x58            # 32: "pop %eax", 64: "pop %r8"

        .byte   0x2c, 0x33      # sub $0x33,%al
        .byte   0x74, 0x21      # je (branches if 32 bit)

        mov     $1,%eax
        ret

        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        mov     $0,%eax
        ret

Wrote this on OSX, your assembler might be different.
Call it with this:
#include <stdio.h>
extern int check64(void);
int main(int argc, char *argv[]) {
  if (check64()) {
    printf("64-bit\n");
  } else {
    printf("32-bit\n");
  }
  return 0;
}

7 bytes
Not relying on 66 prefix.
$$@$Au!
32-bit:
00000000 24 24 and al,24h
00000002 40    inc eax
00000003 24 41 and al,41h
00000005 75 21 jne 00000028h
AL will have bit 0 set after the INC, the second AND will preserve it, the branch will be taken.
64-bit:
00000000 24 24    and al,24h
00000002 40 24 41 and al,41h
00000005 75 21    jne 00000028h
AL will have bit 0 clear after the first AND, the branch will not be taken.

If only C9h were printable...
32-bit:
00000000 33 C9 xor  ecx, ecx
00000002 63 C9 arpl ecx, ecx
00000004 74 21 je   00000027h
The ARPL will clear the Z flag, causing the branch to be taken.
64-bit:
00000000 33 C9 xor    ecx, ecx
00000002 63 C9 movsxd ecx, ecx
00000004 74 21 je     00000027h
The XOR will set the Z flag, the MOVSXD will not change it, the branch will not be taken.

If not for the printable-characters restriction, 5 byte is possible.  x86-32 / x86-64 polyglot machine-code fragment that detects 64bit mode at run-time?. xor eax,eax / db 0x40 (REX or inc eax) / jz .64bit_mode.  xor eax,eax is 31 C0, but the branch displacement could be chosen to be printable.

If we had a known initial state for FLAGS (PF=0), push 'b' / pop eax/rax ; db 0x40 / jne .64bit_mode works (6 bytes).  But with an extra dec or inc to make sure PF has known state in 64-bit mode, it's 7 bytes.  Unfortunately or al, imm8 has an opcode outside the ASCII range, and any ModRM with register operands will have its high bit set.


text:
Chess - Find all legal moves (except castling and en passant)
Write the shortest code that calculates all possible (legal) moves of current player from a given FEN string. What is FEN string? (Wikipedia)

Shortest code wins, language doesn't matter.
Output moves must obey chess rules of movement except en passant, castling, and pawn promotion.
Ignore check, checkmate, and stalemate, king cannot be captured situations too.

You can set outputs differently as you want (for example: A2-A4, A2A4, a2a4, a2->a4...)
Test cases:

# INPUT 1:

rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1

# OUTPUT 1

A2-A4, A2-A3, B2-B4, B2-B3, C2-C4, C2-C3, D2-D4, D2-D3, E2-E4, E2-E3,
F2-F4, F2-F3, G2-G4, G2-G3, H2-H4, H2-H3, B1-A3, B1-C3, G1-F3, G1-H3

# INPUT 2

7k/8/8/8/8/8/PP6/Q1q4K w - - 0 1

# OUTPUT 2

A1-B1, A1-C1, A2-A3, A2-A4, B2-B3, B2-B4, H1-H2, H1-G1, H1-G2

also here is how test case input boards look like: http://i.stack.imgur.com/qlbH4.png

possible duplicate of Play a valid chess move, given a board on stdin

@ugoren, I considered that, but enumerating all possible moves potentially eliminates some shortcuts. I'm not sure, though, why en passant isn't required: part of the point of FEN is that it includes enough information to make en passant possible.

@PeterTaylor I wrote that just to reduce the work.                               I wonder why no one interested in this golf :)

I wrote a mate-in-2 solver a while back that takes FEN as input. I could dig it out and post it; of necessity, it already calculates all the moves. Mi2 problems don't (generally) use en passant or castling but do use pawn promotion - one thought on why you'd have certain move restrictions.

@golffzz shouldn't your test case input 2 be 7k/8/8/8/8/8/PP6/Q1q4K w - - 0 1 instead of 6pk/6pp/8/8/8/p7/PP4pp/Q2p2pK w - - 0 1 (which among other things, seems to have pawns on the end ranks)?

As pointed out by @golffzz, the test case 2 was wrong. Corrected.

@feersum Your last edit is incorrect: See OP "Ignore check, checkmate, and stalemate, king cannot be captured situations too."

@feersum no answer, so I removed the last edit

Any other opinions on this? See discussion of check and test case 2 in my answer.

Holy Hell!

C - 391 bytes
Takes input as command line arguments and prints to stdout with the squares labeled from 0 to 63.
OK, I had a few minutes so I tried to delete all the bits relating to the detection of check. I think it is now not very efficient though...
O(x,y){return((x&7)-(y&7))/5;}
B[64],*b=B,J=32,M,L,x,*X,N;
main(int c,char**V){
for(;x=*V[1]++;c=J&2**V[2])
x>56?*b++=x:x>47?b+=x-48:0;
for(;b-->B;)
for(M=-1,N=*b%J^16,*V=strchr("bGInFJOQrAHkAGHIqAGHIpGHIx",*b|J);*b&&*b&J^c&&(M=M<0?*++*V%J:-M,**V<96);)
for(x=b-B,L=N?9^*b&8:1+(x/8==1+c/6);L--*!(O(x,x+M)|O(x>>3,x+M>>3));L=!*X|~*X&J^c&&N|(!*X^M&1&&M<0^!c)?printf("%d-%d ",b-B,x),L*!*X:0)
X=B+(x+=M);}

478 byte check-detecting version
O(x,y){return((x&7)-(y&7))/5;}
B[64],*b=B,c,I,J=32;
main(int C,char**V){
int*D,M,L,t,x,*X,N;
for(;b-B<64;C=c=J&2**V[2])
(t=*V[1]++)>56?*b++=t:t>47?b+=t-48:0;
for(D=b;D-->B;)
for(M=-1,N=*D%J^16,*V=strchr("bGInFJOQrAHkAGHIqAGHIpGHIx",*D|J);*D&&*D&J^C&&(M=M<0?*++*V%J:-M,**V<96);)
for(x=D-B,L=N?9^*D&8:1+(x/8==1+C/6);L--*!(O(x,x+M)|O(x>>3,x+M>>3));L=!*X|~*X&J^C&&N|(!*X^M&1&&M<0^!C)?c^C?I|=*X%J==11:(*X=*D,*D=I=0,main(C^J,V+1),*D=*X,I||printf("%d-%d ",D-B,x)),L*!(*X=t):0)
X=B+(x+=M),t=*X;}

This is amazing, but does not correspond to the question: "Ignore check, checkmate, and stalemate, king cannot be captured situations too."

@edc65 I don't agree with your interpretation of these unfortunately incoherent instructions. It says "Output moves must obey chess rules of movement except en passant, castling, and pawn promotion." Moving into check does not appear in the bolded list of rules to ignore. I take the third bullet point as a note that you do not need to detect these situations and reflect them in any way in the output (e.g. the convention of writing '+' after a check). Also, the second test case 2 was correct as originally written, given one ignores pawn promotion as specified (but gives no insight on check).

The second test case (input) was invalid having a black pawn on rank 8, and different from the image posted as a comment by OP (also here is how test case input boards look like). Given the position in the image, the original test case output was correct according to the rules.

Oh great, the real spec is in the comments? Ugh, what a poor question.

The clear winner

That's really impressive! Well done.

382 bytes

Java 1455
String q(String f){int[][]b=new int[8][8];int i=0,j=0,k,l,m,n,c;HashSet<String>h=new HashSet<String>();while((c=f.charAt(i))>32){if(c>48&c<57)j+=c-49;if(c==47)j--;if(c>56)b[j%8][j/8]=c;i++;j++;}boolean w=f.charAt(++i)>99;for(i=0;i<8;i++)for(j=0;j<8;j++)if((c=b[i][j])<91?w&c>0:!w){switch(c%32){case 14:for(k=0;k<8;k++){l=(k/4+1)*(k%2*2-1)+i;m=(2-k/4)*(k%4/2*2-1)+j;if(b(l,m)&&(w&b[l][m]%91<40|!w&b[l][m]<91))h.add(h(i,j,l,m));}break;case 11:for(k=0;k<8;k++){l=i+(k==4?1:k/3-1);m=j+(k==4?1:k%3-1);if(b(l,m)&&(w&b[l][m]%91<40|!w&b[l][m]<91))h.add(h(i,j,l,m));}break;case 17:for(k=0;k<8;k++){for(n=1;n<9;n++){l=i+n*(k==4?1:k/3-1);m=j+n*(k==4?1:k%3-1);if(b(l,m)){c=b[l][m];if(w&c%91<40|!w&c<91)h.add(h(i,j,l,m));if(c>0)break;}else break;}}break;case 2:for(k=0;k<4;k++){for(n=1;n<9;n++){l=i+n*(k/2*2-1);m=j+n*(k%2*2-1);if(b(l,m)){c=b[l][m];if(w&c%91<40|!w&c<91)h.add(h(i,j,l,m));if(c>0)break;}else break;}}break;case 18:for(k=0;k<4;k++){for(n=1;n<9;n++){l=i+n*(k/2*(k%2*2-1));m=j+n*((1-k/2)*(k%2*-2+1));if(b(l,m)){c=b[l][m];if(w&c%91<40|!w&c<91)h.add(h(i,j,l,m));if(c>0)break;}else break;}}break;default:m=w?-1:1;if(b[i][j+m]<1){h.add(h(i,j,i,j+m));if(b[i][j+2*m]<1&j==(w?6:1))h.add(h(i,j,i,j+2*m));}for(l=-1;i+l<8&i+l>=0&l<2;l+=2){c=b[i+l][j+m];if(c>0&(c<91?!w:w))h.add(h(i,j,i+l,j+m));}}}return h.toString();}boolean b(int l,int m){return m>=0&m<8&l>=0&l<8;}String h(int i,int j,int l,int m){return""+g(i)+(8-j)+g(l)+(8-m);}char g(int i){return(char)(i+65);}

Python 553 649 678
b,Q=raw_input(),range;R=Q(8);D="w"in b
for i in Q(9):b=b.replace(`i`,"_"*i)
if D:b=b.swapcase()
def X(h,v,c):
 h+=x;v+=y
 if c and h|v in R and"a">b[v*9+h]:print chr(65+x)+`8-y`+chr(65+h)+`8-v`;return"_"==b[v*9+h]
for y in R:
 for x in R:
  z=y*9+x;p=b[z];N=p=="n";j=[p in"qrk"]*4+[p in"qbk"]*4
  if"p"==p:j[D]=k=(1,-1)[D];X(1,k,b[z+10*k]<"_");X(-1,k,b[z+8*k]<"_")
  for i in Q(1,(2,(y==(1,6)[D])+2,8)["kp".find(p)]):
   for k in R:j[k]=X((0,0,-i,i,-i,i,-i,i)[k],(i,-i,0,0,-i,-i,i,i)[k],j[k])
  for v,h in((2,1),(1,2)):X(v,h,N);X(-v,-h,N);X(-v,h,N);X(v,-h,N)

Two-space indent is tab char, which saves 5 bytes.
It occurs to me that you can likely make it evaluate reasonable moves to a decent ply and keep it under 1024 bytes :)  I started looking through other chess questions, but there doesn't seem to be a codegolf chess engine question...

Well done for resurrecting this question! (I think I might put a bounty on it just to see what happens.) Your answer is looking good, but it misses B1C3 and H2H3 in the first example shown in the question.

Sorry,not H2H3, I meant G1H3 — in other words, your white knights are only turning left.

It'll have to wait until I am on a pc, but this is an easy bug and I can see lots of ways to shorten it too.  Hope there are other entries.

@squeamishossifrage fixed :)

Python 638 637 (482?) bytes
exec"""p=raw_input()
for x in"12345678":p=p.replace(x,"~"*int(x))
b=map(ord,"#"*21+p[:71].replace("/","##")+"#"*21)
d,e=-10,126
if not"w"in p:b,d=[x^32*(64<x<e)for x in b],10
B=[-9,9,-11,11]
R=[-1,1,-d,d]
Q=B+R
c=Zx:chr(96+x%10)+chr(58-x/10)
for x,p in enumerate(b):
 def O(y):
    if 111<b[y]:print c(x)+c(y)
 s=ZL:[O(x+X)for X in L];m=ZL,z=x:L&(O(z+L[0]),m(L,z+L[0])if e==b[z+L[0]]else m(L[1:]))
 if p==80:e==b[x+d]&(O(x+d)or e==b[x+d*2]&35==b[x-d*2]&O(x+d*2)),111<b[x+d-1]<e&O(x+d-1),111<b[x+d+1]<e&O(x+d+1)
 p==75&s(Q),p==78&s([-12,12,-8,8,-21,21,-19,19]),p==82&m(R),p==66&m(B),p==81&m(Q)""".replace("Z","lambda ").replace("&"," and ")

Note: after def O(y): there is a newline and a tab char before if
Note: by using zlib module it's possible to get a valid Python source code of 482 bytes by simply compressing the real source:
#encoding=koi8-r
import zlib
exec zlib.decompress("x°MRKkЦ0>╞~┘Pы Eё╜Е4▌Ц█.9Br*1зБ┤B╠#°■╙=Лoъ╠M⌡│╬г0█\\pcл⌡╝x9╣ЧМф9^:Х╘e:·=м⌠Eй2oЭ╞нЫsQ9─ЩeсS{ЦAR ╕ПЭруюь4жрГыBшОhЖхпy`B▌╬ 58ёt:NхИHшк█╫ЁSK}VBmРПgOyР╢\n+'╬Z║╔▒╣иу√═╢╜-ы#G╙├з▓²Yк=╘л!dуkг≈┴?u$dOФ╘\n▐HфАюВ9]Шж╦╝╦9^┼▄пзИ√ Э│mi╜WeЧa3ъА╗╢бae┘.║WsьdЫ√Ы<ТВэГзьъ
ЙПiB╤≥П-Ъ■⌡<╡▌Б┬1╚3╕лGjщЫЙ(з╧н,>$Eш⌠FыdmШ<x,Р╔Mc;≥м╒2DLc!`Л≥рvЕFCИЪtyв%Н║╞╤≤O╝|'═┤)B|н*┘T╛▐рKпK;╔Я╓АШ&  бУ╗j└;│И╬Ж╝Щ\\4e]P&НРeZ╢5┼ДГt╚У")

JAVA 631 599 594
Fixed a bug in the 599-bytes version (thank you Jack for pointing this out!) and shortened the code to 594-bytes.

class F{
public static void main(String[]A){int p=0,i=8,u,v,d,z[]={0,1,-1,2,1,0,1};String f=A[0],S[]="p,n,rqk,bqk,aA,PNBRQK,aAPNBRQK".split(",");
for(;i>0;)f=f.replace(""+i,"a"+(--i==0?"":i));
for(;p<448;p++)
for(int k=p%7,w=A[1].equals("w")?32:0,c=f.charAt(p/7%8+p/56*9),a=z[k],b=k==4?2:1,q=0;S[(k/2-1|k-1)/2].indexOf(c+w)>=0&&q++<(k<3?1:4);i=a,a=b,b=-i){
for(i=1,d=97;d==97&&((u=p/7%8+i*a)|(v=p/56+i*b*(1-w/16)))>=0&&(u|v)<8&&i<(k>4?(c=='K'||c=='k')?2:9:(k<1&&p/56==w/6+1?3:2))&&S[61/(61^(k*k-2))+5].indexOf((d=f.charAt(u+9*v))-w)>=0;i++)System.out.printf("%c%d%c%d ",65+p/7%8,8-p/56,65+u,8-v);}}}

Compile: javac F.java
Run: java F 6pk/6pp/8/8/8/p7/PP4pp/Q2p2pK w - - 0 1
Output: B2B3 B2B4 B2A3 A1B1 A1C1 A1D1 H1H2 H1G1 H1G2

For 3Q4/p4r1k/P4pp1/4P3/5n2/3P4/4BbbP/RN3KN1 w - - 0 0 I'm not seeing moves F1F2 or F1G2 is the king able to capture?

Thank you for pointing this out. You are right. This published version is over optimized :(

So I have to fall back to my 631 byte long solution.

573 bytes

JavaScript (E6) 481 492 550
Edit Fixed a nasty bug in knight moving. A lot of work to keep the byte count the same.
(Not counting leading spaces and newlines kept for readability)
B=f=>
  [for(c of(o=b='',f=f.split(w=' '))[0])b+=-c?w.repeat(c):c<'0'?z=10:c]+
  [...b].map((c,p)=>
    (K=d=>(d=b[p+d])==w?0:d>'a'?m:d>'A'?-m:9)(0)-1||(
      t='pPkKnNrRQqBb'.search(c),
      O=d=>K(d)<1?o+=w+P(p)+P(p+d):0,
      S=(d,s=0)=>O(d*++s)&&!K(d*s)&&S(d,s),
      //o+='\n'+P(p)+' '+c, // Uncomment to display pieces list
      t<2?[for(i of[~(s=t<1?z:-z),1-s])~K(i)||O(i)]+!K(s)&&O(s)&&(p/z|0)==t*5+1&!K(s+=s)&&O(s)
      :t<6?[for(i of t<4?[1,9,z,11]:[12,8,21,19])O(i)+O(-i)]
      :[for(i of[t>7&&9,t>7&&11,t<z,t<z&&z])S(i)+S(-i)]
    )
  ,m=f[1]<'w'?1:-1,
  //console.log(','+([...b]+',').replace(/1,0/g,'\n')), // Uncomment to display chessboard
  P=p=>'ABCDEFGH'[p%z]+(9+~p/z|0))&&o

Less Golfed
B=f=>(
  o=b='',[for(c of f)b+=-c?'.'.repeat(c):c],
  m=(w=b[72]=='w')?1:2,n=3-m,
  t=0,
  P=p=>'ABCDEFGH'[p%9]+(9+~p/9|0),
  b=b.slice(0,71),
  // console.log(b.replace(/\//g,'\n')), // Uncomment to display chessboard

  [...b].map((c,p)=>{
    r=p/9|0
    K=k=>(k=b[k])=='.'?0:k>'a'?m:k>'A'?n:9
    J=d=>K(p+d)<2,
    O=d=>J(d)?o+=' '+P(p)+P(p+d):0,
    S=(s,d)=>O(d*++s)&&!K(p+d*s)?S(s,d):0;

    if(K(p)==2){
      // o+='\n'+P(p)+ ' '+c; // Uncomment to display pieces list
      if (c=='P')
      {
        (f=!K(p-9))&&O(-9),
        f&r==6&&!K(p-18)&&O(-18),
        [for(i of[10,8])K(p-i)==1&&O(-i)]
      }
      else if (c=='p')
      {
        (f=!K(p+9))&&O(+9),
        f&r==1&&!K(p+18)&&O(+18),
        [for(i of[10,8])K(p+i)==1&&O(+i)]
      }
      else if (c=='K' |c=='k')
        [for(i of[1,8,9,10])O(i)+O(-i)]
      else if (c=='N' | c=='n')
        [for(i of[11,7,19,17])O(i)+O(-i)]
      else
      {
        if (c!='r' & c!='R')
          [for(i of[10,8])S(0,i)+S(0,-i)]
        if (c!='b' & c!='B')
          [for(i of[9,1])S(0,i)+S(0,-i)]
      }
    }
  }),
  o
)

Test in FireFox/FireBug console
B("7k/8/8/8/8/1P6/P7/Q1q4K w - - 0 1")

Output
B3B4 A2A3 A2A4 A1B2 A1C3 A1D4 A1E5 A1F6 A1G7 A1H8 A1B1 A1C1 H1G1 H1H2 H1G2


text:
Build an adding machine using NAND logic gates
This is "programming" at its most fundamental.
Build a diagram of (two-wire) NAND logic gates that will take the input wires A1, A2, A4, A8, B1, B2, B4, B8, representing two binary numbers A to B from 0 to 15, and return values on the output wires C1, C2, C4, and C8 representing C, which is the sum of A and B modulo 16.
Your score is determined by the number of NAND gates (1 point per gate). To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

NOT: 1
AND: 2
OR: 3
XOR: 4

Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.
Lowest score wins.

Updates:
03-07 19:09: Due to discussions with Jan Dvorak, it came to my attention that the total number of gates, constants and splits is always determined solely by the number of gates. Because of this, I have simplified the score requirement back down to simply the number of gates required.

I don't think you can get much better than the classic full-adder design.

That uses AND, OR, and XOR gates and would have a score of 29 per digit (minus a few for carrying in the end cases). Can you condense it into using fewer NANDs?

Are multi-wire NANDs allowed?

@JanDvorak Not sure what a multi-wire NAND is.

@JoeZeng NAND(X,Y,Z) = NOT(AND(X,AND(Y,Z)))

They don't seem like a standard construction. I think I'd only allow them with the score it takes to build them out of two-wire NANDs and splits.

They are quite standard. It emits true if any input is false.

I understand that. What I meant is that multi-wire logic gates in general don't seem to be typical of logic gate diagrams, so I don't think I would allow them as one unit with a special score.

But, if you can construct a multi-wire NAND using only regular NANDs and splits, feel free to reuse that construction with its equivalent score.

31 gates

[created in Logisim]

The standard XOR-gate can be built with four NANDs. Tapping the first NAND provides us with a fairly compact half-adder with inverted carry:
hadder(A,B) => (sum, iCarry):

X = A^B

sum = (A^X)^(B^X)
iCarry = X

These can be combined into a 9-gate full adder:
fadder(A,B,C) => (sum, carry):

DD1 = hadder(A,B)
DD2 = hadder(DD1.sum, C)

sum = DD2.sum
carry = DD1.iCarry ^ DD2.iCarry

These combined yield a naive 36-gate four-bit adder. Not bad.
Now, we inline all modules and perform these optimizations:
delete gates with no output (only the final gate)
0^x => 1                    (one gate, twice)
1^(1^x) => 0                (two gates, once)

for a grand total of 31 gates.

Note that the count of splits and NAND-gates are intimately connected: Each 2-input NAND (larger are explicitly forbidden) takes two inputs and produces one output. Each 2-way split (let's assume larger splits are forbidden) takes one input and produces two outputs. Also, there are no unused outputs or floating inputs (let's assume constants are not allowed). If there are N more inputs than outputs, there must be N more NANDs than splits.
Thus, a 31-NAND 8=>4 module will neccessarily have 27 2-way splits.
Here are the split cardinalities for the above adder just in case larger splits are allowed:
18x wire (no split)
  4x output
  14x XOR 2nd stage
16x 2-way split
  8x input
  6x H2 input
  2x last bit XOR 1st stage
4x  3-way split
  4x XOR 1st stage
1x  4-way split
  1x 1st bit XOR 1st stage; if constants are alloweed; this is a three-way split

The 27 splits each count as 1 point, so your total score is actually 58.

@JoeZeng as I elaborated, if you count my diagram as 27 splits (2-way only, constants not allowed), then #splits = #gates - 4

So basically, the score only has one degree of freedom among the number of gates and the number of splits?

Yup. Unless you allow constants.

If I allow constants at 1 point each, will that affect anything?

@JoeZeng if a constant has the same price as a split, then the score is a function of the number of gates.

I see. In that case, I'll just count the number of gates.

Minimum is indeed 31 NANDs. I searched a lot, and found none faster than this one at this size, but there were weird slower ones. This puzzle is solved by John Dvorak.


text:
Generate math problems
Generate math problems (addition, subtraction, or multiplication) using numbers 0-10. Provide feedback on whether the user was right or wrong and show a score.
Specifics:

Must generate addition, subtraction, or multiplication problems
Numbers used must be 0-10
Each problem must be equally likely
If user is correct, must print "correct!" (with the exclamation point)
If user is wrong, must print "wrong!" (with the exclamation point)
After providing correct or wrong feedback, must show score with these specifications:

Starts with "Score:"
Shows number correct and then "correct"
Pipe (|) separation
Shows number wrong and then "wrong"
2 newlines for separation

Must repeat forever

For counting characters, the Text Mechanic counter will be used.
Sample session:
1-7=-6
correct!
Score: 1 correct | 0 wrong

9+3=12
correct!
Score: 2 correct | 0 wrong

4*5=20
correct!
Score: 3 correct | 0 wrong

7-8=3
wrong!
Score: 3 correct | 1 wrong

1*1=3
wrong!
Score: 3 correct | 2 wrong

7+6=

can we assume there is only one operator per problem?

Post-mortem update:
Perl 130 bytes
Combining techniques from dan1111's excellent solution with my own, I was able to squeeze one more byte:
@b=qw(Score: 0 correct | 0 wrong);$b[$#x=eval^<>?4:1]++while print"$b[@x]!
@b

"x/./,$_=(0|rand 11).chr(41^2+rand 3).~~rand 11,'='

There's a few things that might not be immediately obvious. If @x is an array, then $#x (the largest index of @x) will be one smaller than the length of @x. In this way, I can use $#x to point to the appropriate counting variable, and the length of @x to the corresponding message in a single assignment, without having to +1. The score string is repeating by /./, which will return 1 if an only if $_ is non-empty.

Perl 131 bytes
Here's my Perl attempt, which is more or less a direct translation of my PHP solution below.
@r=correct,${_^($n=eval^<>?z:r)}++while@z=wrong,print"@$n!
Score: $- @r | $% @z

"x@r,$_=(0|rand 11).chr(41^2+rand 3).~~rand 11,'='

$- and $% are used for counting variables as they default to 0, alleviating the need for a printf, and at the same time allowing me to combine the print statements into one. The score string is not printed the first iteration because @r has not yet been defined, and therefore x@r (repeat by the length of the array @r) repeats the string zero times, resulting in an empty string.
Once again using chr(41^2+rand 3) to generate +*-, as well as a bitwise xor _^ to switch between r→- and z→%. I would have liked to use a type glob for *n=eval^<>?z:r, saving a byte @$n→@n, but unfortunately typed as a string this comes back as either *main::r or *main::z, which isn't very useful.
</bandwagon>

PHP 157 (155) bytes
Just to get a smattering of languages:
<?for($X=$Y=+$x=correct;$y=wrong;)echo$q=rand(0,10).chr(rand(2,4)^41).rand(0,10),'=',eval("\${_&\$n=$q^fgets(STDIN)?y:x}++;"),$$n,"!
Score: $X $x | $Y $y

";

The initial $X=$Y=+ is necessary, because undefined variables print as an empty string, instead of 0. Unfortunate, but still shorter than using a printf. One thing to notice is the 'magic formula' chr(rand(2,4)^41). 2^41 = 43 (+), 3^41 = 42 (*) and 4^41 = 45 (-). chr(rand(3,5)^46) would also work, but in a different order.
This can be made 2 bytes shorter by using a few binary characters:
<?for($‡=$†=+$x=correct;$y=wrong;)echo$q=rand(0,10).chr(rand(2,4)^41).rand(0,10),~Â,eval("\${~\$n=$q^fgets(STDIN)?y:x}++;"),$$n,"!
Score: $‡ $x | $† $y

";

where †, ‡ and Â are characters 134, 135 and 194 respectively.

Perl beats APL! Well done!

+1, I especially like your use of the while loop to get a single print statement.

Perl, 144 characters
@b=qw/+ - * Score: correct 0 | wrong 0/;sub _{print@_;~~rand 11}{_$_=_.$b[rand 3]._,'=';_$b[$x=eval==<>?4:7];$b[$x+1]++;_"!\n@b[3..8]\n\n";redo}

Updated (thanks ardnew)

very nice. you can save 2 chars by replacing int rand 10 with ~~rand 10 (well technically you should be using ~~rand 11...)

APL 146 145
In index origin zero:
o←'+-×'
s←0 0
t←'wrong' 'correct'
l:⍞←(e←(⍕?11),o[?3],(⍕?11)),'='
r←(⍎e)=⍎⍞
s[r]←s[r]+1
(∊t[r]),'!'
'Score: ',s[1],t[1],'|',s[0],t[0]
' '
' '
→l

10×8=80
correct!
 Score:  1 correct | 0 wrong

2×6=16
wrong!
 Score:  1 correct | 1 wrong

2+5=

Python 2, 180 176
from random import*
r=randrange
a='correct'
b='wrong'
c=w=0
while 1:e=`r(11)`+'+-*'[r(3)]+`r(11)`;x=input(e+'=')==eval(e);c+=x;w+=1-x;print(b,a)[x]+'!\nScore:',c,a,'|',w,b+'\n'

That counter says it's only 171 chars, but I've counted new lines since that's what we normally do in code golf.
Thanks to flornquake for some improvements.
Ungolfed:
from random import *
num_correct = num_wrong = 0
while 1:
    expression = str(randrange(11)) + '+-*'[randrange(3)] + str(randrange(11))
    is_correct = input(expression + '=') == eval(expression)
    num_correct += is_correct
    num_wrong += 1 - is_correct
    print ('wrong', 'correct')[is_correct] + '!\nScore:', num_correct, 'correct', '|', num_wrong, 'wrong\n'

I tried that code in IDLE and nothing happened. EDIT: Never mind, works in a file. +1

Didn't think of using c+=x;w+=1-x, had c[x]+=1 instead and some string formatting.

Any Chance of an un-golfed version? Thanks.

@AriPorad I've added one.

Perl 154 chars
$x=correct;$y=wrong;R:$_=join qw|+ - *|[rand 3],map~~rand 11,0,0;print"$_=";$c+=$b=<>==eval;printf"%s!$/Score: %d $x | %d $y$/$/",$b?$x:$y,$c,$.-$c;goto R

with some newlines:
$x=correct;
$y=wrong;
R:
  $_=join qw|+ - *|[rand 3],map~~rand 11,0,0;
  print"$_=";
  $c+=$b=<>==eval;
  printf"%s!$/Score: %d $x | %d $y$/$/",$b?$x:$y,$c,$.-$c;
  goto R

Javascript 169 chars
Here's a solution that doesn't use the console (does that break the rules?) but works via alert boxes (yeah I know...):
for(c=w=0;r=Math.random;){prompt(x=~~(r()*9+1)+"+-*"[~~(r()*3)]+~~(r()*9+1))==eval(x)?(m="correct",c++):(m="wrong",w++);alert(m+"!\nScore: "+c+" correct | "+w+" wrong")}

The attempts at golfing are quite weak, but this was just for fun right? :)
EDIT: Ungolfed version follows. I expanded variable names and split up the assignment of x into a, op and b. The logic is the same. Bear in mind that ~~(X) == Math.floor(X) for positive X. This is just easier to type.
correct=wrong=0;
rand=Math.random;
while(1){
  a=~~(rand()*9+1);
  op="+-*"[~~(rand()*3)];
  b=~~(rand()*9+1);
  x=a+op+b;
  if(prompt(x)==eval(x)){msg="correct";correct++}
  else{msg="wrong";wrong++}
  alert(msg+"!\nScore: "+c+" correct | "+w+" wrong");
}

do you have an un-golfed version by chance? Thanks

@AriPorad See my edit.

You can save some chars if you replace the if-else with statement?(msg="correct",correct++):(msg="wrong",wrong++);

K, 155
k:l:0;
while[1;
    1@(s:,/(($2?11),(1?"+-*"))0 2 1),"=";
    -1@*$[(.:s)="I"$0:0;("correct!";l+:1);("wrong!";k+:1)];
    -1"Score: ",($l)," correct | ",($k)," wrong\n\n"
    ]

C# - 283 Characters
This is my solution in C# in 283 characters:
var r=new Random();int a=0,b=0,x=0,y=0;var w="";Action C=()=>Console.WriteLine(w);for(;;){x=r.Next(11);y=r.Next(11);int[]R={x+y,x-y,x*y};w=""+x+"+-*"[x%3]+y+"=";C();var f=Console.ReadLine()==""+R[x%3];x=f?a++:b++;w=(f?"correct":"wrong")+"!\nScore:"+a+" correct | "+b+" wrong\n";C();}

With more indentation, it looks like:
var r=new Random();
int a=0,b=0,x=0,y=0;
var w="";
Action C=()=>Console.WriteLine(w);
for(;;){
    x=r.Next(11);y=r.Next(11);
    int[] R={x+y,x-y,x*y};
    w=""+x+"+-*"[x%3]+y+"=";C();
    var f=Console.ReadLine()==""+R[x%3];
    x=f?a++:b++;
    w=(f?"correct":"wrong")+"!\nScore:"+a+" correct | "+b+" wrong\n";C();
}

CJam, 90 bytes
Seems like I'm a little late to this question... as is my language, so per site rules, this answer can't officially be selected as the winner. But I had completed my answer for a recent question that was marked as a duplicate of this question and didn't want to let it go to waste, so I modified it a bit for this question.
{Bmr3mr"+-*"=Bmr]_o'=o~\~li=:R["correct":C"wrong":W?'!N"Score:"SUR+:USCS'|SVR!+:VSWNN]o1}g

Due to the interactive nature of the program, the online interpreter cannot be used. You must use the Java interpreter.
I normally post a lengthy explanation, but the code works in about as straightforward of a manner as you can get. That's not to say that I banged this answer out in all of a couple of minutes, though, as there was a fair amount of time spent searching for and making small optimizations.

Haskell 286
import System.Random
main=0?0
s=show
a°b=s a++b
r=randomRIO
d=r(0,10)
p=putStr
c?w=do a<-d;b<-d;i<-r(0,2);let{(#)=[(+),(-),(*)]!!i;o="+-*"!!i};p(s a++o:b°"=");r<-getLine;let{u=fromEnum$read r/=a#b;d=c+1-u;v=w+u};p(["correct!\n","wrong!\n"]!!u);p("Score: "++d°" correct | "++v°" wrong\n\n");d?v

VBA - 250
Sub t()
a=0
b=0
While 1
x=Int(Rnd()*11)
y=Int(Rnd()*11)
o=Int(Rnd()*3)
If InputBox(x & Array("+","-","*")(o) & y & "=")=Array(x+y,x-y,x*y)(o) Then r="Correct!":a=a+1 Else r="Wrong!":b=b+1
MsgBox r & vbCr & "Score:" & a & " correct|" & b & " wrong"
Wend
End Sub

Runs until the memory limit for the variables is reached, otherwise it runs 'forever'.


text:
substring conversion (in Haskell). Can you beat this?
Ok, I found myself with a nice little problem:
you will get from stdin a string. In this string you will find some hex colors (like #ff00dd). You must return the string with the colors inverted (#ff00dd inverted is #00ff11).
A sample input/output could be:
ascscasad #ff00ff csdcas dcs c#001122 #qq5500
ascscasad #00ff00 csdcas dcs c#ffeedd #qq5500

As I am proficient in Haskell, I tackled the problem with it. Came up with this code, and I think it's the best I can do. Do you see any way to improve it / a completely different way to make it shorter?
import Text.Regex.Posix ( (=~) )

main = getLine >>= putStrLn . f

f [] = []
f x = let (b, q, p) = x =~ "#[0-f]{6}"
          c = '#' : ['0'..'f'] ++ "#"
          a = zip c (reverse c)
          r = map ( (maybe '@' id) . (flip lookup $ a) ) q
      in b ++ r ++ f p

I am also interested to compare other languages to Haskell, so post in other languages are welcome, too!

Shouldn't the inverse of #ff00dd be #00ff22?

main = interact f

Can we assume #ff00 is equivalent to #00ff00 (since it is)?

Perl, 44 chars
Two different tweaks can get it to this length, one suggested by Primo:
s/#\K[\da-f]{6}/sprintf"%06x",~hex ff.$&/eg

Another one by playing around with the /ee modifier:
s/#\K[\da-f]{6}/"sprintf'%06x',~0xff$&"/eeg

Requires -p command line switch (1 char included in count).
Works for lower-case hex numbers (as in example).  An i switch added to the regex would make it work for upper-case as well (though not preserving the case of the original number).

Very nice solution. I see only one minor improvement: (~0>>8)-hex$& can be replaced by ~hex ff.$&.

APL 86
Index origin zero. Takes either a single colour hex string or multiple space separated colour strings as screen input via ←⍞
,' ',h[⊃16,¨,¨⍉¨(⊂16 16)⊤¨255-16⊥¨⍉¨(⊂3 2)⍴¨(⊂h←'0123456789abcdef#')⍳¨(c≠' ')⊂c←⍞~'#']

input: #ff00dd  output: #00ff22

input: #ff00dd #00ff22 output: #00ff22 #ff00dd

APL strikes again... :) Nice solution though!

Ruby, 46 bytes
gets.gsub(/#(\h+)/){"#%06x"%(0xffffff^$1.hex)}


text:
Calculating Resistance (Nerd Sniping)
Good Afternoon Golfers,
Our challenge for today is inspired by XKCD comics 356 and 370. We're going to write a program to calculate the resistance of a group of resistors. A forewarning that this is nearly tough enough to warrant being a code challenge, however I think that there is a certain art to writing slightly more complex programs in a golfed format. The lowest amount of characters wins.
Calculating the resistance relies on the following two formulas:

If the resistors are in series, the resistance is the sum of the each resistor's resistance
If the resistors are in parallel, the resistance is the inverse of the sum of the inverse of the resistance of each resistor

So - for example:

Your challenge is to, in the least amount of characters possible, calculate the resistance of a group of up to 64 resistors. My apologies for the complexity, particularly of the input rules. I've attempted to define them in such a way that every language will be usable.

Each resistor will be connected to 2 or more other resistors.
The input is guaranteed to be valid, with only one entry and one exit point, which will connect
The network will be series-parallel to prevent requiring more maths then what is presented
Input will be via file, argument or stdin, depending on what is appropriate for your language.
Input will consist of a series of newline or forward slashed separated statements consisting of an integer of the resistance of the resistor, and spaces separating the IDs of the resistors that one side of the resistor is connected to.
The ID of the first resistor will be 1, incrementing by one for each successive resistor
The start will always have an ID of 0
The final resistor will always have a resistance of 0 ohms, and only have the connections defined in its line

For example:

Could be represented as
3 0
6 1
1 0
5 0
0 2 3 4

Output can be to stdout or file. It may be represented in one of the following ways:

A number with a minimum of 2 decimal places, followed by a newline
A fraction consisting of an integer (the numerator), a forward slash and another integer (the denominator), followed by a newline. The fraction does not need to be the to be in its lowest form - 4/4 or 10/8 are, for instance acceptable. The fraction must be accurate within 1/100. There is no bonus for being perfectly accurate - this is provided is a crutch to enable languages without fixed or floating point operations to compete.

I hope that covers all the points. Good luck!

/ is not a backslash. Did you mean \\ or a forward slash?

Are we allowed to produce incorrect results if the input is not a series-parallel network?

If there are two parallels in series, will it be represented as two resistors connected to the same two resistors (1 0/1 0/1 1 2/1 1 2)?

Slash fixed. My apologies. Yes - two parallels in series would be represented as you suggest.

The network will be a complete one, with a definite answer. What do you mean by not a series-parallel network? Example please? This might be something I missed

the Wheatstone bridge is not series-parallel if you replace the center voltmeter with a resistor

OK - I see the issue. I thought that it might be an interesting mathematical issue - I didn't consider the details well enough. I will add that the circuit is guaranteed to be a series-parallel.

May I use forward slashes instead of newlines for input? It's hard to input newlines into a javascript prompt or command line arguments.

Sounds reasonable. Added.

will resistors always wire into those with a lower ID or they may be input in any order? Is 1 2/1 0/0 1 valid?

The parallel example is wrong. It should be 15/23, not 15/8.

In example 1, how does 5 + 3 + 1 = 9 ohms? I don't think 2 = 1 yet.

@ASCIIThenANSI where is 2=1? 5+3+1==9 as far as I know.

@StewieGriffin It appears that two years ago, I clearly had no idea how to do math. :| Just looked it over again and 5+3+1 does equal 9.

Python, 329 chars
import sys
N=[[1]]+[map(int,x.split())for x in sys.stdin]
N[-1][0]=1
n=len(N)
S=[set([i])for i in range(2*n)]
for x in range(n):
 C=S[2*x]
 for y in N[x][1:]:C|=S[2*y+1]
 for x in C:S[x]|=C
V=[0]*(2*n-1)+[1]
for k in range(999):
 for i in range(1,2*n-1):V[i]+=sum((V[j^1]-V[i])/N[j/2][0]for j in S[i])/9./len(S[i])
print 1/V[1]-2

Calculates the resistance by doing a voltage relaxation on the circuit.  First it tacks on a 1 ohm resistor to the start and changes the last resistor from 0 ohm to 1 ohm.  Then it sets the input voltage to 0 and the output voltage to 1 volt.  After simulating current flow through the network, the network resistance is calculated using the voltage drop across the first 1 ohm resistor.
Each resistor is given two numbers, the number for its left terminal and the number for its right terminal.  Resistor r's left terminal is 2*r and its right terminal is 2*r+1.  The input is used to calculate S, the sets of terminals that are connected together.  Each terminal is given a voltage V[t] and a relaxation is done by raising the voltage if current is net flowing into a terminal set and lowering the voltage if current is net flowing out.

APL 190
Index origin 1. First loop (s) combines all resistors wired in series, second (p) those wired in parallel and the repeat to first loop to combine any parallel resistors now in series. The specification of the final zero resistor appears to be redundant.
r←¯1↓⍎¨(c≠'/')⊂c
o←⊃↑¨r
r←⊃1↓¨r
s:→(0=+/n←1=+/×r)/p
n←↑n/i←⍳↑⍴r
o[n-1]←+/o[n-0 1]
o←(i←n≠i)/o
r←i⌿r
r←r-r≥n
→s
p:n←1⍪2≠/r[;1]
r←((⍴r),1)⍴r←¯1++\n~0
o←∊1÷¨+/¨1÷¨n⎕penclose o
→(1<⍴o)/s
3⍕o
' '

Tested over the examples in the question plus a slightly more complicated one:
      Input: '5 0/3 1/1 2/0 2'
 9.000

      Input: '3 0/1 0/5 0/0 1 2 3'
 0.652

      Input: '3 0/6 1/1 0/5 0/0 2 3 4'
 0.763

      Input: '2 0/2 1/2 0/2 0/2 4/2 5/2 2 3 6/2 7/2 2 3 6/0 8 9'
 2.424

Always amazed by APL answers - they look absolutely insane. The final resistor was just to give something for the other resistors to connect to - a dummy end link. Well done!

I think you can save a couple of characters. Replace the first two lines with o←⊃↑¨r←¯1↓⍎¨(c≠'/')⊂c. This pattern is applicable in a couple of places.