text:
Tips for golfing in PHP
What general tips do you have for golfing in PHP? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PHP (e.g. "remove comments" is not an answer). Please post one tip per answer.

Wait, am I doing it right?... Anyway, I'm really curious about this one. PHP is used by many people and golfers, but I almost have no idea how to golf a PHP code.

Use short tags  It can save a few bytes.

Understand how variables and whitespace interact with PHP's language constructs.
In my (admittedly short) time golfing, I have found that PHP's language constructs (e.g. echo, return, for, while, etc) behave in a less-than-intuitive way when interacting with variables and whitespace.
echo$v;, for example, is perfectly valid, as are return$v; and other similar constructs. These small reductions in whitespace can lead to a significant cumulative decrease in length.
Keep in mind, though, that variables before language constructs require a space after, as in the following example:
foreach($a AS$b){}

Because AS is a language construct, a space is not required before the variable $b, but if one were to omit the space before it, resulting in $aAS, this would be parsed as a variable name and lead to a syntax error.

foreach($a[1]as$b) needs no white space. This is not about language constructs and variables, but about spaces between word-characters of different words.

Another instance where you need whitespace is in string concatenation. For instance, echo $a+5." text" will not work because PHP thinks the . is a decimal point for the 5. To make it work, you would need to add a space like this: echo $a+5 ." text"

@BasicSunset That statement can be written as echo$a+5," text";. The echo construct allows you to pass multiple parameters. where one would have to write echo"result: ".($a+5)."!";, you can write echo"result: ",$a+5,"!";. In fact, passing multiple parameters to an echo is a micro-optimization, since the code will run a tiny bit faster (since you don't concatenate the output, but send it separately). For challenges about writting the fastest code, this may help a tiny tiny tiny bit.

@IsmaelMiguel It works with echo, but not with print (which you need if you put it inside an expression: echo is a pure construct with no return value while print can act as a function: it requires no parentheses, but it always returns int(1).

@Titus I didn't said anything about print.

Use strings wisely.
This answer is two-fold. The first part is that when declaring strings, you can utilize PHP's implicit conversion of unknown constants to strings to save space, e.g:
@$s=string;

The @ is necessary to override the warnings this will produce. Overall, you end up with a one-character reduction.
is that sometimes, it may be space effective to set a variable to the name of an often used function. Normally, you might have:
preg_match(..);preg_match(..);

But when golfing, this can be shortened easily to:
@$p=preg_match;$p(..);$p(..);

With only two instances of "preg_match", you're only saving a single character, but the more you use a function, the more space you will save.

@ is not needed in codegolf; notices and warnings (including E_DEPRECATED) are acceptable

@Titus But in PHP, the warnings would output to the standard file output, so they are needed.

@Titus I believe you can suppress them in the php.ini file

Does the string tip work for empty strings? e.g. @$k=;

Starting from PHP 8, an undefined constant causes Error to be thrown.

You don't always need to write out conditional checks. For example, some frameworks use this at the top of their files to block access:
<?php defined('BASE_PATH')||die('not allowed');

Or in normal functions
$value && run_this();

instead of
if($value) { run_this(); }

It works also in JS

Use short array syntax
Since PHP 5.4, arrays can be declared using square brackets (just like JavaScript) instead of the array() function:
$arr=['foo','bar','baz'];
// instead of
$arr=array('foo','bar','baz');

It will save five bytes.

But It may cost bytes if you have "holes" in an associative array:
$arr=array(,1,,3,,5);
// is one byte shorter than
$arr=[1=>1,3=>3,5=>5];

the disadvantage hits a little later if you can fill the holes with "empty" values:
// saves two bytes over array()
$arr=[0,1,0,3,0,5];
// but for a larger array
$arr=[0,1,0,3,0,5,0,7,0,9,0,11];
// costs two byte more than
$arr=array(,1,,3,,5,,7,,9,,11);

PHP 7.1 also introduced short list assignment: [,$a,$b,$c]=$argv;.

Use ${0}, ${1}, ${2}, ... instead of $a[0], $a[1], $a[2], ...
Unless you're performing an array manipulation, most references to an array index $a[$i] can be replaced with simply $$i. This is even true if the index is an integer, as integers are valid variable names in PHP (although literals will require brackets, e.g. ${0}).
Consider the following implementation of the Rabonowitz Wagon spigot:
3.<?for(;$g?$d=0|($a[$g]=$d*$g--/2+($a[$g]?:2)%$g*1e4)/$g--:238<<printf($e?'%04d':'',$e+$d/$g=1e4)^$e=$d%$g;);

This can be improved by 6 bytes, simply by replacing both array references $a[$g] with $$g instead:
3.<?for(;$g?$d=0|($$g=$d*$g--/2+($$g?:2)%$g*1e4)/$g--:238<<printf($e?'%04d':'',$e+$d/$g=1e4)^$e=$d%$g;);

I just saved 3 bytes with that: showcase.

Learn a large subset of the library functions.
PHP's library is pretty huge and provides a ton of convenient functions that can greatly shorten various tasks.  You could just search every time you try to do something, but beyond wasting time you might not find anything that matches your particular search.  The best way is just to get familiar with the library and memorize function names and what they do.

That's a lot of memorization, especially given the rather inconsistent naming of a whole lot of functions ;-)

@Joey Agreed. Akin to memorizing the Java library, except that would be arguably less useful since it's more verbose.

I find that the most important functions for the challenges I've come across so far here are the string manipulation and array manipulation functions. Creative use of those can really cut down the code.

Creativity required - there's a bunch of stuff that is very niche, and some stuff that would be useful + should exist but doesn't. Like getting an individual char of a string.

Running functions inside strings.
Try this:
$a='strlen';
echo "This text has {$a('15')} chars";

Or try this:
//only php>=5.3
$if=function($c,$t,$f){return$c?$t:$f;};
echo <<<HEREDOCS
    Heredocs can{$if(true,' be','not be')} used too and can{$if(<<<BE
{$if(true,1,0)}
BE
,'','not')} be nested
HEREDOCS;
//Expected output: Heredocs can be used too and can be nested

This only works with strings using "" and heredocs (DON'T make confusion with nowdocs).
Using nested functions is only possible inside nested heredocs (or you will run into parse errors)!

you will run into parse errors I cant read it myself? How does the pesky Zend engine put this together

The next time I'm in a "PHP is a good programming language" argument, I'm going to use this as a counter-point. Wow.

@primo Is it that bad? :O

fun with typecasts

!!$foo will turn any truthy value to true (or 1 in output), falsy values (0, empty string, empty array) to false (or empty output)
This will rarely be needed in code golf, for in most cases where you need a boolean, there is an implicit cast anyway.

(int)$foo can be written as $foo|0 or foo^0, but may need parentheses.
For booleans and strings, $foo*1 or +$foo can be used to cast to int.

Unlike most other languages, PHP handles strings with numeric values as numbers. So if you have any string that contains a number you have to calculate with, just calculate.

The other way does not work: To multiply any number in a variable with 10, you could append a zero: *10 -> .0. But in this case, PHP will take the dot as decimal point and complain. (It´s different though if you have a variable amount of zeroes in a string.)

To turn an array into a string, use join instead of implode.
If you don´t need a delimiter, don´t use it: join($a) does the same as join('',$a)

Incrementing strings: The most amazing feature imo is that $s=a;$s++; produces $s=b;. This works with uppercase and lowercase characters. $s=Z;$s++; results in $s=AA;.
This also works with mixed case: aZ to bA, A1 to A2, A9 to B0 and z99Z to aa00A.
Decrement does not work on strings. (And it does not on NULL).
Back in PHP 3, $n="001";$n++; produced $n="002";. I am a little sad they removed that.

Whatever you golf: always have the operator precedence table at hand.

by any other name ... function aliases
use ...

join instead of implode
chop instead of rtrim (chop in PERL is different!)
die instead of exit
fputs instead of fwrite
is_int instead of is_integer or is_long
is_real instead of is_float or is_double
key_exists instead of array_key_exists
mysql instead of mysql_db_query

... to name the most important aliases.
Take a look at http://php.net/aliases for more.

Oh ... and did You know that die works with and without parameters? die(1) will exit the program with error code 1 (not completely sure on this; needs testing); die will exit with code 0, and die("Hello") will exit with code 0 after printing Hello.

looping through strings
can be done with 26 bytes or with 24 down to 18:
foreach(str_split($s)as$c)  # A) 26 - general
for($p=0;a&$c=$s[$p++];)    # B) 24 - general
for($p=0;$c=$s[$p++];)      # C) 22 - if $s has no `0` character
for(;a&$c=$s[$p++];)        # D) 20 - if $p is already NULL or 0 (does NOT work for false)
for(;$c=$s[$p++];)          # E) 18 - both C and D

for(;$o=ord($s[$p++]);)     # F) 23 - work on ASCII codes, if $s has no NULL byte and D
for(;~$c=$s[$p++];)         # G) 19 - if $s has no chr(207) and D

$a&$b does a bitwise AND on the (ascii codes of) the characters in $a and $b
and results in a string that has the same length as the shorter of $a and $b.

can you please add ord($s[$p++]) as alternative for(;$s+=ord($argv[++$i])%32?:die($s==100);); against for(;$c=$argv[++$i];)$s+=ord($c)%32;echo$s==100; in this question https://codegolf.stackexchange.com/questions/116933/bernardino-identifies-unaltered-dollar-words

Please add ~ for cases you are working only with digits

Note that PHP 7.2 yields warnings for the ~$c approach.

Use shorttags
In normal code, it's good practice to use <?php and ?>. However, this is not normal code - you are writing a code golf code. Instead of <?php, write <?. Instead of <?php echo, write <?=. Don't type ?> at end - it's completely optional. If you need ?> for some reason (for example to output text, and it's shorter somehow, or something, don't put a semicolon before it - it's not needed, as ?> implies semicolon.
Wrong (definitely too long):
<?php echo ucfirst(trim(fgets(STDIN)));?>s!

Correct:
<?=ucfirst(trim(fgets(STDIN)))?>s!

With the -r flag (which comes free), you don´t even any tags at all (and you´re not allowed to use any).

Use ternary operators
if(a==2){some code;}else{some other code;}

can be abbreviated to this:
(a==2?some code:some other code);

Shorter, huh?

“Conditional shorthands”? Better tell its real name, so those interested in more details can find it in the documentation: ternary operator.

Thanks, corrected. In informal use, I have heard it referred to mainly as 'conditional shorthands' or 'shorthand conditionals'.

The question asks for tips which are somewhat specific to PHP. This is one included in the tips for all languages.

The ternary operator has a weird behaviour in PHP, if you nest it. a?aa:ab?aba:abb:b evaluates to (a?aa:ab)?(aba):(abb) or something like that.

And starting with PHP 5.3, you can omit the second operator: $a?:$b is the same as $a?$a:$b.

@Titus isn't that just ||?

@Cyoce || casts to boolean in PHP.

a-2?some other code:some code. also for all languages.

And with php 7+ you have access to ?? to check if isset. Example $a??$a:$b will evaluate to isset($a)?$a:$b. It's called the Null Coalescing Operator

array_flip vs array_search
use

array_flip($array)[$value]

instead of

array_search($value,$array)

to save 1 Byte in arrays where the occurence of each value is unique

Combining for loops
Suppose you have code of the following form:
for($pre1; $cond1; $post1) for($pre2; $cond2; $post2) $code;

this can generally be re-rolled in the following form:
for($pre1; $cond2 • $post2 || $cond1 • $pre2 • $post1; ) $code;

where • represents a generic combining operator. This usually results in an byte count reduction, but will likely require some creativity. $cond2 will need to be written so that it fails the first time through. $post1 should also fail to execute the first time, although it may be easier to refactor beforehand so that $post1 is not present.
If you're working with three or more nested loops, you can also combine two first, and then combine that to another, and so on. I find that it has generally been easier to combine from the inside outwards.

As an example, consider the following solution to the H-carpet fractal (97 bytes):
for(;$i<$n=3**$argn;$i+=print"$s\n")for($s=H,$e=1;$e<$n;$e*=3)$s.=str_pad($i/$e%3&1?$s:'',$e).$s;

This can be reformulated in the following way:
for(;($i+=$e&&print"$s\n")<$n=3**$argn;)for($s=H,$e=1;$e<$n;$e*=3)$s.=str_pad($i/$e%3&1?$s:'',$e).$s;

$e&&print prevents print on first iteration, and also does not increment $i.
and finally (93 bytes):
for(;$H>$e*=3or$e=($i+=$e&&print"$s\n")<${$s=H}=3**$argn;)$s.=str_pad($i/$e%3&1?$s:'',$e).$s;

$H>$e*=3 will fail the first time as both variables are undefined.

line breaks
if the output requires line breaks, use a physical line break (1 byte) instead of "\n"
This also gives you a possible benefit to chose between single and double quotes.

Associative arrays can be merged with the + operator.
Instead of:
$merged = array_merge($a, $b);

Use:
$merged = $a + $b;

Note the + operator works with indexed arrays as well, but probably doesn't do what you want.

Indeed, frequently a good replacement, though not exactly the same: http://pastebin.com/seYeaP38

Ah yeah, dang it, I originally had the title "associative arrays ... " and then removed it. I'll clarify, thanks.

numeric arrays can also merged using +, as long as the indexes are distinct. If they are not, the values from the first array will be overwritten with those from the second one (just like array_merge). The difference: + does not reorder indexes.

some interesting facts on variable variables
I just had to share them (even before I verified that at least one of them helps golfing):

Use letters: $x=a;$$x=1;$x++;$$x=2;echo"$a,$b"; prints 1,2
but other arithmetic operations do not work with letters.
As primo mentioned earlier, you can use pure numbers as variable names:
$a=1;$$a=5;$a++;$$a=4;${++$a}=3;echo${1},${2},${3}; prints 543.
You can not only use [0-9a-zA-Z_] for variable names, but EVERY string:
$x="Hello!";$$x="Goodbye.";echo${"Hello!"}; prints Goodbye..
But: Everything but [a-zA-Z_][a-zA-Z_0-9]* as variable names requires braces for literal use.
With no variables defined, $$x=1 sets ${NULL}, which is the same as ${false} and ${""}.
$a=1;$$a=5; does not only set ${1}, but also ${true}.
one more, the weirdest one I´ve found so far: Try $a=[];$$a=3;echo${[]};. Yes, it prints 3!

The reason for most of this: variable names are always evaluated to strings.
(Thanks @Christoph for pointing out.)
So, whatever you get when you print or echo the expression, that´s what you get as variable name.

Variable names are converted to strings that explains the last three points on your list. [] converts to Array: ${[]} = 5;echo $Array; prints 5. I'm pretty sure you know that but it might not be obvious to everyone :)

@Jeff I fixed the typo. Thanks for noticing.

PCRE-Related (Regex)
Functions
If the pattern always matches the subject string (thanks to the comment by @Deadcode), instead of preg_replace, you can use preg_filter (1 byte shorter).
Patterns
Sometimes espace sequences are useful, like \d, \w, \W, \s or \S.
Examples
Filter non-alphabet characters:
preg_replace("/[^a-z]/i", "", $s);
preg_filter("/\W|\d/", "", $s); // 3 bytes shorter

Welcome to Code Golf, and nice tip!

@taRadvylfsriksushilani, thanks you very much! :)

Note that this only works if the regex always matches. If it doesn't, it may still be made to work by adding a | at the end of the regex to make it match even when it doesn't match, but then there's no byte savings anymore. Also I'm not sure why you're showing /[^a-z]/i for preg_replace but /\W|\d/ for preg_filter – they both use PCRE and anything that works in the latter should work in the former.

@Deadcode, thanks for the note, added in the answer. And about your last note: I know, but I just wanted to show these two tricks together can shorten the code by 3 characters.

avoid quotes where possible
PHP implicitly casts unknown words to literal strings.
$foo=foo; is the same as $foo='foo'; (assuming that foo is neither a key word or a defined constant): $foo=echo; does not work.
BUT: $p=str_pad; does; and $p(ab,3,c) evaluates to abc.
Using string literals without quotes will yield a Notice for Use of undefined constant; but that won´t show if you use the default value for error_reporting (CLI parameter -n).

I just noticed: This answer is a somewhat extended/updated duplicate of http://codegolf.stackexchange.com/a/2916/55735.

Note: PHP before 7.2 yielded Notices (which you can opress with the -n flag); 7.2 yields Warnings; later versions will throw Errors!

array_merge vs array_push
array_push($a,...$b);

is one byte shorter than
$a=array_merge($a,$b);

Does not work the same with Associative arrays
variable-arg-list PHP >5.6

This is an older tip now, but don't miss out on $a=[...$a,...$b] too!

Use boolean operators instead of strtoupper() and strtolower()
If you're working exclusively with strings consisting of alphabet characters, you can use boolean operators to change them to uppercase or lowercase with fewer keystrokes than PHP's built-in functions.
Example:
// Convert lowercase to uppercase
$s = "g";
echo strtoupper($s);  // Outputs 'G', uses 20 characters
echo~" "&$s;          // Outputs 'G', uses 12 characters

// Convert uppercase to lowercase
$s = "G";
echo strtolower($s);  // Outputs 'g', uses 20 characters
echo$s^" ";           // Outputs 'g', uses 11 characters

// Switch case of each character
$s = "Gg";
echo$s^"  ";          // Outputs 'gG', uses 12 characters

Things are a little trickier for strings of arbitrary length, but the & and ^ operators will truncate the result to the length of the shorter input string. So for example, if $W is a string of spaces at least as long as any input $s, then ~$W&$s is equivalent to strtoupper($s), and $s|$W^$s is equivalent to strtolower($s) (whereas $s|$W by itself will produce a string with additional spaces unless $s and $W are of equal length).

Arrow functions in PHP 7.4
PHP 7.4 is on RC2 version now and hopefully will be released in about 2 months. List of new features are here (this page can actually be updated when 7.4 is released). In 7.4, finally PHP has got the arrow functions, so not only function answers can be shorter now, but also passing closures to other functions can be a lot shorter too. Here are a few examples:
Return input + 1:
Anonymous function (closure) - 25 bytes -
Try it online!
function($n){return$n+1;}

Arrow function - 12 bytes -
Try it online!
fn($n)=>$n+1

Multiply items of first input (array of ints) by second input (int):
Anonymous function (closure) - 72 bytes -
Try it online!
function($a,$n){return array_map(function($b)use($n){return$b*$n;},$a);}

Arrow function - 38 bytes -
Try it online!
fn($a,$n)=>array_map(fn($b)=>$b*$n,$a)

Did you notice that $n is accessible in the inner function without a use $n statement? Yeah that is one of the arrow function features.

As a side note, I could not get arrow functions to work recursively (call the same arrow function inside itself), because we cannot give them a name and storing them as a closure in a variable like $f doesn't make $f accessible withing itself (sad). So this example doesn't work and using $f in first line causes a fatal error:
$f=fn($n)=>$n?$f($n-1):0;
$f(5); // Causes error: "PHP Notice: Undefined variable: f" + "PHP Fatal error: Uncaught Error: Function name must be a string"

But calling an arrow function withing a different arrow function works:
$f1=fn($n)=>$n+1;
$f2=fn($n)=>$f1($n-1);
$f1(2) // Returns 3
$f2(2) // Returns 2

What if instead of $f=fn($n)=>$n?$f($n-1):0; you do $f=$F=fn($n)=>$n?$F($n-1):0;? Would that work? And then you call $(5) as usual.

@IsmaelMiguel it still seems to throw same error. You can actually try on http://tio.run#php yourself as Dennis has updated its PHP to 7.4 RC2 a while back.

Can't get it to work. Seems that only variables defined before are available.

Regarding file I/O:
Linking to another related question, the answers to which fit here.

Directly dereference arrays returned from functions.
E.g., instead of this:
$a = foo();
echo $a[$n];

You can do:
echo foo()[$n];

This works with methods too:
echo $obj->foo()[$n];

You can also directly dereference array declarations:
echo [1, 2, 3, 4, 5][$n];

Use negative indexes to reference the end of a string
If you need the last character in a string, you can use the array reference method, and provide a negative index:
$lastChar = $string[-1];

This also works for functions like substr():
$lastFour = substr($string, -4);

Added as of PHP 7.1.

Use end() instead of array_pop()
The end() function doesn't just move the internal pointer to the end of the array, it also returns the last value. Note of course that it doesn't remove that value, so if you don't care what the array contains afterwards, you can use it instead of array_pop().

double array_flip vs in_array vs array_unique
in this special case a double array_flip saves 10 Bytes
($f=array_flip)($k=$f($c))) remove all double values in the array
and I have dropped this $c=[], , |in_array($o,$c) and replace array_keys($c) with $k
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)
$x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo strtr($x,($f=array_flip)($k=$f($c)))==$y # boolean replacement string 1 equal to string 2
    ?join($k)." ".join($c) # output for true cases
