问:
Program my microwave oven
I'm very lazy so I try to always program my microwave with the fewest possible button presses.  My microwave has the following buttons:

A "minute plus" button which may only be pressed first and implies "start".  It may be pressed multiple times for multiple minutes, but it will not add a minute to a manually entered time.  Output +

A set of 0-9 buttons.  Time entry is MMSS (i.e. "130" means 1 minute 30 seconds).  Seconds may range from 0..99.  So "130" and "90" are equivalent entries.  Obviously each minute is 60 seconds even if the seconds part of the entry exceeds 59.  Output 0..9

A "start" button which must be pressed to start the microwave if the time is entered manually.  Output S

My food packages specify time in MM:SS and so the program must accept that input.

Examples

1:00 is + (remember "minute plus" implies start)

1:01 is 61S (seconds can exceed 59, but "minute plus" does not work in conjunction with digits -- I think this is a design flaw in my microwave)

9:00 is 900S (shorter than +++++++++)

答:
Perl

meets the requirements, but it isn't how I would enter the buttons (e.g. "860S" vs "900S") handles exactly 60 seconds as a special case

```<code>use strict;
use warnings;

sub cook
{
  my ($mins, $secs) = @_;

  my $plus = $secs =~ /00/ ? $mins : undef;

  my $secs_total = $mins * 60 + $secs;
  my $mins_total = 0;

  while ($secs_total > 99)
  {
    ++$mins_total;
    $secs_total -= 60;
  }

  $plus = "+" x $plus if defined $plus;

  my $nums = "";
  my $even = ($mins_total > 0 and $secs_total == 60);

  $secs_total *= not $even;
  $mins_total += $even;

  if ($mins_total > 0)
  {
    $nums = sprintf "%s%02dS", $mins_total, $secs_total;
  }
  else
  {
    $nums = sprintf "%2dS", $secs_total;
  }

  return ($nums, $plus)
    [defined $plus and length $plus < length $nums];
}

die "usage:$/\tperl $0 <MINUTES>:<SECONDS>$/"
  unless @ARGV > 0 and shift =~ /([0-9]{1,2}):([0-9]{1,2})/;

print cook($1, $2), $/;
</code>```

Output

```<code>andrew@gidget:~$ perl mic.pl 9:00
900S
andrew@gidget:~$ perl mic.pl 1:00
+
andrew@gidget:~$ perl mic.pl 1:01
61S
andrew@gidget:~$ perl mic.pl 1:30
90S
andrew@gidget:~$ perl mic.pl 0:07
 7S
andrew@gidget:~$ perl mic.pl 4:00
400S
</code>```

Title: Program my microwave oven

Body:
Perl

meets the requirements, but it isn't how I would enter the buttons (e.g. "860S" vs "900S") handles exactly 60 seconds as a special case

use strict;
use warnings;

sub cook
{
  my ($mins, $secs) = @_;

  my $plus = $secs =~ /00/ ? $mins : undef;

  my $secs_total = $mins * 60 + $secs;
  my $mins_total = 0;

  while ($secs_total > 99)
  {
    ++$mins_total;
    $secs_total -= 60;
  }

  $plus = "+" x $plus if defined $plus;

  my $nums = "";
  my $even = ($mins_total > 0 and $secs_total == 60);

  $secs_total *= not $even;
  $mins_total += $even;

  if ($mins_total > 0)
  {
    $nums = sprintf "%s%02dS", $mins_total, $secs_total;
  }
  else
  {
    $nums = sprintf "%2dS", $secs_total;
  }

  return ($nums, $plus)
    [defined $plus and length $plus < length $nums];
}

die "usage:$/\tperl $0 <MINUTES>:<SECONDS>$/"
  unless @ARGV > 0 and shift =~ /([0-9]{1,2}):([0-9]{1,2})/;

print cook($1, $2), $/;

Output

andrew@gidget:~$ perl mic.pl 9:00
900S
andrew@gidget:~$ perl mic.pl 1:00
+
andrew@gidget:~$ perl mic.pl 1:01
61S
andrew@gidget:~$ perl mic.pl 1:30
90S
andrew@gidget:~$ perl mic.pl 0:07
 7S
andrew@gidget:~$ perl mic.pl 4:00
400S


ContentLicense: CC BY-SA 3.0

Title: Program my microwave oven

Body:
I'm very lazy so I try to always program my microwave with the fewest possible button presses.  My microwave has the following buttons:

A "minute plus" button which may only be pressed first and implies "start".  It may be pressed multiple times for multiple minutes, but it will not add a minute to a manually entered time.  Output +

A set of 0-9 buttons.  Time entry is MMSS (i.e. "130" means 1 minute 30 seconds).  Seconds may range from 0..99.  So "130" and "90" are equivalent entries.  Obviously each minute is 60 seconds even if the seconds part of the entry exceeds 59.  Output 0..9

A "start" button which must be pressed to start the microwave if the time is entered manually.  Output S

My food packages specify time in MM:SS and so the program must accept that input.

Examples

1:00 is + (remember "minute plus" implies start)

1:01 is 61S (seconds can exceed 59, but "minute plus" does not work in conjunction with digits -- I think this is a design flaw in my microwave)

9:00 is 900S (shorter than +++++++++)

Body:
JavaScript

var x = /(\d+):(\d\d)/.exec('<time here>');
x[1] === '0' ? +x[2] + 'S' :
x[1] < 4 && x[2] === '00' ? (
    x[1] === '1' ? '+' :
    x[1] === '2' ? '++' : '+++') :
x[2] < 40 ?
    (x[1] - 1 ? x[1] - 1 : '') + '' + (6 + +x[2][0]) + x[2][1] + 'S' :
x[1] + x[2] + 'S'


问:
Turing Machine Simulator
Write a Turing machine simulator.

For simplicity we can assume statuses as integer, symbols as char, blank symbol equals whitespace

5-tuple in the form of current state, input symbol, next state, output symbol, direction (left or right) the order is not mandatory but specify if you swap it

The machine must stop when an unknown state is reached, no other halt condition allowed.

The tape is infinite in both directions and you can always read an empty character.

Input: the initial tape, an initial state and a program. you are free to read the data from anywhere in the format you like

Output: the tape after the execution of the program

Required: an example program that run on top of your simulator

This is a code-colf so the shortest code win.

I'll post an implementation and some example programs in the next few hours.

答:
C (not golfed yet)

I suppose I can't win with this, still it was fun getting it to work. This is even more true now that it really does work. :)

Except it's only infinite in one direction. I suppose it needs a negative tape, too. Sigh....

Negative wasn't so bad. We interleave the two sides as evens and odds. Complication is now it needs to display the tape in sequential order, as the file itself is now jumbled. This is a legitimate alteration to make, I think. Turing himself simplified this way.

```<code>#include<stdio.h>
int main(int c, char**v){
    int min=0,max=0;
    int pos=0,qi;sscanf(v[1],"%d",&qi);
    FILE*tab=fopen(v[2],"r");
    FILE*tape=fopen(v[3],"r+");
    setbuf(tape,NULL);
    do {
        min = pos<min? pos: min;
        max = pos>max? pos: max;
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        int c = fgetc(tape), qt=qi-1,qr;
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        char x = c==EOF?' ':c, xt=x-1,xr,d[2];
        if (x == '\n') x = ' ';
printf("%d '%c' %d (%d)\n", qi, x, pos, (int)ftell(tape));
        while((qt!=qi)||(xt!=x)){
            fscanf(tab, "%d '%c' %d '%c' %1[LRN]", &qt, &xt, &qr, &xr, d);
            if (feof(tab)){
                goto HALT;
            }
printf("%d '%c' %d '%c' %s\n", qt, xt, qr, xr, d);
        }
        qi=qr;
        rewind(tab);
        fputc(xr,tape);
        pos+=*d=='L'?-1:*d=='R'?1:0;
    } while(1);
HALT:
printf("[%d .. %d]:\n", min, max);
    for (pos = min; pos <= max; pos++){
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        //printf("%d ",pos);
        putchar(fgetc(tape));
        //puts("");
    }
    return qi;
}
</code>```

And here's the test-run:

```<code>522(1)04:33 AM:~ 0> cat bab.tm
0 'a' 0 'b' R
0 'b' 0 'a' R
523(1)04:33 AM:~ 0> echo aaaaa > blank; make tm ; tm 0 bab.tm blank; echo; cat blank
make: `tm' is up to date.
0 'a' 0 (0)
0 'a' 0 'b' R
0 'a' 1 (2)
0 'a' 0 'b' R
0 'a' 2 (4)
0 'a' 0 'b' R
0 ' ' 3 (6)
0 'a' 0 'b' R
0 'b' 0 'a' R
[0 .. 3]:
bbbÿ
babab
</code>```

The program outputs the tape in sequential order, but the file represents the negative and positive sides interleaved.

Title: Turing Machine Simulator

Body:
C (not golfed yet)

I suppose I can't win with this, still it was fun getting it to work. This is even more true now that it really does work. :)

Except it's only infinite in one direction. I suppose it needs a negative tape, too. Sigh....

Negative wasn't so bad. We interleave the two sides as evens and odds. Complication is now it needs to display the tape in sequential order, as the file itself is now jumbled. This is a legitimate alteration to make, I think. Turing himself simplified this way.

#include<stdio.h>
int main(int c, char**v){
    int min=0,max=0;
    int pos=0,qi;sscanf(v[1],"%d",&qi);
    FILE*tab=fopen(v[2],"r");
    FILE*tape=fopen(v[3],"r+");
    setbuf(tape,NULL);
    do {
        min = pos<min? pos: min;
        max = pos>max? pos: max;
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        int c = fgetc(tape), qt=qi-1,qr;
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        char x = c==EOF?' ':c, xt=x-1,xr,d[2];
        if (x == '\n') x = ' ';
printf("%d '%c' %d (%d)\n", qi, x, pos, (int)ftell(tape));
        while((qt!=qi)||(xt!=x)){
            fscanf(tab, "%d '%c' %d '%c' %1[LRN]", &qt, &xt, &qr, &xr, d);
            if (feof(tab)){
                goto HALT;
            }
printf("%d '%c' %d '%c' %s\n", qt, xt, qr, xr, d);
        }
        qi=qr;
        rewind(tab);
        fputc(xr,tape);
        pos+=*d=='L'?-1:*d=='R'?1:0;
    } while(1);
HALT:
printf("[%d .. %d]:\n", min, max);
    for (pos = min; pos <= max; pos++){
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        //printf("%d ",pos);
        putchar(fgetc(tape));
        //puts("");
    }
    return qi;
}

And here's the test-run:

522(1)04:33 AM:~ 0> cat bab.tm
0 'a' 0 'b' R
0 'b' 0 'a' R
523(1)04:33 AM:~ 0> echo aaaaa > blank; make tm ; tm 0 bab.tm blank; echo; cat blank
make: `tm' is up to date.
0 'a' 0 (0)
0 'a' 0 'b' R
0 'a' 1 (2)
0 'a' 0 'b' R
0 'a' 2 (4)
0 'a' 0 'b' R
0 ' ' 3 (6)
0 'a' 0 'b' R
0 'b' 0 'a' R
[0 .. 3]:
bbbÿ
babab

The program outputs the tape in sequential order, but the file represents the negative and positive sides interleaved.


问:
Ode-cay Olf-gay
Write a program which accepts a sentence into stdin, and writes that sentence to stdout in pig latin.

Here are some test cases which your program should handle:

```<code>Input:
    Read your script
Output:
    ead-Ray our-yay ipt-scray
</code>```

Hyphenation is mandatory. Note that multiple consonants at the start of the word must all be moved to the end. Capitalization of the output does not matter; Ead-ray or ead-ray are also valid translations of Read

```<code>Input:
    An utterance is allowed an opening vowel
Output:
    An-way utterance-way is-way allowed-way an-way opening-way owel-vay
</code>```

