text:
EBCDIC code golf (Happy birthday, System/360!)
Pretty soon it's going to be 50 years since IBM unveiled its System/360 family of computers. These were the first to use the EBCDIC character set.
To mark the occasion, let's see who can write the shortest program capable of converting "ordinary" text to and from EBCDIC code page 037. We'll be using a translation table from Wikipedia that maps CP037 to a superset of ISO-8859-1:
EBCDIC037_to_Latin1 = [
    0x00,0x01,0x02,0x03,0x9c,0x09,0x86,0x7f,0x97,0x8d,0x8e,0x0b,0x0c,0x0d,0x0e,0x0f,
    0x10,0x11,0x12,0x13,0x9d,0x85,0x08,0x87,0x18,0x19,0x92,0x8f,0x1c,0x1d,0x1e,0x1f,
    0x80,0x81,0x82,0x83,0x84,0x0a,0x17,0x1b,0x88,0x89,0x8a,0x8b,0x8c,0x05,0x06,0x07,
    0x90,0x91,0x16,0x93,0x94,0x95,0x96,0x04,0x98,0x99,0x9a,0x9b,0x14,0x15,0x9e,0x1a,
    0x20,0xa0,0xe2,0xe4,0xe0,0xe1,0xe3,0xe5,0xe7,0xf1,0xa2,0x2e,0x3c,0x28,0x2b,0x7c,
    0x26,0xe9,0xea,0xeb,0xe8,0xed,0xee,0xef,0xec,0xdf,0x21,0x24,0x2a,0x29,0x3b,0xac,
    0x2d,0x2f,0xc2,0xc4,0xc0,0xc1,0xc3,0xc5,0xc7,0xd1,0xa6,0x2c,0x25,0x5f,0x3e,0x3f,
    0xf8,0xc9,0xca,0xcb,0xc8,0xcd,0xce,0xcf,0xcc,0x60,0x3a,0x23,0x40,0x27,0x3d,0x22,
    0xd8,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0xab,0xbb,0xf0,0xfd,0xfe,0xb1,
    0xb0,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0xaa,0xba,0xe6,0xb8,0xc6,0xa4,
    0xb5,0x7e,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0xa1,0xbf,0xd0,0xdd,0xde,0xae,
    0x5e,0xa3,0xa5,0xb7,0xa9,0xa7,0xb6,0xbc,0xbd,0xbe,0x5b,0x5d,0xaf,0xa8,0xb4,0xd7,
    0x7b,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0xad,0xf4,0xf6,0xf2,0xf3,0xf5,
    0x7d,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0xb9,0xfb,0xfc,0xf9,0xfa,0xff,
    0x5c,0xf7,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0xb2,0xd4,0xd6,0xd2,0xd3,0xd5,
    0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0xb3,0xdb,0xdc,0xd9,0xda,0x9f];

Rules:

Your program should take two inputs: (a) a text string, and (b) a flag indicating the operation to be performed.
Based on this flag, your program should either convert each byte of text into the corresponding EBCDIC character, or vice versa.
Input can be obtained from any sensible sources (e.g., command line arguments, stdin, keyboard input), but must not be hard-coded into your program.
Output should be displayed on the screen (e.g., stdout, document.write) or written to a file/pipeline.
Don't use any built-in or external encoding conversion functions (iconv, etc.).
This is a code-golf challenge, so the shortest answer (fewest bytes) will win.