:0; #Output false cases

Online Version
against
for($c=[],[,$x,$y]=$argv;a&$o=$y[$i];$i++)
  $x[$i]==$o|in_array($o,$c)?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo strtr($x,$c)==$y # boolean replacement string 1 equal to string 2
  ?join(array_keys($c))." ".join($c) # output for true cases
  :0; #Output false cases

Online version
against array_unique it saves 2 Bytes
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)
  $x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo strtr($x,array_unique($c))==$y # boolean replacement string 1 equal to string 2
  ?join(array_keys($c))." ".join($c) # output for true cases
  :0; #Output false cases

Online Version
After finding a bug in this program and replacement $x[$i]==$o?:$c[$x[$i]]=$o to ($p=$x[$i])==$o?:$k[$c[$p]=$o]=$p the double array_flip was not necessary longer

associative safe array_unique. Yay!

@Titus I have add your suggestion

Return two copies of an expression
If you want to get two copies of the result of an expression, you can use this:
$v.$v=expr

But it won't be shorter than the more straightforward ($v=expr).$v if you need to append more things to the result.
For 4 copies:
$v.$v.=$v=expr

You cannot use it to get 3 copies.

intersecting strings
Have you ever used
join("DELIMITER",str_split($s)) (31 bytes) or even
preg_replace(".","DELIMITER",$s) (32 bytes)
?
There´s a builtin for that:
Try chunk_split($s,1,"DELIMITER") (29 bytes).

If you omit the third parameter, chunk_split will use \r\n;  that can save you 7 or 8 bytes.
But beware: chunk_split also appends the delimiter to the string,
so you may not get exactly what you want.
(If you don´t provide the chunk length, it will use 76. Rather unusual for code golf, but who knows.)

Maybe you should add an example in combination with strtr I love this idea.

Removing characters in a string
join(explode(" ",$string));

saves 1 character compared to
str_replace(" ","",$string);

Note that this works for all (nonempty) strings, not just characters.

@CalculatorFeline Why should it not work for empty strings? It make no sense or this case.

Well, the first version doesn't work with "" and it's not very useful anyway.

@CalculatorFeline Could you explain why it should not work? Try it online!

I meant " "="". Try it online!

@CalculatorFeline And for this case a zero byte solution is much better. It make no sense to do this in that way.

Your join example is missing a ). And strtr($string,[" "=>""]) is even shorter.

str_repeat
In some cases you have a input of characters and you should output them repeated with an input greater zero for each characters.
for(;--$z?:($c=$argn[$i++]).$z=$argn[$i++];)echo$c;

(52 bytes) is shorter than
for(;~$c=$argn[$i++];)echo str_repeat($c,$argn[$i++]);

or
for(;~$c=$argn[$i++];)echo str_pad($c,$argn[$i++],$c);

(54 bytes each)
How it works for example input a1b2c1
$z is not set (implicit NULL), so --$z does nothing and is falsy;
$c="a", $z="1" and $i=2 -> $c.$z="a1" is truthy -> output "a"
--$z=0; so we set $c="b", $z="2" (and $i=4) -> $c.$z="b2" is truthy -> output "ab"
--$z=1 -> output "abb"
--$z=0; so we set $c="c" and $z=1 $c.$z="c1" is true output "abbc"
--$z=0 so $c="" and $z="" -> $c.$z="" is falsy -> loop breaks

unset() vs INF
In a case search for a minimum in an array you can use instead of
unset($var[$k]);

$var[$k]=INF;

to save 3 Bytes

use deprecated functions
If you can use POSIX instead of PERL regex without wasting more than 5 bytes on the expression, use ereg or eregi instead of preg_match, split or spliti instead of preg_split.
split Can also be used as a synonym for explode for most delimiters.
These functions are marked deprecated and will throw E_DEPRECATED notices, but (cannot find the source now) I think I have read that warnings and notices are ok.

Watch out! These were removed in PHP 7.0.

Use short append syntax to add elements to the end of an array.
Instead of keeping track of the number of elements:
$array[++$i] = $value;

Or using the explicit push function:
array_push($array, $value);

You can use the implicit push feature:
$array[] = $value;