Words starting with vowels have -way appended in their pig latin form (don't forget to handle capital opening vowels)

```<code>Input:
    sky
    -skyay
</code>```

Words consisting entirely of consonants should have a hyphen prepended, and ay appended

Punctuation is undefined; I don't care if leading or trailing punctuation ends up inside the pig latin word.

This is code golf; the shortest program by character count wins. I've written a solution myself which handles all these cases which I shall post as a response.

答:
Python - <s>122</s> 85 characters

```<code>import re
print re.sub("-a","-wa",re.sub("([^aeiou ]*)(\w*)",r"\2-\1ay",raw_input()))
</code>```

122 -> 85: Improved use of regexes; running regex on whole sentence rather than individual words, and doing all the processing with regexes rather than a conditional expression. This ended up making it pretty similar to grc's answer

Title: Ode-cay Olf-gay

Body:
Python - <s>122</s> 85 characters

import re
print re.sub("-a","-wa",re.sub("([^aeiou ]*)(\w*)",r"\2-\1ay",raw_input()))

122 -> 85: Improved use of regexes; running regex on whole sentence rather than individual words, and doing all the processing with regexes rather than a conditional expression. This ended up making it pretty similar to grc's answer


答:
Python, 89

```<code>import re
print re.sub('-a','-wa',re.sub('(?i)([^aeiou ]*)(\w*)',r'\2-\1ay',raw_input()))
</code>```

Title: Ode-cay Olf-gay

Body:
Write a program which accepts a sentence into stdin, and writes that sentence to stdout in pig latin.

Here are some test cases which your program should handle:

```<code>Input:
    Read your script
Output:
    ead-Ray our-yay ipt-scray
</code>```

Hyphenation is mandatory. Note that multiple consonants at the start of the word must all be moved to the end. Capitalization of the output does not matter; Ead-ray or ead-ray are also valid translations of Read

```<code>Input:
    An utterance is allowed an opening vowel
Output:
    An-way utterance-way is-way allowed-way an-way opening-way owel-vay
</code>```

Words starting with vowels have -way appended in their pig latin form (don't forget to handle capital opening vowels)

```<code>Input:
    sky
    -skyay
</code>```

Words consisting entirely of consonants should have a hyphen prepended, and ay appended

Punctuation is undefined; I don't care if leading or trailing punctuation ends up inside the pig latin word.

This is code golf; the shortest program by character count wins. I've written a solution myself which handles all these cases which I shall post as a response.

Body:
Python, 89

import re
print re.sub('-a','-wa',re.sub('(?i)([^aeiou ]*)(\w*)',r'\2-\1ay',raw_input()))


问:
Finding "sub-palindromes".
The shortest code that finds all unique "sub-palindromes" of a string, that is: any substring with length > 1 that is a palindrome.

eg.1

```<code>input: "12131331"
output: "33", "121", "131", "313", "1331"
</code>```

eg.2

```<code>input: "3333"
output: "33", "333", "3333"
</code>```

ContentLicense: CC BY-SA 2.5

Title: Finding "sub-palindromes".

Body:
J, 24 <s>31</s> <s>40</s>

~.(#~(1<#*]-:|.)&>),<\\.

Sample use:

   ~.(#~(1<#*]-:|.)&>),<\\. '12131331'
┌───┬───┬───┬────┬──┐
│121│131│313│1331│33│
└───┴───┴───┴────┴──┘
   ~.(#~(1<#*]-:|.)&>),<\\. '3333'
┌──┬───┬────┐
│33│333│3333│
└──┴───┴────┘

Take that, GolfScript!


问:
The Strange Unsorting Machine for Nefarious Purposes
Good Evening Golfers!

Your challenge is to completely unsort a series of numbers.

Input

Exactly 100 integers will be fed to your program. Your program may accept the input either as a file, or via stdin. Each integer will be separated by a newline character.

Those 100 integers will range from the minimal to the maximal values of a signed integer in your chosen language.

There will be no duplicate values. The values may be ordered, unordered or partially ordered - your program should be able to handle each case.

Output

The output must be each of the 100 integers, completely unsorted, each separated by a newline character. The output may be via stdout, or to a file.

Completely Unsorted means that no value is adjacent to any value which it would be adjacent to if the list were completely sorted in an ordered sequence.

Score

1 point per character, and lowest score wins. There is a bonus of -100 for any solution using no built in or library sorting functions. There is a bonus of -20 for any solutions using no built in random number functions.

I have tried to define this question as completely as possible. If you have any questions, please ask. If you have any comments on how I could do better next time, please let me know.

Fore!

答:
Python 2: 90 char

```<code>n=100
s=sorted(int(raw_input())for i in range(n))
for i in range(n):print s[(4*i+4*i/n)%n]
</code>```

lazy attempt but just for starters

Body:
Python 2: 90 char

n=100
s=sorted(int(raw_input())for i in range(n))
for i in range(n):print s[(4*i+4*i/n)%n]

lazy attempt but just for starters


问:
Implementing a Traffic Light Checker
A three-color traffic light must switch lights in the following order: red, green, yellow, red.

To indicate when crossing slowly without a stop is permitted, the yellow signal may be flashed. To indicate when crossing immediately after a full stop is permitted, the red signal may be flashed.

Either flash sequence may only be started after the red light is lit and must be followed with a red. All lights are initially off. All sequences must begin a red light. Lighting any light causes all other lights to turn off.  No color may be repeated: e.g., red, red is not allowed.

Task:

Write a program that checks a sequence of light codes and determines if that sequence follows or violates the traffic light rules.

Input
Read from STDIN a sequence of the follow codes:  R (red), Y (yellow), G (Green),  P (Pause - flash red),  C (Caution - flash yellow), and X (off). Each code must be separated with a space.  The entire sequence is submitted by an end-of-line (e.g., pressing the Enter key.)  A sequence must have no more than 15 codes in total.

Winning criteria:

Output
Write to STDOUT an evaluation of the sequence:

ACCEPT     >> The entire input sequence meets all rules.

REJECT     >> The input sequence violates any sequence constraint; for example G Y.

ERROR      >> The input is malformed – undefined code, too short, too long, etc.

```
EXAMPLES:

1 - Input: R G Y R C R G Y R                  Output: ACCEPT
2 - Input: G Y R G Y R                        Output: REJECT
3 - Input: R Y G P                            Output: REJECT
4 - Input: R G Y                              Output: ERROR
5 - Input: X 8 S                              Output: ERROR
6 - Input: R G Y R C R P R G Y R G Y R G Y R  Output: ERROR
```

You do not have to worry about the reasons listed below, they are only used a reference as to why the input strings have either been Accepted, Rejected or Erroneous.

Reasons:

Correct

Doesn’t start with R

Invalid sequence

Undefined code

Undefined Codes e.g. X is not part of the grammar

The input is malformed – undefined code, too short, too long, etc.

答:
^^ Neat line ardnew, but check yourself for cases

```<code>1: R G Y R P
2: R G Y C
</code>```

This was one of the questions from the IEEE contest

To determine the next light in the sequence its simply (let c = color of light)

```<code>(c == 'R') ? ('G', 'P', 'C') : (c == 'G') ? ('Y') : ('R')
</code>```

Those conditions follows from the question statement

If the light is RED, the next light can only be (GREEN, PAUSE, CAUTION)

If the light is GREEN, the next light can only be (YELLOW)

Else (light is (YELLOW, PAUSE, CAUTION)) the next light is RED

The first conditions follow from the fact that its always RED GREEN YELLOW

The flashing lights PAUSE and CAUTION require there be a RED immediately before and after

Title: Implementing a Traffic Light Checker

Body:
^^ Neat line ardnew, but check yourself for cases

1: R G Y R P
2: R G Y C

This was one of the questions from the IEEE contest

To determine the next light in the sequence its simply (let c = color of light)

(c == 'R') ? ('G', 'P', 'C') : (c == 'G') ? ('Y') : ('R')

Those conditions follows from the question statement

If the light is RED, the next light can only be (GREEN, PAUSE, CAUTION)

If the light is GREEN, the next light can only be (YELLOW)

Else (light is (YELLOW, PAUSE, CAUTION)) the next light is RED

The first conditions follow from the fact that its always RED GREEN YELLOW

The flashing lights PAUSE and CAUTION require there be a RED immediately before and after


答:
J, -63 (57-120) characters

Since everyone else is going down the self-written sort route...

```<code>,50(}.,.{.)($:@([-.m),~m=.]#~]=<./)^:(0<#),".[;._2[1!:1[3
</code>```

Doesn't use any random number function, nor any built-in sort.

Uses a simple recursive selection sort to sort the input.

Title: The Strange Unsorting Machine for Nefarious Purposes

Body:
Good Evening Golfers!

Your challenge is to completely unsort a series of numbers.

Input

Exactly 100 integers will be fed to your program. Your program may accept the input either as a file, or via stdin. Each integer will be separated by a newline character.

Those 100 integers will range from the minimal to the maximal values of a signed integer in your chosen language.

There will be no duplicate values. The values may be ordered, unordered or partially ordered - your program should be able to handle each case.

Output

The output must be each of the 100 integers, completely unsorted, each separated by a newline character. The output may be via stdout, or to a file.

Completely Unsorted means that no value is adjacent to any value which it would be adjacent to if the list were completely sorted in an ordered sequence.

Score

1 point per character, and lowest score wins. There is a bonus of -100 for any solution using no built in or library sorting functions. There is a bonus of -20 for any solutions using no built in random number functions.

I have tried to define this question as completely as possible. If you have any questions, please ask. If you have any comments on how I could do better next time, please let me know.

Fore!

Body:
J, -63 (57-120) characters

Since everyone else is going down the self-written sort route...

,50(}.,.{.)($:@([-.m),~m=.]#~]=<./)^:(0<#),".[;._2[1!:1[3

Doesn't use any random number function, nor any built-in sort.

Uses a simple recursive selection sort to sort the input.


答:
Python 27 (147 - 100 - 20)

```<code>R=range
def S(L):
 for i in R(len(L)-1):
    if L[i]>L[i+1]:L[i:i+2]=[L[i+1],L[i]];S(L)
a=map(input,['']*100);S(a)
for i in R(100):print a[i/2+i%2*50]
</code>```

Note: the spaces before if L[i]>... should be a tab but apparently show up as spaces in a code block.

Body:
Python 27 (147 - 100 - 20)

R=range
def S(L):
 for i in R(len(L)-1):
    if L[i]>L[i+1]:L[i:i+2]=[L[i+1],L[i]];S(L)
a=map(input,['']*100);S(a)
for i in R(100):print a[i/2+i%2*50]

Note: the spaces before if L[i]>... should be a tab but apparently show up as spaces in a code block.


答:
GolfScript (score 27 - 120 = -93)

```<code>~].,{{.2$<{\}*}*]}*.(;+2%n*
</code>```

Note: that $ is referencing an element on the stack. There is sorting, but it's done with an manually coded bubble sort.

Thanks to Howard, for -90 => -92; and Ilmari, who inspired -92 => -93.

Body:
GolfScript (score 27 - 120 = -93)

~].,{{.2$<{\}*}*]}*.(;+2%n*

Note: that $ is referencing an element on the stack. There is sorting, but it's done with an manually coded bubble sort.

Thanks to Howard, for -90 => -92; and Ilmari, who inspired -92 => -93.


问:
Minimum number of transactions so everyone has paid the same
On a road trip, N people pay for fuel. Each pays a different amount. At the end of the trip, calculate the minimum number of transactions so that each person has paid the same amount.

e.g. on the road trip, these people pay for fuel

Dave - $50

John - $25

George - $5

Barry - $0

After the road trip:

Barry pays Dave $20

George pays John $5

George pays Dave $10

Added: The output of the program should list the transactions.

Bonus points if the solution is written in Visual Basic.

答:
Python, 308 Characters

I chose not to go after the bonus because the last time I used VB was over a decade ago, and I am still suffering from the PTSD ;-)

I didn't try and golf this very much because I'm not sure if that's the goal.  This code is guaranteed to return a solution with the minimum number of transactions.

```<code>def t(p):
 a=sum(p)/float(len(p))
 q=[([],p)]
 l=len(p)
 r=range(l)
 while q:
  n=q.pop(0)
  g=1
  for i in r:
   d=n[1][i]-a
   if d>0:
    g=0
    for j in r:
     if n[1][j]<a:
      v=min(d,a-n[1][j])
      y=list(n[1])
      y[i]-=v
      y[j]+=v
      if i!=j:q+=[(n[0]+[(j,i,v)],y)]
  if g:return n[0]
</code>```

Usage

The t function takes a list of the amounts that each person paid.  Using the example from the question:

```<code>> print t([50,25,5,0])
[(2, 0, 15.0), (3, 0, 15.0), (3, 1, 5.0)]
</code>```

So the solution is for person 2 (George) to pay person 0 (Dave) $15 and for person 3 (Barry) to pay 0 (Dave) $15 and also to pay 1 (John) $5.

Body:
Python, 308 Characters

I chose not to go after the bonus because the last time I used VB was over a decade ago, and I am still suffering from the PTSD ;-)

I didn't try and golf this very much because I'm not sure if that's the goal.  This code is guaranteed to return a solution with the minimum number of transactions.

def t(p):
 a=sum(p)/float(len(p))
 q=[([],p)]
 l=len(p)
 r=range(l)
 while q:
  n=q.pop(0)
  g=1
  for i in r:
   d=n[1][i]-a
   if d>0:
    g=0
    for j in r:
     if n[1][j]<a:
      v=min(d,a-n[1][j])
      y=list(n[1])
      y[i]-=v
      y[j]+=v
      if i!=j:q+=[(n[0]+[(j,i,v)],y)]
  if g:return n[0]

Usage

The t function takes a list of the amounts that each person paid.  Using the example from the question:

> print t([50,25,5,0])
[(2, 0, 15.0), (3, 0, 15.0), (3, 1, 5.0)]

So the solution is for person 2 (George) to pay person 0 (Dave) $15 and for person 3 (Barry) to pay 0 (Dave) $15 and also to pay 1 (John) $5.


答:
Python 48 = (148 - 100)

```<code>from random import*
x=[input()for i in range(100)]
while any(abs(x[i]-x[i+1])>1 for i in range(99)):n=randint(1,99);x=x[n:]+x[:n]
for j in x:print j
</code>```

Haven't tested this because it isn't guaranteed (or likely) to run in any reasonable amount of time, but should work in theory given infinite time.

Body:
Python 48 = (148 - 100)

from random import*
x=[input()for i in range(100)]
while any(abs(x[i]-x[i+1])>1 for i in range(99)):n=randint(1,99);x=x[n:]+x[:n]
for j in x:print j

Haven't tested this because it isn't guaranteed (or likely) to run in any reasonable amount of time, but should work in theory given infinite time.


答:
ruby

```<code>#Build a string for the microwave
def build_result(minutes, seconds)
  duration = minutes * 60 + seconds
  if duration < 99
    result = "%iS" % [ duration]    #shortcut '90S' instead '130S'
  else
    result = "%i%02iS" % [ minutes, seconds]
  end
  result
end

#Call microwave optimizer
def microwave( input )
  minutes  = input.split(/:/).first.to_i
  seconds = input.split(/:/).last.to_i

  #build result
  result = build_result(minutes, seconds)
  #try a shorter result, make 999S out of '10:39':
  if seconds < 40 and minutes > 0
    result2 = build_result(minutes - 1, seconds + 60)   #try a
    result = ( result.size <= result2.size ? result : result2 )
  end

  #Check if a version with only '+' is shorter
  if seconds == 0 and minutes <= result.size
    result = '+' * minutes
  end
  result
end

#Test if called with an argument
if ARGV.empty?
  require 'test/unit'   #Exceute a test
  class MicrowaveTest < Test::Unit::TestCase
    def test_007
      assert_equal('7S', microwave('0:07'))
    end
    def test_100
      assert_equal('+', microwave('1:00'))
    end
    def test_101
      assert_equal('61S', microwave('1:01'))
    end
    def test_130
      assert_equal('90S', microwave('1:30'))
    end
    def test_400
      #~ assert_equal('400S', microwave('4:00'))
      assert_equal('++++', microwave('4:00'))
    end
    def test_500
      assert_equal('500S', microwave('5:00'))
    end
    def test_900
      assert_equal('900S', microwave('9:00'))
    end
    def test_1000
      #~ assert_equal('1000S', microwave('10:00'))
      assert_equal('960S', microwave('10:00'))
    end
    def test_1015
      #~ assert_equal('1015S', microwave('10:15'))
      assert_equal('975S', microwave('10:15'))
    end
    def test_1039
      #~ assert_equal('1039S', microwave('10:39'))
      assert_equal('999S', microwave('10:39'))
    end
  end
else  #started via shell, evaluate input
  puts microwave(ARGV.first)
end
</code>```

Remarks:

Start it with ruby program-my-microwave-oven.rb and a unit test is evaluated.

Start it with ruby program-my-microwave-oven.rb 10:00 and it writes 960S

Some remarks on the rules (and my interpretation):

The shortest for 10:00 is 960S (9 minutes and 60 seconds -> 10 minutes).

The shortest for 10:39 is 999S (9 minutes and 99 seconds -> 10 minutes and 39 seconds).

for 4:00 it prefers ++++ (less finger movements)

Title: Program my microwave oven

Body:
ruby

#Build a string for the microwave
def build_result(minutes, seconds)
  duration = minutes * 60 + seconds
  if duration < 99
    result = "%iS" % [ duration]    #shortcut '90S' instead '130S'
  else
    result = "%i%02iS" % [ minutes, seconds]
  end
  result
end

#Call microwave optimizer
def microwave( input )
  minutes  = input.split(/:/).first.to_i
  seconds = input.split(/:/).last.to_i

  #build result
  result = build_result(minutes, seconds)
  #try a shorter result, make 999S out of '10:39':
  if seconds < 40 and minutes > 0
    result2 = build_result(minutes - 1, seconds + 60)   #try a
    result = ( result.size <= result2.size ? result : result2 )
  end

  #Check if a version with only '+' is shorter
  if seconds == 0 and minutes <= result.size
    result = '+' * minutes
  end
  result
end

#Test if called with an argument
if ARGV.empty?
  require 'test/unit'   #Exceute a test
  class MicrowaveTest < Test::Unit::TestCase
    def test_007
      assert_equal('7S', microwave('0:07'))
    end
    def test_100
      assert_equal('+', microwave('1:00'))
    end
    def test_101
      assert_equal('61S', microwave('1:01'))
    end
    def test_130
      assert_equal('90S', microwave('1:30'))
    end
    def test_400
      #~ assert_equal('400S', microwave('4:00'))
      assert_equal('++++', microwave('4:00'))
    end
    def test_500
      assert_equal('500S', microwave('5:00'))
    end
    def test_900
      assert_equal('900S', microwave('9:00'))
    end
    def test_1000
      #~ assert_equal('1000S', microwave('10:00'))
      assert_equal('960S', microwave('10:00'))
    end
    def test_1015
      #~ assert_equal('1015S', microwave('10:15'))
      assert_equal('975S', microwave('10:15'))
    end
    def test_1039
      #~ assert_equal('1039S', microwave('10:39'))
      assert_equal('999S', microwave('10:39'))
    end
  end
else  #started via shell, evaluate input
  puts microwave(ARGV.first)
end

Remarks:

Start it with ruby program-my-microwave-oven.rb and a unit test is evaluated.

Start it with ruby program-my-microwave-oven.rb 10:00 and it writes 960S

Some remarks on the rules (and my interpretation):

The shortest for 10:00 is 960S (9 minutes and 60 seconds -> 10 minutes).

The shortest for 10:39 is 999S (9 minutes and 99 seconds -> 10 minutes and 39 seconds).

for 4:00 it prefers ++++ (less finger movements)


答:
Perl (60)

Use perl -n. The -n switch is counted (as two characters).

```<code>s/(.*?)([aeiou].*)/print"$2-$1"."w"x!$1."ay "/iefor split
</code>```

Title: Ode-cay Olf-gay

Body:
Perl (60)

Use perl -n. The -n switch is counted (as two characters).

s/(.*?)([aeiou].*)/print"$2-$1"."w"x!$1."ay "/iefor split


答:
Mathematica -56 44 4    (95-120) = -25

Edit:

This version relies on neither built-in functions for sorting lists, nor randomization functions.

```<code>Riffle[RotateLeft[#[[All, 2]], 2], #[[All, 1]]] &
[Partition[l //. {x___, a_, b_, y___} /; b < a :> {x, b, a, y}, 2]]
</code>```

Body:
Mathematica -56 44 4    (95-120) = -25

Edit:

This version relies on neither built-in functions for sorting lists, nor randomization functions.

Riffle[RotateLeft[#[[All, 2]], 2], #[[All, 1]]] &
[Partition[l //. {x___, a_, b_, y___} /; b < a :> {x, b, a, y}, 2]]


答:
APL (110)

(It's not even that short...)

```<code>0(''⍞){×⍴X←0~⍨⍺∘{x y S T s m t←⍺,⍵⋄S T≡x,⊃⊃⌽y:s,⊂(⊃y){m:(¯1↓⍺)(⍵,⍨¯1↑⍺)⋄(⍺,⊃⍵)(1↓⍵)}t,1↓⊃⌽y⋄0}¨⍵:⍵∇⍨⊃X⋄,/⊃⌽⍺}⎕
</code>```

It reads two lines from the keyboard: the first is the program and the second is the initial tape.

The format is

```<code>(in-state in-tape out-state movement out-tape)
</code>```

and they should all be on the same line. 'Movement' is 0 to move right and 1 to move left.

Example program (line breaks inserted for clarity, they should be all on one line.)

```<code>(0 ' ' 1 0 '1')
(0 '1' 0 0 '1')
(1 '1' 1 0 '1')
(1 ' ' 2 1 ' ')
(2 '1' 3 1 ' ')
</code>```

The program adds two unary numbers together, for example:

```<code>in:  1111 111
out: 1111111
</code>```

Example 2 (adapted from the binary increment program from Marco Martinelli's entry):

```<code>(0 '0' 0 0 '0')
(0 '1' 0 0 '1')
(0 ' ' 1 1 ' ')
(1 '0' 2 0 '1')
(1 '1' 3 1 '0')
(3 '0' 2 0 '1')
(3 ' ' 2 0 '1')
(3 '1' 3 1 '0')
</code>```

Title: Turing Machine Simulator

Body:
Write a Turing machine simulator.

For simplicity we can assume statuses as integer, symbols as char, blank symbol equals whitespace

5-tuple in the form of current state, input symbol, next state, output symbol, direction (left or right) the order is not mandatory but specify if you swap it

The machine must stop when an unknown state is reached, no other halt condition allowed.

The tape is infinite in both directions and you can always read an empty character.

Input: the initial tape, an initial state and a program. you are free to read the data from anywhere in the format you like

Output: the tape after the execution of the program

Required: an example program that run on top of your simulator

This is a code-colf so the shortest code win.

I'll post an implementation and some example programs in the next few hours.

Body:
APL (110)

(It's not even that short...)

0(''⍞){×⍴X←0~⍨⍺∘{x y S T s m t←⍺,⍵⋄S T≡x,⊃⊃⌽y:s,⊂(⊃y){m:(¯1↓⍺)(⍵,⍨¯1↑⍺)⋄(⍺,⊃⍵)(1↓⍵)}t,1↓⊃⌽y⋄0}¨⍵:⍵∇⍨⊃X⋄,/⊃⌽⍺}⎕

It reads two lines from the keyboard: the first is the program and the second is the initial tape.

The format is

(in-state in-tape out-state movement out-tape)

and they should all be on the same line. 'Movement' is 0 to move right and 1 to move left.

Example program (line breaks inserted for clarity, they should be all on one line.)

(0 ' ' 1 0 '1')
(0 '1' 0 0 '1')
(1 '1' 1 0 '1')
(1 ' ' 2 1 ' ')
(2 '1' 3 1 ' ')

The program adds two unary numbers together, for example:

in:  1111 111
out: 1111111

Example 2 (adapted from the binary increment program from Marco Martinelli's entry):

(0 '0' 0 0 '0')
(0 '1' 0 0 '1')
(0 ' ' 1 1 ' ')
(1 '0' 2 0 '1')
(1 '1' 3 1 '0')
(3 '0' 2 0 '1')
(3 ' ' 2 0 '1')
(3 '1' 3 1 '0')


Title: Ode-cay Olf-gay

Body:
K, 95

" "/:{$[&/~x in v:v,_v:"AEIOU";"-",x,"ay";("-"/:|_[;x]0,*&t),$[*t:x in v;"way";"ay"]]}'" "\:0:0


答:
APL

APL has a bad reputation that it's unreadable, which is totally not the case if it's not golfed.

The rules:

Whole minutes <= 4 get +, ++, +++, and ++++

960-999 is preferred above 1000-1039. 9960-9999 is preferred above 10000-10039, etc.

If the time can be rewritten such that the seconds are 66, 77, 88, or 99 then this is done. (This never gives a worse solution and usually gives a better one, i.e. 888 instead of 928.)

```
∇ Microwave;time;secs;mins;fmt;⎕ML

 ⎕ML←3

 ⎕←'Enter the time (m+:ss)'
 time←⍞
 mins secs←⍎¨(time≠':')⊂time

⍝ 'minute plus' can only be used on whole minutes ≤ 4
 :If (secs=0)∧(mins≤4)
     ⎕←mins⍴'+'
     :Return
 :EndIf
⍝ If possible, save a keypress by using seconds > 60
⍝ if mins is a power of ten
 :If (mins>0)
     :If ((⌈10⍟mins)=(⌊10⍟mins))∧(secs<40)
         ⎕←('BI2'⎕FMT mins-1),(⎕FMT secs+60),'S'
         :Return
     :EndIf
 :EndIf
⍝ For the 'finger movement' requirement we want as many
⍝ of the keypresses as possible to be of the same key.
⍝ So 888S i.p.v. 928S.
 :If secs∊66 77 88 99-60
     ⎕←('BI2'⎕FMT mins-1),(⎕FMT secs+60),'S'
     :Return
 :EndIf
⍝ Otherwise, just output mmssS, there was no better alternative.
 :If mins>0
    ⍝ output seconds with leading zero
     ⎕←('BI2'⎕FMT mins),('G⊂99⊃'⎕FMT secs),'S'
 :Else
    ⍝ only output seconds, not with leading zero
     ⎕←('BI2'⎕FMT secs),'S'
 :EndIf
∇
```

Title: Program my microwave oven

Body:
I'm very lazy so I try to always program my microwave with the fewest possible button presses.  My microwave has the following buttons:

A "minute plus" button which may only be pressed first and implies "start".  It may be pressed multiple times for multiple minutes, but it will not add a minute to a manually entered time.  Output +

A set of 0-9 buttons.  Time entry is MMSS (i.e. "130" means 1 minute 30 seconds).  Seconds may range from 0..99.  So "130" and "90" are equivalent entries.  Obviously each minute is 60 seconds even if the seconds part of the entry exceeds 59.  Output 0..9

A "start" button which must be pressed to start the microwave if the time is entered manually.  Output S

My food packages specify time in MM:SS and so the program must accept that input.

Examples

1:00 is + (remember "minute plus" implies start)

1:01 is 61S (seconds can exceed 59, but "minute plus" does not work in conjunction with digits -- I think this is a design flaw in my microwave)

9:00 is 900S (shorter than +++++++++)

Body:
APL

APL has a bad reputation that it's unreadable, which is totally not the case if it's not golfed.

The rules:

Whole minutes <= 4 get +, ++, +++, and ++++

960-999 is preferred above 1000-1039. 9960-9999 is preferred above 10000-10039, etc.

If the time can be rewritten such that the seconds are 66, 77, 88, or 99 then this is done. (This never gives a worse solution and usually gives a better one, i.e. 888 instead of 928.)

∇ Microwave;time;secs;mins;fmt;⎕ML

 ⎕ML←3

 ⎕←'Enter the time (m+:ss)'
 time←⍞
 mins secs←⍎¨(time≠':')⊂time

⍝ 'minute plus' can only be used on whole minutes ≤ 4
 :If (secs=0)∧(mins≤4)
     ⎕←mins⍴'+'
     :Return
 :EndIf
⍝ If possible, save a keypress by using seconds > 60
⍝ if mins is a power of ten
 :If (mins>0)
     :If ((⌈10⍟mins)=(⌊10⍟mins))∧(secs<40)
         ⎕←('BI2'⎕FMT mins-1),(⎕FMT secs+60),'S'
         :Return
     :EndIf
 :EndIf
⍝ For the 'finger movement' requirement we want as many
⍝ of the keypresses as possible to be of the same key.
⍝ So 888S i.p.v. 928S.
 :If secs∊66 77 88 99-60
     ⎕←('BI2'⎕FMT mins-1),(⎕FMT secs+60),'S'
     :Return
 :EndIf
⍝ Otherwise, just output mmssS, there was no better alternative.
 :If mins>0
    ⍝ output seconds with leading zero
     ⎕←('BI2'⎕FMT mins),('G⊂99⊃'⎕FMT secs),'S'
 :Else
    ⍝ only output seconds, not with leading zero
     ⎕←('BI2'⎕FMT secs),'S'
 :EndIf
∇


问:
Find The Least Common Characters
Given a string, find the 10 least common alpha-numeric characters within that string.

Output should be formatted with numbers left-padded with spaces so they look like this:

```<code>e:      1
t:     16
c:     42
b:    400
z:  50000
a: 100000
</code>```

Use this to test your program: here

Output for test case:

```<code>j:  2
x:  3
q:  9
k: 32
v: 67
c: 73
w: 79
f: 93
b: 94
p: 96
</code>```

Shortest code wins. You can submit a program or a function.

答:
Python, <s>206</s> <s>199</s> 195 characters

```<code>import sys
t=sys.stdin.read().lower()
f={}
for c in t:
 if c.isalnum():f[c]=f.get(c,0)+1
s=lambda x:x[1]
h=sorted(f.items(),key=s)[:10]
for n in h:print n[0]+': '+`n[1]`.rjust(len(`max(h,s)[1]`))
</code>```

Undoubtedly there is a lot of room for improvement, but here's my first attempt. Produces identical output for the test case provided.

206 -> 199: Removed unnecessary newline and keyword argument

199 -> 195: <s>iter</s>items()

Title: Find The Least Common Characters

Body:
Python, <s>206</s> <s>199</s> 195 characters

import sys
t=sys.stdin.read().lower()
f={}
for c in t:
 if c.isalnum():f[c]=f.get(c,0)+1
s=lambda x:x[1]
h=sorted(f.items(),key=s)[:10]
for n in h:print n[0]+': '+`n[1]`.rjust(len(`max(h,s)[1]`))

Undoubtedly there is a lot of room for improvement, but here's my first attempt. Produces identical output for the test case provided.

206 -> 199: Removed unnecessary newline and keyword argument

199 -> 195: <s>iter</s>items()


答:
Javascript, 271 characters

I'm not sure whether this breaks the rules of not (it doesn't justify the numbers in the output, but here's my solution anyway:

```<code>c=[];t=128;while(t--)c[t]=[0,t];i=prompt().toLowerCase();for(n=0;n<i.length;x=i.charCodeAt(n++),c[x][0]+=x>96&&x<123);for(n=i=0,c=c.sort(function(a,b){return(a[0]-b[0])});n<10;i++)if(c[i][0]>0){console.log(String.fromCharCode(c[i][1])+": "+("  "+c[i][0]).slice(-2));n++}
</code>```

I'm pretty sure it can be simplified (I won't win with this character count :P), but now I can't find anything.

Okay, so I completely forgot that the padding was actually a requirement :O
Corrected that and fixed a bug. (250 -> 271)

Title: Find The Least Common Characters

Body:
Given a string, find the 10 least common alpha-numeric characters within that string.

Output should be formatted with numbers left-padded with spaces so they look like this:

```<code>e:      1
t:     16
c:     42
b:    400
z:  50000
a: 100000
</code>```

Use this to test your program: here

Output for test case:

```<code>j:  2
x:  3
q:  9
k: 32
v: 67
c: 73
w: 79
f: 93
b: 94
p: 96
</code>```

Shortest code wins. You can submit a program or a function.

Body:
Javascript, 271 characters

I'm not sure whether this breaks the rules of not (it doesn't justify the numbers in the output, but here's my solution anyway:

c=[];t=128;while(t--)c[t]=[0,t];i=prompt().toLowerCase();for(n=0;n<i.length;x=i.charCodeAt(n++),c[x][0]+=x>96&&x<123);for(n=i=0,c=c.sort(function(a,b){return(a[0]-b[0])});n<10;i++)if(c[i][0]>0){console.log(String.fromCharCode(c[i][1])+": "+("  "+c[i][0]).slice(-2));n++}

I'm pretty sure it can be simplified (I won't win with this character count :P), but now I can't find anything.

Okay, so I completely forgot that the padding was actually a requirement :O
Corrected that and fixed a bug. (250 -> 271)


答:
Postscript (205) (156) (150) (135)

```<code><<
>>begin
/${stopped}def([){add dup{load}${exit}if}def
0 A{1 index{load}${pop( )}if
get{exec}${exit}if}loop
3{-1[pop}loop{1[print}loop
</code>```

This is probably cheating, but the transition table contains code to perform the transitions. And since the tape is represented by a mapping from integers to integers, I've represented states as a mapping from names to dictionaries so the tape and the program coexist in the same anonymous dictionary.

Extra savings by making all state names executable, so they auto-load.

Ungolfed with embedded "Hello" program. An extra 52 chars buys a loop to read the tape from stdin. Run with gsnd -q tm.ps.

```<code>%!
<<
    /A<<( ){dup(H)def 1 add B}>>
    /B<<( ){dup(e)def 1 add C}>>
    /C<<( ){dup(l)def 1 add D}>>
    /D<<( ){dup(l)def 1 add E}>>
    /E<<( ){dup(o)def 1 add F}>>
>>begin %ds: int-keys=tape name-keys=prog
0 A %pos state
{ %loop
    1 index{load}stopped{pop( )}if  %pos state tape(pos)
    get    {exec}stopped{exit  }if  %new-pos new-state
} loop
% Loop from tape position 0 to left until left tape end is found
0{                                  %pos
  -1 add                            %new-pos
  dup{load}stopped{exit}if          %new-pos tape(new-pos)
  pop                               %new-pos tape(new-pos)
}loop
% Move to the right and print all chars until right end is hit
{                                   %pos
  1 add                             %new-pos
  dup{load}stopped{exit}if          %new-pos tape(new-pos)
  print                             %new-pos tape(new-pos)
}loop
</code>```

So the table-format is

```<code>/in-state<<in-tape{dup out-tape def movement add out-state}
           in-tape2{dup out-tape2 def movement2 add out-state2}>>
</code>```

where in-state is a name, in-tape and out-tape are chars (ie. integers, or expressions which yield integers), movement is -1 for left or 1 for right, and out-state is an executable name. Multiple in-tape transition for the same state must be combined as above.

Title: Turing Machine Simulator

Body:
Postscript (205) (156) (150) (135)

<<
>>begin
/${stopped}def([){add dup{load}${exit}if}def
0 A{1 index{load}${pop( )}if
get{exec}${exit}if}loop
3{-1[pop}loop{1[print}loop

This is probably cheating, but the transition table contains code to perform the transitions. And since the tape is represented by a mapping from integers to integers, I've represented states as a mapping from names to dictionaries so the tape and the program coexist in the same anonymous dictionary.

Extra savings by making all state names executable, so they auto-load.

Ungolfed with embedded "Hello" program. An extra 52 chars buys a loop to read the tape from stdin. Run with gsnd -q tm.ps.

%!
<<
    /A<<( ){dup(H)def 1 add B}>>
    /B<<( ){dup(e)def 1 add C}>>
    /C<<( ){dup(l)def 1 add D}>>
    /D<<( ){dup(l)def 1 add E}>>
    /E<<( ){dup(o)def 1 add F}>>
>>begin %ds: int-keys=tape name-keys=prog
0 A %pos state
{ %loop
    1 index{load}stopped{pop( )}if  %pos state tape(pos)
    get    {exec}stopped{exit  }if  %new-pos new-state
} loop
% Loop from tape position 0 to left until left tape end is found
0{                                  %pos
  -1 add                            %new-pos
  dup{load}stopped{exit}if          %new-pos tape(new-pos)
  pop                               %new-pos tape(new-pos)
}loop
% Move to the right and print all chars until right end is hit
{                                   %pos
  1 add                             %new-pos
  dup{load}stopped{exit}if          %new-pos tape(new-pos)
  print                             %new-pos tape(new-pos)
}loop

So the table-format is

/in-state<<in-tape{dup out-tape def movement add out-state}
           in-tape2{dup out-tape2 def movement2 add out-state2}>>

where in-state is a name, in-tape and out-tape are chars (ie. integers, or expressions which yield integers), movement is -1 for left or 1 for right, and out-state is an executable name. Multiple in-tape transition for the same state must be combined as above.


问:
Print a Binary Tree
Inspired by a recent question on SO...

Write a function to print a binary tree in the following format:

```<code>   3
 /   \
1     5
 \   / \
  2 4   6
</code>```

The output should consist of a line of nodes, followed by a line of / and \ characters indicating relationships, followed by a line of nodes, etc.

You can assume all nodes are representable as a single character.

Adjacent nodes on the lowest level should be separated by at least one space, nodes further up should be separated as appropriate.

Nodes with two children should be placed precisely in the middle of their direct children.

Relationship slashes should be halfway between the parent and the appropriate child (round whichever way you want).

Input:

The input will be provided as an argument to your function. I won't specify the exact structure of the tree, however it must be usable as an actual binary tree. No "trees are represented in my program as strings coincidentally looking like the expected output".

You may print to an output stream or return a string containing the output, your choice.

Points for shortest code, but I'd much prefer a fully working long solution than a 90%-working short one.

Update for the bounty:

For the bounty, I (Optimizer) am making slight changes:

Input can be from STDIN,ARGV or function argument.

Output needs to be on STDOUT (or console.log for JS)

You can assume that input is in a form of array, for ex. [1,2,3] or [1 2 3]

Update 2 - The binary tree should actually be a binary search tree. Since I did not mention this initially, I will allow users to treat the converting a normal array into a binary search tree array as a separate program and the final byte count will only be for the program to take in the array as argument and print it like a binary tree.

答:
Fortran 77 -- 1085 characters

```<code>      subroutine q(u,t)
      implicit integer(i-z)
      character*33 f,g
      dimension t(u)
      m=ceiling(log(real(u))/log(2.))
      v=2**(m+1)-1
      do l=1,m
         n=2**(l-1)
         k=2**(m-l+2)-3
         w=(3+k)*2**(l-1)-k
         p=1+(v-w)/2
         if(l.ne.1)then
            write(f,'(A,I3,A)')'(A',p,',$)'
            print f,' '
            write(f,'(A5,I3,A3)')'(A3,A',k,',$)'
            do j=2**(l-1),2**l-1
               if(t(j/2).lt.0.or.t(j).lt.0)then
                  print f,'   ',' '
               elseif(mod(j,2).eq.0)then
                  print f,'  /',' '
               else
                  print f,' \ ',' '
               endif
            enddo
            print*
         endif
         write(f,'(A,I3,A)')'(A',p,',$)'
         print f,' '
         write(f,'(A5,I3,A3)')'(I3,A',k,',$)'
         write(g,'(A2,I3,A3)')'(A',k+3,',$)'
         do j=2**(l-1),2**l-1
            if(t(j).ge.0)then
               print f,t(j),' '
            else
               print g,' '
            endif
         enddo
         print*
      enddo
      end
</code>```

The tree is represented in the input array t in the usual fashion, root at 1, root->left at 2, root->right at 3 root->left->left at 4...

The output should fit in a conventional terminal up to 5 levels deep.

I use exactly one slash between each pair of nodes, which looks pretty silly near the top once there are four or more levels. I allowed for up to three digit nodes.

Full program with comments and a launching scaffold:

```<code>      program tree

      parameter (l=8)          ! How many nodes to support
      dimension i(l)

c     Initialize the array to all empty nodes
      do j=1,l
         i(j)=-1
      end do
c     Fill in some values
      i(1)=3
      i(2)=1
      i(3)=5
      i(5)=2
      i(6)=4
      i(7)=7
c      i(14)=6
c      i(15)=8
c     Call the printing routine
      call q(l,i)

      stop
      end

c     Print an ASCII representation of the tree
c
c     u the length of the array containing the tree
c     t an integer array representing the tree.
c
c     The array contains only non-negative values, and empty nodes are
c     represented in the array with -1.
c
c     The printed representation uses three characters for every node,
c     and places the (back) slash equally between the two node-centers.
      subroutine q(u,t)
      implicit integer(i-z)
      character*33 f,g
      dimension t(u)
      m=ceiling(log(real(u))/log(2.)) ! maximum depth of the tree
      v=2**(m+1)-1              ! width needed for printing the whole tree
                                ! Optimized from 3*2**m + 1*((2**m)-1) at
                                ! the bottom level
      do l=1,m
         n=2**(l-1)             ! number of nodes on this level
         k=2**(m-l+2)-3         ! internode spacing
         w=(3+k)*2**(l-1)-k     ! width needed for printing this row
                                ! Optimized from 3*2**l + k*((2**l)-1) at
                                ! the bottom level
         p=1+(v-w)/2            ! padding for this row
c     Print the connecting lines associated with the previous level
         if(l.ne.1)then         ! Write the connecting lines
            write(f,'(A,I3,A)')'(A',p,',$)'
            print f,' '
            write(f,'(A5,I3,A3)')'(A3,A',k,',$)'
            do j=2**(l-1),2**l-1
               if(t(j/2).lt.0.or.t(j).lt.0)then
                  print f,'   ',' '
               elseif(mod(j,2).eq.0)then
                  print f,'  /',' '
               else
                  print f,' \ ',' '
               endif
            enddo
            print*
         endif
c     Print the nodes on this level
         write(f,'(A,I3,A)')'(A',p,',$)'
         print f,' '
         write(f,'(A5,I3,A3)')'(I3,A',k,',$)'
         write(g,'(A2,I3,A3)')'(A',k+3,',$)'
         do j=2**(l-1),2**l-1
            if(t(j).ge.0)then
               print f,t(j),' '
            else
               print g,' '
            endif
         enddo
         print*
      enddo
      end
</code>```

Output with input equivalent to the example:

```<code>$ ./a.out
         3
     /      \
     1       5
      \    /  \
       2   4   7
</code>```

Title: Print a Binary Tree

Body:
Fortran 77 -- 1085 characters

      subroutine q(u,t)
      implicit integer(i-z)
      character*33 f,g
      dimension t(u)
      m=ceiling(log(real(u))/log(2.))
      v=2**(m+1)-1
      do l=1,m
         n=2**(l-1)
         k=2**(m-l+2)-3
         w=(3+k)*2**(l-1)-k
         p=1+(v-w)/2
         if(l.ne.1)then
            write(f,'(A,I3,A)')'(A',p,',$)'
            print f,' '
            write(f,'(A5,I3,A3)')'(A3,A',k,',$)'
            do j=2**(l-1),2**l-1
               if(t(j/2).lt.0.or.t(j).lt.0)then
                  print f,'   ',' '
               elseif(mod(j,2).eq.0)then
                  print f,'  /',' '
               else
                  print f,' \ ',' '
               endif
            enddo
            print*
         endif
         write(f,'(A,I3,A)')'(A',p,',$)'
         print f,' '
         write(f,'(A5,I3,A3)')'(I3,A',k,',$)'
         write(g,'(A2,I3,A3)')'(A',k+3,',$)'
         do j=2**(l-1),2**l-1
            if(t(j).ge.0)then
               print f,t(j),' '
            else
               print g,' '
            endif
         enddo
         print*
      enddo
      end

The tree is represented in the input array t in the usual fashion, root at 1, root->left at 2, root->right at 3 root->left->left at 4...

The output should fit in a conventional terminal up to 5 levels deep.

I use exactly one slash between each pair of nodes, which looks pretty silly near the top once there are four or more levels. I allowed for up to three digit nodes.

Full program with comments and a launching scaffold:

      program tree

      parameter (l=8)          ! How many nodes to support
      dimension i(l)

c     Initialize the array to all empty nodes
      do j=1,l
         i(j)=-1
      end do
c     Fill in some values
      i(1)=3
      i(2)=1
      i(3)=5
      i(5)=2
      i(6)=4
      i(7)=7
c      i(14)=6
c      i(15)=8
c     Call the printing routine
      call q(l,i)

      stop
      end

c     Print an ASCII representation of the tree
c
c     u the length of the array containing the tree
c     t an integer array representing the tree.
c
c     The array contains only non-negative values, and empty nodes are
c     represented in the array with -1.
c
c     The printed representation uses three characters for every node,
c     and places the (back) slash equally between the two node-centers.
      subroutine q(u,t)
      implicit integer(i-z)
      character*33 f,g
      dimension t(u)
      m=ceiling(log(real(u))/log(2.)) ! maximum depth of the tree
      v=2**(m+1)-1              ! width needed for printing the whole tree
                                ! Optimized from 3*2**m + 1*((2**m)-1) at
                                ! the bottom level
      do l=1,m
         n=2**(l-1)             ! number of nodes on this level
         k=2**(m-l+2)-3         ! internode spacing
         w=(3+k)*2**(l-1)-k     ! width needed for printing this row
                                ! Optimized from 3*2**l + k*((2**l)-1) at
                                ! the bottom level
         p=1+(v-w)/2            ! padding for this row
c     Print the connecting lines associated with the previous level
         if(l.ne.1)then         ! Write the connecting lines
            write(f,'(A,I3,A)')'(A',p,',$)'
            print f,' '
            write(f,'(A5,I3,A3)')'(A3,A',k,',$)'
            do j=2**(l-1),2**l-1
               if(t(j/2).lt.0.or.t(j).lt.0)then
                  print f,'   ',' '
               elseif(mod(j,2).eq.0)then
                  print f,'  /',' '
               else
                  print f,' \ ',' '
               endif
            enddo
            print*
         endif
c     Print the nodes on this level
         write(f,'(A,I3,A)')'(A',p,',$)'
         print f,' '
         write(f,'(A5,I3,A3)')'(I3,A',k,',$)'
         write(g,'(A2,I3,A3)')'(A',k+3,',$)'
         do j=2**(l-1),2**l-1
            if(t(j).ge.0)then
               print f,t(j),' '
            else
               print g,' '
            endif
         enddo
         print*
      enddo
      end

Output with input equivalent to the example:

$ ./a.out
         3
     /      \
     1       5
      \    /  \
       2   4   7


答:
Python, 144

```<code>import os
s=os.read(0,10000).lower()
n=s.count
a=sorted(filter(str.isalnum,set(s)),key=n)[:10]
for c in a:print c+': %%%ii'%len(`n(a[-1])`)%n(c)
</code>```

Title: Find The Least Common Characters

Body:
Python, 144

import os
s=os.read(0,10000).lower()
n=s.count
a=sorted(filter(str.isalnum,set(s)),key=n)[:10]
for c in a:print c+': %%%ii'%len(`n(a[-1])`)%n(c)


问:
Score a game of Yahtzee
For each of the 13 rows of a Yahtzee scoresheet you are given (from stdin)
a space separated list of 5 numbers (dice).
Your task is to calculate the score for each line and output the Grand Total of the game.

Example

Input and how to interpret it:

```<code>Input       Box              Score
6 1 4 1 3   Aces              2
3 2 2 1 2   Twos              6
6 3 2 3 3   Threes            9
4 2 3 6 5   Fours             4
6 3 5 5 1   Fives            10
1 5 6 5 6   Sixes            12
            Bonus             -
4 2 4 4 1   3 of a kind      15
2 2 3 2 4   4 of a kind       -
3 2 2 2 3   Full house       25
1 3 1 6 1   Small straight    -
2 5 4 6 3   Large straight   40
2 2 2 2 2   Yahtzee          50
5 5 4 5 2   Chance           21
            Grand Total     194
</code>```

We will disregard the Yahtzee Bonus and Joker rules, and only sum up the scores from the Upper and Lower Section and the Bonus in the Upper Section. If in doubt, refer to these rules.

May the shortest code win!

Title: Score a game of Yahtzee


问:
Print this diamond
This question has been spreading like a virus in my office. There are quite a variety of approaches:

Print the following:

```<code>        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1
</code>```

Answers are scored in characters with fewer characters being better.

答:
Javascript, 137

With recursion:

```<code>function p(l,n,s){for(i=l;i;s+=" ",i--);for(i=1;i<=n;s+=i++);for(i-=2;i>0;s+=i--);return(s+="\n")+(l?p(l-1,n+1,"")+s:"")}alert(p(8,1,""))
</code>```

First time on CG :)

Or 118

If I can find a JS implementation that executes 111111111**2 with higher precision.

(Here: 12345678987654320).

```<code>a="1",o="\n";for(i=0;i<9;i++,o+="         ".substr(i)+a*a+"\n",a+="1");for(i=8;i;i--)o+=o.split("\n")[i]+"\n";alert(o)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Print this diamond

Body:
Javascript, 137

With recursion:

function p(l,n,s){for(i=l;i;s+=" ",i--);for(i=1;i<=n;s+=i++);for(i-=2;i>0;s+=i--);return(s+="\n")+(l?p(l-1,n+1,"")+s:"")}alert(p(8,1,""))

First time on CG :)

Or 118

If I can find a JS implementation that executes 111111111**2 with higher precision.

(Here: 12345678987654320).

a="1",o="\n";for(i=0;i<9;i++,o+="         ".substr(i)+a*a+"\n",a+="1");for(i=8;i;i--)o+=o.split("\n")[i]+"\n";alert(o)


Title: Find The Least Common Characters

Body:
K, 60

{(-:|/#:'f)$f:10#$(!x)[i]!r i:<r:. x:#:'=_x@&x in,/.Q`a`A`n}


答:
Mathematica, <s>102</s> 93:

v2:

```<code>  Grid[SortBy[
             Tally@StringCases[ToLowerCase@#,x_?LetterQ:>x<>":"],
              Last@# &],
      Alignment->Right]&@s
</code>```

v1:

```<code>TableForm[
         SortBy[Tally@StringCases[ToLowerCase@#, x_?LetterQ :> x <> ":"],
                #[[2]] &],
         TableAlignments -> Right] &
</code>```

Title: Find The Least Common Characters

Body:
Mathematica, <s>102</s> 93:

v2:

  Grid[SortBy[
             Tally@StringCases[ToLowerCase@#,x_?LetterQ:>x<>":"],
              Last@# &],
      Alignment->Right]&@s

v1:

TableForm[
         SortBy[Tally@StringCases[ToLowerCase@#, x_?LetterQ :> x <> ":"],
                #[[2]] &],
         TableAlignments -> Right] &


答:
Haskell (229)

```<code>import Char
import Data.List
z=filter
t=show
l=length
k x=[(l$z(==m)x,m)|m<-x]
s z=[b:':':take(1+(maximum$map(l.t.fst)z)-l(t a))(repeat ' ')++t a++"\n"|(a,b)<-z]
main=interact$concat.s.take 10.sort.nub.k.map toLower.z isAlphaNum
</code>```

Title: Find The Least Common Characters

Body:
Haskell (229)

import Char
import Data.List
z=filter
t=show
l=length
k x=[(l$z(==m)x,m)|m<-x]
s z=[b:':':take(1+(maximum$map(l.t.fst)z)-l(t a))(repeat ' ')++t a++"\n"|(a,b)<-z]
main=interact$concat.s.take 10.sort.nub.k.map toLower.z isAlphaNum


Title: Find The Least Common Characters

Body:
Perl, 86 chars

given string is in $_

s/[a-z]/$h{lc($&)}++/eig;printf"$_:%9d$/",$h{$_}for(sort{$h{$a}<=>$h{$b}}keys%h)[0..9]


答:
Python -26

(94-120): New, crude approach. Keep popping lowest elements into new list to get the elements sorted, then iterate:

```<code>t=l=[]
i=N=100
exec't=t+[input()];'*N+'l+=[t.pop(t.index(min(t)))];'*N+'print l[i%N];i+=3;'*N
</code>```

Python -13

(107-120): First approach:
Removes four lowest elements at a time, then print these four in another order:

```<code>exec'l=[]'+'+[input()]'*100
while l:
 a,b,c,d=eval('l.pop(l.index(min(l))),'*4)
 for e in[b,d,a,c]:print e
</code>```

Body:
Good Evening Golfers!

Your challenge is to completely unsort a series of numbers.

Input

Exactly 100 integers will be fed to your program. Your program may accept the input either as a file, or via stdin. Each integer will be separated by a newline character.

Those 100 integers will range from the minimal to the maximal values of a signed integer in your chosen language.

There will be no duplicate values. The values may be ordered, unordered or partially ordered - your program should be able to handle each case.

Output

The output must be each of the 100 integers, completely unsorted, each separated by a newline character. The output may be via stdout, or to a file.

Completely Unsorted means that no value is adjacent to any value which it would be adjacent to if the list were completely sorted in an ordered sequence.

Score

1 point per character, and lowest score wins. There is a bonus of -100 for any solution using no built in or library sorting functions. There is a bonus of -20 for any solutions using no built in random number functions.

I have tried to define this question as completely as possible. If you have any questions, please ask. If you have any comments on how I could do better next time, please let me know.

Fore!

Body:
Python -26

(94-120): New, crude approach. Keep popping lowest elements into new list to get the elements sorted, then iterate:

t=l=[]
i=N=100
exec't=t+[input()];'*N+'l+=[t.pop(t.index(min(t)))];'*N+'print l[i%N];i+=3;'*N

Python -13

(107-120): First approach:
Removes four lowest elements at a time, then print these four in another order:

exec'l=[]'+'+[input()]'*100
while l:
 a,b,c,d=eval('l.pop(l.index(min(l))),'*4)
 for e in[b,d,a,c]:print e


答:
C: 11 (131 - 120)

The programm reads from stdin and does a simple insert sort, after that it prints the nth together with th n+50th number, like many of the other solutions.

```<code>main(){int*i,a[101],*j=a;while(scanf("%d",a)>0)for(i=++j;i-->a;)i[1]=*i>=*a?*i:*(i=a);while(a<(i=j-50))printf("%d\n%d\n",*i,*j--);}
</code>```

Body:
C: 11 (131 - 120)

The programm reads from stdin and does a simple insert sort, after that it prints the nth together with th n+50th number, like many of the other solutions.

main(){int*i,a[101],*j=a;while(scanf("%d",a)>0)for(i=++j;i-->a;)i[1]=*i>=*a?*i:*(i=a);while(a<(i=j-50))printf("%d\n%d\n",*i,*j--);}


问:
When does (x == x+2)?
The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.

Simple - should be small, use basic language features.

Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.

Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.

Floating point. Large numbers, infinity or NaN all work.

Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:

Operator overloading - A + that doesn't add or a == that always returns true.

Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.

A one-bit data type. Then x == x+2 (mod 2).

Changing 2 - some language let you assign 0 to it.

答:
Python 2.X (Using redefinition of (cached) integers)

I've noticed all of the python answers have defined classes that redefine the + operator. I'll answer with an even more low-level demonstration of python's flexibility. (This is a python2-specific snippet)

In python, integers are stored more or less this way in C:

typedef struct {            // NOTE: Macros have been expanded
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
    long ob_ival;
} PyIntObject;
```
<p>That is, a struct with a <code>size_t</code>, <code>void *</code>, and <code>long</code> object, in that order.<br />
Once we use, and therefore cache an integer, we can use python's <code>ctypes</code> module to redefine that integer, so that not only does <code>x == x+2</code>, but <code>2 == 0</code></p>
<pre class="lang-python prettyprint-override"><code>import ctypes
two = 2 # This will help us access the address of "2" so that we may change the value

# Recall that the object value is the third variable in the struct. Therefore,
# to change the value, we must offset the address we use by the "sizeof" a
# size_t and a void pointer
offset = ctypes.sizeof(ctypes.c_size_t) + ctypes.sizeof(ctypes.c_voidp)

# Now we access the ob_ival by creating a C-int from the address of
# our "two" variable, offset by our offset value.
# Note that id(variable) returns the address of the variable.
ob_ival = ctypes.c_int.from_address(id(two)+offset)

#Now we change the value at that address by changing the value of our int.
ob_ival.value = 0

# Now for the output
x = 1
print x == x+2
print 2 == 0
</code>```

Prints

```<code>True
True
</code>```

Title: When does (x == x+2)?

Body:
Python 2.X (Using redefinition of (cached) integers)

I've noticed all of the python answers have defined classes that redefine the + operator. I'll answer with an even more low-level demonstration of python's flexibility. (This is a python2-specific snippet)

In python, integers are stored more or less this way in C:

typedef struct {            // NOTE: Macros have been expanded
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
    long ob_ival;
} PyIntObject;

That is, a struct with a size_t, void *, and long object, in that order.

Once we use, and therefore cache an integer, we can use python's ctypes module to redefine that integer, so that not only does x == x+2, but 2 == 0

import ctypes
two = 2 # This will help us access the address of "2" so that we may change the value

# Recall that the object value is the third variable in the struct. Therefore,
# to change the value, we must offset the address we use by the "sizeof" a
# size_t and a void pointer
offset = ctypes.sizeof(ctypes.c_size_t) + ctypes.sizeof(ctypes.c_voidp)

# Now we access the ob_ival by creating a C-int from the address of
# our "two" variable, offset by our offset value.
# Note that id(variable) returns the address of the variable.
ob_ival = ctypes.c_int.from_address(id(two)+offset)

#Now we change the value at that address by changing the value of our int.
ob_ival.value = 0

# Now for the output
x = 1
print x == x+2
print 2 == 0

Prints

True
True


答:
GNU sed with -r - 133 117 111 93 chars

Yes, sed is turing complete. GNU sed and -r (extended regexps) is only to save a few characters, it is only a small change to work with POSIX sed.

```<code>:s
s/^(.*@)(.*)>(.)(.*#\1\3([^@]*@)(..))/\5\2\6>\4/
T
s/(..)l>|r>/>\1/
s/>@/@> /
s/>#/> #/
bs
</code>```

Input format is

```<code>[initial state]@[non-empty tape with > marking head position]#[state]@[input symbol][next state]@[output symbol][direction l or r]#...
</code>```

The delimiters @, # and head character > cannot be used as a symbol on the tape. State labels cannot contain @ > or #.

It will run all of the programs in the input, one per line

Examples:

Marco's anbn program

Input

```<code>0@>aaabbb#0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr
</code>```

Output

```<code>5@    T>  #0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr
</code>```

Marco's Hello! program

Input

```<code>0@> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r
</code>```

Output

```<code>6@Hello!> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r
</code>```

Title: Turing Machine Simulator

Body:
Write a Turing machine simulator.

For simplicity we can assume statuses as integer, symbols as char, blank symbol equals whitespace

5-tuple in the form of current state, input symbol, next state, output symbol, direction (left or right) the order is not mandatory but specify if you swap it

The machine must stop when an unknown state is reached, no other halt condition allowed.

The tape is infinite in both directions and you can always read an empty character.

Input: the initial tape, an initial state and a program. you are free to read the data from anywhere in the format you like

Output: the tape after the execution of the program

Required: an example program that run on top of your simulator

This is a code-colf so the shortest code win.

I'll post an implementation and some example programs in the next few hours.

Body:
GNU sed with -r - 133 117 111 93 chars

Yes, sed is turing complete. GNU sed and -r (extended regexps) is only to save a few characters, it is only a small change to work with POSIX sed.

:s
s/^(.*@)(.*)>(.)(.*#\1\3([^@]*@)(..))/\5\2\6>\4/
T
s/(..)l>|r>/>\1/
s/>@/@> /
s/>#/> #/
bs

Input format is

[initial state]@[non-empty tape with > marking head position]#[state]@[input symbol][next state]@[output symbol][direction l or r]#...

The delimiters @, # and head character > cannot be used as a symbol on the tape. State labels cannot contain @ > or #.

It will run all of the programs in the input, one per line

Examples:

Marco's anbn program

Input

0@>aaabbb#0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr

Output

5@    T>  #0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr

Marco's Hello! program

Input

0@> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r

Output

6@Hello!> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r


问:
Shortest code that raises a SIGSEGV
Write the shortest code that raises a  Segmentation Fault (SIGSEGV) in any programming language.</p>

答:
Python 33

```<code>import os
os.kill(os.getpid(),11)
</code>```

Sending signal 11 (SIGSEGV) in python.

Title: Shortest code that raises a SIGSEGV

Body:
Python 33

import os
os.kill(os.getpid(),11)

Sending signal 11 (SIGSEGV) in python.


问:
Constant output program
I was wondering how one might go and produce a program that takes input from some kind of random source and uses it to produce constant output. An obvious way is, for example, to take an integer x and output x/x for 1, but that isn't too clever, is it? Therefore, the task is to write a program that outputs the same thing, no matter which input is given to it.

Specifications

The program may assume that the input is either a number or a one line string (that is, valid characters are [a-z][A-z][0-9] and spaces). If you adopt one of those restrictions, specify which in your answer.

The program must use the entered input in some way. To put it more formally, the contents of the variable that takes the input must be used afterwards in some calculation that affects the final variable to be printed.

The winner will be the most upvoted solution.

答:
Python

```<code>print eval('42#'+raw_input())
</code>```

Accepts any input

Title: Constant output program

Body:
Python

print eval('42#'+raw_input())

Accepts any input


答:
dc - 7 chars

```<code>[dx0]dx
</code>```

causes a stack overflow

Title: Shortest code that raises a SIGSEGV

Body: Write the shortest code that raises a  Segmentation Fault (SIGSEGV) in any programming language.</p>

Body:
dc - 7 chars

[dx0]dx

causes a stack overflow


问:
Tips for golfing in Postscript?
As one of the less popular languages, it's difficult to find literature on the avant garde of postscript hackery. So what discoveries have the golfers here made to exploit the stack model (or other features) to overcome Postscript's inherent verbosity?</p>

答:
While most postscript operators are syntactically identifiers (and therefore must be space- (or otherwise-) delimited), the names [, ], <<, and >> are self-delimiting and scanner will detect them without intervening space. For the same reason, you cannot refer to these names with the usual /literal syntax (eg. /[ is two tokens: an empty literal name equivalent to ()cvn cvlit, and the executable name [ equivalent to ([)cvn cvx exec).

In order to redefine these names, which cannot be mentioned by name, we can use strings which are implicitly converted to names when used as keys in a dictionary (convenient!).

This example illustrates abusing these operators to perform arithmetic.

```<code>%!
([)0 def
(])1 def
(<<){add}def
(>>){mul}def
 ]]<<]]]<<<<>> =
%1 1 add 1 1 1 add add mul = %prints 6
</code>```

Also << and [ (and mark) all mean the same thing.

My own postscript interpreter, xpost, also makes the right-curly brace available with some restrictions. discussion

Title: Tips for golfing in Postscript?

Body:
While most postscript operators are syntactically identifiers (and therefore must be space- (or otherwise-) delimited), the names [, ], <<, and >> are self-delimiting and scanner will detect them without intervening space. For the same reason, you cannot refer to these names with the usual /literal syntax (eg. /[ is two tokens: an empty literal name equivalent to ()cvn cvlit, and the executable name [ equivalent to ([)cvn cvx exec).

In order to redefine these names, which cannot be mentioned by name, we can use strings which are implicitly converted to names when used as keys in a dictionary (convenient!).

This example illustrates abusing these operators to perform arithmetic.

%!
([)0 def
(])1 def
(<<){add}def
(>>){mul}def
 ]]<<]]]<<<<>> =
%1 1 add 1 1 1 add add mul = %prints 6

Also << and [ (and mark) all mean the same thing.

My own postscript interpreter, xpost, also makes the right-curly brace available with some restrictions. discussion


问:
Morse code translator
Write the shortest program to transform the standard input into Morse code. Characters not in the table should be printed as they are.

答:
Postscript (310) (462) (414) (319) including (46) for the table.

Combined numbers and letters with a ternary encoding. 5 ternary digits fit in a byte! This eliminates those silly difference loops, and special-casing numbers entirely.

ASCII85 cuts 1/3 of each table. And simplifying the code (finally!) gets back under 400!

```<code>errordict/undefined{pop( )dup 0 4 3 roll put print{}}put<</*{{[exch/@ cvx]cvx 1
index 1 add}forall pop}def/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def/#{load
exec}/P{print}0{}1{(.)P}2{(---)P}/S{( )P}48<~o'u/0b'A;]L7n~>* 65 C 97 C/@{5{dup
3 mod # S 3 idiv}repeat # S S S}>>begin{(%stdin)(r)file read not{exit}if #}loop
</code>```

Sample output

```Luser Dr00g!
. --- . .     . . ---      . . .      .        . --- .          --- . .      . --- .      --- --- --- --- ---    --- --- --- --- ---    --- --- .      !
```

Ungolfed and commented. I'm very proud of this one. I feel it's elegant, making the numbers do the work. :)

```<code>%!
%Morse Code Translator (Simplified)

%if `load` signals /undefined in /#{load exec},
%  pop --load--,
%  print the char,
%  leave dummy object for `exec` to find
errordict/undefined{pop( )dup 0 4 3 roll put print{}}put

<<
%create int->proc pairs
%from initial int and string values
/*{{[exch/@ cvx]cvx 1 index 1 add}forall pop}def

%the alpha map is applied to Upper and Lower case
/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def
65 C 97 C

%the number map
48<~o'u/0b'A;]L7n~>*

/#{load exec}  %execute a number
/P{print}

0{}       % 0: nop
1{(.)P}   % 1: '.' dit
2{(---)P} % 2: '---' dah
/S{( )P}  % S: space

%execute a morse sequence, from the table
/@{5{dup 3 mod # S 3 idiv}repeat # S S S}
>>begin

%read and execute each char from stdin
{(%stdin)(r)file read not{exit}if #}loop
</code>```

The tables (33)+(13)=(46)

Here's how the strings encode the table. Each byte represents a 5-digit ternary number. And the bytes are further encoded in ASCII85 (which postscript can automagically decode).

```<code>%The Morse Table in Ternary Encoding
% 3  ^4 ^3 ^2 ^1 ^0
%    81 27  9  3  1                 Dec  Hex  dc ->ASCII85
%   ---------------                 ---  ---  ---
% A            2  1            6+1    7    7  7 256*41+256*50+256*14+
% B      1  1  1  2      27+ 9+3+2   41   29  d85%n85/d85%n85/d85%n85/d85%n85/n
% C      1  2  1  2      27+18+3+2   50   32  2 25 53 35 27  chr(x+33)
% D         1  1  2          9+3+2   14    E  #  :  V  D  <
% E               1              1    1    1
% F      1  2  1  1      27+18+3+1   49   31
% G         1  2  2          9+6+2   17   11  0 32 47 15 22
% H      1  1  1  1      27+ 9+3+1   40   28  !  A  P  0  7
% I            1  1            3+1    4    4
% J      2  2  2  1      54+18+6+1   79   4F
% K         2  1  2         18+3+2   23   17  1 32 60 70 64
% L      1  1  2  1      27+ 9+6+1   43   2B  "  A  ]  g  a
% M            2  2            6+2    8    8
% N            1  2            3+2    5    5
% O         2  2  2         18+6+2   26   1A  2 49 8 11 6
% P      1  2  2  1      27+18+6+1   52   34  #  R )  , '
% Q      2  1  2  2      54+ 9+6+2   71   47
% R         1  2  1          9+6+1   16   10
% S         1  1  1          9+3+1   13    D  22 71 30 10 17
% T               2              2    2    2   7  h  ?  +  2
% U         2  1  1         18+3+1   22   16
% V      2  1  1  1      54+ 9+3+1   67   43
% W         2  2  1         18+6+1   25   19  7 13 14 82 12
% X      2  1  1  2      54+ 9+3+2   68   44  (  .  /  s  -
% Y      2  2  1  2      54+18+3+2   77   4D  77 256*44+256*256*
% Z      1  1  2  2      27+ 9+6+2   44   2C  24 68 21 [23 36]
%                                              9  e  6 [ 8  E] (omit final 2)
% 0   2  2  2  2  2  162+54+18+6+2  242   F2
% 1   2  2  2  2  1  162+54+18+6+1  241   F1
% 2   2  2  2  1  1  162+54+18+3+1  238   EE  78 6 84 14 15
% 3   2  2  1  1  1  162+54+ 9+3+1  229   E5   o '  u  /  0
% 4   2  1  1  1  1  162+27+ 9+3+1  202   CA
% 5   1  1  1  1  1   81+27+ 9+3+1  121   79
% 6   1  1  1  1  2   81+27+ 9+3+2  122   7A  65 6 32 26 60
% 7   1  1  1  2  2   81+27+ 9+6+2  125   7D   b '  A  ;  ]
% 8   1  1  2  2  2   81+27+18+6+2  134   86  134 256*161+256*256*
% 9   1  2  2  2  2   81+54+18+6+2  161   A1  43 22 77 [50 40]
%                                              L  7  n [ S  I] (omit final 2)
</code>```

Title: Morse code translator

Body:
Postscript (310) (462) (414) (319) including (46) for the table.

Combined numbers and letters with a ternary encoding. 5 ternary digits fit in a byte! This eliminates those silly difference loops, and special-casing numbers entirely.

ASCII85 cuts 1/3 of each table. And simplifying the code (finally!) gets back under 400!

errordict/undefined{pop( )dup 0 4 3 roll put print{}}put<</*{{[exch/@ cvx]cvx 1
index 1 add}forall pop}def/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def/#{load
exec}/P{print}0{}1{(.)P}2{(---)P}/S{( )P}48<~o'u/0b'A;]L7n~>* 65 C 97 C/@{5{dup
3 mod # S 3 idiv}repeat # S S S}>>begin{(%stdin)(r)file read not{exit}if #}loop

Sample output

Luser Dr00g!
. --- . .     . . ---      . . .      .        . --- .          --- . .      . --- .      --- --- --- --- ---    --- --- --- --- ---    --- --- .      !

Ungolfed and commented. I'm very proud of this one. I feel it's elegant, making the numbers do the work. :)

%!
%Morse Code Translator (Simplified)

%if `load` signals /undefined in /#{load exec},
%  pop --load--,
%  print the char,
%  leave dummy object for `exec` to find
errordict/undefined{pop( )dup 0 4 3 roll put print{}}put

<<
%create int->proc pairs
%from initial int and string values
/*{{[exch/@ cvx]cvx 1 index 1 add}forall pop}def

%the alpha map is applied to Upper and Lower case
/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def
65 C 97 C

%the number map
48<~o'u/0b'A;]L7n~>*

/#{load exec}  %execute a number
/P{print}

0{}       % 0: nop
1{(.)P}   % 1: '.' dit
2{(---)P} % 2: '---' dah
/S{( )P}  % S: space

%execute a morse sequence, from the table
/@{5{dup 3 mod # S 3 idiv}repeat # S S S}
>>begin

%read and execute each char from stdin
{(%stdin)(r)file read not{exit}if #}loop

The tables (33)+(13)=(46)

Here's how the strings encode the table. Each byte represents a 5-digit ternary number. And the bytes are further encoded in ASCII85 (which postscript can automagically decode).

%The Morse Table in Ternary Encoding
% 3  ^4 ^3 ^2 ^1 ^0
%    81 27  9  3  1                 Dec  Hex  dc ->ASCII85
%   ---------------                 ---  ---  ---
% A            2  1            6+1    7    7  7 256*41+256*50+256*14+
% B      1  1  1  2      27+ 9+3+2   41   29  d85%n85/d85%n85/d85%n85/d85%n85/n
% C      1  2  1  2      27+18+3+2   50   32  2 25 53 35 27  chr(x+33)
% D         1  1  2          9+3+2   14    E  #  :  V  D  <
% E               1              1    1    1
% F      1  2  1  1      27+18+3+1   49   31
% G         1  2  2          9+6+2   17   11  0 32 47 15 22
% H      1  1  1  1      27+ 9+3+1   40   28  !  A  P  0  7
% I            1  1            3+1    4    4
% J      2  2  2  1      54+18+6+1   79   4F
% K         2  1  2         18+3+2   23   17  1 32 60 70 64
% L      1  1  2  1      27+ 9+6+1   43   2B  "  A  ]  g  a
% M            2  2            6+2    8    8
% N            1  2            3+2    5    5
% O         2  2  2         18+6+2   26   1A  2 49 8 11 6
% P      1  2  2  1      27+18+6+1   52   34  #  R )  , '
% Q      2  1  2  2      54+ 9+6+2   71   47
% R         1  2  1          9+6+1   16   10
% S         1  1  1          9+3+1   13    D  22 71 30 10 17
% T               2              2    2    2   7  h  ?  +  2
% U         2  1  1         18+3+1   22   16
% V      2  1  1  1      54+ 9+3+1   67   43
% W         2  2  1         18+6+1   25   19  7 13 14 82 12
% X      2  1  1  2      54+ 9+3+2   68   44  (  .  /  s  -
% Y      2  2  1  2      54+18+3+2   77   4D  77 256*44+256*256*
% Z      1  1  2  2      27+ 9+6+2   44   2C  24 68 21 [23 36]
%                                              9  e  6 [ 8  E] (omit final 2)
% 0   2  2  2  2  2  162+54+18+6+2  242   F2
% 1   2  2  2  2  1  162+54+18+6+1  241   F1
% 2   2  2  2  1  1  162+54+18+3+1  238   EE  78 6 84 14 15
% 3   2  2  1  1  1  162+54+ 9+3+1  229   E5   o '  u  /  0
% 4   2  1  1  1  1  162+27+ 9+3+1  202   CA
% 5   1  1  1  1  1   81+27+ 9+3+1  121   79
% 6   1  1  1  1  2   81+27+ 9+3+2  122   7A  65 6 32 26 60
% 7   1  1  1  2  2   81+27+ 9+6+2  125   7D   b '  A  ;  ]
% 8   1  1  2  2  2   81+27+18+6+2  134   86  134 256*161+256*256*
% 9   1  2  2  2  2   81+54+18+6+2  161   A1  43 22 77 [50 40]
%                                              L  7  n [ S  I] (omit final 2)


答:
Embedded Decoder

A Postscript program has a unique(?) ability to read it's own program text as data. This is normally used by the image operator which receives a data-acquisition-procedure as input, and this procedure often uses currentfile followed by readline, readstring, or readhexstring. But seen another way, image is just another looping operator, so any loop can read-ahead. An example is the line-printer emulator from the Green Book.

Using the token operator invokes the scanner on a file or string, pulling off a number or space- (or otherwise-: see other answer) -delimited name.

A simple PS interpreter in PS:

```<code>{currentfile token not {exit} if dup type /arraytype ne {exec} if }loop
</code>```

Binary Operator String Decoder

Since I can't seem to get raw binary tokens to work for me (see other answer), I've made use of the "embedded decoding" idea to exploit the binary token mechanism to pack code into 8-bit strings, and then manipulate and parse the commands from the string on the fly.

```<code>/.{
    <920>  % two-byte binary-encoded name template with 0x92 prefix
    dup 1 4 3 roll put  % insert number into string
    cvx exec  % and execute it
}def
/${
    //.   %the /. procedure body defined above
    73 .  %"forall" (by code number)
}def
</code>```

The . procedure takes a number from the stack and inserts it as the second byte in a two-byte string, the first byte being the prefix-byte for a binary token, specifying an executable system name. We save a byte in the hexstring by using a rule of the scanner that an odd number of nibbles in the hexstring is padded with an extra 0 nibble, so 3 hex nibbles produces a 2-byte string. The string is then marked executable and called with exec which invokes the scanner, produces the desired executable system name, and then loads the name and executes the operator. The $ does this on each byte of a string on the stack, using the . procedure twice, once as the loop body, and then to execute the looping operator forall by number.

More compactly, these procedures look like this:

```<code> /.{<920>dup 1 4 3 roll put cvx exec}def/${//. 73 .}def
%123457890123456789012345678901234567890123456789012345
%        1         2         3         4         5
</code>```

So, 55 chars buys binary token strings. Or, for 6 (maybe 7, if you terminate it with a space) chars, you can load the G library with (G)run which defines . and $ as above (+ a few others to extend the range of ascii-reachable codes).

Further illustrated in my crossword puzzle answer.

Title: Tips for golfing in Postscript?

Body: As one of the less popular languages, it's difficult to find literature on the avant garde of postscript hackery. So what discoveries have the golfers here made to exploit the stack model (or other features) to overcome Postscript's inherent verbosity?</p>

Body:
Embedded Decoder

A Postscript program has a unique(?) ability to read it's own program text as data. This is normally used by the image operator which receives a data-acquisition-procedure as input, and this procedure often uses currentfile followed by readline, readstring, or readhexstring. But seen another way, image is just another looping operator, so any loop can read-ahead. An example is the line-printer emulator from the Green Book.

Using the token operator invokes the scanner on a file or string, pulling off a number or space- (or otherwise-: see other answer) -delimited name.

A simple PS interpreter in PS:

{currentfile token not {exit} if dup type /arraytype ne {exec} if }loop

Binary Operator String Decoder

Since I can't seem to get raw binary tokens to work for me (see other answer), I've made use of the "embedded decoding" idea to exploit the binary token mechanism to pack code into 8-bit strings, and then manipulate and parse the commands from the string on the fly.

/.{
    <920>  % two-byte binary-encoded name template with 0x92 prefix
    dup 1 4 3 roll put  % insert number into string
    cvx exec  % and execute it
}def
/${
    //.   %the /. procedure body defined above
    73 .  %"forall" (by code number)
}def

The . procedure takes a number from the stack and inserts it as the second byte in a two-byte string, the first byte being the prefix-byte for a binary token, specifying an executable system name. We save a byte in the hexstring by using a rule of the scanner that an odd number of nibbles in the hexstring is padded with an extra 0 nibble, so 3 hex nibbles produces a 2-byte string. The string is then marked executable and called with exec which invokes the scanner, produces the desired executable system name, and then loads the name and executes the operator. The $ does this on each byte of a string on the stack, using the . procedure twice, once as the loop body, and then to execute the looping operator forall by number.

More compactly, these procedures look like this:

 /.{<920>dup 1 4 3 roll put cvx exec}def/${//. 73 .}def
%123457890123456789012345678901234567890123456789012345
%        1         2         3         4         5

So, 55 chars buys binary token strings. Or, for 6 (maybe 7, if you terminate it with a space) chars, you can load the G library with (G)run which defines . and $ as above (+ a few others to extend the range of ascii-reachable codes).

Further illustrated in my crossword puzzle answer.


答:
Here's a quickie: wrap multiple definitions in [...>>begin to eliminate the keyword def (nb. [ is the same as <<).

```<code> def def
[>>begin
</code>```

So remember: more than three two ... flock together! ;)

Title: Tips for golfing in Postscript?

Body:
Here's a quickie: wrap multiple definitions in [...>>begin to eliminate the keyword def (nb. [ is the same as <<).

 def def
[>>begin

So remember: more than three two ... flock together! ;)


问:
Finding "sub-palindromes" 2: subsequences.
The same task as Finding "sub-palindromes" but instead of finding substrings you must find subsequences that are not substrings.

eg1:

```<code>input: "12131331"
output:
"11", "33", "111", "121", "131", "313", "333", "1111", "1331", "11311", "13331"
or
"11", "33", "111", "333", "1111", "11311", "13331"
</code>```

eg2:

```<code>input: "3333"
output:
"33", "333"
or
(null)
</code>```

Input is a string of printable ascii characters.

Output is a list of unique strings.

If a subsequence also appears as a substring it may be omitted.

Shortest code wins.

答:
Golfscript (95)

```<code>);.{{(\a\:x;.{[x]\+}%+}:b;{.!{[$]}{b}if}:a;.a{..-1%=&},\{,}{(;}/{{,}{);}/}%{+}*-.&{`}%", "*}and
</code>```

I haven't really tried to golf this further, it's just a combination of left overs.

The question is inconsistent. My program prints all palindromic subsequences that are not substrings. Hope this is OK.

Example 1:

```<code>echo "12131331" | ruby golfscript.rb subseq_not_substr.gs
"11", "111", "13331", "13131", "1111", "11311"
</code>```

Example 2:

```<code>echo "3333" | ruby golfscript.rb subseq_not_substr.gs
</code>```

Empty String Example:

```<code>echo "" | ruby golfscript.rb subseq_not_substr.gs
</code>```

With uglier output formatting, eg [11 111 13331 13131 1111 11311], it could be made a bit shorter.

Body:
Golfscript (95)

);.{{(\a\:x;.{[x]\+}%+}:b;{.!{[$]}{b}if}:a;.a{..-1%=&},\{,}{(;}/{{,}{);}/}%{+}*-.&{`}%", "*}and

I haven't really tried to golf this further, it's just a combination of left overs.

The question is inconsistent. My program prints all palindromic subsequences that are not substrings. Hope this is OK.

Example 1:

echo "12131331" | ruby golfscript.rb subseq_not_substr.gs
"11", "111", "13331", "13131", "1111", "11311"

Example 2:

echo "3333" | ruby golfscript.rb subseq_not_substr.gs

Empty String Example:

echo "" | ruby golfscript.rb subseq_not_substr.gs

With uglier output formatting, eg [11 111 13331 13131 1111 11311], it could be made a bit shorter.


答:
Bash, 72

Assuming no single-letter-named files in the current directory; input from stdin:

```<code>grep -io [a-z]|sort -f|uniq -ci|sort|head|sed -E 's/(.*)([a-z])/\2:\1/'
</code>```

Works on Linux, but for some reason, my mac's grep seems to ignore the -i when used with -o (bug or undocumented gotcha?), but the following (78) works:

```<code>tr A-Z a-z|grep -o [a-z]|sort|uniq -c|sort|head|sed -E 's/(.*)([a-z])/\2:\1/'
</code>```

If the output were allowed to be reversed, the sed part could be dropped to save 30 characters in each of the previous solutions.

Title: Find The Least Common Characters

Body:
Given a string, find the 10 least common alpha-numeric characters within that string.

Output should be formatted with numbers left-padded with spaces so they look like this:

```<code>e:      1
t:     16
c:     42
b:    400
z:  50000
a: 100000
</code>```

Use this to test your program: here

Output for test case:

```<code>j:  2
x:  3
q:  9
k: 32
v: 67
c: 73
w: 79
f: 93
b: 94
p: 96
</code>```

Shortest code wins. You can submit a program or a function.

Body:
Bash, 72

Assuming no single-letter-named files in the current directory; input from stdin:

grep -io [a-z]|sort -f|uniq -ci|sort|head|sed -E 's/(.*)([a-z])/\2:\1/'

Works on Linux, but for some reason, my mac's grep seems to ignore the -i when used with -o (bug or undocumented gotcha?), but the following (78) works:

tr A-Z a-z|grep -o [a-z]|sort|uniq -c|sort|head|sed -E 's/(.*)([a-z])/\2:\1/'

If the output were allowed to be reversed, the sed part could be dropped to save 30 characters in each of the previous solutions.


问:
Tips for golfing in C
What general tips do you have for golfing in C? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C (e.g. "remove comments" is not an answer). Please post one tip per answer. Also, please include if your tip applies to C89 and/or C99 and if it only works on certain compilers.</p>

答:
Use cursors instead of pointers. Snag the brk() at the beginning and use it as a base-pointer.

```<code>char*m=brk();
</code>```

Then make a #define for memory access.

```<code>#define M [m]
</code>```

M becomes a postfix * applied to integers. (The old a[x] == x[a] trick.)

But, there's more! Then you can have pointer args and returns in functions that are shorter than macros (especially if you abbreviate 'return'):

```<code>f(x){return x M;} //implicit ints, but they work like pointers
#define f(x) (x M)
</code>```

To make a cursor from a pointer, you subtract the base-pointer, yielding a ptrdiff_t, which truncates into an int, losses is yer biz.

```<code>int p = sbrk(sizeof(whatever)) - m;
strcpy(m+p, "hello world");
</code>```

This technique is used in my answer to Write an interpreter for the untyped lambda calculus.

Title: Tips for golfing in C

Body:
Use cursors instead of pointers. Snag the brk() at the beginning and use it as a base-pointer.

char*m=brk();

Then make a #define for memory access.

#define M [m]

M becomes a postfix * applied to integers. (The old a[x] == x[a] trick.)

But, there's more! Then you can have pointer args and returns in functions that are shorter than macros (especially if you abbreviate 'return'):

f(x){return x M;} //implicit ints, but they work like pointers
#define f(x) (x M)

To make a cursor from a pointer, you subtract the base-pointer, yielding a ptrdiff_t, which truncates into an int, losses is yer biz.

int p = sbrk(sizeof(whatever)) - m;
strcpy(m+p, "hello world");

This technique is used in my answer to Write an interpreter for the untyped lambda calculus.