Examples:
(Note: These examples were produced in a terminal configured to use UTF-8 encoding. You may see different results depending on how your system is configured. Hex equivalents are shown for reference only, and don't have to be generated by your code.)
Input: "HELLO WORLD", convert to EBCDIC
Output: "ÈÅÓÓÖ@æÖÙÓÄ" (0xc8c5d3d3d640e6d6d9d3c4)

Input: "ÈÅÓÓÖ@æÖÙÓÄ", convert from EBCDIC
Output: "HELLO WORLD"

Input: "lower case mostly ends up as gremlins", convert to EBCDIC
Output "" <-- unprintable in utf-8
(0x9396a68599408381a285409496a2a393a840859584a240a4974081a24087998594938995a2)

#5 means for example I can't have a base64-encoded string and to s.decode('base64') to get my look-up table?

What is "ordinary" text? ASCII? UTF-8? A native String type?

Are we converting control codes as well? Or just printable characters? If so, by what rules?

@intx13, the translation table is in the question.

@Claudiu That would be absolutely fine

@intx13 Yes, convert control codes too. (By "ordinary" I was referring to character sets that have the alphanumeric characters in the same places as ASCII, but just stick to the translation table given and treat the input and output as binary data.)

@Peter, Then can we explicitly represent the input and output as byte arrays? Or do they have to be strings in the native environment (UTF-8 for bash, UTF-16 for C#'s console, etc.)

Bash + tr, 240 bytes
Hexdump
00000000  58 3d 27 9c 09 86 7f 97  8d 8e 0b 2d 13 9d 85 08  |X='........-....|
00000010  87 18 19 92 8f 1c 2d 1f  80 2d 84 0a 17 1b 88 2d  |......-..-.....-|
00000020  8c 05 06 07 90 91 16 93  2d 96 04 98 2d 9b 14 15  |........-...-...|
00000030  9e 1a 20 a0 e2 e4 e0 e1  e3 e5 e7 f1 a2 2e 3c 28  |.. ...........<(|
00000040  2b 7c 26 e9 ea eb e8 ed  ee ef ec df 21 24 2a 29  |+|&.........!$*)|
00000050  3b ac 5c 2d 2f c2 c4 c0  c1 c3 c5 c7 d1 a6 2c 25  |;.\-/.........,%|
00000060  5f 3e 3f f8 c9 ca cb c8  cd ce cf cc 60 3a 23 40  |_>?.........`:#@|
00000070  27 5c 27 27 3d 22 d8 61  2d 69 ab bb f0 fd fe b1  |'\''=".a-i......|
00000080  b0 6a 2d 72 aa ba e6 b8  c6 a4 b5 7e 73 2d 7a a1  |.j-r.......~s-z.|
00000090  bf d0 dd de ae 5e a3 a5  b7 a9 a7 b6 bc bd be 5b  |.....^.........[|
000000a0  5d af a8 b4 d7 7b 41 2d  49 ad f4 f6 f2 f3 f5 7d  |]....{A-I......}|
000000b0  4a 2d 52 b9 fb fc f9 fa  ff 5c 5c f7 53 2d 5a b2  |J-R......\\.S-Z.|
000000c0  d4 d6 d2 d3 d5 30 2d 39  b3 db dc d9 da 9f 27 3b  |.....0-9......';|
000000d0  5b 20 24 31 20 5d 26 26  74 72 20 04 2d ff 20 22  |[ $1 ]&&tr .-. "|
000000e0  24 58 22 7c 7c 74 72 20  22 24 58 22 20 04 2d ff  |$X"||tr "$X" .-.|

Rather trivial solution. Reads from STDIN, prints to STDOUT.
How to use

To save the script and make it executable, run these commands:
base64 -d <<< WD0nnAmGf5eNjgstE52FCIcYGZKPHC0fgC2EChcbiC2MBQYHkJEWky2WBJgtmxQVnhogoOLk4OHj5efxoi48KCt8Junq6+jt7u/s3yEkKik7rFwtL8LEwMHDxcfRpiwlXz4/+MnKy8jNzs/MYDojQCdcJyc9IthhLWmru/D9/rGwai1yqrrmuMaktX5zLXqhv9Dd3q5eo6W3qae2vL2+W12vqLTXe0EtSa309vLz9X1KLVK5+/z5+v9cXPdTLVqy1NbS09UwLTmz29zZ2p8nO1sgJDEgXSYmdHIgBC3/ICIkWCJ8fHRyICIkWCIgBC3/ > ebcdic.sh
chmod +x ebcdic.sh

To convert to EBCDIC (encode), execute the plain command:
./ebcdic.sh

To convert from EBCDIC (decode), specify any first argument:
./ebcdic.sh -d

Nice idea, but I can't get it to work in Darwin or Debian. What system are you running it on?

I mixed up encoding and decoding. I actually had the direction right in the first version (which uses the inverse of the lookup table), but I somehow managed to delete the double quotes around the variables. Fixed.

Working now :-)

Could it easily take from the stream in? (the pipe)


text:
Solve the Global Debt, the Code Golf way
The leaders of the world have met and have finally admitted that the best (and only) way of resolving global economic woes is to take stock of how much they owe each other and just pay each other off with huge cheques. They have hired you (ironically, at the lowest contract rate possible) to work out the best means of doing so.
After much deliberation, and asking someone to draw a simple example they've come up with the following spec.
Each country is represented by their ISO 3166-1 alpha-2 code: US for the USA, AU for Australia, JP for Japan, CN for China and so on...

A ledger is drawn up as a series of country entries and the amounts
owing to each country.
Each country's entry starts off with their domain ID a colon, and how much they have in surplus/deficit (in billions of Euro), followed by a semicolon, then a coloned
comma-separated list of the countries and how much (in billions of
Euro) they owe.
If a country owes nothing to another country, no mention of that country is entered after that semicolon separator.
Deficits are indicated as negative numbers, surplus is indicated as a positive number.
Values can also be floats.
The ledger must be taken from STDIN. The end of the ledger is indicated by a carriage return on a blank line. The tally must be delivered to STDOUT.

An example of a ledger:
Input:
AU:8;US:10,CN:15,JP:3
US:14;AU:12,CN:27,JP:14
CN:12;AU:8,US:17,JP:4
JP:10;AU:6,US:7,CN:10

The system then works out how much each country owes and is owed and determines their surplus/deficit, for example, for AU:
AU = 8 (current surplus) -10 (to US) -15 (to CN) -3 (to JP) +12 (from US) +8 (from CN) +6 (from JP) = 6
When all the computing is done, a tally must be shown:
Output:
AU:6
US:-5
CN:35
JP:8

Your job is to create this system, capable of taking any number of ledger entries for any number of countries and capable of determining how much each country has in deficit/surplus when everything is paid out.
The ultimate test is for you to use your code to resolve the debt owed between the following countries in the test case below. These figures were taken from BBC News as of June 2011. (http://www.bbc.com/news/business-15748696)
For the purposes of the exercise, I have used their respective GDP as their current surplus... Please bear in mind that this is strictly an exercise in code quality assurance... there will be no talk of global economic resolution here in this question... If you want to talk economics I'm sure there's another subdomain in SE that handles it...
US:10800;FR:440.2,ES:170.5,JP:835.2,DE:414.5,UK:834.5
FR:1800;IT:37.6,JP:79.8,DE:123.5,UK:227,US:202.1
ES:700;PT:19.7,IT:22.3,JP:20,DE:131.7,UK:74.9,US:49.6,FR:112
PT:200;IT:2.9,DE:26.6,UK:18.9,US:3.9,FR:19.1,ES:65.7
IT:1200;JP:32.8,DE:120,UK:54.7,US:34.8,FR:309,ES:29.5
IE:200;JP:15.4,DE:82,UK:104.5,US:39.8,FR:23.8
GR:200;DE:15.9,UK:9.4,US:6.2,FR:41.4,PT:7.5,IT:2.8
JP:4100;DE:42.5,UK:101.8,US:244.8,FR:107.7
DE:2400;UK:141.1,US:174.4,FR:205.8,IT:202.7,JP:108.3
UK:1700;US:578.6,FR:209.9,ES:316.6,IE:113.5,JP:122.7,DE:379.3

Now, be the economic savior of the world!
Rules:

Shortest code wins... this is code-golf after all...
Please provide your output of the major test case with your code answer...

In the "ultimate test", shouldn't there be a semicolon after JP:4100?

@MathieuRodic Thanks for the sharp eye to detail... +1 to you, my friend...

@WallyWest: the sharp eye is not mine... but my script's, when it failed at parsing!

Merci bien, all the same...

I can't help but wonder if this is a very clever way of having a homework assignment completed for you. If so, you deserve it.

Yeah, if you did this will real numbers you'd notice an astonishing contradiction. The sum of all surpluses and deficits will be negative.

seems like this could be solved with linear programming (such as AMPL), although I've never seen it used for a code golf problem.

@Tobia I'm not sure what country you live in where you have "private banks" printing currency. Probably not a financially stable one...

Actually, it's not homework in disguise... It was inspired from my weekly poker tournament with my friends... Trying to figure out a quicker way of working out the winnings for each player ;)

@WallyWest LOL ;) btw, apologies for the OT comments, but it's a matter I'm quite passionate about. Now let's get back to some fun coding and forget the woes of the world...

@Tobia, Forgiven! I'd love to see an entry from you for this question...

Ok, will do an APL one over the weekend!

@JBentley If you want to talk economics, go elsewhere... This question was not to incite opinions about global economics...
Please keep comments like this out of this question or I'll start plucking these comments out like stray grey hairs...

@WallyWest I was responding to an existing series of comments. But I shall not post further on the subject.

K, 66
{(((!)."SF"$+":"\:'*+a)-+/'d)+/d:"F"$(!).'"S:,"0:/:last'a:";"\:'x}

.
k)input:0:`:ledg.txt
k){(((!)."SF"$+":"\:'*+a)-+/'d)+/d:"F"$(!).'"S:,"0:/:last'a:";"\:'x} input
US| 9439.3
FR| 2598.9
ES| 852.1
PT| 90.1
IT| 887.5
IE| 48
GR| 116.8
JP| 4817.4
DE| 2903.7
UK| 1546.2

Incredibly impressed with this one... any chance you can provide a link to the K programming paradigm?

@WallyWest http://code.kx.com/ provides lots of information on q, which is the syntactic sugar that sits on top of k. q, moreso thank k, is what you'll find in production systems but for golfing k has the edge. Also check out Kona (https://github.com/kevinlawler/kona) which is an open source implementation of an older version of k

Perl, 139 137 134 119 112
Here's another working piece of code... I will document it later.
Golfed code
With dictionary (112):
for(<>){~/:(.+);/g;$d{$c=$`}+=$1;$l=$';$d{$1}+=$2,$d{$c}-=$2while$l=~/(..):([^,]+)/g}print"$_:$d{$_}
"for keys%d

Without dictionary (137):
for($T=$t.=$_ for<>;$t=~/(..:)(.+);(.+)/g;print"$c$s\n"){$c=$1;$l=$3;$s=$2;$s-=$&while$l=~/[\d.]+/g;$s+=$1while$T=~/$c([\d.]+)(?!;|\d)/g}

Output
US:9439.3
FR:2598.9
ES:852.1
PT:90.1
IT:887.5
IE:48
GR:116.8
JP:4817.4
DE:2903.7
UK:1546.2

See it in action!
http://ideone.com/4iwyEP

The definition of "short" should be judged by amount of tokens, not characters. Readability 4 life!

@Domi - you're new here, aren't you ;-)

@jimbobmcgee: I also have a feeling this website is not much about readability...

Python, 211 185 183
import sys,re;t,R,F=sys.stdin.read(),re.findall,float;S=lambda e,s:sum(map(F,R(e,s)))
for m in R('(..:)(.+);(.+)',t):print m[0]+`F(m[1])+S(m[0]+'([\d.]+)(?!;|\d)',t)-S('[\d.]+',m[2])`

Output with major test case:
US:9439.300000000001
FR:2598.9
ES:852.0999999999999
PT:90.09999999999997
IT:887.5
IE:48.0
GR:116.8
JP:4817.4
DE:2903.7
UK:1546.2000000000003

(test it here: http://ideone.com/CjWG7v)

C - 257 253 if no CR at end of line
Depends on sizeof(short)==2.
No check for buffer overflow.
#define C(c) x[*(short*)c]
main(i){double x[23131]={0},d;char*q,b[99],*(*s)()=strtok;for(;gets(b);)for(s(b,":"),C(b)+=atof(s(0,";"));q=s(0,":");C(b)-=d=(atof(s(0,","))),C(q)+=d);for(i=b[2]=0;i<23131;memcpy(b,&i,2),x[i]?printf("%s:%f\n",b,x[i++]):++i);}

Output:
DE:2903.700000
IE:48.000000
UK:1546.200000
JP:4817.400000
FR:2598.900000
GR:116.800000
ES:852.100000
US:9439.300000
IT:887.500000
PT:90.100000

Less golfed:
#define C(c) x[*(short*)c]

main(i)
{
    double x[23131]={0}, d;
    char *q, b[99], *(*s)()=strtok;
    for(;gets(b);)
        for(s(b, ":"),C(b)+=atof(s(0, ";"));
            q=s(0, ":");
            C(b)-=d=(atof(s(0, ","))), C(q)+=d) ;

    for(i=b[2]=0;
        i<23131;
        memcpy(b, &i, 2), x[i]?printf("%s:%f\n", b, x[i++]):++i) ;
}

PHP - 338, 280
Should work with any version of PHP 5.
Golfed:
while(preg_match("#(..):(.+);(.*)#",fgets(STDIN),$m)){$l[$m[1]][0]=(float)$m[2];foreach(explode(",",$m[3])as$x){$_=explode(":",$x);$l[$m[1]][1][$_[0]]=(float)$_[1];}}foreach($l as$c=>$d)foreach($d[1]as$_=>$o){$l[$_][0]+=$o;$l[$c][0]-=$o;}foreach($l as$c=>$d)echo$c,":",$d[0],"\n";

Un-golfed:
<?php

while( preg_match( "#(..):(\d+);(.*)#", fgets( STDIN ), $m ) )
{
    $l[$m[1]][0] = (float)$m[2];

    foreach( explode( ",", $m[3] ) as $x )
    {
        $_ = explode( ":", $x );
        $l[$m[1]][1][$_[0]] = (float)$_[1];
    }
}

foreach( $l as $c => $d )
    foreach( $d[1] as $_ => $o )
    {
        $l[$_][0] += $o;
        $l[$c][0] -= $o;
    }

foreach( $l as $c => $d )
    echo $c, ":", $d[0], "\n";

Output:
US:9439.3
FR:2598.9
ES:852.1
PT:90.1
IT:887.5
IE:48
GR:116.8
JP:4817.4
DE:2903.7
UK:1546.2

Wouldn't it be shorter if you used preg_match_all() and then just looped once?

perl (184 characters)
Code
%c,%d,%e=();while(<>){$_=~/(..):(.+);(.*)/;$n=$1;$c{$1}=$2;for $i(split /,/,$3){$i=~/(..):(.+)/;$d{$1}+=$2;$e{$n}+=$2;}}for $i(keys %c){$c{$i}+=$d{$i}-$e{$i};print $i.":".$c{$i}."\n";}

Output
UK:1546.2
DE:2903.7
IT:887.5
FR:2598.9
PT:90.1
US:9439.3
JP:4817.4
ES:852.1
IE:48
GR:116.8

Perl - 116 114 112
for(<>){($n,$m,@l)=split/[:;,]/;$h{$n}+=$m;$h{$n}-=$p,$h{$o}+=$p while($o,$p,@l)=@l}print"$_:$h{$_}\n"for keys%h

Output:
GR:116.8
UK:1546.2
DE:2903.7
IE:48
IT:887.5
US:9439.3
PT:90.1
ES:852.1
FR:2598.9
JP:4817.4

Ungolfed:
for(<>) {
    ($n, $m, @l)=split(/[:;,]/);
    $h{$n}+=$m;

    $h{$n}-=$p, $h{$o}+=$p while ($o,$p,@l)=@l
}
print "$_:$h{$_}\n" for keys%h

Nice! I like your approach :)

AWK - 138 120
{l=split($0,h,"[:,;]");t[h[1]]+=h[2];for(i=3;i<l;i+=2){t[h[1]]-=h[i+1];t[h[i]]+=h[i+1]}}END{for(v in t){print v":"t[v]}}

And the results
$ cat data.withoutInputHeadline |awk -f codegolf.awk
IT:887.5
UK:1546.2
DE:2903.7
PT:90.1
ES:852.1
FR:2598.9
GR:116.8
Input:0
JP:4817.4
IE:48
US:9439.3

Ungolfed
{
    l=split($0,h,"[:,;]");
    t[h[1]]+=h[2];
    for(i=3;i<l;i+=2){
        t[h[1]]-=h[i+1]
        t[h[i]]+=h[i+1]
    }
}
END{
    for(v in t){
        print v":"t[v]
    }
}

(test it here: http://ideone.com/pxqc07)

Why even put those headers in? You'll save more bytes without them... they weren't even part of the spec I set... ;)

@WallyWest: Ok, so I didn't understood that, because they are displayed in your first example of Input and Output e.g.:  (..)a tally must be shown: Output: (..) No worry about that, I remove my first example right now.

C++ - 1254
#include<iostream>
#include<cstring>
#include<vector>
#include<sstream>
#include<cstdlib>
using namespace std;int main(){vector<string>input,countries,output;vector<double>results;string last_val;int j,k,i=0;cout<<"Input\n";do{getline(cin,last_val);if(last_val!=""){input.push_back(last_val);countries.push_back(last_val.substr(0,2));}}while(last_val!="");for(j=0;j<countries.size();j++){results.push_back(0);for(k=0;k<input.size();k++)input[k].substr(0, 2)==countries[j]?results[j]+=atof(input[k].substr((input[k].find(countries[j])+3),(input[k].find(',',input[k].find(countries[j]))-input[k].find(countries[j]))).c_str()):results[j]+=atof(input[k].substr((input[k].find(countries[j],3)+3),(input[k].find(',',input[k].find(countries[j]))-input[k].find(countries[j]))).c_str());}for(j=0;j<input.size();j++){for(k=0;k<countries.size();k++){if(input[j].substr(0,2)!=countries[k]){results[j]-=atof(input[j].substr((input[j].find(countries[k])+ 3),(input[j].find(',',input[k].find(countries[k]))-input[j].find(countries[j]))).c_str());}}}for(i=0;i<countries.size();i++){stringstream strstream;strstream<<countries[i]<<":"<<results[i];output.push_back(strstream.str().c_str());}cout<<"Output:\n";for(i=0;i<output.size();i++){cout<<output[i]<<'\n';}return 0;}

I realize the code is very long, but enjoyed the good fun. This is my first time code golfing, and I am new to C++, so suggestions for improving my code are much appreciated.
Final Challenge Results
Output:
US:9439.3
FR:2598.9
ES:852.1
PT:90.1
IT:887.5
IE:48
GR:116.8
JP:4817.4
DE:2903.7
UK:1546.2

Ungolfed Code
#include<iostream>
#include<cstring>
#include<vector>
#include<sstream>
#include<cstdlib>

using namespace std;

int main() {
  vector<string> input, countries, output;
  vector<double> results;
  string last_val;
  int i, j, k;

  cout << "Input\n";
  do {
    getline(cin, last_val);
    if(last_val != "") {
      input.push_back(last_val);
      countries.push_back(last_val.substr(0, 2));
    }
  } while(last_val != "");

  for(j = 0; j < countries.size(); j++) {
    results.push_back(0);
    for(k = 0; k < input.size(); k++) {
      if(input[k].substr(0, 2) == countries[j]) {
        results[j] += atof(input[k].substr((input[k].find(countries[j]) + 3),
                             (input[k].find(',', input[k].find(countries[j])) -
                              input[k].find(countries[j]))).c_str());
      } else {
        results[j] += atof(input[k].substr((input[k].find(countries[j], 3) + 3),
                             (input[k].find(',', input[k].find(countries[j])) -
                              input[k].find(countries[j]))).c_str());
      }
    }
  }

  for(j = 0; j < input.size(); j++) {
    for(k = 0; k < countries.size(); k++) {
      if(input[j].substr(0, 2) != countries[k]) {
        results[j] -= atof(input[j].substr((input[j].find(countries[k]) + 3),
                             (input[j].find(',', input[k].find(countries[k])) -
                              input[j].find(countries[j]))).c_str());
      }
    }
  }

  for(i = 0; i < countries.size(); i++) {
    stringstream strstream;
    strstream << countries[i] << ":" << results[i];
    output.push_back(strstream.str().c_str());
  }

  cout << "Output:\n";
  for(i = 0; i < output.size(); i++) {
    cout << output[i] << '\n';
  }

  return 0;
}

Hi, Nice to see an example in C++. You could reduce number of characters by using one-letter identifiers in stead of descriptive names, i.e. use i for input, c for countries and so on.

Agreed with @ahy1 here... If you reduce your variables to 1 letter you can cut a fair bit of this... You may also find this of interest for future golf challenges: http://codegolf.stackexchange.com/questions/132/tips-for-golfing-in-c

Oh, and you won't need cout << "Output:\n"; either... That's a 20 byte saving there...

Ruby - 225
First try in a challenge like this, sure it could be a lot better...
R=Hash.new(0)
def pd(s,o=nil);s.split(':').tap{|c,a|R[c]+=a.to_f;o&&R[o]-=a.to_f};end
STDIN.read.split("\n").each{|l|c,d=l.split(';');pd(c);d.split(',').each{|s|pd(s,c.split(':')[0])}}
puts R.map{|k,v|"#{k}: #{v}"}.join("\n")

And the results
$ cat data|ruby codegolf.rb
US: 9439.299999999997
FR: 2598.8999999999996
ES: 852.1
JP: 4817.4
DE: 2903.7
UK: 1546.2000000000003
IT: 887.5
PT: 90.09999999999998
IE: 48.0
GR: 116.8

JavaScript(ES6) 175,166, 161, 156, 153147
Golfed
R={};prompt().split(/\s/).map(l=>{a=l.split(/[;,:]/);c=b=a[0];a.map(v=>b=!+v?v:(R[b]=(R[b]||0)+ +v c==b?b:R[c]-=+v))});for(x in R)alert(x+':'+R[x])

Ungolfed
R = {};
prompt().split(/\s/).map(l => {
    a = l.split(/[;,:]/);       // Split them all!!
                                // Now in a we have big array with Country/Value items
    c = b = a[0];               // c - is first country, b - current country
    a.map(v =>
         b = !+v ? v                 // If v is country (not a number), simply update b to it's value
                 : (R[b] = (R[b] ||0) + +v   // Safely Add value to current country
                   c == b ? c : R[c] -= +v)  // If current country is not first one, remove debth
    )
});
for (x in R) alert(x + ':' + R[x])

Output
US:9439.299999999997
FR:2598.8999999999996
ES:852.1
JP:4817.4
DE:2903.7
UK:1546.2000000000003
IT:887.5
PT:90.09999999999998
IE:48
GR:116.8

Not sure that ungolfed variant will be working correctly because in golfed variant i'm using one-line operators

can you please show your output?

Sure, but it's kind'a the same, as in other results

Replaced R[b] ? R[b] += +v : R[b] = +v to R[b]=R[b]||0+ +v

Removed index i=0;i++%2==0?b=v to b=isNaN(+v)?v:

isNaN(+v) -> !+v

Nice reductions! +1 to each...

JS, 254 240 245
z='replace';r={};p=eval(('[{'+prompt()+'}]')[z](/\n/g,'},{')[z](/;/g,','));for(i in p){l=p[i];c=0;for(k in l){if(!c){c=k;r[c]=0;}else{r[c]-=l[k];}};for(j in p){w=p[j][c];if(w!=null)r[c]+=w}};alert(JSON.stringify(r)[z](/"|{|}/g,'')[z](/,/g,'\n'))

Well..I know it is quite long but this is my second code golf.
Suggestions are welcome!
BTW, Interesting Javascript preserves the order of elements in hashmaps,
so, even if p contains an array of dictionaries, I can iterate each dictionary
as an array and I'm sure that the first element of a dict is the first inserted. (the name of the country referred to the current line)
Ungolfed:
z='replace';
r={};
p=eval(('[{'+prompt()+'}]')[z](/\n/g,'},{')[z](/;/g,',')); // make the string JSONable and then evaluate it in a structure
for(i in p){
    l=p[i];
    c=0;
    for(k in l){
            if(!c){ // if c is not still defined, this is the country we are parsing.
                    c=k;
                    r[c]=0;
            }
            else r[c]-=l[k];
    };
    for(j in p){
            w=p[j][c];
            if(!w)  r[c]+=w
    }
};
alert(JSON.stringify(r)[z](/"|{|}/g,'')[z](/,/g,'\n')) # Stringify the structure, makes it new-line separated.

Note: the input is a prompt() which should be a single line. But if you copy/paste a multi line text (like the proposed input) in a prompt() window then JS read it all.
Output:
US:9439.3
FR:2598.9
ES:852.1
PT:90.09999999999998
IT:887.5
IE:48
GR:116.8
JP:4817.4
DE:2903.7000000000003
UK:1546.2

You use the word "replace" four times in your code. How about shortening it like this: z='replace';r={};p=eval(('[{'+prompt()+'}]')[z](/\n/g,'},{')[z](/;/g,','));for(i in p){l=p[i];c=0;for(k in l){if(!c){c=k;r[c]=0;}else{r[c]-=l[k];}};for(j in p){w=p[j][c];if(w!=null)r[c]+=w}};alert(JSON.stringify(r)[z](/"|{|}/g,'')[z](/,/g,'\n'))?

Woah this saved me 74-(34+11) characters! (I also put (w!=null) as (!w)

@AntonioRagagnin Could you please show your output?

Thanks for your message @WallyWest. Turns out !w was not a good idea to check w!=null and the script wasn't working anymore :p. Now I'll update it with the results

Try using: z="replace";r={};p=eval(("[{"+prompt()+"}]")[z](/\n/g,"},{")[z](/;/g,","));for(i in p){l=p[i];c=0;for(k in l)c?r[c]-=l[k]:(c=k,r[c]=0);for(j in p)w=p[j][c],null!=w&&(r[c]+=w)}alert(JSON.stringify(r)[z](/"|{|}/g,"")[z](/,/g,"\n")) for 229 bytes...
What I've done here is reduced the if(!c) sequence to a single ternary operator, and I've also incorporated it in its parent for loop... I've also done something similar with the other for loop... comma operators can work wonderfully to join multiple statements within a loop...

Oh, and while I'm at it... welcome to Codegolf.Stackexchange... I hope you enjoy it here! :)

Groovy 315
def f(i){t=[:];i.eachLine(){l=it.split(/;|,/);s=l[0].split(/:/);if(!z(s[0]))t.put(s[0],0);t.put(s[0],x(z(s[0]))+x(s[1]));(1..<l.size()).each(){n=l[it].split(/:/);t.put(s[0],x(z(s[0]))-x(n[1]));if(!z(n[0]))t.put(n[0],0);t.put(n[0],x(z(n[0]))+x(n[1]))}};t.each(){println it}};def x(j){j.toDouble()};def z(j){t.get(j)}

Output:
US=9439.299999999997
FR=2598.8999999999996
ES=852.1
JP=4817.4
DE=2903.7
UK=1546.2000000000003
IT=887.5
PT=90.09999999999998
IE=48.0
GR=116.8

Ungolfed:
input = """US:10800;FR:440.2,ES:170.5,JP:835.2,DE:414.5,UK:834.5
FR:1800;IT:37.6,JP:79.8,DE:123.5,UK:227,US:202.1
ES:700;PT:19.7,IT:22.3,JP:20,DE:131.7,UK:74.9,US:49.6,FR:112
PT:200;IT:2.9,DE:26.6,UK:18.9,US:3.9,FR:19.1,ES:65.7
IT:1200;JP:32.8,DE:120,UK:54.7,US:34.8,FR:309,ES:29.5
IE:200;JP:15.4,DE:82,UK:104.5,US:39.8,FR:23.8
GR:200;DE:15.9,UK:9.4,US:6.2,FR:41.4,PT:7.5,IT:2.8
JP:4100;DE:42.5,UK:101.8,US:244.8,FR:107.7
DE:2400;UK:141.1,US:174.4,FR:205.8,IT:202.7,JP:108.3
UK:1700;US:578.6,FR:209.9,ES:316.6,IE:113.5,JP:122.7,DE:379.3"""

ungolfed(input)

def ungolfed(i){
    def tallyMap = [:]
    i.eachLine(){
        def lineList = it.split(/;|,/)
        def target = lineList[0].split(/:/)

        if(!tallyMap.get(target[0])){tallyMap.put(target[0],0)}
        tallyMap.put(target[0],tallyMap.get(target[0]).toDouble() + target[1].toDouble())
        (1..lineList.size()-1).each(){ e ->
            def nextTarget = lineList[e].split(/:/)
            //subtract the debt
            tallyMap.put(target[0], (tallyMap.get(target[0]).toDouble() - nextTarget[1].toDouble()))
            //add the debt
            if(!tallyMap.get(nextTarget[0])){ tallyMap.put(nextTarget[0], 0) }
            tallyMap.put(nextTarget[0], (tallyMap.get(nextTarget[0]).toDouble() + nextTarget[1].toDouble()))
        }
    }
    tallyMap.each(){
        println it
    }
}

Do you happen to have a link to where I can find more info on Groovy?

@WallyWest: I have this book, and learned tons from it. I feel that this is one of those languages that it is good to have a reference on the shelf. link, Also tons of info here: link

PHP, 333
$a='';while(($l=trim(fgets(STDIN)))!='')$a.=$l.'\n';$a=rtrim($a,'\n');$p=explode('\n',$a);foreach($p as $q){preg_match('/^([A-Z]+)/',$q,$b);preg_match_all('/'.$b[0].':(\d+(?:\.\d+)?)/',$a,$c);$e=ltrim(strstr($q,';'),';');preg_match_all('/([A-Z]+)\:(\d+(?:\.\d+)?)/',$e,$d);echo $b[0].':'.(array_sum($c[1])-array_sum($d[2])).PHP_EOL;}

Ungolfed version :
$a='';
while(($l=trim(fgets(STDIN)))!='')
    $a .= $l.'\n';
$a = rtrim($a,'\n');
$p = explode('\n',$a);
foreach($p as $q){
    preg_match('/^([A-Z]+)/',$q,$b);
    preg_match_all('/'.$b[0].':(\d+(?:\.\d+)?)/',$a,$c);
    $e = ltrim(strstr($q,';'),';');
    preg_match_all('/([A-Z]+)\:(\d+(?:\.\d+)?)/', $e, $d);
    echo $b[0].':'.(array_sum($c[1])-array_sum($d[2])).PHP_EOL;
}

source: Stack Exchange

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

sort: votes


text:
Math without numbers
You must write functions for addition, subtraction, multiplication, and division; however, you can never use any of your language's number types / primitives -- this means no ints, no floats, no Integers; no nothing. You cannot reference these types at all; not even implicitly, e.g. no pushing and popping numbers on a stack.
Valid statically-typed pseudocode (does not solve the problem):
boolean result = true && false
string helloWorld = "hello" + " world"
Object[] things = [new Object(), "foo", true]

Invalid statically-typed pseudocode (does not solve the problem):
float num = 42F
Object foo = "100".toInt()

To make things simpler, pointers are allowed.
This is code-golf, so make it short and sweet.

@Sylwester not a duplicate; here you are allowed to use anything but number primitives, and this is also a code golf, not a popularity contest.

So basically it's a code golf where the specification is to make the four math operations and the user gets to define how numbers are to be represented since you cannot use numbers not numeric functions?

If we can't refer to built-in number types, the input has to be some other type. We just declare that it's some other type that already supports the operations we want - for example, NumPy array types in Python - and then all the work is shoved into that code. Our code degenerates to add=lambda x,y:x+y. This question needs more work.

@user2357112 NumPy code, for example, would be invalid because it seems that you must explicitly use integer literals to initialize the arrays/matrices, am I correct?

@Jwosty: No, you can use strings. Doesn't matter, though. We only need to write the functions; we don't need to write the input. By the time the input reaches us, it's an array.

Whoa, whoa, whoa, you just completely changed the question. Not cool.

@user2357112 ah, I see the problem. I rewrote the question to exlclude that kind of solution.

Eh so now you want people to do recursive descent parsing on expressions with integers... that itself is more code and effort than the actual math-without-numbers.

Rolled back question; I realize the implications of my revision.

In C (as well as many languages), true is defined to be 1 (that is, an integer), and false is just 0 (another integer). So can we use them?

@ace: I would say it's fine; you don't really think of booleans as numerical types.

Haskell: 162 characters
This is algebraic data types 101.
data N=E|Z|P N
a x Z=x
a x (P y)=a(P x)y
s x Z=x
s Z _=E
s (P x)(P y)=s x y
m _ Z=Z
m Z _=Z
m x (P y)=a x$m x y
d _ Z=E
d x (P Z)=x
d Z _=Z
d x y=a(P Z)$d(s x y)y

I think it is cheating to use Haskell for this. It is too awesome.

Javascript
Example: 24.5-20.5+2*1 = bd.e-bz.e+b*a = 6
 f="bd.e-bz.e+b*a";
    n=function(a){
    if(a.match('^[+/*.-]$')) {
        return a;
    }
    if(a=="z") {a="`";}
    return a.charCodeAt()-"`".charCodeAt();
    }
    o=[];
    tx=f.split("");
    tx.forEach(function(t,idx){
                o.push(n(t));
            });
    o=o.join("");
    eval(o);

REBEL
3 + 9 + 23 + 29 = 64

Addition:
/;/

Subtraction:
/0;0/;/;/

Multiplication:
/0(0+;(0*))/$1:$2/0;|:/

Division:
/(0+)(0*;\1$)/1$2/10|1;/1/1/0

Input format:
2 strings of 0s, separated by a semicolon. The value is the length of the string.
0000;00

Output format:
1 string of 0s, with the same semantics.
000000

Since this works with natural numbers (positive integers), subtraction and division will not always yield the correct answer. Subtraction yields the absolute value of the result, and division rounds down.
These are not complete programs, but they use the current state of the program as input. Similarly, they leave the program in the result state when they are done.
Here is an example of how to use them (using division as an example):
000000;00/(0+)(0*;\1$)/1$2/10|1;/1/1/0

When this terminates, the current state will be 000.

Since REBEL has no primitive number types, this effectively became "Implement math any way you can".

Just rewrote the question; you will need to update your answer.

@Jwosty I probably won't change it. This answer was valid when it was posted, and changing it to the new question would be several orders of magnitude harder.

Ok, on second thought, I shouldn't change it so dramatically (that's what the sandbox is for :/). I'll roll it back.

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


text:
Build a 2-way universal logic processor using NAND logic gates
A 2-way universal logic processor (2ULP) is a network of logic gates that takes two input wires A and B, as well as four other inputs L_, L_a, L_b, and L_ab, and produces a single output L(a, b) using the four L inputs as a truth table function:

The 2ULP returns L_ if A and B are both 0.
It returns L_a if A = 1 and B = 0.
It returns L_b if A = 0 and B = 1.
It returns L_ab if A and B are both 1.

For example, given the inputs L_ = 0, L_a = 1, L_b = 1, and L_ab = 0, then the output L(a, b) will be equal to A xor B.
Your task is to build a 2ULP using only NAND gates, using as few NAND gates as possible. To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

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

Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.
The logic circuit that uses the fewest NAND gates to produce a correct construction wins.

My digital logic design skills are so rusty it's laughable, but I greatly enjoy the end results of these competitions. +1

With two-input NAND gates, there's not much room for creativity in this design.  Perhaps, rather than requiring that the device take six inputs, design a block with has an arbitrary number of inputs and one output, and require that given two inputs A and B and a choice of one of the sixteen functions, it must be possible to connect the block's inputs to some combination of A, B, High, and Low, such that the output will yield that function.  Such a device would be a universal 2-way logic processor (just add wires), but could probably be done in a lot less than 11 gates.

We should invent [tag:gate-golf], where you write in the smallest amount of gates.

That's what [tag:atomic-code-golf] + [tag:logic-gates] is for.

11 NANDs
Define the gate MUX (cost 4) as
MUX(P, Q, R) = (P NAND Q) NAND (NOT P NAND R)

with truth table
P Q R    (P NAND Q)   (NOT P NAND R)    MUX
0 0 0        1               1           0
0 0 1        1               0           1
0 1 0        1               1           0
0 1 1        1               0           1
1 0 0        1               1           0
1 0 1        1               1           0
1 1 0        0               1           1
1 1 1        0               1           1

Then this is the familiar ternary operator MUX(P, Q, R) = P ? Q : R
We simply have
2ULP = MUX(A, MUX(B, L_ab, L_a), MUX(B, L_b, L_))

for a cost 12, but there's a trivial one-gate saving by reusing the NOT B from the two inner MUXes.

You just gave me an idea of something to try with redstone in Minecraft, thanks

Absolute minimum is 11 NANDs. I searched thoroughly. And the fastest circuit I found has a depth of 5 gates. So this puzzle is solved by Peter Taylor.

cost: 4*4*14+4*(13)+13*3+3*3+24*1+4=352
I'm not a boolean man, this is my best in coding this things (I know this won't give me many immaginary internet points..).
# l1 is for a=F , b=F
# l2 is for a=F , b=T
# l3 is for a=T , b=F
# l4 is for a=T , b=T

2ULP(l1,l2,l3,l4,a,b) =
 (l1&l2&l3&l4)|             # always true
 (!l1&l2&l3&l4)&(a|b)|      # a=F,b=F->F; ee in T
 (l1&!l2&l3&l4)&(!a&b)|     # a=F,b=T->F; ee in T
 (!l1&!l2&l3&l4)&(a)|       # a=F,b=F->F; a=F,b=T->F; a=T,b=F->T; a=T,b=T->T;
 (l1&l2&!l3&l4)&(a&!b)|     # a=T,b=F->F, ee in T
 (!l1&l2&!l3&l4)&(b)|       # a=T,b=F->F, ee in T
 (!l1&!l2&!l3&l4)&(a&b)|    # a=T,b=T->T, ee in F
 (l1&l2&l3&!l4)&(!(a|b))|   # a=T,b=T->F, ee in T
 (!l1&l2&l3&!l4)&(!(avb))|  # a=T,b=F->T, a=F,b=T->T, ee in T , note v is the exor.
 (l1&!l2&l3&!l4)&(!b)|      # T when b=T
 (!l1&!l2&l3&!l4)&(a&!b)|   # T when a=T,b=F
 (l1&l2&!l3&!l4)&(!a)|      # T when a=F
 (!l1&l2&!l3&!l4)&(!a&b)|   # T when a=F,B=T
 (l1&!l2&!l3&!l4)&(!(a|b))  # T when a=F,B=F

If you follow the system outlined by the bullet points in the question then you get a cost of 29, so this is impressively bad.

I'm sorry Mr  Taylor, I just hope this haven't ruin your eyes.

By using Wolfram language I can get a 13 gates formula:
logicfunc = Function[{a, b, Ln, La, Lb, Lab},
                   {a, b, Ln, La, Lb, Lab} -> Switch[{a, b},
                          {0, 0}, Ln, {1, 0}, La, {0, 1}, Lb, {1, 1}, Lab]
                  ];
trueRuleTable = Flatten[Outer[logicfunc, ##]] & @@ ConstantArray[{0, 1}, 6] /. {0 -> False, 1 -> True};
BooleanFunction[trueRuleTable, {a, b, Ln, La, Lb, Lab}] // BooleanMinimize[#, "NAND"] &

which outputs:

Here Ln, La, Lb and Lab are the L_, L_a, L_b and L_ab separately in OP.
sidenote: The results of the BooleanMinimize function in Wolfram language are restricted to two-level NAND and NOT when invoking as BooleanMinimize[(*blabla*), "NAND"], so it's not as good as Peter Taylor's four-level formula above.


text:
Smallest code to return sum of all characters in an array of strings
Smallest code to return sum of all characters of an array of C-strings, including null-byte-terminattor of each string in the array.
example in C:
    const char *a[] = { "abc", "bdef", "cee", "deee" };
    size_t n = sumOfAllBytes(a);
    printf("n = %d\n", n); // n = 18

e.g.,
   strlen(a[0]) + 1 + ... + strlen(a[n])

where n is array-size-1, ie, the last elemet in the array, in this case, deee word. Note that n = 4 (starting from 0 as C does)
Each character is an ASCII character in C it's 1 byte-size.

How do you define the value of each character?

by sizeof(char) = 1, e.g, strlen("abc") + sizeof('0') = 4

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳  Looks like it is the count of each character: 14 chars + 4 null-byte-terminators = 18.

Do you have to create a complete program, or is it OK to write only a function with an array as parameter?

Only the function with some usage example.

That's not the sum of characters. That's the number of characters.

How do you know how many strings are in the array? Your example doesn't have any sort of length argument or sentinel value to indicate it.

How is this sum of all characters or sumOfAllBytes. Isn't it just a count, rather than a sum? At best sumoflengthsof, but not sum of characters or bytes.

@user2357112: In C it's by sizeof(a)/sizeof(a[0])

@BillWoodger: I mean sum of the length of all string in the array. It isn't count. My previously comment show how count is. It's sum:    strlen(a[0]) + 1 + ... + strlen(a[n])

@Jack: Doesn't work. The function only receives a pointer to the first element of the array; the size information isn't available.

@user2357112: I' don't limited you to don't pass the count of elements in the array by no means. You can write an extra parameter called size and then pass sizeof(a)/sizeof(a[0]) which will give the count of elements in the array not all many the sum of length of each string into it. In this case you need to something like a loop from 0 to size plus strlen(a[i]).

Also, you can use any language you want to, if you do C++ there's a trick with C++ using templates. It just make easy know the count of array passed by parameter without an extra parameter also array itself. It does work fine. I have both C and C++ working version (the initial challenge was limited to C/C++ but I changed in order to everybody join)

You say "array of C-strings", so presumably the program needs to actually use C-style strings.

You say sum of bytes, sum of characters. You are asking for neither of those things. It is a count of characters, or bytes, including delimiters, or a sum of the lengths, including delimiters. It is not the sum of bytes/characters. This is computers.

@user2357112: Since I removed the limit to use C or C++ language people are using other languages and just assuming there's a 0 byte at end of string just adding plus one in the length.

GolfScript [4 bytes]
n*,)

There are no functions in GolfScript, so you should use a standard input instead:
["abc" "bdef" "cee" "deee"]
n*,)

>>> 18

DEMO: http://golfscript.apphb.com/?c=WyJhYmMiICJiZGVmIiAiY2VlIiAiZGVlZSJdCgpuKiwp

I need to learn GolfScript. :)

Haskell, 21 19 bytes
succ.length.unwords

Edit: Removed two bytes thanks to ais523!

Hi, and welcome to PPCG! We allow submitting anonymous functions here; you don't need to name them. As such, you could remove the s= to save two bytes, as the submission evaluates to an expression of function type as it is. (I'm also curious as to whether there's a way to golf down the succ into something shorter, but all the possibilities I've thought of, such as (+1), are the same number of bytes or longer.) Incidentally, you can use # or ## at the start of a line for heading-bold (# is larger); that's the formatting most people use for their answers.