With a rare exception: when you need to append more than 3 elements, array_push($array, $value, $value, $value, $value); may be shorter;

Heh yeah, also note, if $value is itself an array, it's probably not going to do what you want.

JSON encode static array definitions
JSON encoding is one byte shorter per element than native PHP encoding for associative arrays. Of course, then you have to quote the resulting string (an additional two chars) and call json_decode() on that string (an additional 13 chars.) So, if you have a static associative array with more than 15 elements, try JSON encoding it. Note this probably won't work if you can use the "unquoted string literals" trick in your PHP array definition.
Instead of:
$array = [...];

Use:
$array = json_decode('...');

I think explode is also worth a shot.

Switches base on arrays or strings
A little collection which can save Bytes for different conditions
Switch a function through an array

<?=(bc.[sub,add,mul,pow][($x=$argn)&3])($x,$x);

Make different Math operations

<?=[0,($x=$argn)+$x,$x*$x,$x**$x][$x&3];

Ternary Operator to switch a function

echo(strto.(rand()&1?low:upp).er)($c);

Using the Keys in an array as conditions

echo[ctype_alpha($s=dechex($argn))=>"Only letters",ctype_digit($s)=>"Only numbers",Mix][1];

special on strings but only not in all cases you must use a function and trim will do nothing
($bool?trim:strtolower)($string)

character switch

"char"[$x%4]

character only in zero cases

"c"[$x%2]

I didn't see it listed so when using a list and explode you can use a number as the delimiter ( assuming its not in the string of course ). This lets you get rid of the quotes.
If there is backslash before the delimiter then it has to be 8 or 9 so it doesn't get confused with octal ( such as \0 )
So instead of:
explode(",", "one,two,buckle,my,shoe")

You can do this
explode(1, "one1two1buckle1my1shoe")

Saving 2 bytes for the quotes.
As I mentioned for backslashes
explode(",", "/ \,| .. |,\ /");

Use 8 or 9
explode(8, "/ \8| .. |8\ /");  // so you get \8 instead of \0 etc..

seek potential in combining several expressions to one
It´s easy to see that A?B:C; is shorter than if(A)B;else C;
A&&B is shorter than if(A)B; and A||B; is shorter than if(!A)B;
But how can if(A){B;C;}else{D;E;} be golfed?
Assume that B returns something truthy and D something falsy:
if(A){B; C;}else{B; C;}  # 21 bytes
A?    B&&C  :    B||C;   # 12 bytes

another one:
if(A){$b=123;$c="hello";} # 25 bytes
A&&$b=123+!$c="hello":    # 22 bytes
A&&$c="hello".!$b=123;    # also 22 bytes

$c="hello is truthy, so !$c is false. + casts to int; so we add 0 to 123.
$b=123 is truthy, so !$b is false. . casts to string, and that´s empty for false.
I even had a case today where appending digits to the string didn´t make a difference.
(See line 5 of the breakdown.)
more examples:
for(;;$a++,print$x);
for(;;$a+=print$x);

print always returns true, so its return value can be added to $a instead of incrementing $a separately.
$a=1,$b=0
$a=!$b=0

if(X){$a=123;$b=0;}
X&&$a=123+$b=0;     # useful if you need $b to be and int (for printing)
X&&$b=!$a=123;

if(X){$a=123;$b=1;}
X&&$b=!!$a=123;
X&&$a=123*$b=1;

advanced: combining nested loops
takes a new level to combining expressions. There is no general solution or approach; and it doesn´t always make the code shorter. Good chances are when the outer loop has no body except the inner loop; imagine shifting through a 2D array or sorting one.
Try
for($a=1;$a<20;$a+=print"\n")for($b=$a;$b++<20;)echo$a*$b,"\t";

61 bytes (counting the control characters as one each)
that loop $a from 1 to 19, $b from $a+1 to 20
and print the products, breaking the line when $a increments.
Ok, one simple two-byte saving is
for($a=1;20>$b=$a;$a+=print"\n")for(;$b++<20;)echo$a*$b,"\t";

Combining the two loops to one saves another two bytes:
for($a=$b=1;$b++<20||21>$b=1+$a+=print"\n";)echo$a*$b,"\t";

And you can save two more bytes with a leading linebreak instead of a trailing one (this often saves a byte or two):
for($b=20;$b++<20||21>$b=1+$a+=print"\n";)echo$a*$b,"\t";

This is a pretty easy and rewarding example; so don´t be upset if your first attempts fail on saving bytes. It may take a while until you get an eye for it.
Ok, for(;20>$b=++$a;print"\n")for(;$b++<20;)echo$a*$b,"\t"; is golfier; and in PHP 7, you can even avoid trailing tabs without any costs: for(;20>$b=++$a;)for(;$b++<20;)echo$a*$b,"\n\t"[$b<20];
But imagine you have to loop $a from somewhere else but 1, like through ascii codes.
I may one day come up with an example that makes more sense. No promises on these premises though.

primo also posted on combining loops in March 2014. Don´t miss out on that one!

When using array_values() to re-index an array with numeric keys, from PHP7.4 you can use a technique that I call splatpacking (see link for further details and a demonstration).
You use the "splat/spread" operator to "unpack" the array, then immediately "repack" the elements into an empty array.  Though not designed for this purpose, the result is the same -- in that limited scenario.
Technique using $a representing an array:
array_values($a)  // 14 characters (not counting $a)

becomes
[...$a]  // 5 characters (not counting $a)

Little-known tricks with increment/decrement
$x = 'a';
echo ++$x; // Outputs "b"

$x = 'z';
echo ++$x; // Outputs "aa"

And many more at the following RFC, showing they will be removed/normalized in PHP 8.3
https://wiki.php.net/rfc/saner-inc-dec-operators

authors: Евгений Новиков


text:
Pinyin Combinations
Create a function that takes a string of a pinyin syllable as the argument, and returns true of the combination exists, false otherwise.
Use "v" for "ü".
Here is a full list of combinations.
http://www.pinyin.info/rules/initials_finals.html
Examples
f("bu") == true
f("zheng") == true
f("nv") == true
f("ri") == true
f("cei") == false
f("ia") == false
f("kian") == false
f("qa") == false

Please, don't do things like scraping webpages or reading input method files to reduce character count. (If you do, the length of the data will be counted toward character count)
One of the purposes of this code golf is to see how rules can be simplified.
Shortest code wins.

What about something like nar? :P

Just as a note, despite what the examples say, I don't believe nvi is ever a valid combination.

If the linked page already says » er has been omitted from this table« shouldn't it be included as well? (After all, it was a number, if I remember correctly ;-))

JavaScript 1.6, 503 496 477 characters
function g(s){return/^([bfmpw]?o|[yjqx]ua?n|[ln]ve?|ei?|y[aio]ng|w?[ae]ng?|w?ai?|wei|y?ao|y?ou|y[ai]n?|yu?e|[^aeiou]+u)$/.test(s)|(((k=6*("ccsszzdflmnprtbghkjqx".indexOf(s[0])+(f=s[1]=='h')))|(r="a.e.ai.ei.ao.ou.an.ang.en.eng.ong.ua.uo.uai.ui.uan.uang.un.i.ia.ie.iao.iu.ian.iang.in.ing.iong.u.ue".split('.').indexOf(s.slice(f+1))))<0?0:k>84?r>17^k<108:parseInt("009m2f00b8jb009m2f00b7r3009m2n00b8jj1dwcfz0000rtfjba4f1xgbnjfj01rz1uyfb1009nn61b37cv1uyfa5".slice(k,k+6),36)>>r&1)}

Fomatted a little bit more readably (barring any errors in breaking the code into a few lines):
function _g(s)
{
  f = s[1] == 'h'
  k = "ccsszzdfghjklmnpqrtxb".indexOf(s[0]) * 6
  k += 6 * f
  return /^(weng|[bfmp]?o|[yjqx]ua?n|[ln]ve?|[ae]i?|y[aeiu]|y[aio]ng|[ae]ng?|wang?|wai?|we[in]|w[ou]|y?ao|y?ou?|y[ai]n|yue)$/.test(s) |
         !!(k >= 0 && (1 << "a.e.ai.ei.ao.ou.an.ang.en.eng.ong.u.ua.uo.uai.ui.uan.uang.un.i.ia.ie.iao.iu.ian.iang.in.ing.iong.u.ue".split('.').indexOf(s.slice(f + 1)) & parseInt("00j85300mh2v00j85300mgan00j85b00mh332rsovz0002cp00b8jj00b8jjqmlts000b8jjv2mkfz3uwo3jv203jz3pwvelqmlts000jbaq2m6ewvqmlts03pwvdp".slice(k, k + 6), 36)))
}

The zero-initial cases plus a few one-offs are tested with a regular expression. After that, the table is encoded as a (concatenated) series of 6-digit, base-36 numbers, one per initial sound. The lookup then uses a pair of indexOf calls and a shift to select the right bit.
Tested against all cells in the table of combinations (filled cells tested for true, empty cells tested for false).
Edit: Replaced some of the 36 chars of the base-36 lookup with comparisons since g–, k–, h–, j–, q–, and z– have dense blocks of true/false.
Edit: Rearranged the bit test to avoid an unnecessary !! and compacted the regex more.

Why do you need a !!? I'm not sure I understand why you would ever need a double not...

With it, the return is 0 or 1; without it "true" is returned as non-zero but not necessarily 1. My test script is validating with if (g(s) == (validList.indexOf(s) >= 0) which returns false on 16 == true; I debated it from a "what does 'true' really mean" perspective and left the thing in. In either case, I have a planned change for later today that will do away with the !! by replacing 1<<r&*parseInt with (more or less) (parseInt>>r)&1 so that the return is 1 and I shave off two chars.

PHP, 548 characters
Granted, it's likely not optimal, but I wrote a regex to match valid pinyin combinations. Reduced characters by replacing repeating substrings with variables.
Code
<?php $a='?|e(i|ng?)';$b='|o(u|ng)|u';$c='|a?n)?|i(a[on]';$d='(a(ng?|o|i)';$e='|ng?)';$f='(i|ng)?';echo(preg_match("/^([bpm](a(i|o$e$a|u|o|i(e|a[on]$e?)|[pm]ou|m(e|iu)|f(a(ng?)?|ou$a|u)|d$d$a?$b(o|i$c?|e|u)?)|[dtnl]$d?|e$f$b(o$c|e)?)|[jqxy](i(a(o$e?|e|u|o?ng|n)|u(e|a?n))|([zcs]h?|r)i|[nl](ve?|i(n|ang?|u))|[dl]ia|[dt](ing|ui)|[dn]en|diu|([gkh]|[zcs]h?)(e(ng?)|a(o|ng?|i)?|ou|u(o|i|a?n)?)|r(e(ng?)?|a(o$e$b(a?n?|o|i)?)|[gkh](ei|ong|u(a$f))|[zcs]hua$f|([zcs]|[zc]h)ong|(z|[zs]h)ei|a(i|o$e?|ou$a?|w(u|a(i$e?|o|e(i$e))$/",$argv[1]))?"true":"false";

Usage
> php pinyin.php bu
> true
> php pinyin.php cei
> false

F#, 681 characters
type l=Y|J|Q|X|W|F|B|P|M|N|L|T|D|Z|K|H|Zh|G|Sh|Ch|C|S|R|Iong|Vn|Van|Ia|Iu|In|Iang|Ve|V|Ian|Iao|Ie|Ing|I|Ei|A|Ai|An|Ang|Eng|U|Ao|E|Ou|Uo|Uan|Un|Ui|En|Ong|Ua|Uang|Uai|Ueng|O
let v x=x.GetHashCode()
let n x=J.GetType().GetNestedType("Tags").GetFields().GetValue(v x).ToString().Substring(6).ToLower();
let(^)a b=List.collect(fun x->List.map(fun z-> n x+ n z)b)a
let(-)a b=[v a..v b]
let(&)a b=a@b
let(!)a=[v a]
[<EntryPoint>]
let main a=
 printf"%b"(List.exists(fun x->x=a.[0])(Y-X^Iong-I& !W^Ei-Ui@Ua-O& !F^Ei-A@An-U@ !Ou&(F-N@D-Sh)^ !En&F-M^ !O&B-M^ !In&N-L^Iu-Un& !D^Ia-Iu&B-D^Ian-Ao& !M^E-Ou&Ch-S^A-Ong&T-Sh^Ei-Ui&N-G^ !Ong&K-Ch^Ua-Uai& !R^An-Ua&(Sh-R@ !Z@ !Zh)^ !I&["lia";"pou";"mui"]))
 0

Doesn't quite get the syllables without initial consonant correct (Y, W etc).

APL (Dyalog Extended), 475 bytes
s←⊢⊆⍨' '≠⊢
a b c←2097144 131064 1957895
f←{(⊂⍵)∊(12↑v),(s'yi ya ye yao you yan yang yin ying yong yu yue yuan yun wu wa wo wai wei wan wang wen weng nv lv nve lve'),(,⊤(a-8)1966080 393208 1966064 2096720 1966072 1048568a a 2056184a 131048a 7288b 7280 106488b 7280b 0 1958911 73735c c 352263c 24583 1859591c,5⍴7)/,('bpmfdtnlgkhzcs',s'zh ch sh r j q x')∘.,v←'aoe',s'ai ei ao ou an ang en eng ong u ua uo uai ui uan uang un ueng i ia ie iao iu ian iang in ing iong u ue uan un'}

Try it online!
Golfing in progress.
Ungolfed
s←{⍵⊆⍨' '≠⍵}
con←s'b p m f d t n l g k h z c s zh ch sh r j q x'
vwl←s'a o e ai ei ao ou an ang en eng ong u ua uo uai ui uan uang un ueng i ia ie iao iu ian iang in ing iong u ue uan un'
tab←con∘.,vwl
bin←,⊤2097136 1966080 393208 1966064 2096720 1966072 1048568 2097144 2097144 2056184 2097144 131048 2097144 7288 131064 7280 106488 131064 7280 131064 0 1958911 73735 1957895 1957895 352263 1957895 24583 1859591 1957895 7 7 7 7 7
all←'aoe',(12↑vwl),(s'yi ya ye yao you yan yang yin ying yong yu yue yuan yun wu wa wo wai wei wan wang wen weng nv lv nve lve'),bin/,tab
f←{(⊂⍵)∊all}

Try it online!
The helper function s unpacks a space-delimited string:
{⍵⊆⍨' '≠⍵}    monadic function taking a string
    ' '≠⍵       0s at spaces, 1s elsewhere
 ⍵⊆⍨            Partition (split at 0s)

I first store the possible initial and final strings in the syllable, then make a table tab containing the concatenation of each string from the first list with each string from the second list.
Next, I store binary data as a list of integers. Some of the integers are repeated and can therefore be stored in variables, which also allows elision of some spaces.
Each integer is decoded into binary, and represents one row of the table. Each bit in the number represents whether a certain syllable in that row is a valid syllable, with the MSB representing the first column. All invalid syllables are removed from the table.
We flatten the table into a list, add on the forms with no initial consonant as a special case, and finally check if our input is in the list.
Possible further golfing potential:

Write base64 or base255 encoding
Reorder the columns and rows to make the numbers smaller.

Python helpful script and test-case generator: Try it online!

source: Stack Exchange

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

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

sort: votes


text:
Generate a random program in your favorite language
We all heard of testing compilers using randomly generated inputs. Your task is to write a program to generate a valid program (including no undefined behavior) in your favorite language. The generating program language doesn't have to be the same as the generated program language.
Your program will receive an integer as the argument which you can use as seed for your random number generator. The generated programs should be structurally different (given different seeds) not just different variable names or constants.
Examples:
$ ./generate 1
int main() { return 0; }

$ ./generate 2
#include <math.h>
int main() { return (int) pow(4, 3); }

Please include a couple of outputs in your answers.
The shortest solution wins. I will give a small bonus based on the number of votes, so please vote the most creative solutions.

Perfect task for developing genetic algorithms with open-ended evolution. I've always wondered how it might be done.

I think the lack of a fixed specification makes this a bad question. "Structurally different" is open to interpretation, and in some interpretations this is an extremely simple problem.

@Peter: What interpretations of 'structurally different' do you see? For example, return 1 + (seed times) + 1 is according to rules.

If rnd(seed) mod 2 == 0 then ';' else '' would seem to be a valid answer. The output is Golfscript.

Not necessarily. You get the same answer for different seeds (2, 4, 6). Your set of possible programs is of size 2, while I specifically forbid that.

Where? The only restriction on the way the program depends on the seed is "The generated programs should be structurally different (given different seeds)" - which can be interpreted either as that no two seeds can give isomorphic abstract syntax trees (likely to be impractical) or that at least two seeds give non-isomorphic ASTs.

The idea was not to choose between a small set of predefined programs as per your suggestion. I understand that it is possible to get unintentional collisions, so I will not disqualify such programs. The spirit of the question is meta-programming. You are welcome to improve the question or provide some other suggestions.

@PeterTaylor let us continue this discussion in chat

Seems like this would make a better code-challenge than code-golf.

All one really needs to do is golf a program that can generate a random sentence from a given BNF grammar (this is trivial).  Then just plug in the grammar for any other programming language and poof: a valid program in that language.  This will work for any context-free language (which unfortunately rules out Perl).

@ESultanik: Most languages, on the semantic level, are not context-free.  The question says "valid program (including no undefined behavior)".  Ensuring that variables are declared before use, that subscripts are in range, etc. goes beyond the definition of a context-free grammar.

@Joey: True.  I guess the method I described would just produce programs that have correct syntax.

main(seed) {  return 4; // Chosen by dice roll - Guaranteed to be random } Reference

Neil: Just to note: Probably everyone here knows xkcd, especially the linked one. They probably also know the Dilbert one on random numbers. And it has no relevance here as it's asking for a program with random structure, not just a random number.

Target language must be Turing-complete?

Do quines but then altering the code a litte bit count?

Python → Brainf*ck (185 223 233 255 285 287 303 characters)
Code
import random as r,sys
r.seed(int(sys.argv[1]))
c=list('<>.,+-')+['']
n=9/r.random()
def b():
 global n
 s=''
 while n>0:n-=1;o=r.choice(c);s+=o if o else'[%s]'%b()
 return s
print b()

303 → 287 Characters: Removed math.ceil (it's not really necessary).
287 → 285 Characters: Switched to an empty string to denote the branch operator.
285 → 255 Characters: Condensed the if statement in the while loop.
255 → 233 Characters: Implemented JBernardo's suggestions from the comments.
233 → 223 Characters: Implemented tjko's suggestion from the comments.
223 → 185 Characters: Implemented some whitespace reduction suggestions from the comments.

Examples
$ python generate.py 1
-->,,+-<<-,-<,->[[<<,[.>.<>,,>>>,.<-,+>[[<.-+[.-+.+[-,+<>-.>,++.,,-,.,<<+[+]]]]]]]]
$ python generate.py 2
[<<--+.+++>]
$ python generate.py 3
,.++<<->>[,-,+>+[,-+<-+.<[,-[+[.-,[[<<>[,+.]]]]]]]]

Actually figuring out what the resulting BF programs do is left as an exercise to the reader.

you can also use if o: s+=0(NL)else: s+='['+b()+']'

@Alexandru: Thanks!  I missed that.  Your code didn't seem to work exactly, but it helped me get it shorter.

Does this somehow mean Brainfuck is your favorite language?

@zneak: Heh, well, I've been working on a high-level language → BF compiler on-and-off for a while, so it's been on my mind.  Also, the syntax is so simple that it seemed like an easy choice for this challenge.

Not that this is a problem, but the outputted code will likely cause an infinite loop.

@Peter, true, but avoiding that using this method of random generation is likely equivalent to solving the Halting Problem!

could be c='<>.,+-' but will not have the empty string. c=list('<>.,+-')+[''] is also smaller

BTW, s+=o if o else '[%s]'%b() is even better

@JBernardo: Thanks!  Also, the space between "else" and "'[%s]'%b()" doesn't appear to be necessary.

import random as r,sys saves 10 bytes.

Simon Brown proposed an edit to move the three lines inside the while loop onto one line, separated by semicolons. Also, I note that you seem to be counting tabs as 4 characters rather than 1. Given the limitations of Markdown you're probably best indenting with a single space rather than a tab.

@PeterTaylor: Thanks!  IIRC, I counted the characters using wc -c, which must have counted the tabs that way.

Couldn't you from random import* and then leave off the r and sys

@Timtech: If I just needed to import random that would save a few bytes, but the issue is that I also need sys to read from argv, and if I convert to using from random import * I'd have to have a separate line to import sys, which requires more bytes.

@ESultanik So you can't do something like from random,sys inport *

@Timtech, ah, I see, I wasn't aware that that syntax worked.  I'll try it.  Thanks!

@ESultanik I'm not saying it works, but at least try it ;)

@Timtech Unfortunately that syntax doesn't work; syntax error at the comma :-(

@ESultanik Sorry about that; I hoped it would work.

If you're willing to require Python 3.7,  you can change else'[%s]'%b() to else f'{b()}' to save 2 bytes (if I counted correctly).

Very short, but it will not generate all possible programs. All loops only go deep... they are never at the same level. For instance, this program will never be generated [][]
In other words the first 50% brackets are always [ (facing right), and the last 50% brackets are ] (facing left)...  The following is one example:
[---[,.[<<[--[<..[[+<+,,.<>>>>+.<-.->-+><+.,>.-+]]]]]]]

Python -> Piet, 385 345 char
It's possible to generate any Piet program with this.  I could've just stopped at random pixels, but I wanted to make "interesting" programs.  The function m paints a pixel a color, and recursively steps into each of that pixels neighbors.  There are better ways to draw random blobs, but this is tuned to terminate in a reasonable number of steps, so it's good enough for golf.  The function R(w,h,n) draws n random blobs onto a (w x h) white image, and prints the result in PPM format.
I'm especially proud of how I generate the colors -- for a random choice of 0 <= c < 20,
`[0,192,255][int(x)]`for x in'0002212220200101121100'[c:c+3]

is the decimal code for a valid color in the Piet palette by way of a single-track Gray code.  That is, each color is represented by 3 adjacent bits, and every slice '0003...0'[c:c+3] represents a different color.  Since this isn't the full list of 27 words on 3 letters, I really lucked out in finding the Gray code.
from random import*
r=randint
def R(w,h,n):
 M=[6]*h*w
 def m(x,y,c,d):M[y%h*w+x%w]=c;t=r(0,15)*(r(0,d)<2);t&8and m(x+1,y,c,d+1);t&4and m(x-1,y,c,d+1);t&2and m(x,y+1,c,d+1);t&1and m(x,y-1,c,d+1)
 while n:m(r(0,w),r(0,h),r(0,19),0);n-=1
 print"P3 %s %s 255 "%(w,h)+' '.join(`[0,192,255][int(x)]`for c in M for x in'0002212220200101121100'[c:c+3])

Sample output, generated by the command R(30,40,500)

Without the import, I can write it as a proper (semicolon-free) 1-liner, too:
import random
R=(lambda P,I,E,T:lambda w,h,n:E(w,h,I(w,h,n,lambda z,c,d,t:sum((((z,c),)*t*T(0,1)or m((z[0]+a,z[1]+b),c,d+1,T(0,d)>1)for a,b in((0,1),(1,0),(-1,0),(0,-1))),()))))(range,lambda w,h,n,m:dict(sum((m((T(0,w),T(0,h)),T(0,19),0,0)for _ in P(n)),())),lambda w,h,M:"P3 %s %s 255 "%(w,h)+' '.join(' '.join(`(x&1)*255+(x&2)*96`for x in map(int,'0001121110100202212200'[c:c+3]))for c in(M[z]if z in M else 6for z in((x,y)for y in P(h)for x in P(w)))),random.randint)

but it's ridiculously slow (and almost 100 characters longer)... though I'm not entirely sure why (and not terribly inclined to find out).

Python -> Python, 135 chars
import random,sys
random.seed(int(sys.argv[1]))
R=range(9)
print'print 1'+''.join(random.choice('+*')+'%d'%random.choice(R)for x in R)

Generates little random expression evaluations, like this:
> ./genprogram.py 1
print 1+7*2+4*7+0*3*0+6+8
> ./genprogram.py 2
print 1*8+0*6*2*5*1+3*8*4
> ./genprogram.py 3
print 1+4+5*0+7+2*4*4*1*7
> ./genprogram.py 4
print 1+0+1+3*7*1*2+0+8*7

Python -> HQ9+ : 108 chars
import random
def g(): return ''.join([random.choice(['H','Q','9','+']) for x in range(random.randint(1,9))])

PHP, 352 characters
Generates PHP code in PHP.
I decided I didn't care as much about length, but instead wanted an interesting and diverse set of solutions. This is my answer to that.
Code
<?php mt_srand(0+$argv[1]);$r=mt_rand(1,100);$s="\$i=rand(1,$r);";while($r>0){$s.='$i';if(!($r%10))$s.='*=2;';if(!($r%9))$s.='++;';if(!($r%8))$s.='=pow($i,rand(1,$i));';if(!($r%7))$s.='--;';if(!($r%6))$s.='=substr($i,0,2);';if(!($r%5))$s.='/=2;';if(!($r%4))$s.='+=4;';if(!($r%3))$s.='*=-1;';$r-=mt_rand(1,5);}$s.='var_dump($i);';echo"<?php $s
";

Ungolfed
<?php
mt_srand(0+$argv[1]);
$r = mt_rand(1,100);
$s = "\$i=rand(1,$r);";
while ($r > 0)
{
    if (!($r%10)) $s .= '$i*=2;';
    if (!($r%9))  $s .= '$i++;';
    if (!($r%8))  $s .= '$i=pow($i,rand(1,$i));';
    if (!($r%7))  $s .= '$i--;';
    if (!($r%6))  $s .= '$i=substr($i,0,2);';
    if (!($r%5))  $s .= '$i/=2;';
    if (!($r%4))  $s .= '$i+=4;';
    if (!($r%3))  $s .= '$i*=-1;';
    $r -= mt_rand(1,5);
}
$s .= 'var_dump($i);';
echo "<?php $s
";

Example
> php r.php 1
<?php $i=rand(1,58);$i*=-1;$i=pow($i,rand(1,$i));$i=substr($i,0,2);$i+=4;$i*=-1;$i=pow($i,rand(1,$i));$i=substr($i,0,2);$i+=4;$i*=-1;$i*=2;$i/=2;$i+=4;$i/=2;$i*=-1;$i*=2;$i/=2;$i=substr($i,0,2);$i*=-1;var_dump($i);
> php r.php 2
<?php $i=rand(1,57);$i*=-1;$i+=4;$i--;$i=substr($i,0,2);$i*=-1;$i*=-1;$i--;$i+=4;$i/=2;$i++;$i=substr($i,0,2);$i*=-1;$i=pow($i,rand(1,$i));$i+=4;$i--;$i=substr($i,0,2);$i+=4;$i*=-1;$i--;$i+=4;var_dump($i);

Could you please include an output example?

scala: 1543 (scala => scala)
I have variables (x, y, z), functions (mul, add, neg, abs), values and balanced parenthesis.
<!--code:language-scala-->
object FormelBauer {
    val fun = List (" mul10 (", " add1 (", " neg (", " abs (")
    val ops = List (" * ", " + ", " - ", " / ")
    def c(maxLen: Int, m: Int) : String = {
        def f()= new StringBuffer (fun (r.nextInt (fun.length)))
        def w()= new StringBuffer ("" + (r.nextInt (180) - 90))
        def v()= new StringBuffer ("" + ('x' + r.nextInt (3)).toChar)
        def o()= new StringBuffer (ops (r.nextInt (ops.length)))
        def g(t: Int, b: Int, d: List [Char]) : StringBuffer ={
            var a = d.filterNot (x => if (b > 0) x == '.' else x == ')')
            if (b > m) a = a.filterNot (_ == 'k')
            if (b > m) a = a.filterNot (_ == 'f')
            if (t > maxLen) a = a.filterNot (_ == '+')
            val elem = r.nextInt (a.length)
            val start = a(elem)
            start match {
                case '.' => new StringBuffer ("")
                case 'f' => f.append(g (t + 1, b + 1, List ('(', '8', 'x')))
                case '(' => new StringBuffer ("(").append   (g (t + 1, b + 1, List ('(', '8', 'x')))
                case '8' => w.append(g (t + 1, b, List ('.', ')', '+')))
                case 'x' => v.append(g (t + 1, b, List ('.', ')', '+')))
                case ')' => new StringBuffer (") ").append  (g (t + 1, b -1, List ('.', ')', '+')))
                case '+' => o.append(g (t + 1, b, List ('f', '(', '8', 'x')))
        }}
        (g (0,0,List('f','(','8','x'))).toString
    }
import util._
  var r : Random = _
    def main (as: Array [String]) : Unit = {
      val s=as(0).toInt
        r=new Random(s)
        "xyz".map(c=>println("val "+c+"="+(c+r.nextInt(s))))
        println("""def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
"""+c(45,5))}
}

As you see, it is not very golfed. Because, it will not get me close to the other solutions, but a problem is, that more variation costs more. 3 variables, 4 functions could be easily reduced to two, for example.
Generating some samples:
for i in {1..7} ; do scala FormelBauer $i; echo; done

val x=120
val y=121
val z=122
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
(y)  / 79

val x=121
val y=121
val z=123
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
 add1 ((((78 +  neg (z * z) )  / x) ) )  + -23 - ((-83)  * y)

val x=122
val y=123
val z=122
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
x / -71 - (y)

val x=122
val y=124
val z=125
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
x

val x=122
val y=123
val z=126
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
-24 + z

val x=121
val y=121
val z=124
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
 abs (z)

val x=123
val y=126
val z=126
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
 add1 (-62 - 30 * (-68)  /  neg (x - 69 + 33 / 45 + x * x)  -  abs (-18 * (y + x)  /  neg (x)  - y)  *  abs ((61) ) )  + (y)

Testing the longest one:
add1 (-62 - 30 * (-68)  /  neg (x - 69 + 33 / 45 + x * x)  -  abs (-18 * (y + x)  /  neg (x)  - y)  *  abs ((61) ) )  + (y)

res6: Int = -5425

Perl -> shell : 66 chars

@p=split(':',$ENV{PATH});
@c=`ls @p[@ARGV[0]]`;
print @c[rand($#c)];

Possibly a little off topic, but maybe so.

s153254@helios:/home/s153254/lab$ perl code.p 1
telnet
s153254@helios:/home/s153254/lab$ perl code.p 2
in.rlogind
s153254@helios:/home/s153254/lab$ perl code.p 2
df
s153254@helios:/home/s153254/lab$ perl code.p 3
svenv

Ruby → Brainfuck (110 107 characters)
s="";m=%w:< > . , + -:;rand(99).downto(r=0){s<<(rand(40)==0? (r+=1)&&'[%s':'%s')%m.shuffle[0]};p(s<<']'*r)

Usage
$ ruby bf.rb

Produces an executable brainfuck program.
Sort of a shameless ripoff of ESultanik's, so I will credit him for the idea.

Changed .zero? to ==0

Javascript -> Brainf*ck: 119 chars
s=prompt();a=["+","-",">","<",".",",","[-]"];i=0;b="";while(i++<s*s){b+=a[Math.floor(((Math.random()*s)%1)*7)]}alert(b)

Sample I/O:
10
.--.+,-><->.<+.[-].->.>[-][-]<+,[-]>><-[-]>,,>>[-].-+<[-]+>,<[-][-]<<[-]<[-]+,+[-][-][-].-[-],[-]>.<<[-]-..<-.->.++,>+-[-],.[-]..+,<-[-].+-[-]
11
,..[-]--,[-].,[-]>[-]->..[-]<,<..>[-]<>++-.[-].,,<[-].<+<[-]>-->[-]+-[-]+>-[-][-]>-,[-]->>-,-..++<+,,-,.,[-]->[-]<,+[-][-]+.,-,>+->.[-],.>..,++,.[-],+[-]-,.,--.--,

The code could definitely be shorter, but some things would, IMHO, make it less interesting. But if someone else comes up with a shorter program, I'll cut down more.

Python -> Fractran (117)
import random as r,sys
r.seed(int(sys.argv[1]))
z=r.randint
print','.join(`z(1,99)`+'/'+`z(1,99)`for q in[0]*z(1,99))

Python -> Python, 148 chars
Longer than the other Python entries at the expense of being (subjectively) a little more interesting.
import sys as s,random as r
w,o=s.stdout.write,__builtins__
r.seed(s.argv[1])
w('print\\')
for i in'\n....':n=r.choice(dir(o));o=getattr(o,n);w(i+n)

This prints a deeply nested attribute of a built-in object.
$ python randprog.py 1
print\
round.__setattr__.__delattr__.__init__.__class__

PowerShell, generating PowerShell – 43
In the spirit of Keith's solution:
-join(0.."$input"|%{'-','+'|random;random})

generates random expressions of additions and subtractions:
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
+2-0-0+3-7
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-7+1+7+1-5+2+8
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-1+7+7-0-6-0-2
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
+2-6-5+3-2+7
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-6

A Powershell way gcm|random -c @args|% na* :)

Game Maker Language -> Arduino or Ti84-Basic, 63 characters
a=argument0;if a mod 2{return("void setup(){Serial.begin(9600);}void loop(){Serial.print"+string(a*random(9))+";delay("+string(floor(random(999)))+")}"}else{return(":Lbl A:Horizontal "+string(a*random(9))+":Goto A")}

Explanation:
a=argument0 Puts the input into variable a
if a mod 2 Basically, half the chance the program will be Arduino, half Ti-Basic 84
The Arduino program outputs random stuff at random intervals, randomly skipping random things.
The Ti-Basic Program draws horizontal lines like crazy.
Also, there is a bonus - the generated programs are already golfed! Not sure if that would be helpful...

Perl -> HQ9+ (42 Characters)
$a="HQ9+";for(1..<>%4){chop$a}print chop$a

Example input
4264532623562346

Output
Q

JavaScript -> Javascript (44 characters)
alert('alert("'+Math.random()*prompt()+'")')

And with 43 characters, it can execute the generated program instead of displaying it's source:
eval('alert("'+Math.random()*prompt()+'")')

Examples:
Seed: 5
Executed 3 times:
alert("2.335241624386981")
alert("0.4577956395223737")
alert("0.8359265828039497")

Where's the seed?

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


text:
Write a program to print the sum of the ascii codes of the program
Your task is to write a program to print the sum of the ASCII codes of the characters of the program itself. You are not allowed to open any file (Any input such as command line arguments, standard input or files is prohibited).
The program that prints the lowest number (i.e. has the lowest sum of ASCII codes) wins.
Here is an example (not the shortest) of such a program  written in C:
#include <stdio.h>
int main(){
printf("4950");/*i*/
return 0;
}

(no new line after })

It'd be interesting to see a quine solution: one that produces and sums its own bytes.

Not very challenging imho. It can be trivially brute-forced, especially for languages that simply dump tokens, such as PowerShell, Golfscript, etc.

Might have been a bit more interesting to have the program open itself and manually sum/print the characters.

I don't understand the down votes. It's an easy question which, as Joey guessed, was meant to be brute forced, but judging by the number of answers people seem to like it.

I downvoted and the comment gives the reason, why. As I have noted before, I don't consider the number of answers an indication of quality. Just because it can be easily solved does not make this an interesting or even challenging challenge. My opinion, at least.

Wait. What? On one hand you complain that the question is easy and not interesting and then you downvote me (-2 for me). On the other hand you post 25% of answers on this question (+70 for you).

So you see this as a reputation battle? Fine, I can easily change my answers to CW. In a way the large number of answers was a bit of a protest and to show that it's trivial to churn out lots of answers. Compare this for example to the task that wanted the alphabet four times. Also my answering self (bound to the task specifications) and my commenting self (hoping to improve general site quality) are often fairly separate. Anyway, happier now that I deleted them? They were still valid answers, though.

I think the title should be changed to say "compute and print".

I love how the example program exhibits undefined behavior. That is, there is no newline at the end of the file.

@trinithis: I don't think it's undefined behavior. Can you point to a reference (best would be standard section)? It's related with the fact that #include doesn't add extra new line at the end.

It actually applies for non-empty source files. The C++ standard says it in 2.1.1.2 (Phases of translation). C says it in 5.1.1.1.2.3 (Translation phases). C simply mandates it. C++ says you would otherwise get undefined behavior. I just googled "c99 standard" and "c++ standard" and took a look at the drafts there (should be first pdf search results).

wc, prints 0
Someone said "cat-like languages", so...
An empty file:

Execute with wc -c file.wc. At 0 bytes, I think this is the winner in the 'not really a programming language' category.
Also
cat, prints 80 (base 13)
80

No terminating newline, the number 8013 is equivalent to 104 in decimal. You can go shorter with 6017 (102 dec), but I figured "base 13" would be worth more geek points.
EDIT: New wc example, this one can be run as a program.
#!/usr/bin/wc
ÿÿzw17

(As encoded in Latin-1 - the ÿ is a byte with value 255)
Sum of bytes is 2223, output is:
  2  2 23 ./w

But wc should read a file, containing a 0-byte to produce Number 0, not an empty one. Empty is not Null.

user: One might argue that the sum of values in an empty set is still 0. Nevertheless, wc -c is forbidden in the question anyway.

The only clause which seems to do so is "Any input such as command line arguments ... is prohibited" so leave off the -c, then it prints 0 0 0 (if the file being passed as a file prohibits it, then all scripting languages are also forbidden)

+1 for wc, -1 for base cheating, +1 for making jokes in base 13.

I would say wc is an application, not a language.

You could do 10 in base 97.

@userunknown $ >file will create a 0-byte file by overwriting (or creating) its contents with the output of nothing

@B1KMusic: The program, as I understand it, would be wc -c file.wc and that should be the content of the file file.wc, if it is the program. It would not be empty.

@userunknown yes, I was adding to your point, >test && wc -c test outputs 0 test

PHP, m4, and other cat-like languages: 150
150

Found this solution using a simple Haskell program to brute-force it:
f :: String -> Bool
f s = (read s :: Int) == (sum . map fromEnum) s

main = mapM_ print [filter f $ sequence $ replicate n ['0'..'9'] | n <- [1..10]]

I guess this is the absolute shortest.

@Alexandru: Not necessarily.  There may be program that is one or two characters long that correctly prints the sum using some built-in functions, say like 5! in J.

@mellamokb The sum of the ASCII characters in 5! is 86, not 125.

@Peter: Indeed, I was showing an example of the type of solution that might be smaller than 150, but not an actual solution. I haven't found one yet (and btw, 5! is 120, not 125) :-)

Brainf*ck, 255
-.¤

This will not print the number 255, but rather the 255th ASCII character.
This might be considered cheating because the BF compiler skips over the ¤.

Tim: The lowest number wins, not the shortest program. In any case, I don't think the ¤ is cheating, as it's just a normal comment.

You get a lower score by substracting a little bit more: ----.␦

Javascript, prints 9432 6902
(function a(){b="("+a+")()";c=0;for(i=0;i<b.length;i++){c+=b.charCodeAt(i-0)}alert(c)})()

This is the first quine solution so far, unless I am not understanding the Haskell one correctly.

That Haskell code is just searching for the smallest number which will equal the sum of its digit's ASCII codes. I guess most answers here were done by brute-force.

Can be reduced further from 89 to 86 bytes with: (function a(){b="("+a+")()";for(i=c=0;i<b.length;i++)c+=b.charCodeAt(i-0);alert(c)})()

PowerShell
((310))

prints 310.

Perl, 500
say     500

There are two tabs between say and 500. :)
(Run as a one-liner with perl -E, as far as I can tell this is within the rules)

I like the 2 tabs

Ruby, prints 380
p (380)

No trailing newline after the closing parenthesis.

PowerShell
(230)

prints 230, obviously.

PowerShell
-(-320)

prints 320.

J, 150
?!6

With the caveat that it will be correct only 1/720th of the time.

Random on factorial 6? Hmmm, I don't think so, Tim.

Python, prints 781
print  781

Two spaces.

I especially like the 2 spaces.

Element, 220
This is a language of my own creation, and it is documented on my answer to another question here.
220`!

Here is a walkthrough of how it works: The 220 pushes that number onto the stack. Then the ` outputs the top element of the stack. The ! then performs a logical NOT on the control stack (a separate stack), setting it to 1.

INTERCAL, 1572
I can't believe no one's done INTERCAL yet!
DOREADOUT#1572

DOGIVEUP

(Includes terminating newline.) This program prints out MDLXXII.

PHP, prints 4440
<?php
for($x=0;$x<15000;$x++)if($x==4440){printf($x);exit;}

PowerShell, prints 3902
&{[char[]]$myinvocation.Line|%{$s+=+$_};$s}

Looks into the line currently run and sums the code point values.

C, 1700
Strange - nobody posted a C solution yet (excluding the example in the question).
main(R){puts("1700");}

No newline at the end.

J, 198
33*6

and
6*33

Found it by brute force. In J there are no 1 or 2 char solutions, and the only 3-char solution is 150. Barring any bugs in my search, there are no other 4-char solutions, either.

From the #jsoftware IRC channel, we also had <.%:10!20 at 429 and a self-counting quine +/a.i.2#(,{:)'+/a.i.2#(,{:)''' at 1706.

naz, score 777 333
3a
3o

I think this is allowed.
The newline is normalized to \r\n by the naz interpreter at runtime, a sequence which contributes 23 to the overall score.
Explanation
3a # Add 3 to the register
3o # Output 3 times

The previous solution:
7a2o1m1o1a

Perl, prints 690
die 690 . $/

Or, if we can post one-liners (perl -E)
say(570)

Prints 570.
(No trailing newlines)

JavaScript, 1750 900 860 790
alert(790)
(Carriage return (CR, \r or \x0D) after or before the program)
These programs are found by brute-forcing.
Bigger values:
alert(860)%0
alert(900)&&6
document.write(1750)

Java -128
I know reading stdin isn't allowed but I wanted to provide an example of how I calculated my score.
My code sums the ASCII count of itself passed on stdin and prints out -128
class P{public static void main(String[]z)throws Exception{byte v=0;int b=0;while((b=System.in.read())!=-1){v+=(byte)b;}System.out.println(v);}}

No trailing new line

I think your sum is overflowing.

Ruby, prints 300
p   300

There is a space and a tab between the p and the 300. No trailing newline.

Batch files, 500
ECHO  500

As well, notice the two spaces between "ECHO" (uppercase on purpose) and "500".

K (923 796 795 746 513)
I'm not sure if this falls afoul of the rules or not. It doesn't use stdin, it opens itself as a vector of bytes and sums.
+/1:.z.f

Usage:
q scriptname.k

edit 2012.05.08 - no need to hsym the file handle
2012.05.09 - saved 1 point by converting to byte instead of int
2012.05.17 -  Can save a load of points by reading file as bytestream rather than text:

Lenguage, 4 bytes, prints 0
Source code consists of 4 null bytes. Therefore, it should output (0+0+0+0)=0.

Wow. For once, Lenguage wins (and has a golfing chance).

bc 1160
invoked with echo and blanks, the whole String, including 7 blanks, echo 1160    |  bc has a bytesum of 1160.
echo 1160    |  bc

150 works for bc too:
echo "150" > 150
bc -q 150
150

D, 9752
this one actually calculates it similar to my quine
enum c=q{import std.stdio;void main(){int s;foreach(d;"enum c=q{"~c~"};mixin(c);")s+=d;write(s);}};mixin(c);

Brainf*ck, 253 (or 252)
Slight improvement on Peter Olson's solution:
---.H

Provided non-printables are allowed, it can be improved further by adding a - and replacing H by ASCII code 26.

Scala, 1090 bytes
println (1090)

Whitespace, 369
This 20-character program prints the number 369, which is the sum of the ascii values of its characters (which are Tab,Space,Linefeed characters, here symbolized by T,S,L, respectively):
SSSTSTTTSSSTLTLSTLLL

(369 = 7*9 + 8*32 + 5*10, there being 7 Tabs, 8 Spaces, and 5 Linefeeds.)

Haskell, 7518
A small modification of my quine:
main=print.sum.map fromEnum$q++show q;q="main=print.sum.map fromEnum$q++show q;q="

Python, 5440
Highest score wins, right?
import sys
print sum(ord(i)for i in open(sys.argv[0]).read())

I just thought I'd post it anyway b/c it's a halfway quine solution.

Clojure - 8008
There's only a handful of quines so far, and clojure's not represented, so I figured I'd give it a go:
(let[s"(let[s%s](apply +(map int(format s(pr-str s)))))"](apply +(map int(format s(pr-str s)))))

05AB1E, 5 bytes (300)
C25LO

Try it online!

R, score 198
6*33

Try it online!
TIO link includes the code used to find this solution, which is the only 1+2 digit solution possible using the "*" operator.
Of, course, after finding this, I searched all the other answers for the string "6*33", which revealed that AlliedEnvy discovered the same solution in J 6 years ago...

Stax, score 354
|?|+

Run and debug it
|? returns the program's source. |+ sums it.

Zsh, 6 bytes, score 333
<<<333

< = 60, 3 = 51, so it adds up to a nice expression.


text:
Write a self-replicating program.
Write a simple program that copies itself when executed.
Your program should be some kind of executable file on Windows, Linux, etc.., should generate new executable file, which is identical to your original executable file, with random name, and quits.
Your program shouldn't involve any kind of file reading or copying. Only file writing for generating new executable file is permitted.
(PS. I was quite embarrassed when at Wikipedia, Self-replicating program redirects to Computer virus article... :/...)
Smallest executable file size wins. Your answer may be a programming code with proper OS & compiler, assembly code, or HEX dump of a executable file.

This seems to vary only trivially from the existing [quine] challenges. Or have I misunderstood?

@dmckee I saw Assembly Language Quine and Self replicating Hello World program accepting copying, but I couldn't find program writes itself, not its code.

For scripting languages (like say the three top answers to Golf you a quine for great good! ) there is no distinction between code and program, and the basic technique for building quines extends exactly to embedding compiled binaries instead of the source code.

... but I want to see how it actually works!.. I don't know how the idea can be extended with binary codes.. even though I read Quine article at Wikipedia. PS. no compilers for replicating and no script languages are allowed... :/

Alright, I have some ideas, but I don't think that this problem isn't quite as easy as quine..

Any problem can be made slightly harder and uglier by adding more constraints to it. I find this problem a trivial extension of the quine problem.

I edited your question. Scripts are executables (even .bat, .wsh and .js-Files are executable on Windows). You meant compiled files, native executable, binary files, which are, indeed, a different beast. Maybe you don't like JVM-bytecode? Then feel free to reedit.

This question should not make @JiminP quite embarrassed as stays on the speech "Reflections on Trusting Trust" by Ken Thompson as a good practice.

If smallest executable size wins, shouldn't we also factor in the interpreter code as part of the executable size for this to be fair to users of compiled languages?

Bash, 236
Longer than strictly necessary, but I hate long lines.  The trailing newline is non-optional.
b=\\ q=\' r=\> d=\$
s='exec >$$; echo b=$b$b q=$b$q r=$b$r d=$b$d; echo s=$q$s$q'
t='echo t=$q$t$q; echo $s; echo $t; chmod 777 $$'
exec >$$; echo b=$b$b q=$b$q r=$b$r d=$b$d; echo s=$q$s$q
echo t=$q$t$q; echo $s; echo $t; chmod 777 $$

Actually, it's not what I wanted, however, since I wrote a "wrong" question and your answer is a great quine...

@JiminP: How is it not what you wanted? I just read the problem description twice again, and fail to understand.

Well... what I wanted was an executable binary code. As I admitted above, since my question was not quite 'right'... sorry for that.

@JiminP Well, yeah, the word "binary" doesn't appear at all in the question.  I just found it in the comments, but for such a restriction, it just doesn't cut it.  You could open a new question with all the consolidated input from the comments.  I suggest you used the sandbox to ensure the regulars help you iron out the little details.  But beware, binary answers tend to be real boring.

Assembly for x86 Linux, 106 bytes
BITS 32
                org     0x2E620000
                db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
                dd      0, 0
                dw      2                       ; e_type
                dw      3                       ; e_machine
                dd      1                       ; e_version
                dd      _start                  ; e_entry
                dd      phdr - $$               ; e_phoff
                dd      0                       ; e_shoff
                dd      0                       ; e_flags
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
phdr:           dd      1                       ; e_phnum       ; p_type
                                                ; e_shentsize
                dd      0                       ; e_shnum       ; p_offset
                                                ; e_shstrndx
                dd      $$                                      ; p_vaddr
fname           equ     $ - 2
                db      'out', 0                                ; p_paddr
                dd      filesize                                ; p_filesz
                dd      filesize                                ; p_memsz
                dd      5                                       ; p_flags
                dd      0x1000                                  ; p_align
_start:         mov     al, 5                   ; 5 = open syscall
                mov     ebx, fname
                mov     cl, 65                  ; 65 = O_WRONLY | O_CREAT
                mov     dx, 666q
                int     0x80
                lea     edx, [byte ecx + filesize - 65]
                xchg    eax, ebx
                xchg    eax, ecx
                mov     cl, 0
                mov     al, 4                   ; 4 = write syscall
                int     0x80
                mov     al, 1                   ; 1 = exit syscall
                int     0x80
filesize        equ     $ - $$

This is for the nasm assembler. Build the binary with the command line: nasm -f bin -o a.out selfrep.asm && chmod +x a.out
Here's the same file as a hex dump: 7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 62 2E 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 62 2E 6F 75 74 00 6A 00 00 00 6A 00 00 00 05 00 00 00 00 10 00 00 B0 05 BB 36 00 62 2E B1 41 66 BA B6 01 CD 80 8D 51 29 93 91 B1 00 B0 04 CD 80 B0 01 CD 80
As requested, the program copies itself to a separate file. (The program could have been significantly shorter if it had been allowed to just write to stdout and let the user redirect to a file.)
I avoided using any borderline tricks to reduce the size. This should be a fully conformant 32-bit ELF binary.
Edited to add: In the above version the created file is just a plain file, but it occurs to me that for a couple of bytes (and a tiny bend of the rules), you can create something a little more interesting. This version is only two bytes longer, at 108 bytes:
BITS 32
                org     0x00010000
                db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
                dd      0, 0
                dw      2                       ; e_type
                dw      3                       ; e_machine
                dd      1                       ; e_version
                dd      _start                  ; e_entry
                dd      phdr - $$               ; e_phoff
                dd      0                       ; e_shoff
                dd      0                       ; e_flags
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
phdr:           dd      1                       ; e_phnum       ; p_type
                                                ; e_shentsize
                dd      0                       ; e_shnum       ; p_offset
                                                ; e_shstrndx
                dd      $$                                      ; p_vaddr
fname:          db      'asr', 0                                ; p_paddr
                dd      filesize                                ; p_filesz
                dd      filesize                                ; p_memsz
                dd      7                                       ; p_flags
                dd      0x1000                                  ; p_align
_start:         mov     al, 5                   ; 5 = open syscall
                mov     ebx, fname
                inc     byte [ebx]
                mov     cl, 65                  ; 65 = O_WRONLY | O_CREAT
                mov     dx, 777q
                int     0x80
                lea     edx, [byte ecx + filesize - 65]
                xchg    eax, ebx
                xchg    eax, ecx
                mov     cl, 0
                mov     al, 4                   ; 4 = write syscall
                int     0x80
                mov     al, 1                   ; 1 = exit syscall
                int     0x80
filesize        equ     $ - $$

Name this version asr, for "a self-replicator": nasm -f bin -o asr asr.asm && chmod +x asr
Hex dump version for the nasm-impaired:
7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 01 00 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 01 00 61 73 72 00 6C 00 00 00 6C 00 00 00 07 00 00 00 00 10 00 00 B0 05 BB 38 00 01 00 FE 03 B1 41 66 BA FF 01 CD 80 8D 51 2B 93 91 B1 00 B0 04 CD 80 B0 01 CD 80
When you run it, it creates an almost-identical file named bsr, but one that is itself executable. Running it will create another binary file named csr. And so on.
(Note that annoying things start to happen after zsr. I considered making a version that would cascade the name change to atr and so on, but I think most people will get bored well before then, so it probably isn't worth all the extra bytes.)

+1 for assembly answer! Have you seen the assembly quine challenge?

Here is a proof-of-concept (ungolfed) that shows how the Compilation services in .NET might be used to compile the source code on-the-fly to generate an identical output.  The first copy is not identical to the original, but subsequent copies from subsequent runs are exactly identical with random file names:
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace _2947
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world!");

            var s = @"
using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace _2947
{{
    class Program
    {{
        static void Main(string[] args)
        {{
            Console.WriteLine({1}Hello world!{1});

            var s = @{1}{0}{1};
            s = string.Format(s, s, '{1}');

            string exeName = Environment.CurrentDirectory + @{1}\{1} + new Random().Next(1000, 9999) + {1}.exe{1};

            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = true;
            cp.OutputAssembly = exeName;
            cp.GenerateInMemory = false;
            cp.TreatWarningsAsErrors = false;
            cp.ReferencedAssemblies.Add({1}System.dll{1});

            var c = CSharpCodeProvider.CreateProvider({1}cs{1});
            var cr = c.CompileAssemblyFromSource(cp, s);
        }}
    }}
}}
";
            s = string.Format(s, s, '"');

            string exeName = Environment.CurrentDirectory + @"\" + new Random().Next(1000, 9999) + ".exe";

            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = true;
            cp.OutputAssembly = exeName;
            cp.GenerateInMemory = false;
            cp.TreatWarningsAsErrors = false;
            cp.ReferencedAssemblies.Add("System.dll");

            var c = CSharpCodeProvider.CreateProvider("cs");
            var cr = c.CompileAssemblyFromSource(cp, s);
        }
    }
}

Demonstration output on command-line:
C:\projects\codegolf\2947\2947\bin\Debug>2947
Hello world!

C:\projects\codegolf\2947\2947\bin\Debug>dir
 Volume in drive C has no label.
 Volume Serial Number is 361D-4479

 Directory of C:\projects\codegolf\2947\2947\bin\Debug

09/27/2011  02:17 PM    <DIR>          .
09/27/2011  02:17 PM    <DIR>          ..
09/27/2011  02:17 PM             7,680 2947.exe
09/27/2011  02:17 PM            13,824 2947.pdb
09/27/2011  01:33 PM            11,600 2947.vshost.exe
09/27/2011  02:17 PM             6,656 8425.exe
               4 File(s)         39,760 bytes
               2 Dir(s)   6,486,368,256 bytes free

C:\projects\codegolf\2947\2947\bin\Debug>8425
Hello world!

C:\projects\codegolf\2947\2947\bin\Debug>dir
 Volume in drive C has no label.
 Volume Serial Number is 361D-4479

 Directory of C:\projects\codegolf\2947\2947\bin\Debug

09/27/2011  02:17 PM    <DIR>          .
09/27/2011  02:17 PM    <DIR>          ..
09/27/2011  02:17 PM             7,680 2947.exe
09/27/2011  02:17 PM            13,824 2947.pdb
09/27/2011  01:33 PM            11,600 2947.vshost.exe
09/27/2011  02:17 PM             6,656 7538.exe
09/27/2011  02:17 PM             6,656 8425.exe
               5 File(s)         46,416 bytes
               2 Dir(s)   6,486,360,064 bytes free

C:\projects\codegolf\2947\2947\bin\Debug>7538
Hello world!

C:\projects\codegolf\2947\2947\bin\Debug>dir
 Volume in drive C has no label.
 Volume Serial Number is 361D-4479

 Directory of C:\projects\codegolf\2947\2947\bin\Debug

09/27/2011  02:17 PM    <DIR>          .
09/27/2011  02:17 PM    <DIR>          ..
09/27/2011  02:17 PM             7,680 2947.exe
09/27/2011  02:17 PM            13,824 2947.pdb
09/27/2011  01:33 PM            11,600 2947.vshost.exe
09/27/2011  02:17 PM             6,656 4127.exe
09/27/2011  02:17 PM             6,656 7538.exe
09/27/2011  02:17 PM             6,656 8425.exe
               6 File(s)         53,072 bytes
               2 Dir(s)   6,486,351,872 bytes free

C:\projects\codegolf\2947\2947\bin\Debug>

Batch
Version 1 (30 bytes)
type%0>%random%.bat&type%0>con

I win! :)