It also took me some time to figure out that this answer was correct. Often it's a good idea to include a link to an online interpreter that shows the program working. Here's one for your program; you could edit it into your answer.

By the way, don't worry about the downvote: it was caused by a bug in the Stack Exchange software, not made by an actual user.

You can use unlines instead of unwords and drop the succ, because unlines adds a final newline: Try it online!

Mathematica 31 29 bytes
-2 bytes thanks to numbermaniac
StringLength[""<>#]+Length@#&

Example
StringLength[""<>#]+Length@#&@{ "abc", "bdef", "cee", "deee" }

18

I don't think you need to assign the function name to a variable to be a valid answer, so you could save 2 bytes there.

@numermaniac, you are right. Thanks.

bash+coreutils - function body 10 bytes
sumOfAllBytes()(wc -c<<<$@)

Call as follows:
$ a=("abc" "bdef" "cee" "deee")
$ sumOfAllBytes ${a[@]}
18
$

Perl, function body: 15 bytes
sub sumOfAllBytes{!!@_+length"@_"}

Function sumOfAllBytes returns the sum of the string lengths including a "virtual" terminator byte. Perl does not have the concept of terminating a string with a null byte.
A variant without a "terminating byte":
sub sumOfAllBytes{$"=$;@_+length"@_"}

Byte count: The body of the functions are 15 or 17 bytes (with or without terminator). 7 bytes must be added, if the whole function with one-byte name should be counted.
Test with degolfed version:
sub sumOfAllBytes {
    # the argument(s) are put into array @_ by Perl
    !!@_ +       # short for: @_ ? 1 : 0
                 # (if the array is empty nothing should be added)
    length "@_"  # The array elements are interpolated into the double-
                 # quoted string; the elements are separated by a space ($").
    # without explicit return statement, the value of the last
    # statement is returned.
}

@a = qw[abc bdef cee deee];
print sumOfAllBytes(@a), "\n"; # prints 18

Rebol (body: 18 chars, function: 30 chars)
1 + length? form x

Usage example in Rebol console:
>> f: func[x][1 + length? form x]

>> f ["abc" "bdef" "cee" "deee"]
== 18

C, 78 minus declaration of a[]
Assumes 64 bit target and a[] containing at least one string.
char *a[]={"abc","bdef","cee","deee"};
f(int i){return strlen(a[i])+1+(i?f(i-1):0);}
main(){return f(sizeof(a)/8-1);}

To see the result, invoke thusly:
$ ./whatever || echo $?

c preprocessor macros, 94 chars
The example in the question is not doable in c as a regular function as the function would have no idea the size of the array if just a pointer to the array is passed in.  But we can do this as a couple of preprocessor macros:
#define c(s) sizeof(s)/sizeof(s[0])-1
#define sumOfAllBytes(s) s[c(s)]-s[0]+strlen(s[c(s)])+1

We assume that the array is declared, defined and initialised as in the question.  That way the strings should be laid out sequentially in memory.  We can then subtract the address of the first element from the last element and add the strlen() of the last element.  No need to loop over all elements and strlen().

Haskell 24
s=sum.(map$(+1).length)

Usage, in ghci:
ghci> s ["abc", "bdef", "cee", "deee"]
18

Java: 56 characters (body) 74 characters (full method)
Hey, this is as good as it gets in Java!
This is the method:
int z(String[]a){int s=0;for(String b:a)s+=b.length();return s+a.length;}

The main code is just 56 characters (witout spaces and comments):
int s=0;            // The sum variable.
for(String b:a)     // The 'for each' loop is handy
    s+=b.length();  // Adding the length of each String
return s+a.length;  // Adding the length of the array

Calling this function:
int answer = z(new String[]{ "abc", "bdef", "cee", "deee" }); // Stores 18

I know it's been over three years, but you can golf two bytes by changing int s=0; to int s=a.length; and removing the +a.length in the return.

05AB1E, 5 bytes
JgIg+

Try it online!
-1 thanks to @Datboi

JgIg+ should work as well

I have no idea how that works. I is supposed to read the current input as a String, and if the first input was consumed by J, how is it still reading the input, as an array no less? Unless they changed what I does... Weird...

As far as I know it will read the input as an array if it is in the form of  [item1, item2, ...]. To answer your second question: If there are no items on the stack nor in the input I will use a copy of the bottom input to pop. Jg¹g+ should also work though

@Datboi yeah, I think they changed it since a year ago. A year ago I don't think that would've worked. Then again this is a 3 year old question, so this answer is non-competing anyway; just noticed that too lol.

C [body: 48 chars, function: 107 chars]
int f(const char** r, const char* c, const char** e) {
  return r-e?1+(*c?f(r,c+1,e):f(r+1,*(r+1),e)):0;
}

Ugly piece of code. Just trying to do it without loops by using recursion.
Call it this way:
    const char *a[] = { "abc", "bdef", "cee", "deee" };
    size_t n = f(a,*a,a+4);
    printf("n = %zu\n", n);

No warnings and result is OK:
$ gcc koe.c -Wall -Wextra -o koe
$ ./koe
n = 18

C - Loop:64, Recursion:56 (-18 for function body overhead)
Loop
s(char*a[],int n){int r=0;for(;n;)r+=strlen(a[--n])+1;return r;}

Recursion
r(char*a[],int n){return n?strlen(a[0])+1+r(a+1,n-1):0;}

PHP 5.3 - 60
array_sum(array_map(function($v){return strlen($v)+1;},$a));

Where $a is the array.

<?=strlen(join(_,$_GET))+1; should do the same

Python - 55 42 38
def s(v):print sum(1+len(x)for x in v)

can be shortened some more: def s(v):print sum(1+len(x)for x in v) to 38 chars

Here's a TIO with a lambda instead, 32 bytes. https://tio.run/##K6gsycjPM/pfbBvzPycxNyklUaHMqrg0V8NQOyc1T6NCMy2/SKFCITNPoUzzf0FRZl6JQrFGtFJiUrKSjlJSSmoakEpOTQWSKalAKlbzPwA

JavaScript - 42 characters without declaration
function s(x){return x.join(" ").length+1}

Usage:
a=["abc","bdef","cee","deee"];console.log(s(a));

D - 58 54 bytes
int x(T)(T t){return reduce!"a+b.length"(t.length,t);}

This requires std.algorithm, so add the characters necessary for making that import if you want to.
Example of usage:
import std.stdio,std.algorithm;

int x(T)(T t){return reduce!"a+b.length"(t.length,t);}

void main(){
    writeln(x!(string[])(["abc","bdef","cee","deee"]));
}

Fortran 90+ - 75 total, 23 for function alone
Unfortunately, Fortran doesn't allow for implicit typing of character strings, but we can abuse F77+F90 for golfing purposes. The whole program would be:
character*4::c(4)=["abc","bdef","cee","deee"];print*,sum(len_trim(c)+1);end

The function alone, written using a statement function would be
k(s)=sum(len_trim(s)+1)

which would be called using print*,k(c).

in C# 34 Excluding  "string [] a=new [] { "abc", "bdef", "cee", "deee" };"
   string [] a=new [] { "abc", "bdef", "cee", "deee" };
                var i=string.Join(" ",a).Length+1;
sol:2
var j =  string.Concat(a).Length + a.Length;

JavaScript - 20 17 Characters
s.join().length+1

Assumes that the array of strings is in variable 's' and outputs the answer to the console.

APL 6
+/1+⍴¨a

where
a←"abc" "bdef" "cee" "deee"

yields
      +/1+⍴¨a
 18

Read as "Sum over 1 plus size of each element in a"

Isn't that 6? +/1+⍴¨ Anyway, you can make it 4: ⍴⊢,∊

C#, 52 including variable declaration
int c=0;for(int i=0;i<a.Length;i++)c+=1+a[i].Length;

Uncompressed version for ease of reading:
int count = 0;
for (int i = 0; i < a.Length; i++)
    count += 1 + a[i].Length;

q/kdb+, 14 bytes
Solution:
sum 1+(#:)each

Example:
q)sum 1+(#:)each("abc";"bdef";"cee";"deee")
18

Explanation:
Evaluated right-to-left, thus:
// count (#:) length of each item in the list
q)(#:)each("abc";"bdef";"cee";"deee")
3 4 3 4
// add one to each item
q)1+ 3 4 3 4
4 5 4 5
// sum up the items
q)sum 4 5 4 5
18

Jelly, 3 bytes
KL‘

Try it online!

Clojure, 32 bytes
#(apply +(map(comp inc count)%))

Composition FTW. Aww it is the same length as #(apply +(count %)(map count %)).

F#, 56 bytes
Still practicing with F#...
let f a=(a|>Seq.map String.length|>Seq.sum)+Seq.length a

Invoke with:
[<EntryPoint>]
let main argv =
    let sum = [| "abc"; "bdef"; "cee"; "deee" |] |> f
    printfn "%A" sum
    0

Seq.sumBy(fun s->s.Length+1)

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

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


text:
Sort-a-number. Sorta
Inspired by the ill-fated sorting-a-numbers-digits-without-using-an-array, but I thought it made a better code golf than SO question.
Given a positive integer, sort the digits in that integer.
Lowest score wins!

Start with 0 points.
Add one point per character.
Add 20 points for each array you use.
Add 10 points for each multi-character string in your code. (Except the initial input as long as it is converted to an integer without any other operations done on it.)
Add 32 points if the maximum number of digits your program can handle is limited by your program (as opposed to the machine).
Subtract 10 points if your code can change the direction of the sort given another argument (whatever you want, but for example 0 for descending sort and 1 for ascending.)

Every language is different, but the idea is to avoid any kind of iterable-of-digits hackery.
Example:
Input: 52146729
Output: 97654221 or 12245679
Notes:

Use any built-in sorting capabilities your programming language provides, but if that sort feature involves strings or arrays, take the penalty!
You can write the solution as a function that takes an integer directly, or as a program that takes an argument from argv, a file or stream and converts it to an integer. As long as you convert it to an integer immediately and discard the original char* input without doing any further operations on it, no penalty applies.
The penalties apply not only to string literals in your program text, but any part of your program feature that arguably inputs or outputs a string or iterable. For example, JavaScript String.prototype.split has at least one string as input (this) and an Array as output, so +30 for using that.
I've tried to make these rules guide the principle of the algorithm design, not the initial/final I/O (hence note #2). I don't think the penalty ought to apply to int(input()) even if input's signature says it returns a string, as long as that expression is the initial entry point of the program. Likewise, if the final output of the program is print(x) and x must be a string, the penalty doesn't apply to the last-ditch string casting operation. All that said, I explicitly never said that this had to be a program or where the I/O had to come from or go. A function that takes an int and returns an int would serve, and wouldn't suffer from these ambiguities.

If I take a number and convert it to a string, and then use split but don't define the array directly will you count that as me using an array?

Also, is '' counted as a multi-character string even though there's no characters within it?

Does " " count as a multi character string? A single character would not be considered as "multi"...

I think to really be in the spirit of the no strings rule the program should not be able to handle an input with a non-numeric character in it.

How are zeros to be handled? Sorting 100 should yield what? 001? That's going to be very hard to do without strings. How 'bout 1? Of course, reverse sorting is easy.

Sorting 100 should yield 1 or 100.

A single character is not multi character, until you combine it with another non empty character.

Seems to me like an easy implementation of sleepsort.

You don't forbid the language's sorting funtions.

Is it okay if I don't add the main() method in JAVA? (i'm not considering console input.)

With all the "it doesn't count if the string isn't explicitly declared" pseudo-solutions, I'm tempted to write a pointfree answer that does all the work in integers without ever explicitly mentioning an integer anywhere.

Yeah, I really meant no strings longer than one character, regardless of how the string comes to be. The only reasonable exception to this is the necessary initial step of converting the input from strong to int.

I don't forbid the language's sorting functions. If you can find a way to use them without strings, arrays or iterables-of-digits, more power to you.

I'd write better the rules about built-in functions, also penalities are too low: this incentivate the use of an array instead of an alternative (probably longer) method.

@AntonioRagagnin I didn't want to change the penalties ex post facto, but I clarified the rules around built-in functions.

Please elaborate on Note #2

Can I use a function that inputs a string? Does the function have to return or print ?

Does a regex count as a string?

@Hasturkun that's a tough one. I think to be fair they probably should, but even if the expression itself gets a pass it's hard to argue that regular expressions operate on non-strings. Wikipedia says regex are mainly for use in pattern matching with strings.

@ace Here's a sleepsort answer. Not sure if you posted your comment before or after this

String is backed by an array. Does that mean if I use a multi-char string it actually costs me 30 chars? +20 for the array in the string? If not, then shouldn't ArrayList in java be free?

Can't I just use an empty array to gain a 20-point bonus? Repeat that a few times, profit. ;)

GolfScript, 11 4
(4 + 10 (string) - 10 (reverse option))
Input on STDIN.
~`$%

Input format is this:
(1 or -1) (the number)

1 to sort normally, -1 to reverse. 4 characters - 10 for reverse option = score of -6.
The input is technically a string, so I'm not sure whether that counts for +10. I'm interpreting the rule as "a string declared in your program" (since it says "in your code").

Old answer (score of 11):
$

Strings are technically arrays in GS, just to really complicate the scoring debate.

Yes, input of a string (that is not immediately converted into an integer) is +10.

@kojiro ~ immediately converts to integer. But then it's converted back to a string with ```. Does converting into a string count? Because sometimes the string might not be multicharacter (1 digit input)

Yes, converting into a string counts unless the function (or whatever) can only output a one-character string. This should be assessed based on the function signature or documentation. If it's designed to output one character (like chr), it's fine.

Haskell 106
t=10;d=divMod;s z|z<w z=s$w z|t>0=z
w x|x<t=x|y>z=(q*t+y)*t+z|t>0=y+t*(w v)where{(v,y)=d x t;(q,z)=d v t}

example:
ghci> s 502010406072952146729521467295214672952146729
999997777766666555554444422222222221111100000

An answer that doesn't dodge the question.
An explanation was requested, here it is ungolfed. It's a very inefficient bubble sort.
-- t=10 - alias for 10. d=divMod - alias for divMod.
-- The alias for '10' turns out to be unnecessary; inlining it
-- and using '1>0' for True has the same character count. It's
-- a relic of earlier versions of the code.

-- 's': if no digits need swapped, return the number,
-- otherwise return 's' applied to the number with
-- that pair of digits swapped.
sort z=
  let temp=sort_pair z
  -- because we are sorting in descending order,
  -- sorting a pair of digits always increases the number.
  -- testing > costs one less char than ==.
  if z<temp then
    -- golfed version uses guards instead of if/else to save space.
    -- t>0 is '10 > 0', which is 'True', in fewer chars.
    sort temp
  else
    z
-- 'w': recursively swap one pair of out of order digits, or
-- return the original number if no pairs needed swapped.
sort_pair x=
  -- haskell does the assignments below lazily, they aren't
  -- calculated unless I use them. 'divMod' lets me do this
  -- with fewer chars.
  let y = x `mod` 10 -- last digit
      v = x `div` 10 -- all but last digit
      z = v `mod` 10 -- second last digit
      q = v `div` 10 -- all but last 2 digits
  in
  if x < 10 then
    x
  else if y > z then
    -- last 2 digits are out of order. swap them & return
    -- This is rearranged using Horner's method to save space
    -- http://en.wikipedia.org/wiki/Horner%27s_method
    -- ... although it turns out not to save anything, it's a relic.
    (q * 10 + y)*10 + z
  else
    -- last digit is ok, so try sort_pair on remaining digits
    let temp = sort_pair v in
    -- put last digit back on the end and return
    -- having the bracketed expression last here
    -- let me remove a space before 'where'
    y+(10*temp)

Shorter answers exist in Haskell, equivalent to some of the others posted, eg:
import Data.List;s=read.sort.show::Integer->Integer

... scores 52+20=72, or this, scoring 45+20=65:
import Data.List;main=interact(reverse.sort)

... but the spirit of the question - no arrays, strings, or characters - is more interesting.

Could you add an explanation?

You should get a bonus point reduction for having the integer input size not even being limited by the machine due to Haskell's implicit arbitrary precision integers.

@awashburn Well, he got it (i.e. he didn't add 32 points!) And supposedly, so did I (here)

@ambigram_maker I think he means that yours, for example, can't take input larger than Integer.MAX_VALUE-it takes an int. Mine, and some of the others, accept any size input-the input type of s is Integer, equivalent in BigDecimal in java. That isn't what I took the question to mean though, I thought it was penalizing answers that 'sort' only one digit numbers.

Oh no... ur right, the max limit of an array is Integer.MAX_VALUE

It's easily changed. I don't think its a big deal.

@awashburn The integer input size is limited by the machine, though: the machine has only so much space available to store that number. One googolplex of random numbers might bust that limit, even if it might not bust Haskell.

C + x86 assembly, 636
I know this isn't gonna win but it felt so much unnatural and twisted that I had to share it. No arrays or strings (as long as you don't count the input arguments). The number of digits its limited by the 32 bit range.
So here's a little explanation on what I did:
I thought I'd do this without using any arrays or strings, and then recursion came into mind, but of course, with recursion I wouldn't be able to swap values from other recursive calls... and then was when I realized that there was a way. Linking my C program with an assembly function I could jump up in the stack and return a pointer to the base pointer of the desired call, that's what "recursionStackAt" function does. Of course recursionStackAt is a very ugly function, its result doesn't only depend on the input or program's state but on the caller itself. Note that that's what made me change the indexes from 0 based to 1 based.
Without further ado, here's the code:
#include <stdio.h>
#include <stdlib.h>

int numberToSort;
int totalLength = 0;
int decreasing;

int* recursionStackAt(int pos); //Here's the magic

void swapAtStack(int pos1, int pos2) {
    int a = *(recursionStackAt(pos1)+3);
    *(recursionStackAt(pos1)+3) = *(recursionStackAt(pos2)+3);
    *(recursionStackAt(pos2)+3) = a;
}

int getAt(i) {
    return *(recursionStackAt(i)+3);
}

void printNumber(int len) {
    int i = 0;
    for(i = 1; i <= len; ++i) {
        printf("%d",*(recursionStackAt(i)+3));
    }
    printf("\n");
}

void computeNextDigit(int remainingNumber, int nextDigit) {

    if(remainingNumber == 0) {
        //Bubble sort cause I was lazy and it's quite compact
        ++totalLength;

        int i, j;

        for(i = 1; i <= totalLength; ++i)
            for(j = 1; j <= totalLength-1; ++j) {
                if(decreasing) {
                    if(getAt(j) > getAt(j+1))
                        swapAtStack(j,j+1);
                }
                else {
                    if(getAt(j) < getAt(j+1))
                        swapAtStack(j,j+1);
                }
            }

        printNumber(totalLength);
    }
    else {
        ++totalLength;
        computeNextDigit(remainingNumber/10, remainingNumber%10);
    }
}

int main(int argc, char* argv[]) {
    if(argc == 3) {
        numberToSort = atoi(argv[1]);
        decreasing = atoi(argv[2]);
    }
    else exit(1);
    computeNextDigit(numberToSort/10, numberToSort%10);
}

And of course the x86 (AT&T sintax, btw) assembly code for the recursionStackAt function:
.text
    .align 4
    .globl  recursionStackAt
    .type   recursionStackAt, @function
recursionStackAt:
        pushl %ebp
        movl %esp,%ebp
        pushl %esi
        movl $0, %esi #i = 0
        movl (%ebp), %eax #pointer
while:
        cmp %esi, 8(%ebp)
        je endwhile
        movl (%eax),%eax
        incl %esi
        jmp while
endwhile:
        popl %esi
        movl %ebp, %esp
        popl %ebp
        ret

Some examples on the output: (1 means increasing and 0 decreasing)
$ ./sortasort 6543210 1
0123456
$ ./sortasort 32507345 1
02334557
$ ./sortasort 32507345 0
75543320

Here's the obfuscated version (which is unreadable but works fine):
http://pastebin.com/XkYt9DLy (C code)
http://pastebin.com/h0S0dfeU (x86 code)
So if LibreOffice isn't lying my obfuscated code consists of 646 characters (without spaces, should I count them?) and with all the other conditions met I get a -10 for the incresing/decreasing choice.
Oh, and to compile this you should do (On Unix-like systems)
gcc -c [-m32] recursionStackAt.s
gcc -o sortasort [-m32] sortasort.c recursionStackAt.o

Note that the -m32 flag is only if you're on a 64 bit machine. You also need the 32 bit libraries to compile it.

I think necessary whitespace is normally counted.  At least thats what I do, after stripping out unnecessary whitespace.  Anyone who has the balls to mess with the stack like this gets my upvote!  +1

Bash (echo) (0+7+0+0+32-10) = 29
Sorta:
echo $*

Usage:
sorta 5
5

Use "-e" to sort in reverse:
sorta -e 3
3

produces the correct result for positive integers 1-9, plus 0
avoids any kind of iterable-of-digits hackery.
7 characters (+7)
no arrays
no multi-character strings
maximum number of digits it can handle: 1 (+32)
can optionally reverse the sort (-10)

EDIT: changed "cat" to "echo" so it would actually work.
EDIT 2: Added " $*" and put it into "sorta" script

Haha; nice trick, but it's still the losing answer out of all the (also rule-bending) answers so far ;)

Allowing yourself the -10 for sorting a single digit 'both ways' feels rather undeserved.

The whole thing is undeserved; why pick on the sorting?

Hmm, the rules state that you have to give another argument to reverse the sort. What is that argument?

The argument can be whatever I want.  I chose the empty string.  I'll add an example.

Legendary abuse of rules.  +1

@kojiro: For example, -e could be used as argument for the reverse output.

"-e " would cost another 3 bytes.  "" doesn't cost anything.

Never mind, you are right, "-e" would work as well as "".  I'd have to rewrite the user manual though, and for backward compabibility I'd have to continue to accept "".

Bash is sooo inefficient for this task! If you switch to bc and read from STDIN, you can use an empty script or one containing solely the shebang #!/usr/bin/bc (which isn't included in the character count). This will break backward compatibility though; you'll have to teach your userbase to use -l, -q or -w for reversing the output.

Keeping backward compatibility: If "sorta" contains "bc<<<$1", then "sorta 5" and "sorta 3 ' ' " still work.  But it's no shorter than the current implementation.  And there are no points to be gained by increasing the speed of the program.  Thanks, though; I was looking for a 2-byte equivalent of "echo" but overlooked "bc".

Python3
My script features:
No arrays
No strings
Complexity is O(n): I used countingsort (modified by me to not use arrays, but prime numbers to count occourences)
No limitations in size
Characters: 260 234
n=int(input())
def C(n,k):
    return (n//(10**(k-1)))%10
P=lambda l:((((29-6*l%2,19-2*l%2)[l<9],13-2*l%2)[l<7],2*l-1)[l<5],2)[l==1]

p=1
while n>=1:
    c =C(n,1)
    p*=P(c+1)
    n=n//10
f=1
k=r=0
while p>2:
    if(p%P(f)==0):
        r+=(f-1)*10**k
        p=p//P(f)
        k+=1
    else: f+=1
print(r)

I could be wrong, but I think you can lose the parens around some of that arithmetic to shave some characters off.

I really like the use of primes here. It's so very weird. Also, I think P can be written lambda l:((((29-6*l%2,19-2*l%2)[l<9],13-2*l%2)[l<7],2*l-1)[l<5],2)[l==1], shaving off quite a few characters. I may have messed it up a little, but the idea is to use a nested version of the old-school Python ternary (before Python had a ternary) (false_result, true_result)[boolean].

Thanks random guy from the internet! BTW I'm having fun with this now, try to see if you like: http://codegolf.stackexchange.com/a/25086/16992

Bash+coreutils, 14 (24 chars - 10 for reverse)
I think this might be bending the rules a bit, but here goes, its Friday...
I assume use of standard libraries is allowed.  My interpretation of standard library for bash is coreutils:
fold -1|sort $1|tr -d\\n

No arrays - streams are used instead
No quotes == no multi-character strings
No limit to input/output length
optional arg "-r" reverses the output.

Input from stdin.  In use:
$ declare -i i=52146729
$ ./ksort.sh <<< $i
12245679 $
$ ./ksort.sh -r <<< $i
97654221 $
$

I really wish I'd included a rule against the program working with anything that isn't an integer. I guess it's too late now.

Don't count the newline after the "\n" so you score 20 not 21.

I'm not counting the newline, but as a script saved in a file it has a \0 at the EOF as saved by my editor.  I usually count these anyway.  But I can strip that \0 off, and the script still works, so I'll take it!

@kojiro It works with bash's idea of integers too (declare -i).  Edited.

(BSD/OSX tr doesn't like your syntax, which would cost you one character on those systems.) Anyway, I'd argue that these are still all string operations at heart. declare -i doesn't make a name an integer, it just makes the shell use arithmetic context on it on the RHS of assignment expressions.

What about suppressing leading zeroes?

This answer was written before I clarified the rules on that.

c function (little-endian arch), 131 108 chars
No sorting challenge is complete without a sleepsort answer.  This one will take up to 10 seconds to return, but it does work, and I think it is fully within spec.  This function takes a single int param and returns an int with the decimal digits sorted:
c=0,d;
k(i){
    for(;i;i/=10,fork()?c++:(sleep(d),exit(d)))
        d=i%10;
    for(;c--;i=i*10+(d>>8&255))
        wait(&d);
    return i;
}

newlines and indentation added for readability
Call as follows:
int main (int argc, char **argv) {
    int i = 52146729;

    printf("%d\n", k(i));
    return (0);
}

Nice. But I think you can use global variables to save some chars. Also, you can use ?: instead of if-else. fork()?c++:(sleep(d),exit(d));

@ace Thanks for the tips!  I tried the ternary operator earlier but slipped up on the (,).

C - 64 characters, 64 points
main(int a,char**b){b++;qsort(*b,strlen(*b),1,strcmp);puts(*b);}

You might wonder how I get this to work without any headers.  Simple, compile with:
gcc -include stdio.h stdlib.h string.h test.c -o test --std=gnu11 -Wall -g -O3

Un-golfed:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main(int a, char **b)
{
    b++;
    qsort(*b, strlen(*b), sizeof(char), strcmp);  // sizeof(char) is guaranteed to be 1 by standards
    puts(*b);
}

I also decided to include sorting of characters, just because I could.
Test runs:
$ ./test 132815
112358
$ ./test 423791
123479
$ ./test 1234767189728975213132471243985123957120837412
0111111112222222233333344445556777777788889999
$ ./test 4789359uihjasvb8ygohq9poi3n4jiouy58g
3344557888999abgghhiiijjnooopqsuuvyy

Nicely done bit of "golfing" :D

I can't compile this on Ubuntu 14.04 but I can compile main(int a,char**b){b++;qsort(*b,strlen(*b),1,strcmp);puts(*b);} which is shorter anyway.

@gmatht I'm not sure why it wouldn't compile, it was able to on my system just fine.  Thanks for the hint BTW!

It didn't like c(*a, my version of gcc insisted that we needed to do c(char*a instead.

TeX/LaTeX (332)
If the actual code is put in a package s, then the main LaTeX file looks nice and easy. The number is just given as math. If the number is negative, the sorting order is reversed. The code of package s can also used with plain TeX, example further below.
\documentclass{book}
\usepackage{s}
\begin{document}
  $52146729$

  $-52146729$ % reversed ordering

  $277981468517523153773703292073191466142223027369188752287219582183$
\end{document}

The package s (one line, line ends are not needed):
\TeXXeTstate1\everymath{\aftergroup\B\def~#1{\gdef#1{}\aftergroup#1}
~\a~\b~\c~\d~\e~\f~\g~\h~\i~\j\aftergroup\E\xdef\B{}\xdef\E{}}
\def~#1#2{\mathcode`#1"8000\lccode`~`#1\lowercase{\def~{\xdef#2{#2#1}}}}
~0\a~1\b~2\c~3\d~4\e~5\f~6\g~7\h~8\i~9\j\mathcode`-"8000\lccode`~`-
\lowercase{\def~{\xdef\B{\beginR}\xdef\E{\endR}}}

Result:

Score: hopeless

Using plain TeX with etex or pdftex, the file can be reduced to:
<contents of s.sty>\rm\shipout\hbox{$<number>$}\bye
Bytes: 318 bytes (s.sty) + 24 bytes for the rest without the number
Arrays are not used: 0
I do not see multi-character strings: 0
The number is not limited by the algorithm. The largest TeX number is 231 - 1 = 2147483647. The example uses a 66-digit number, way larger:
0
If a minus is given, then the sorting order is reverted to descending: −10

0 + 318 + 24 + 0 + 0 − 10 = 332
Algorithm:
The digits are made active characters in math mode. Each digit remembers and collects each usages in a macro. After the math mode the macros are output with the digits in ascending order.
The direction change is done by right-to-left text, an e-TeX feature.
Degolfed version of the code in s.sty
\TeXXeTstate = 1 % enable mixed direction typesetting
\everymath{%
  % \B and \E surround the number, they will be redefined
  % with right-to-left primitives to output the reverted number
  \xdef\B{}
  \xdef\E{}
  \aftergroup\B
  % the active character ~ is defined as help macro;
  % the argument is the collector macro
  \def~#1{%
    \gdef#1{}% initially the macro is empty
    \aftergroup#1%
  }%
  % the ten macros \a to \j form the result number
  ~\a~\b~\c~\d~\e~\f~\g~\h~\i~\j
  \aftergroup\E
}
% the active ~ is used as helper macro;
% first argument is the digit, the second argument is the collector macro
\def~#1#2{%
  \mathcode `#1  = "8000 % make digit active in math mode
  \lccode `~ = `#1 % trick for defining the active digit
  \lowercase{%
    \def~{%
      \xdef#2{#2#1}% the digit adds itself to its collector macro
    }%
  }%
}
~0\a~1\b~2\c~3\d~4\e~5\f~6\g~7\h~8\i~9\j
% Defining the minus character as switch for descending digits:
\mathcode `- = "8000 % minus sign active in math mode
\lccode `~ = `- % trick for defining the active minus
\lowercase{%
  % the minus sign redefines the wrapper macros \B and \E that
  % surround the result number. These macros now uses
  % primitives for right-to-left typesetting.
  \def~{%
    \xdef\B{\beginR}%
    \xdef\E{\endR}%
  }%
}

Reproducing
There are some online LaTeX compilers, a list can be found here.
I tried the first item on the list, LaTeX servlet on sciencesoft.at. It can be used without signing and it can also create permanent URLs:
source and result as image.

I do not have the LaTeX chops to assess this myself. I'll have to take your word for it. :)

@kojiro: There are some online compilers for LaTeX, see the updated answer for an example.

This is horrifying, Heiko.  +1! XD

Java : 262 points
Yeah, yeah I know, it's hopeless, but still..
class G{Object m(StringBuffer s,int o){for(int i=1;i<s.length();i++){int j=i-1,t=s.charAt(i),u=s.charAt(j);boolean c=o==0?t>u:t<u;for(;j>-1&c;){s.setCharAt(j+1,s.charAt(j));c=--j>-1;c=c?(o==0?t>s.charAt(j):t<s.charAt(j)):c;}s.setCharAt(++j,(char)t);}return s;}}

Analysis (marking):

Starting with 0. (score = 0)
262 characters total. (score =  0 + 262 = 262)
+10 - for using StringBuffer (I used it because it's shorter than StringBuilder) (score = 262 + 10 = 272)
-10 - for making the output flexible. I've considered 0 = descending, 1 = ascending, so back to 262!

Usage:
When you try and compile the G.java file in command prompt, it generates a hell lot of problems (errors). So, the solution?

Compile the G.java class in an IDE like NetBeans or Eclipse or even BlueJ. It should compile without any trouble (ignore any warnings).

Then, this class should be called by a main() method from any other class (or even that class itself). I'm putting it another class, so I'm not adding it to my character count. Compile the other class in a similar manner (without using cmd). Now the main() method in the other class should be something like:
public static void main(String[]a){
    System.out.println(new G().m(new StringBuffer(a[0]),1));
    //for descending, put '0' instead of '1'
}

Excluding unnecessary spaces, comments and line breaks, it's another 93 characters. I'm not adding it to my character because this is just for demonstration through console.
Output:
ZERO i.e. 0 is considered. Supposing the external class is Helper.java, and it has been successfully compiled, a few examples through console are:

INPUT : C:...>java Helper 008321
OUTPUT:001238
INPUT : C:...>java Helper 79359105
OUTPUT:01355799

When changed to 0 i.e. descending...

INPUT : C:...>java Helper 008321
OUTPUT:832100
INPUT : C:...>java Helper 79359105
OUTPUT:99755310

NOTES:

I didn't explicitly declare any array in G.java. That is the core class.
I'm using insertion sort to sort the number digit-wise.
The number can be of of the maximum length - Integer.MAX_VALUE because that is the maximum size any array can hold (in Java).
This answer can be shortened (I believe) so please help me (improve my first answer).
Darn those great Gods who accidentally created such a lengthy yet great language like Java (and also who came up with code conventions)!

C - 65
r,t,i;s(n){for(;++i;)for(t=n;t;t/=10)r=t%10-i?r:10*r+i;return r;}

The astute observer will note that this sorting algorithm runs in O(n) time on the number of digits in n.
The pragmatic observer will note that this sorting algorithm runs in time proportional to the range of signed integers on the platform, that it mutates global state which must be re-initialized between runs, and that many other sacrifices have been made in favor of brevity.
The ungolfed version is not exactly equivalent, but it better conveys the actual algorithm involved.
int s(int n)
{
    int r = 0;
    int t;
    int i;
    for(i = 0; i < 10; i++)
    {
        for(t = n; t != 0; t /= 10)
        {
            if(t % 10 == i)
            {
                r = 10 * r + i;
            }
        }
    }
    return r;
}

Here's a test harness for the function:
#include <stdio.h>
#include <stdlib.h>

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

Haskell - 96
96 characters, no arrays, no strings, no integer limit, can't reverse
d=(`divMod`10)
a&(0,0)=a
a&(y,z)=(z%d a)&d y
a%(y,z)|z>a=10*(a%d y)+z|1<3=100*y+10*z+a
s=(0&).d

Examples:
λ: s 52146729
12245679
λ: s 502010406072952146729521467295214672952146729
1111122222222224444455555666667777799999
λ: s 100
1

This one is insertion sort, performed directly on the integers themselves. This is similar to the other Haskell entry which is bubble sort, though I swear I was working on it before I saw that one.
Brief guide:

d divides a number into units and tens, i.e.: d 135 is the pair (13,5)
a%x is sorted insertion of digit a into the number x
a&x sorts x by inserting the units digit into a and recursing on the result and remainder
s x sorts x by kicking off the & recursion on 0 and x

The trick is that the second argument of % and & isn't x directly, but x divMod'd using d

Nice. I'd forgotten about using infix. I can maybe shave a couple of chars that way, but you have me beat. +1

J, 10 characters (+ 1 string) score = 20
s=./:~&.":

Usage:
   s 52146729
12245679

Works for all 32 bit numbers.
Explanation:
/:~ sort up &. under ": format. My previous version used an array as well, but they're costly so now I need to just use a string and sort the characters alphabetically. ": converts the number that is input into a string and /:~ sorts the digits into ascending order. Because the sort is done 'under' format, when the sort is finished, the string is converted back into a number. Adding the ability to reverse would probably cost more than it saves, so I didn't bother.
The argument could be made that since J, like APL and K, is an array-based language, the single input is an array of 1 item, but I chose not to take such a harsh view when calculating my score.
The 32-bit limit is imposed by J, rather than my program. Any higher and J switches the numbers to scientific notation. It's not clear from the question whether the 32 point penalty applies in this case, but even if both of the previous penalties apply (I don't think they should) the score goes up to 72 and still comfortably beats the vast majority of the other answers.

Can you provide an explanation? This looks like it's formatting the number as a string, splitting into an array, sorting the array, then reforming it as a string...aren't there penalties for the array & string?

@bazzargh I deliberately didn't declare a score when I submitted my answer for two reasons: 1) it's tagged [code-golf] so bonuses don't really make sense, and 2) it wasn't clear to me which would apply. I'll add an explanation.

What tag should I have used? It's code golf with penalties…

@kojiro - mouse over the code-golf tag it tells you - code-challenge.

Python 2.7: 174
import math
i=input()
d={n:0for n in xrange(10)}
for n in(i/10**c%10for c in xrange(1+math.log10(i))):d[n]+=1
print"".join(str(n)for n in xrange(10)for c in xrange(d[n]))

No arrays (iterators and a dictionary are used instead)
No multi-character strings (except output)
No artificial maximum number of digits
No reversing

It works by creating a dictionary mapping all 10 digits to 0. Then it iterates over the length of the number (log10(i)), extracting each digit ((i / (10 ** c)) % 10), and incrementing the counter for that digit in the dictionary. Finally it creates a string made by iterating over all 10 digits, and for each digit yielding one instance of the digit as a string.
I could change the last line to print"".join(d[n]*str(n)for n in xrange(10)) which would be 16 characters less, but would use multi-character strings.

i=int(input()) can be just i=input() as input() automatically evals the number.

@user80551: Yes, of course! Good call.

Python3.3 61 points
print(''.join(sorted(input())))

This program takes in the input as a string, which counts as a string because it is not changed to an integer immediately. +10
The string is sorted into an array +10
This array is joined together into a string +10
Note: The '' used to join the array's contents is not a multi character string, so +10 is not added to the score.
The program consists of 31 characters. +31
31+10+10+10 = 61 points

+1 although the data you process is never a number. (It's not the only answer like that, I know.)

It's not explicitly stated, although it is said that. My original code was print(int(''.join(sorted(input())))), but the cast to integer only added points and did not make the code follow the rules any closer. I didn't really stay true to the challenge I suppose. But he does state that the input can be a string, and the output can be a string (for print statements), and says nothing about in between :]

C# - 179
using System.Linq;class S{void Main(string[] a){Console.Write(string.Concat(string.Concat(a).Replace("-","").OrderBy(o=>a[0].Contains('-')?-o:o)));}}

Un-golfed
using System.Linq;

class S
{
    void Main(string[] a)
    {
        Console.Write(string.Concat(
            string.Concat(a)
                .Replace("-", "")
                .OrderBy(o => a[0].Contains('-') ? -o : o )));
    }
}

Test
Normal:
app.exe 52313698

Reversed:
app.exe 52313698-

Points:
(I hope I understood the point system properly - feel free to correct)

Chars: 149
Strings: 10+10
Arrays: +20
Order: -10
Total: 149+10+20-10 = 179

C# with LINQPAD - 123
void Main(string[] a){Console.Write(string.Concat(string.Concat(a).Replace("-","").OrderBy(o=>a[0].Contains('-')?-o:o)));}

Test
Normal:
lprun.exe sorta.linq 52313698

Reversed:
lprun.exe sorta.linq 52313698-

Points:

Chars: 122
Strings: 10+10
Arrays: +20
Order: -10
Total: 122+10+20-10 = 152

C (up to C90) or C++, 78 66 points
The function so sort an integer is called s.
s(i){t=10,a=i?s(i/t):0,b=i%t,c=a%t;return c>b?t*s(a-c+b)+c:t*a+b;}

Scoring:

66 Characters (+66)
0 arrays (+0)
0 strings (+0)
Range defined by machine (size of int) (+0)
Only one sorting direction (-0)

Old version (78 points, works also with C++ and more modern C versions)
int s(int i){int t=10,a=i?s(i/t):0,b=i%t,c=a%t;return c>b?t*s(a-c+b)+c:t*a+b;}

Java 1469
A  string and array free solution in Java. 1437 characters + 32 because it only takes up to Long.MAX_VALUE as input. By using Double I could go to over 300 digits instead but that would be too tedious to implement. Anything bigger than that would need BigInteger and AFAIK that uses arrays internally. If you use less than 19 digits for the input the output will have leading zeroes. Negative input will give all zeroes and anything not a number will cause an exception.
For the sort I used the easiest I could think of so it's pretty inefficient. (should be O(n*n))
input:  9212458743185751943
output: 1112233444555778899

I know this doesn't really compare to the solutions in other languages but I feel this at least is the shortest I can get it in Java. (if anyone knows how to get this even shorter feel free to edit/comment)
class D
{
    long c,d,e,f,g,h,k,l,m,n,o,p,q,r,s,t,u,v,w;
    long x;

    public D(Long a)
    {
        x = a;
        c = g();
        d = g();
        e = g();
        f = g();
        g = g();
        h = g();
        k = g();
        l = g();
        m = g();
        n = g();
        o = g();
        p = g();
        q = g();
        r = g();
        s = g();
        t = g();
        u = g();
        v = g();
        w = g();
        int i=0;
        while(i++ < 19) s();
        System.out.printf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",c,d,e,f,g,h,k,l,m,n,o,p,q,r,s,t,u,v,w);
    }

    long g()
    {
        if( x <= 0 ) return 0;
        long b = x % 10;
        x = x / 10;
        return b;
    }

    void s()
    {
        if(c > d) {c += d; d = c - d; c -= d;}
        if(d > e) {d += e; e = d - e; d -= e;}
        if(e > f) {e += f; f = e - f; e -= f;}
        if(f > g) {f += g; g = f - g; f -= g;}
        if(g > h) {g += h; h = g - h; g -= h;}
        if(h > k) {h += k; k = h - k; h -= k;}
        if(k > l) {k += l; l = k - l; k -= l;}
        if(l > m) {l += m; m = l - m; l -= m;}
        if(m > n) {m += n; n = m - n; m -= n;}
        if(n > o) {n += o; o = n - o; n -= o;}
        if(o > p) {o += p; p = o - p; o -= p;}
        if(p > q) {p += q; q = p - q; p -= q;}
        if(q > r) {q += r; r = q - r; q -= r;}
        if(r > s) {r += s; s = r - s; r -= s;}
        if(s > t) {s += t; t = s - t; s -= t;}
        if(t > u) {t += u; u = t - u; t -= u;}
        if(u > v) {u += v; v = u - v; u -= v;}
        if(v > w) {v += w; w = v - w; v -= w;}
    }

    public static void main(String[] y)
    {
        D d = new D(Long.parseLong(y[0]));
    }
}

Python lambda function (reversible), 69
lambda n,d:''.join(sorted(n,reverse=d))

39 chars (+39)
Two multi-char strings: n(input) and ''.join(...) (+20)
One list: sorted(...) (+20)
Can reverse direction depending on the parameter d (-10)

Python lambda function (non-reversible), 67
lambda n:''.join(sorted(n))

EDIT: Input should be a string. I am considering the penalty of using that string directly.

I clarified the game a little above, particularly about using built-in sorts. A generator might be OK, but the Python help (for 2 and 3 both) clearly states raw_input([prompt]) -> string, so sorted(raw_input()) is +10. Also sorted -> new sorted list, so +20. Then, S.join -> string, so +10 again. Slice notation also implies strings, so +10 (anything else supporting slice notation would arguably be +20). So I calculate 73 and 108, respectively.

@kojiro Please clarify: Can I use a function that takes the string of the number as an argument(I accept the penalty). Can I use a function that prints instead of returning?

Please see note 4. (Although on a specific note, I'm curious why you didn't use a lambda here.)

@kojiro My main issue about print/return is that print is shorter and doesn't require wrappers. I didn't know that you would allow lambda functions. Kind of facepalmed when I read that. Is it correct now?

''.join(sorted(str(n))) .could you please tell me why this won't be considered as an answer?I'm kinda new

Dear @stevieG, your code is legit, but you are sorting a string (rules of this game penalize the use of strings and built-in sorting functions). However your code (including penalities) will take more points than mine: this is why I complained to the author. In fact penalities are so soft that (ironically) they incentivate the use of builtin functions and strings.

@AntonioRagagnin: ohhkk,thanks buddy :)

@AntonioRagagnin this game penalize the use of strings and built-in sorting functions) --Nowhere does it say that sorting functions are penalized. The penalty is because the particular sorting function returns a list. The use of that list is penalized. If python had a sorting generator function, there would be no such penalty.

Dear @user80551, I may be wrong, but isn't sorted a built-in sorting function?

@AntonioRagagnin Yes it is, but the penalty is for the list it returns, not for using the function itself.

I don't see anything about sorting functions in the question, so... (I'm gonna remove the answer if it bends or breaks the rules, let me know)
JavaScript 56 96
function s(){alert(+prompt().split('').sort().join(''))}

JavaScript 69 109 (reversable)
function s(r){x=prompt().split('').sort();x=r?x.reverse():x;alert(+x.join(''))}

Can be golfed down a bit using EcmaScript 6 arrow functions:
ES6 50 90
s=()=>{alert(+prompt().split('').sort().join(''))}

ES6 63 103 (reversable) (73-10)
s=(r)=>{x=prompt().split('').sort();x=r?x.reverse():x;alert(+x.join(''))}

prompt returns a string (that you don't immediately convert into an integer): +10; split returns an array: +20; sort does an in-place sort (so it's still the same array); join returns a new string, +10. Total: 96.

How the rules are written made me understand that only literals were counted. Updating the score, anyway.

AWK - 101
The 'x' file:
BEGIN{n=ARGV[1]
r=ARGV[2]
for(d=r;d<10;d++)for(p=1;p<=length(n);p++){D=r?d:9-d
if(D==substr(n,p,1))printf D}print}

The run:
$ awk -f x 52146729
97654221
$ awk -f x 52146729 0
97654221
$ awk -f x 52146729 1
12245679
$ awk -f x 1234567890123456789012345678901234567890
9999888877776666555544443333222211110000
$ awk -f x 1234567890123456789012345678901234567890 1
111122223333444455556666777788889999

The only array used is ARGV and this is no help in sorting, it only is access to the commandline parameters and these values are in non-array variables where actually needed for calculations. I think this won't count against this solution. The following calculation does not take the ARGV-array into account:
111 (chars) - 10 (can do reverse)

Sometimes the only sane answer to an insane world is insanity. – Fox Mulder

:-D Indeed! :-D

SED 67 Chars (score either 67 or 107)
s/$/;0123456789/;:a;s/\(.\)\(.\)\(.*;.*\2.*\1\)/\2\1\3/;ta;s/;.*//;

This uses a bubble sort for brevity.
Score would be 107 if each regular expression pattern and replacement count as a string (i.e. 67 + (10 * 4))
Number of digits handled limited by memory (and probably patience)

Common Lisp - 126
(defun s(n p)(labels((a(n)(if(= 0 n)()(cons(mod n 10)(a (floor n 10)))))(b(a)(if(null a)0(+(car a)(* 10(b(cdr a)))))))(b(sort(a n) p))))

The ungolfified (stylistically as well as lexically, but functionally identical) version:
(defun sorta (n p)
  (labels ((digits (n)
             (unless (zerop n)
               (multiple-value-bind (quotient remainder)
                   (truncate n 10)
                 (cons remainder (digits quotient)))))
           (digit-cat (digits)
             (if (null digits)
                 0
               (+ (car digits)
                  (* 10 (digit-cat (cdr digits)))))))
    (digit-cat (sort (digits n) p))))

The digits of a negative number are treated as having negative value, and digits are sorted least-significant-first (i.e., little-endian). Examples:
CL-USER> (sorta 1234 #'<)
=> 4321
CL-USER> (sorta 12344321 #'<)
=> 44332211
CL-USER> (sorta 12344321 #'>)
=> 11223344
CL-USER> (sorta -12344321 #'>)
=> -44332211
CL-USER> (sorta 0 #'>)
=> 0
CL-USER> (sorta 8675309 #'<)
=> 9876530

There are 136 characters in the golfed version, including whitespace. It uses no strings and no arrays, and handles arbitrary-precision integers, including negative integers. The sorting is parameterized on a binary predicate which defines a total ordering on the integers in [-9, 9], including but not limited to < and >:
CL-USER> (sorta 3546219870 (lambda (a b)
                             (cond ((and (evenp a)
                                         (oddp b))
                                    t)
                                   ((and (evenp b)
                                         (oddp a))
                                    nil)
                                   (t
                                    (< a b)))))
=> 9753186420

This gives a score of 126.

JavaScript 416 / 185
No Arrays, no Strings, no arbitrary length constraint...
But sorting up/down would have used up more than 10 characters ^^ But I found the idea of counting digits and printing them interesting - maybe someone can use this idea in GolfScript and win the prize ;-)
var x=window.prompt(),y=0,z=0,a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0;
do
{
    z=x%10;
    x=(x-z)/10;
    if(!z)a++;
    if(z==1)b++;
    if(z==2)c++;
    if(z==3)d++;
    if(z==4)e++;
    if(z==5)f++;
    if(z==6)g++;
    if(z==7)h++;
    if(z==8)i++;
    if(z==9)j++;
}while(x);

while(a--)y=y*10;
while(b--)y=y*10+1;
while(c--)y=y*10+2;
while(d--)y=y*10+3;
while(e--)y=y*10+4;
while(f--)y=y*10+5;
while(g--)y=y*10+6;
while(h--)y=y*10+7;
while(i--)y=y*10+8;
while(j--)y=y*10+9;

alert(y);

The same code shorter, using eval: (but that would likely be considered using strings...)
var i = window.prompt(),o=0,i0=0,i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0;
do
{
    eval("i"+i%10+"++");
    i = ~~(i/10);
} while (i > 0)

for(var j=0;j<10;j++) while (eval("i"+j+"--")>0) o = o*10+j;

alert(o);

You can shorten the longer version by 30 bytes by using 1-character names instead of iN.

@GlennRanders-Pehrson Thank you :-)

Why all the semicolons? And who cares about indenting?

C (222)
static int a[10],r=1;o(n,c){while(n--)printf("%""i",c);}p(){int n;for(n=r<0?9:0;n>=0&&n<10;n+=r)o(a[n],n);}main(int _,char**v){char*s=v[1];if(*s=='-'){r=-1;++s;}do++a[*s-'0'];while(*++s);p();}

Points:

192 (192 Chars)
40 (2 Arrays: argv(v) and a)
0 (no multi char strings)
0 (it's not limited to n digits)
-10 (sorts reverse if the number (argv[1]) is negative)
= 222 Points

Flags needed to get rid of the 1000 compiler warnings:
gcc -Wno-implicit-function-declaration -Wno-return-type -Wno-implicit-int -Wno-char-subscripts -o count2 counta2.c
"Better" readable:
static int a[10],r=1;
o(n,c){while(n--)printf("%""i",c);}
p(){int n;for(n=r<0?9:0;n>=0&&n<10;n+=r)o(a[n],n);}
main(int _,char**v){char*s=v[1];if(*s=='-'){r=-1;++s;}do++a[*s-'0'];while(*++s);p();}

Somewhat ungolfed:
static int a[10],r=1;
o(n,c){
    while(n--) printf("%""i",c);
}
p(){
    int n;
    for(n=r<0?9:0;n>=0&&n<10;n+=r) o(a[n],n);
}
main(int _,char**v){
    char*s=v[1];
    if(*s=='-'){
        r=-1;
        ++s;
    }
    do ++a[*s-'0']; while(*++s);
    p();
}

Why use "%""i" instead of "%i"? They compile to the same thing, so you're just wasting two chars.

@Gabe Yes I'm wasting 2 Chars but "%i" is a "multi char string" (10 Points) where "%""i" is not ... at least that's what people argumented here...

Is there a reason I dont see this solution already?
Ruby
pry(main)> 52146729.to_s.split("").sort.join.to_i
=> 12245679

Am not sure how to score this. The split would generate an array, but beyond that not sure.. 38 chars + 2x20 for arrays? Or should it include all arrays that sort might create internally?

VBScript - 76 (96?)
x = "7892347684578892348025023389054859034234"

for i=0 to 9:n=n&string(len(x)-len(replace(x,i,"")),""&i):next:x=n

' x -> 00002222233333344444455556777888888889999

66 character + 10 for the use of string n
(Don't know if the use of the replace function and string function that returns n amount of character x is counted as an extra string).
It counts the amount of a certain digit by comparing the length of the original string with the same string with the certain digit replaced. Then it attaches that amount of digits to n.

Python 3 sleepsort (168)
With absolutely no list or loop, only generators.
import math, threading
n=input()
if any(threading.Timer(x,lambda x:print(x,end='',flush=1),(x,)).start()for x in(n//10**i%10for i in range(math.log10(n)//1+1))):pass

could probably be improved.

Racket 97
97 points (87 +20 for two strings, -10 for sorting, no arrays)
(define(s n <)(string->number(list->string(sort(string->list(number->string n))<))))

This uses lists of chars so you need to give it a char comparison function like char<? or char>?. I feel this also passes as ungolfed since it's not much to do than add spaces and increase variable names. My old version is perhaps more honorable :)
Old version without strings:
110 points (120 bytes (utf-8) - 10 for allowing for changing sort order. It uses no strings and no arrays)
(define(S d <)(foldl(λ(x a)(+(* a 10)x))0(sort(let L((l'())(
d d))(if(= d 0)l(L(cons(modulo d 10)l)(quotient d 10))))<)))

Ungolfed:
(define (number-digit-sort number <)
  (foldl (λ (x a) (+ (* a 10) x))
         0
         (sort (let loop ((acc '()) (number number))
                 (if (= number 0)
                     acc
                     (loop (cons (modulo number 10) acc)
                           (quotient number 10))))
               <)))

I tested it with the 100,000th fibonacci number:
(number-digit-sort (fibonacci 100000) <)
;==> 1111... basically it's the digits:
; 1 2135 times
; 2 2149 times
; 3 2096 times
; 4 2023 times
; 5 2053 times
; 6 2051 times
; 7 2034 times
; 8 2131 times
; 9 2118 times

And the same in opposite order:
(number-digit-sort (fibonacci 100000) >)
; ==> 999... and the digest is
; 9 2118 times
; 8 2131 times
; 7 2034 times
; 6 2051 times
; 5 2053 times
; 4 2023 times
; 3 2096 times
; 2 2149 times
; 1 2135 times
; 0 2109 times