the %0 reference causes a read from the file, which violates the rules.  Besides, my binary version is even shorter. :-)

DOS COM file - 50 bytes
Creates a file X.COM where X is replaced with the ones digit of the current time. COM files are simply loaded into memory at offset 100h of the data segment (CS and DS are set to be the same) so we can simply write this memory out to a file.
0000000: b402 cd1a 80e6 0f80 ce30 8836 2c01 31c9  .........0.6,.1.
0000010: ba2c 01b4 3ccd 21c6 062c 0178 89c3 b440  .,..<.!..,.x...@
0000020: ba00 01b9 3200 cd21 b44c cd21 782e 636f  ....2..!.L.!x.co
0000030: 6d00                                     m.

nasm source
org 100h ; this is a COM file
mov ah,02h ; fn=get time
int 1ah ; rtc interrupt
; convert to ascii - dh gets ones digit of seconds
and dh,0fh
or dh,30h
mov [fname],dh ; move time into filename
xor cx,cx ; clear attributes
mov dx,fname ; load filename
mov ah,3ch ; fn=create file
int 21h ; dos interrupt
mov byte [fname],'x' ; reset filename
mov bx,ax ; set filehandle
mov ah,40h ; fn=write to file
mov dx,100h ; offset is the loaded binary
mov cx,len ; length of write
int 21h ; dos iterrupt
mov ah,4ch ; fn=exit
int 21h ; dos interrupt
fname: db 'x.com',0
len equ $-$$

DOS .COM file, 29 bytes
The '@' is replaced randomly by an odd letter in the first half+ part of the alphabet (A, C, E, G, etc).  Output files are either 255 or 256 bytes.
Initial registers in real DOS (as opposed to a debugger) are that AX=0000, CX=00FF, SI=0100.
40       INC  AX         ;"@"
2E       CS:             ;"."
43       INC  BX         ;"C"
4F       DEC  DI         ;"O"
4D       DEC  BP         ;"M"
00 20    ADD  [BX+SI],AH ;"\0" and dummy parm
E4 40    IN   AL,40
24 0F    AND  AL,0F
0C 41    OR   AL,41
88 04    MOV  [SI],AL
B4 3C    MOV  AH,3C
41       INC  CX
89 F2    MOV  DX,SI
CD 21    INT  21
93       XCHG BX,AX
B4 40    MOV  AH,40
49       DEC  CX
CD 21    INT  21
C3       RET

DOS COM File - 36 bytes
56 BE 80 00 AD FE C8 A2 10 01 7E 17 89 F2 88 74
02 B4 3C 33 C9 CD 21 72 0A 8B D8 B4 40 5A B9 24
00 CD 21 C3

Output file name is specified on the command line, truncated to 8.3 format, spaces OK (spaces in DOS filenames are legal). Tested using WinXP command prompt.


text:
Count number of hefty decimals between 2 numbers
Let's say we have a non-negative integer that is "hefty" (that is, "heavy") if its average digit value is greater than 7.
The number 6959 is "hefty" because:
(6 + 9 + 5 + 9) / 4 = 7.5
The number 1234 is not, because:
(1 + 2 + 3 + 4) / 4 = 2.5
Write a function, in any language,
HeftyDecimalCount(a, b)
which, when provided two positive integers a and b returns an integer indicating how many "hefty" integers are within the interval [a..b], inclusive.
For example, given a=9480 and b=9489:
9480   (9+4+8+0)/4 21/4 = 5.25
9481   (9+4+8+1)/4 22/4 = 5.5
9482   (9+4+8+2)/4 23/4 = 5.75
9483   (9+4+8+3)/4 24/4 = 6
9484   (9+4+8+4)/4 25/4 = 6.25
9485   (9+4+8+5)/4 26/4 = 6.5
9486   (9+4+8+6)/4 27/4 = 6.75
9487   (9+4+8+7)/4 28/4 = 7
9488   (9+4+8+8)/4 29/4 = 7.25   hefty
9489   (9+4+8+9)/4 30/4 = 7.5    hefty

Two of the numbers in this range are "hefty" and so the function should return 2.
Some guidelines:

assume that neither a or b exceeds 200,000,000.
an n-squared solution will work, but will be slow -- what's the fastest we can solve this?

what threw the TIMEOUT?

This is a really old question, (10 years wow) and the site has changed quite a bit.  I'm going to close this challenge now as lacking an objective scoring criterion, since it doesn't specify how we should consider speed, which is something that we would expect of a modern challenge.

The problem can be solved in \$O(\operatorname{polylog}(b))\$.
We define \$f(d, n)\$ to be the number of integers of up to \$d\$ decimal digits with digit sum less than or equal to \$n\$.  It can be seen that this function is given by the formula
$$f(d, n) = \sum_{i=0}^d (-1)^i \binom d i \binom {n+d - 10i} d$$

Let's derive this function, starting with something simpler.
$$h(n,d) = \binom{n+d-1}{d-1} = \binom{(n+1)+(d-1)-1}{d-1}$$
The function \$h\$ counts the number of ways to choose \$d - 1\$ elements from a multi-set containing \$n + 1\$ different elements.  It's also the number of ways to partition \$n\$ into \$d\$ bins, which can be easily seen by building \$d - 1\$ fences around \$n\$ ones and summing up each separated section . Example for \$n = 2, d = 3\$:

3-choose-2
fences
number

11
||11
002

12
|1|1
011

13
|11|
020

22
1||1
101

23
1|1|
110

33
11||
200

So, \$h\$ counts all numbers having a digit-sum of \$n\$ and \$d\$ digits.  Except it only works for \$n < 10\$, since digits are limited to 0 to 9.  In order to fix this for values 10 to 19, we need to subtract the number of partitions having one bin with a number greater than 9, which I'll call  overflown bins from now on.
This term can be computed by reusing \$h\$ in the following way.  We count the number of ways to partition \$n - 10\$, and then choose one of the bins to put the 10 into, which results in the number of partitions having one overflown bin.  The result is the following preliminary function.
$$g(n,d) = \binom{n+d-1}{d-1} - \binom{d}{1} \binom{n+d-1-10}{d-1}$$
We continue this way for n less or equal 29, by counting all the ways of partitioning \$n - 20\$, then choosing 2 bins where we put the 10's into, thereby counting the number of partitions containing 2 overflown bins.
But at this point we have to be careful, because we already counted the partitions having 2 overflown bins in the previous term. Not only that, but actually we counted them twice.  Let's use an example and look at the partition \$(10,0,11)\$ with sum 21.  In the previous term, we subtracted 10, computed all partitions of the remaining 11 and put the 10 into one of the 3 bins.  But this particular partition can be reached in one of two ways:
$$(10, 0, 1) \to (10, 0, 11) \\ (0, 0, 11) \to (10, 0, 11)$$
Since we also counted these partitions once in the first term, the total count of partitions with 2 overflown bins amounts to 1 - 2 = -1, so we need to count them once more by adding the next term.
$$g(n,d) = \binom{n+d-1}{d-1} -  \binom{d}{1} \binom{n+d-1-10}{d-1} + \binom{d}{2} \binom{n+d-1-20}{d-1}$$
Thinking about this a bit more, we soon discover that the number of times a partition with a specific number of overflown bins is counted in a specific term can be expressed by the following table (column \$i\$ represents term \$i\$, row \$j\$ partitions with \$j\$ overflown bins).
1 0 0 0 0 0 . .
1 1 0 0 0 0 . .
1 2 1 0 0 0 . .
1 4 6 4 1 0 . .
. . . . . .
. . . . . .

Yes, it's Pascals triangle.  The only count we are interested in is the one in the first row/column, i.e. the number of partitions with zero overflown bins. And since the alternating sum of every row but the first equals 0 (e.g. \$1 - 4 + 6 - 4 + 1 = 0\$), that's how we get rid of them and arrive at the penultimate formula.
$$g(n,d) = \sum_{i=0}^{d} (-1)^i \binom{d}{i} \binom{n+d-1 - 10i}{d-1}$$
This function counts all numbers with \$d\$ digits having a digit-sum of \$n\$.
Now, what about the numbers with digit-sum less than \$n\$ ?  We can use a standard recurrence for binomials plus an inductive argument, to show that
$$\begin{align} \bar{h}(n,d) & = \binom{n+d}{d} \\ & = \binom{n+d-1}{d-1} + \binom{n+d-1}{d} \\ & = h(n,d) + \bar{h}(n-1,d)\end{align}$$
counts the number of partitions with digit-sum at most \$n\$.  And from this \$f\$ can be derived using the same arguments as for \$g\$.

Using this formula, we can for example find the number of heavy numbers in the interval from 8000 to 8999 as \$1000 - f(3, 20)\$, because there are thousand numbers in this interval, and we have to subtract the number of numbers with digit sum less than or equal to 28 while taking in to account that the first digit already contributes 8 to the digit sum.
As a more complex example let's look at the number of heavy numbers in the interval \$[1234, 5678]\$.  We can first go from 1234 to 1240 in steps of 1.  Then we go from 1240 to 1300 in steps of 10.  The above formula gives us the number of heavy numbers in each such interval:

\$[1240, 1249]\$
\$10 - f(1, 28 - (1+2+4))\$

\$[1250, 1259]\$
\$10 - f(1, 28 - (1+2+5))\$

\$[1260, 1269]\$
\$10 - f(1, 28 - (1+2+6))\$

\$[1270, 1279]\$
\$10 - f(1, 28 - (1+2+7))\$

\$[1280, 1289]\$
\$10 - f(1, 28 - (1+2+8))\$

\$[1290, 1299]\$
\$10 - f(1, 28 - (1+2+9))\$

Now we go from 1300 to 2000 in steps of 100:

\$[1300, 1399]\$
\$100 - f(2, 28 - (1+3))\$

\$[1400, 1499]\$
\$100 - f(2, 28 - (1+4))\$

\$[1500, 1599]\$
\$100 - f(2, 28 - (1+5))\$

\$[1600, 1699]\$
\$100 - f(2, 28 - (1+6))\$

\$[1700, 1799]\$
\$100 - f(2, 28 - (1+7))\$

\$[1800, 1899]\$
\$100 - f(2, 28 - (1+8))\$

\$[1900, 1999]\$
\$100 - f(2, 28 - (1+9))\$

From 2000 to 5000 in steps of 1000:

\$[2000, 2999]\$
\$1000 - f(3, 28 - 2)\$

\$[3000, 3999]\$
\$1000 - f(3, 28 - 3)\$

\$[4000, 4999]\$
\$1000 - f(3, 28 - 4)\$

Now we have to reduce the step size again, going from 5000 to 5600 in steps of 100, from 5600 to 5670 in steps of 10 and finally from 5670 to 5678 in steps of 1.
An example Python implementation (which received slight optimisations and testing meanwhile):
def binomial(n, k):
    if k < 0 or k > n:
        return 0
    result = 1
    for i in range(k):
        result *= n - i
        result //= i + 1
    return result

binomial_lut = [
    [1],
    [1, -1],
    [1, -2, 1],
    [1, -3, 3, -1],
    [1, -4, 6, -4, 1],
    [1, -5, 10, -10, 5, -1],
    [1, -6, 15, -20, 15, -6, 1],
    [1, -7, 21, -35, 35, -21, 7, -1],
    [1, -8, 28, -56, 70, -56, 28, -8, 1],
    [1, -9, 36, -84, 126, -126, 84, -36, 9, -1]]

def f(d, n):
    return sum(binomial_lut[d][i] * binomial(n + d - 10*i, d)
               for i in range(d + 1))

def digits(i):
    d = map(int, str(i))
    d.reverse()
    return d

def heavy(a, b):
    b += 1
    a_digits = digits(a)
    b_digits = digits(b)
    a_digits = a_digits + [0] * (len(b_digits) - len(a_digits))
    max_digits = next(i for i in range(len(a_digits) - 1, -1, -1)
                      if a_digits[i] != b_digits[i])
    a_digits = digits(a)
    count = 0
    digit = 0
    while digit < max_digits:
        while a_digits[digit] == 0:
            digit += 1
        inc = 10 ** digit
        for i in range(10 - a_digits[digit]):
            if a + inc > b:
                break
            count += inc - f(digit, 7 * len(a_digits) - sum(a_digits))
            a += inc
            a_digits = digits(a)
    while a < b:
        while digit and a_digits[digit] == b_digits[digit]:
            digit -= 1
        inc = 10 ** digit
        for i in range(b_digits[digit] - a_digits[digit]):
            count += inc - f(digit, 7 * len(a_digits) - sum(a_digits))
            a += inc
            a_digits = digits(a)
    return count

Edit: Replaced the code by an optimised version (that looks even uglier than the original code).  Also fixed a few corner cases while I was at it.  heavy(1234, 100000000) takes about a millisecond on my machine.

Hi, this solution works and it was a correct computation, however the time limit for small numbers was only 0.10 second, and time limit for big number was 0.35 second. The above code that you posted took about 1 second. Do you think there is any better way, and smart way of handling this, such that, to skip some numbers because we already know that the particular number would have a digit sum less than 7? Or maybe if there is a smarter way to handle this? For your information, this question was also tagged as a hard question.

@Bob:  The code is written in Python, and not optimised at all.  If you want it to be fast, write it in C.  But also in pure Python there is a lot of room for improvement.  The first thing that needs optimisation is the binomial() function.  There are also a few more things that can easily be improved.  I'll post an update in a few minutes.

Or we can just use a lookup table with precomputed f(m,n). Given that 200,000,000 is the limit, the memory usage should be minimal. (You have my +1 already).

@Moron: That certainly seems to be the best option -- I'll try it.

@Moron: I'd need to include the lookup table in the source code.  Usually f(d, n) is not called twice with the same parameters during one run of the program.

@Sven: My guess is the f(d,n) computation would be the bottleneck. So even if it is not called twice, having a lookup table will help. Of course, if you want to avoid putting the lookup table in the source, you could run your algorithm twice as a proof of concept. First time you time the run as you create the necessary entries, and second time you time the same run, but instead do a lookup instead of computing f(n,d). I guess it will give you a comparison too.

Can anyone explain how you derived the formula formula for f(d,n) ?

@AmolSharma: Sorry, I don't think anybody can explain how I derived this formula. :)  I didn't include an explanation at that time because I arrived at this in a rather esoteric way, and straightening out the details and writing a good explanation would have taken a significant amount of time.  Now, more than a year later, it would take even more time, so you'll have to work it out yourself.

Recurse, and use permutations.
Suppose we define a general function that finds the values between a and b with a heaviness more than x:
heavy_decimal_count(a,b,x)

With your example of a=8675 to b=8689, the first digit is 8, so throw it away - the answer will be the same as 675 to 689, and again from 75 to 89.
The average weight of the first two digits 86 is 7, so the remaining digits need an average weight of more than 7 to qualify. Thus, the call
heavy_decimal_count(8675,8689,7)

is equivalent to
heavy_decimal_count(75,89,7)

So our range for the (new) first digit is 7 to 8, with these possibilities:
7: 5-9
8: 0-9

For 7, we still need an average of more than 7, which can only come from a final digit of 8 or 9, giving us 2 possible values.
For 8, we need an average of more than 6, which can only come from a final digit of 7-9, giving us 3 possible values.
So, 2+3 yields 5 possible values.
What is happening is that the algorithm is starting with the 4-digit number and dividing it into smaller problems. The function would call itself repeatedly with easier versions of the problem until it has something it can handle.

So you are claiming Heavy(886,887) = Heavy(6,7)?

@Moron: No, because the first two 8s change the threshold for heaviness. In the example, the first two were 86, which average to 7 and thus don't change the threshold. If (8+8+x)/3 > 7, then x>5. So Heavy(886,887,7.0) == Heavy(6,7,5.0).

@Phil H, I don't think this idea as it stands would work: if you take 9900 and 9999, it would alter it to could the heavies between 0 and 99, taking e.g. 8 into account and 9908 is not a heavy number (@Aryabhatta).

Maybe you can skip many candidates in the interval from a to b by accumulating their "heaviness".
if you know the length of you number you know that every digit can change the heaviness by only 1/length.
So, if you start at one number which is not heavy you should be able to calculate the next number which will be heavy, if you increase them by one.
In your example above starting at 8680 avg=5.5, which is 7-5.5=1.5 point away from you heaviness border, you'd know that there are 1.5/(1/4)=6 numbers in between, which are NOT heavy.
That should to the trick!

Same goes for a row of "heavy" numbers. You can just calculate the number and skip them!

Just multiply everything by the number of digits and you will get rid of those pesky /lengths.

How about a simple recursive function? To keep things simple, it calculates all heavy numbers with digits digits, and a minimal digit sum of min_sum.
int count_heavy(int digits,int min_sum) {
  if (digits * 9 < min_sum)//impossible (ie, 2 digits and min_sum=19)
    return 0; //this pruning is what makes it fast

  if (min_sum <= 0)
      return pow(10,digits);//any digit will do,
      // (ie, 2 digits gives 10*10 possibilities)

  if (digits == 1)
  //recursion base
    return 10-min_sum;//only the highest digits

  //recursion step
  int count = 0;
  for (i = 0; i <= 9; i++)
  {
     //let the first digit be i, then
     count += count_heavy(digits - 1, min_sum - i);
  }
  return count;
}

count_heavy(9,7*9+1); //average of 7,thus sum is 7*9, the +1 is 'exceeds'.

Implemented this in python and it found all 9-digit heavy numbers in ~2 seconds. A little bit of dynamic programming could improve this.

C, for interval [a,b] it is O(b-a)
c(n,s,j){return n?c(n/10,s+n%10,j+1):s>7*j;}

HeftyDecimalCount(a,b){int r; for(r=0;a<=b;++a)r+=c(a,0,0); return r;}

//the exercise
main()
{
 printf("[9480,9489]=%d\n", HeftyDecimalCount(9480,9489));
 printf("[0,9489000]=%d\n", HeftyDecimalCount(9480,9489000));
 return 0;
}

//the results
//[9480,9489]=2
//[0,9489000]=66575

What does it mean "Standard loopholes"?

@Riker Here the tag is not  it is

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