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

Putting one tip per answer would be way too many answers.

Learn to think in Brainfuck. It's very different than anything else. Read and write, and rewrite, and rewrite lots of brainfuck programs. The language doesn't give you much to work with, so it's important to use what it does give you flexibly and efficiently. Don't let any abstractions get between you and the language--get in there and grapple with it.
Get very comfortable with nondestructive flow control. To get out of a decision loop, rather than zeroing the starting cell by copying it elsewhere and then copying it back after leaving the loop, it's often better to move the pointer to a pre-existing zero nearby. Yes, this means the pointer will be in different places depending on whether you went through the loop, but that also means those places probably have different arrangements of nearby zeros and nonzeros, which you can use to resynch the pointer location using another loop. This technique is fundamental to good Brainfuck programming, and various forms of it will constantly prove useful.
That and the fact that every > or < costs mean that the details of memory layout are important. Try out as many variations of your layout as you have patience for. And remember, your memory layout does not have to be a rigid mapping of data to locations. It can morph over the course of execution.
On a larger scale, consider and even try implementing a variety of different algorithms. Initially it will not be obvious exactly what algorithm will be best; it may not even be obvious what basic approach will be best, and it will probably be something different than what would be best in a normal language.
If you're dealing with large or variable-sized data, see if there's any way you can possibly deal with it locally, without having to keep track of how big it is or your numerical location within it.
The same data can be two different things. (Most often, a number or character and also a nonzero positional marker. But see random.b, where a bit counter doubles as the value of one cell of a cellular automaton.)
The same code can do two different things, and it's a lot easier to make it do so in a language where code is as generic as <+<. Be alert to such possibilities. In fact, you may occasionally notice, even in what seems to be a well-written program, that there are small portions that could be deleted entirely, nothing added, and the thing would, by happenstance, still run flawlessly.
In most languages, you use a compiler or interpreter frequently to check your program's behavior. The Brainfuck language demands greater conceptual control; if you need a compiler to tell you what your program does, you don't have a firm enough grasp of your program, and you probably need to stare at it some more--at least if you want to have a clear enough image of the conceptual halo of similar programs to be good at golf. With practice, you'll be producing a dozen versions of your program before you try running one, and by that point you'll be 95% sure that your shortest one will run correctly.
Good luck! Very few people bother to write Brainfuck concisely, but I think that's the only way the language can possibly justify continuing attention--as a stunningly obscure art form.

Reading this makes me want to try programming in Brainfuck now..

"you may occasionally notice ... that there are small portions that could be deleted entirely, nothing added, and the thing would, by happenstance, still run flawlessly." This is so true, especially for a beginner. I've only ever written one answer in BF as far as I can remember, yet its revision history contains at least 3 instances where I was playing with the program and randomly went, "hey, the program still works if I remove this bit!"

"Try out as many variations of your layout as you have patience for," or can brute-force :P

Really nice answer

Speaking of reading others' BF programs, you can also find BF programs on Rosetta Code or GitHub.

A few tips here:
Constants:
The Esolangs' constants page has an extremely useful list of the shortest ways to create specific values. I find myself consulting this page at least twice per program.
The start of everything:
+++[[<+>>++<-]>]

This sets up the tape in the format 3*n^2, which looks like
3 6 12 24 48 96 192 128 0 0'
Why is this so important?
Let's go down the list:

3 and 6 are boring
12: Close to 10 (newline) or 13 (carriage return). Can also be used for the counter for 0-9
24: Close to 26, the number of letters in the alphabet
48: ASCII for 0
96: Close to 97, ASCII for a
196 and 128: 196-128=64, close to 65, the ASCII for A.

From this one algorithm, we're at the start of practically every sequence in the ASCII range, along with a counter for each and a newline in easy reach.
A practical example:
Printing all uppercase and lowercase letters and digits.
With algorithm:
+++[[<+>>++<-]>]<<[-<->]<<<<++[->>+.>+.<<<]<--[>>.+<<-]

Without:
+++++++++++++[->+++++++>++>+++++>++++>+<<<<<]>+++++>[-<+.>>.+<]>>---->---[-<.+>]

We spend most of the bytes just initialising the tape in the second example. Some of this it offset by the extra movements in the first example, but this method clearly has the advantage.
A couple of other interesting algorithms in the same vein:
3*2^n+1:
+++[[<+>>++<-]+>]
Tape: 4 7 13 25 49 65 197 129 1 0'

This offsets the values by 1, which accomplishes a few things. It makes the 12 a carriage return, the 64 the actual start of the uppercase alphabet, and the 24 one closer to 26.
2^n:
+[[<+>>++<-]>]
Tape: 1 2 4 8 16 32 64 128

Because 64 is good for uppercase letters, 32 is the ASCII for space, and 128 can be used as the counter for 26 (130/5 = 26). This can save bytes in certain situations where digits and lowercase letters aren't needed.
Choose the implementation that suits the question:

Negative cells are almost always useful, and there's no reason to avoid them (unless it doesn't change your bytecount)
Almost the exact same thing with wrapping cells, even more so because many constants use wrapping.
Arbitrary cell sizes are useful for infinite math sequences, such as calculating the Fibonacci sequence infinitely (+[[-<+>>+>+<<]>]), or processing larger/negative numbers. The downside is that some common methods, such as [-] and [->+<] can't be relied upon, just in case the number is negative.
EOF as 0, -1 or no change. 0 is usually preferable, as you can loop over an entire input without extra checks. -1 is useful when looping over array structures. I haven't yet found a use for no change :(.

Keep track of what the frick is going on:
At all times you should have comments on where the pointer should be in relation to the data around it, and make sure that you know the range of possible values of each cell. This is especially important when you've split the pointer before a loop, because you'll want to join the two possibilities back together afterwards.
At any point, my code is littered with comments on every other line that look like this:
*0 *dat a_1 ?  0' !0 0*
 or
*0 *dat 0' ap1 0  !0 0*

Some extra advice is to assign symbols special meanings. In the above example, ' is where the pointer is, * means repetition in that direction, ? means a cell with unknown value, !0 means a non-zero cell, _ is a substitute for - and p is a substitute for +. or implies that the tape could look like either of representations, and needs to be handled as such.
Your symbol scheme doesn't necessarily have to be the same as mine (which has a few flaws), it just has to be consistent. This is also extremely useful when debugging, because you can run it up to that point and compare the actual tape to what you should have, which can point out potential flaws in your code.

My principal piece of advice would be don't.
OK, fine, you want something more useful than that. BF is already a very terse language, but what really kills you is arithmetic, which effectively needs to be done in unary. It's worth reading over the constants page in Esolang to pick out exactly how to write large numbers efficiently, and to exploit wrapping wherever possible.
Memory access is also very expensive. Since you're reading from a tape, you need to keep in mind where your head is moving at any given time. Unlike other languages where you can just write a, b, c, in bf you have to explicitly move the head some number of bytes left or right, so you must be mindful of where you store what. I'm pretty sure that organising your memory in the optimal way is NP-hard, so good luck with that one.

In this answer I'm going to refer to a specific cell on the tape many times. It doesn't matter which cell it is, but it's the same cell throughout the entire answer. For the purposes of this post, I'll call that cell "Todd".
When trying to set a cell to a constant value, it sometimes pays to not finish it immediately. For example, say you wanted Todd to contain 30. Later on in your code (which may modify Todd's value but never reads it) you come back to Todd. If Todd's value is 0, the program exits. Otherwise, Todd's value is printed forever.
According to the esolangs.org page of brainfuck constants (which could probably be the subject of a tip on its own!) the shortest way to get 30 is >+[--[<]>>+<-]>+. That leading > is only there to ensure that nothing to the left of the pointer is modified, but in this case we'll assume we don't care about that and drop it. Using that code, your code would look something like this:
+[--[<]>>+<-]>+(MISC. CODE)(GO TO TODD)[.]

You can think of the first chunk of code like this:
(SET TODD TO 30)(MISC. CODE)(GO TO TODD)[.]

But remember the last two characters in that chunk: >+. It's just as valid to think of it this way:
(SET TODD TO 29)(GO TO TODD)(ADD 1 TO TODD)(MISC. CODE)(GO TO TODD)[.]

Notice that you (GO TO TODD) twice! You could instead write your code this way:
(SET TODD TO 29)(MISC. CODE)(GO TO TODD)(ADD 1 TO TODD)[.]
+[--[<]>>+<-](MISC. CODE)(GO TO TODD)+[.]

Assuming that the number of bytes it takes to (GO TO TODD) is the same before, one less move == one less byte! Sometimes the fact that your starting position has changed does take that benefit away, but not always.

A tiny little tip for challenges without input. You can use , instead of [-], if you need to clear the cell quickly, as most of the interpreters (including the TIO.run one) will set the cell contents to EOF representation being zero. This makes programs a tiny bit unportable, but who cares about it in code golf anyway?


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

Related, but not a duplicate: Tips for golfing in Octave

Something that one must know before starting to golf:
In MATLAB calculations a character behaves the same as its ascii code.
'abc' - 'a'  % Returns: [0 1 2]
'123' - '0'  % Returns: [1 2 3]
'“' == 8220  % Returns: 1 (logical)
'a':'e'==100 % Returns: [0 0 0 1 0] (logical)

Shortening property names
In MATLAB, strings identifying properties can be shortened as long as it does not result in ambiguity.
plot(X,'C','k') % Ambiguous property found.
plot(X,'Co','k') % Expands to Color  (black)

This actually won me a challenge :)

Very nice, though the answer is correct I want to emphasize that this applies to the name of name, value pairs as shown above. (So not to things like sort(rand(4,1),'descend'))

It does apply to some of those things too, like conv(1:5,[1 1],'s') instead of conv(1:5,[1 1],'same')

Casting as char can be done by concatenation with a char:
x='a'+magic(5) % Array with character codes of several letters

char(x) % The standard way
['' x] % The compact way

Though it only saves one char, this can be used quite frequently.

Strings are just character row vectors. This means that instead of
for i=numel(str)
    a=str(i)
    ...
end

you can simply write
for(a=str)
    ...
end

First time I used this: https://codegolf.stackexchange.com/a/58387/32352

Related, but not identical tips for Octave.
A little known and little used feature of both MATLAB and Octave is that most builtin functions can be called without parentheses, in which case they will treat whatever follows it as a string (as long as it doesn't contain spaces). If it contains spaces you need quotation marks. This can frequently be used to save a byte when using disp:
disp('Hello, World!')
disp 'Hello, World!'

Other, less useful examples include:
nnz PPCG
ans = 4

size PPCG
ans = 1  4

str2num 12
ans = 12

I've actually used this twice in the "How high can you count?"-challenge:
strchr sssssssssssssst t

is equivalent to strchr('sssssssssssssst','t') and returns 15.
nnz nnnnnnnnnnnnnn

is equivalent to nnz('nnnnnnnnnnnnnn') and returns 14.
Stuff like gt r s works too (equivalent to 'r'>'s' or gt('r','s').

Roots of unity via discrete Fourier transform
Given a positive integer n, the standard way to generate the n-th roots of unity is
exp(2j*pi*(0:n-1)/n)

This gives the roots starting at 1 and moving in the positive angular direction. If order doesn't matter, this can be shortened to
exp(2j*pi*(1:n)/n)

Since exp(2j*pi/4) equals the imaginary unit (j), this can be written more compactly as follows (trick due to @flawr):
j.^(4*(0:n-1)/n)

or
j.^(4*(1:n)/n)

But the discrete Fourier transform provides an even shorter way (thanks to @flawr for removing two unnecessary parentheses):
fft(1:n==n)

which gives the roots starting at 1 and moving in the positive angular direction; or
fft(1:n==2)

which starts at 1 and moves in the negative angular direction.

Try all of the above here.

Great trick! You can even golf it down to fft(1:n==2)

@flawr I never know the precedence rules... Thanks!

nnz can sometimes save you a few bytes:

Imagine you want the sum of a logical matrix A. Instead of sum(sum(A)) or sum(A(:)), you can use nnz(a) (nnz implitictly applies (:)).
If you want to know the number of elements of an array, and you can be sure there are no zeros, instead of numel(x) you can use nnz(x). This is applicable for instance if x is a string.

Iteration over vectors in matrices.
Given a set of vector as matrix, you can actually iterate over them via a single for loop like
for v=M
    disp(v);
end

while "traditionally" you probably would have done it like
for k=1:n
    disp(M(:,k));
end

I've only learned about this trick just now from @Suever in this challenge.

2D Convolution Kernels
This is maybe a niche topic, but apparently some people like to use convolution for various things here. [citation needed]
In 2D following kernels are often needed:
0 1 0
1 1 1
0 1 0

This can be achieved using
v=[1,2,1];v'*v>1 %logical
v=[1,0,1];1-v'*v  %as numbers

which is shorter than
[0,1,0;1,1,1;0,1,0]

Another kernel often used is
0 1 0
1 0 1
0 1 0

which can be shortened using
v=[1,-1,1];v'*v<0   % logical
[0,1,0;1,0,1;0,1,0] % naive verison

Second kernel as numbers, same byte count: toeplitz([0 1 0])

I quite often find myself using meshgrid or ndgrid, let's say we want to compute a mandelbrot image, then we initialize e.g.
[x,y]=meshgrid(-2:1e-2:1,-1:1e-2,1)

Now for the mandelbrot set we need another matrix c of the size of x and y but initialized with zeros. This can easily be done by writing:
c=x*0;

You can also initialize it to another value:
c=x*0+3;

But you can actually save some bytes by just adding another dimension in meshgrid/ndgrid:
[x,y,c]=meshgrid(-2:1e-2:1,-1:1e_2,1, 0); %or for the value 3
[x,y,c]=meshgrid(-2:1e-2:1,-1:1e_2,1, 3);

And you can do this as often as you want:
[x,y,c1,c2,c3,c4,c5]=meshgrid(-2:1e-2:1,-1:1e_2,1, 1,pi,exp(3),1e5,-3i)

Note that in the meantime there is automatic broadcasting: In many cases the first example could be replaced by x=-2:1d-2:1;y=x'.

The built-in ones and zeros are a typically a waste of space. You can achieve the same result by simply multiplying an array/matrix (of the desired size) by 0 (to get the output of zeros) and add 1 if you want the output of ones.
d = rand(5,2);

%// Using zeros
z = zeros(size(d));

%// Not using zeros
z = d*0;

%// Using ones
o = ones(size(d));

%// Not using ones
o = 1+d*0

This also works if you want to create a column or row vector of zeros or ones the size of one dimension of a matrix.
p = rand(5,2);

z = zeros(size(p,1), 1);
z = 0*p(:,1);

o = ones(size(p, 1), 1);
o = 1+0*p(:,1);

If you want to create a matrix of a specific size you could use zeros but you could also just assign the last element to 0 and have MATLAB fill in the rest.
%// This
z = zeros(2,3);

%// vs. This
z(2,3) = 0;

I like to use ~(1:n) for 1-d zero vectors.

Counting the number of non zero elements in a matrix
zeronum(i)=nnz C;
zeronum(i)=nnz(C);
zeronum(i)=sum(C~=0);
zeronum(i)=sum(abs(C)>=eps);
zeronum(i)=numel(find(C~=0));
zeronum(i)=prod(size(find(C~=0)));

Horizontal replication is 3 copies, vertical replication is 2 copies
repmat([1,2;3,4],2,3)
kron(ones(2,3),[1,2;3,4])

Multiple variables, all initialized with the same data
[A,B,C,D]=deal([1 4;2 5;3 6]);

%%%%
A = [1 4; 2 5; 3 6];
B=A;
C=A;
D=A;

Declare a zero matrix of the same size as matrix A
X=0*A(:,1);
X=zeros(size(A));
X=zeros(size(A),'like',A);

Summation of a sequence of functions

For summing up functions f(x_n) where n is a vector of consecutive integers, feval is adviced rather than symsum.
Syms x;symsum(f(x),x,1,n);
Sum(feval(@(x)f(x),1:n));

Notice that an elementary operation .* and ./ is necessary instead of pairwise binary operations * and /
If the function can be naively written no one from either last ways is suitable.
for example if the function is log you can simply do: sum(log(1:n)) , which represents:
Sum(f(1:n));

for relatively sophisticated functions as log(n)/x^n you can do:
Sum(log(1:n)./5.^(1:n))

and even shorter in some cases when a function is longer as f(x)=e^x+sin(x)*log(x)/x....
Sum(feval(@(y)e.^(y)+sin(y).*log(y)./y,1:n))

that is remarkably shorter than sum(feval(@(y)e.^(1:n)+sin(1:n).*log(1:n)./(1:n),1:n))

Note: This trick can be applied for other inclusive operators as prod or mean

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

Related, but not a duplicate: Tips for golfing in MATLAB

Once you know, that a is free of zero values, using nnz(a) spares you 2 chars compared to numel(a).
Prefer a(a==0) to a(find(a==0)).
~t is shorter than t==0 , and even ~~t is shorter than t!=0.
0*(1:n) is shorter than zeros(1,n)
Generally, || and && , unlike many other operators, scalarize the result when the first argument is a scalar. For matrices, only non-empty matrices without elements equal to zero have the logical value of true.
Hence, we can do 0||m instead of all(all(m)) for any matrix.
Try with 0||[1 1;1 0] and 0||[1 1;1 1] to convince yourself.
When you are using a builtin a number of times, do a function handle to spare characters eg. f=@find . For short function names at least 3 occurrences justify this, for long ones - even with two occurrences.
When a function is a single statement, prefer f=@(n)dosomething(n) notation to function r=f(n)r=dosomething(n);end one.
Unfortunately, global variables have to be declared both in global scope and in each function using them. But there is an exception: anonymous @(n)... functions "see" all variables from the scope where they are called from.
It's possible to do f(a=0,b=0) instead of a=0;b=0;f(a,b).
This seems undocumented feature, but the order of evaluation is from left to right (checked at v. 3.8.1), you can do zeros(a=n,b=a*a) to both create a n x n^2 matrix and store it's row and column number in a and b variables.
The operator precedence table is your friend. Don't do b=(a==0) since b=a==0 is the same.

Using argument list:
Octave is capable to get default arguments so expressions can be evaluated in the argument list.
This feature is useful when we want to compute an expression and use it multiple times:
f = @(x,a=sort(x))a(a>.5);

One use case is when we use an indexed assignment to modify part of an array and we want to use the array:
a=[1 2 3 4]
a(2)=5;

But the expression (a(2)=5) returns a(2), or the expression (a([1 3])=4) returns a two elements array. Neither returns the whole array. We can use the argument list:
f=@(a=[1 2 3 4],b=a(2)=5)a;

Here the result of the indexed assignment is stored into a dummy variable b and the function returns the array.

I do not remember in what challenge I saw it someone use (please tell us=), but I found this a neat trick:
Usually if you add matrices you have to have the same size, but for one dimensional (1xn and nx1) matrices there is a shortcut (that does not work in Matlab):
z = (1:5)+(6:10)';

produces the same effect as
[x,y]=meshgrid(1:5,6:10);
z = x+y;

Then something that pawel.boczarski already mentioned: In Octave you can (while you cannot in Matlab) define auxiliary variables within function handles, AND a variable assignment itself has the value of the assignment so you can really shorten code (well this is an useless example but you'll get the trick):
f=@(n)(z=n+1)*z; %returns (n+1)^2

Then another trick (also applicable in Matlab) is abusing strings for storing (hardcoded) numbers (this neat trick is stolen from feersum), you just need something that interprets the string as number, which is as easy as e.g. adding zero:
a = 'abc';
a+0 %returns
[97 98 99]

Or
sum('abc') == 294

I believe it's supposed to be a+0, not a+'0'. Other than that the tips are nice =)

Right, thanks! PS: Could you add the += -= /= etc operators in your list below?

+a is shorter than a+0

-In Octave it is possible to apply indexing on a temporary expression, a feature that prohibited in MATLAB and this feature is very useful for golfing.
example:
Octave: [1 23 4 5 7](3:4)       and its MATLAB equivalent: a=[1 23 4 5 7];a(3:4)
Octave: hilb(4)(4:5,4:5)        and its MATLAB equivalent: h=hilb(4);h(4:5,4:5)
Octave: {1,4,{4 5 6},[7 ;3]}{3} and its MATLAB equivalent: a={1,4,{4 5 6},[7 ;3]};a{3}
Octave: num2cell([1 2 3 4]){:} for creation of comma separated list
Octave: a'(:)'
-Sometimes in an anonymous function as of a normal function we require to evaluate multiple expressions,that include assignment,
One approach is that we can place each expression in a cell(since cell can contain object of multiple types ) and when we need the value of each expression we can use indexing to extract that element.
{1,4,{4 5 6},[7 ;3]}{3}
or
{a=1,b=4,c={4 5 6},[b ;3]}{4}

@StewieGriffin Nice tip! Answer updated!

Skip semicolons!
I'll use this answer to illustrate the point.
The original code was:
function f(x);if~movefile('f.m',x);disp("+-+\n| |\n+-+");end

After removing semicolons, it could be reduced to the following, saving three bytes:
function f(x)if~movefile('f.m',x)disp("+-+\n| |\n+-+")end

This can be used quite a few places, and stuff you don't even try because it looks like a syntax error often works.

stuff you don't even try because it looks like a syntax error often works Octave in a nutshell

This is a simple, but useful one.
In Octave, but not MATLAB, you can do as in C++:
x = 0  ->  x = 0
x++    ->  ans = 0
x      ->  x = 1
++x    ->  ans = 2
x      ->  x = 2

Use the e function instead of ones  or zeros
Octave has an e function, which I don't think is very well known. It's like onesor zeros, but it produces copies of the number e. And it's shorter. This function can be useful sometimes:

Instead of ones(m,n) you can use ~~e(m,n) if you can get away with having true instead of 1. Or even use e(m,n) directly if all you need is a nonzero value, not specifically 1 (for example if you are going to convert to logical later).
Instead of zeros(m,n) you can use ~e(m,n) if false is acceptable instead of 0; or +~e(m,n) to produce actual zeros.

I'm trying to imagine why this is in Octave. seems weird to me. Or it did until I found that the same is true for other random constants like pi, I (1i), NaN, Inf, eps, realmax, realmin...

@Giuseppe Indeed. To me e is the weirdest because it doesn't even exist as a scalar in Matlab (the others do)

Another simple, but useful one (not possible in MATLAB):
Assign the same value to several variables:
a=b=c=0;

Use rows(a) instead of size(a,1)

Use eval!
Inspired by Luis Mendo's answer here.

Anonymous functions are in most cases shorter than creating a script that needs one or more calls to input(''). The downside is that loops and variable modifications (such as swapping two elements in a matrix) is impossible cumbersome.
With eval, you can fetch the input as you do with a normal anonymous function, and run the script as you do with a normal script:
Consider this:
c=(i=@input)('');N=i('');A=i('');for C=c,A(flip(k))=A(k=[x=find(A==C),N^2+1-x]);end,A

Compared to this:
@(c,N,A)eval('for C=c,A(flip(k))=A(k=[x=find(A==C),N^2+1-x]);end,A')

The code is identical, but the input section is much shorter.

This can also be used to modify input variables, like this (credit to Luis Mendo for this!):
f(x)eval('x([1,4])=x([4,1])`;

The code is identical Only uglier, slower, and less readable. What more can you ask for? :-D

Related, but not identical tips for MATLAB.
A little known and little used feature of Octave is that most builtin functions can be called without parentheses, in which case they will treat whatever follows it as a string (as long as it doesn't contain spaces). If it contains spaces you need quotation marks. This can frequently be used to save a byte or two when using disp. All the following work, and gives the same result:
disp('Hello')
disp Hello
disp"Hello"

If you have spaces, then you must have the quotation marks:
disp('Hello, World!')
disp"Hello, World!"

Other, less useful examples include:
nnz PPCG
ans = 4

size PPCG
ans = 1  4

str2num 12
ans = 12

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


text:
Tips for golfing in VBScript
What general tips do you have for golfing in VBScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to VBScript. Please post one tip per answer.
Thanks to Marcog for the original idea. :)

My friends would like this :)

Just in case anyone is editing vbs in notepad and just running the file - you can save yourself from having to see lots of MsgBoxs by replacing the MsgBoxs with WScript.Echos and running the VBScipt file in cmd.exe with CScript (CScript C:\filepath\file.vbs)

Oh and you can add syntax highlighting for VBScript (or any VB derivative) using the markdown notation <!-- language-all: lang-vb -->

Use an empty variable instead of ""

Uninitialized variables are set to a special value: empty.  When empty is cast to a string it becomes "".
Contrived example (using z instead of ""):
s=InputBox(z)
For i=1To 5
    For j=1To i
        r=r&s
    Next
    MsgBox r
    r=z
Next

For numeric types Empty is 0, and for booleans it is false.  This can cut down on initialization code.
a=inputbox("Enter Starting Value")
b=a
while done=0
    i=i+1
    b=b*2
    done=(b>10000 or i>10)
wend
msgbox "Your "&a&" rabbit(s) have turned into "&b&" rabbit(s) in "&i&" years."

Shorter IF Then: save 10 bytes
If you terminate an IF/THEN clause with a carriage return, you don't need to use an END IF.
Example:
For x=1 to 1
  IF x=1 THEN MSGBOX "No Error"
Next

Use IIf instead of If...Then
IIf() is essentially a ternary operator. You can potentially save quite a few bytes.
For example:
var = "World"

If foo Then
    MsgBox "Hello" & var
Else
    MsgBox "Goodbye" & var
End If

Vs.
MsgBox IIf(foo, "Hello", "Goodbye") & "World"

Note: VBA only. VBScript doesn't support this one.

Iff() isn't an intrinsic VBScript function, thus it's not supported.

Well, I'll be damned. I can't believe I never knew knew that. You're right. I'm going to leave it here because the tip will be useful for vba folks.

Unfortunately Iff() isn't an intrinsic VBA function as well :D

Yes it is. Oh. Lol. Damned typo.

Use Line Separators
Newlines count as two bytes ("\n"), but a colon is only one.
For i = 0 To 10
    MsgBox "Hello"
Next

Vs.
For i = 0 To 10: MsgBox "Hello": Next

Note: You can't use the line separator for If statements.

Newlines only count as one byte on Unix Systems, however, Windows Systems use \r\n (Which is two bytes, 13 and 10 respectively)

Condense For statements
In For statements (and in fact any statement comprised of a " or numeric literal followed by a reserved command) the space that separates any numeric and a following word may be removed
This means that
For i = 1 To 100 Step 2
...
Next

May be condensed down to
For i=1To 100Step 2
...
Next

and following this logic,
If t = "TEST" Then ...

may be condensed to
If t="Test"Then ...


text:
Just one note - musical instrument synthesizing
Statement
The task is to synthesize sound (one note played) of some musical instrument (of your choice) using function in some general purpose programming language (of your choice).
There are two goals:

Quality of the resulting sound. It should resemble the real instrument as fine as possible;
Minimality. Keeping the code under 1500 bytes is adviced (less if there's only basic sound generation).

Only generation function need to be provided, boilerplate is not counted for the score.
Unfortunately no score can be calculated for the sound fidelity, so there can't be strict rules.
Rules:

No dependance on sample libraries, specialized music generation things;
No downloading from network or trying to use microphone or audio card's MIDI or something too external like this;
The code size measure unit is bytes. File can get created in current directory. Pre-existing files (coefficient tables, etc) may exist, but their content is added to the score + they must by opened by name.
The boilerplate code (not counted to score) receives array (list) of signed integers and only deals with outputting them.
Output format is signed little endian 16-bit words, 44100 samples per seconds, with optional WAV header. No trying to output compressed audio instead of plain wav;
Please choose different instruments for synthesizing (or other quality vs code size category for the instrument); but don't initially tell what are you simulating - let other users to guess in comments;
Electronic instruments are discouraged;
Drum is an instrument. Human voice is an instrument.

Boilerplates
Here are boilerplates for some languages. You can write similar boiler plate for your language as well. Commented out "g" function is just for a demo (1 second 440 Hz sine tone).
C:
//#!/usr/bin/tcc -run
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

/*
void g(signed short *array, int* length) {
    *length = 44100;
    int i;
    for(i=0; i<44100; ++i) array[i]=10000*sin(i*2.0*3.14159265358979323*440.0/44100.0);
}
*/

// define your g here

signed short array[44100*100];
int main(int argc, char* argv[]) {
    int size=0;
    memset(array,0,sizeof array);
    // i(array); // you may uncomment and implement some initialization
    g(array, &size);
    fwrite("RIFFH\x00\x00\x00WAVEfmt\x20\x12\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00\x00\x00LIST\x1a\x00\x00\x00INFOISFT\x0e\x00\x00\x00GolfNote\0\0\0\0\0\0data\x00\xff\xff\xff", 1, 80, stdout);
    fwrite(array, 1, size*sizeof(signed short), stdout);
    return 0;
}

Python 2:
#!/usr/bin/env python
import os
import re
import sys
import math
import struct
import array

#def g():
#    return [int(10000*math.sin(1.0*i*2*3.141592654*440.0/44100.0)) for i in xrange(0,44100)]

# define your g here

sys.stdout.write("RIFFH\x00\x00\x00WAVEfmt\x20\x12\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00\x00\x00LIST\x1a\x00\x00\x00INFOISFT\x0e\x00\x00\x00GolfNotePy\0\0\0\0data\x00\xff\xff\xff");
array.array("h", g()).tofile(sys.stdout);

Perl 5:
#!/usr/bin/perl

#sub g() {
#    return (map 10000*sin($_*3.14159265358979*2*440.0/44100.0), 0..(44100-1))
#}

# define you g here

my @a = g();
print "RIFFH\x00\x00\x00WAVEfmt\x20\x12\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00\x00\x00LIST\x1a\x00\x00\x00INFOISFT\x0e\x00\x00\x00GolfNotePl\0\0\0\0data\x00\xff\xff\xff";
print join("",map(pack("s", $_), @a));

Haskell:
#!/usr/bin/runhaskell

import qualified Data.Serialize.Put as P
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8
import Data.Word
import Control.Monad

-- g :: [Word16]
-- g = map (\t->floor $ 10000 * sin(t*2*3.14159265358979*440/44100)) [0..44100-1]
-- insert your g here

main = do
    B.putStr $ C8.pack $ "RIFFH\x00\x00\x00WAVEfmt\x20\x12\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00\x00\x00LIST\x1a\x00\x00\0INFOISFT\x0e\x00\x00\x00GolfNote\0\0\0\0\0\0data\x00\xff\xff\xff"
    B.putStr $ P.runPut $ sequence_ $ map P.putWord16le g

Example
Here's ungolfed C version modeled after piano sound:
void g(signed short *array, int* length) {
    *length = 44100*5;
    int i;

    double overtones[]={4, 1, 0.5, 0.25, 0.125};

    double freq[]   = {393, 416, 376, 355, 339, 451, 555};
    double freq_k[] = {40,  0.8,  1,  0.8,   0.7,  0.4, 0.25};
    double corrector = 1/44100.0*2*3.14159265358979323;

    double volumes_begin[] ={0,     0.025, 0.05,   0.4};
    double volumes_end  [] ={0.025, 0.05,  0.4,    5};

    double volumes_kbegin[]={0,     1.8,   1,      0.4};
    double volumes_kend [] ={1.8,     1,   0.4,    0};

    for(i=0; i<44100*5; ++i) {
        int j;
        double volume = 0;

        for(j=0; j<sizeof volumes_begin/sizeof(*volumes_begin); ++j) {
            double t = i/44100.0;
            if(t>=volumes_begin[j] && t<volumes_end[j]) {
                volume += volumes_kbegin[j]*(volumes_end[j]-t  )/(volumes_end[j]-volumes_begin[j]);
                volume += volumes_kend[j]  *(t-volumes_begin[j])/(volumes_end[j]-volumes_begin[j]);
            }
        }

        int u;
        for(u=0; u<sizeof freq/sizeof(*freq); ++u) {
            for(j=0; j<sizeof overtones/sizeof(*overtones); ++j) {
                double f = freq[u]*(j+1);
                array[i] += freq_k[u]*volume*10000.0/(f)/1*overtones[j]*sin(1.0*i*corrector*f);
            }
        }
    }
}

It scores approximately 1330 bytes and provides poor/mediocre quality.

To be an appropriate codegolf challenge, you are required to define an objective winning criterion. (Given the nature of this challenge, I think it'll have to be "popularity contest", i.e. most number of upvotes.)

The example doesn't seem to work. The output is completely distorted and has many break-ups in it. Compiled in MinGW with "gcc -o piano.exe piano.c" and executed with "piano.exe >piano.wav". Even using the simple 440 Hz tone g function has the same result. BTW, you can use M_PI in place of your huge numbers. It's defined in math.h.

@Mike C, The beginning of output of C boilerplate with uncommented q should look like this: http://pastebin.com/ZCB1v7QQ . Is your host big-endian?

No, I'm using MinGW so I'm x86. I'll try it on one of my Linux boxes. I don't understand why I'm having a problem though. Strange.

does $><<7.chr in Ruby count? :P for 9 characters! or $><<?\a for 7 chars

Don't understand the question. Typed that in ruby1.9.1 started in console, got no response... (I'm not a Ruby programmer). Score counting is simple: 1. Remove everything expect of the function that does the actual math and it's dependencies, 2. Save this to file, 3. See the file size.

@Vi. Maybe it only works in Windows... ASCII 7 is the 'bell' character, which is supposed to make a "beep" noise :P

@Doorknob, Even if it works, it's not by the rules: No dependance on sample libraries, specialized music generation things, such as system beep sound, which can be considered as a sample and OS as musical library in this context.

Java
My boilerplate plays the sound. I could golf g() a bit more, but it's currently at 273 chars which is well under 1500. I originally wrote this for 16kHz for a 4kB game and had to tweak the constants a bit to get the right tonal qualities at 44.1kHz playback, but I'm reasonably happy with it.
import java.io.*;
import javax.sound.sampled.*;

public class codegolf13003 {
    byte[]g(){byte[]d=new byte[88000];int r=1,R=1103515247,b[]=new int[650],i,o,s,y;for(i=0;i<b.length;r*=R)b[i++]=0x4000+((r>>16)&0x3fff);for(i=o=0;i<d.length;o=s){s=(o+1)%b.length;y=(b[o]+b[s])/2*((r&0x10000)<1?-1:1);r*=R;d[i++]=(byte)(b[o]=y);d[i++]=(byte)(y>>8);}return d;}

    public static void main(String[] args) throws Exception {
        byte[] data = new codegolf13003().g();
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 1, 2, 44100, false/*LE*/);
        AudioInputStream stream = new AudioInputStream(bais, format, data.length / 2);
        new Previewer().preview(stream);
    }

    static class Previewer implements LineListener {
        Clip clip;

        public void preview(AudioInputStream ais) throws Exception {
            AudioFormat audioFormat = ais.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, audioFormat);

            clip = (Clip)AudioSystem.getLine(info);
            clip.addLineListener(this);

            clip.open(ais);
            clip.start();
            while (true) Thread.sleep(50); // Avoid early exit of program
        }

        public void update(LineEvent le) {
            LineEvent.Type type = le.getType();
            if (type == LineEvent.Type.CLOSE) {
                System.exit(0);
            }
            else if (type == LineEvent.Type.STOP) {
                clip.close();
            }
        }
    }
}

Further reading: Karplus-Strong synthesis.

To start without PulseAudio I use this: java -Djavax.sound.sampled.Clip=com.sun.media.sound.DirectAudioDeviceProvider -Djavax.sound.sampled.Port=com.sun.media.sound.PortMixerProvider -Djavax.sound.sampled.SourceDataLine=com.sun.media.sound.DirectAudioDeviceProvider -Djavax.sound.sampled.TargetDataLine=com.sun.media.sound.DirectAudioDeviceProvider codegolf13003

Assuming you wanted some percussions, but unsure which one exactly. It sounds a bit too "electronical".

@Vi., I'll leave it a while for other people to say which instrument they think I'm aiming for before I unveil it.

Since people have had a few days to guess, I'm going to spill the beans. The intended instrument is a snare.

Can you give a link to actual recorded sample to compare?

@Vi., I might be able to extract one from a MIDI sound bank, but I'll have to check the licence...

C
Here's the g() function, without the boilerplate.
void g(signed short *array, int* length)
{
    short r[337];
    int c, i;

    *length = 44100 * 6;
    for (i = 0 ; i < 337 ; ++i)
        r[i] = rand();
    *array = *r;
    for (i = c = 1 ; i < *length ; ++i) {
        array[i] = r[c];
        r[c] = (r[c] + array[i - 1]) * 32555 / 65536;
        c = (c + 1) % 337;
    }
}

An interesting experiment is to play with the first loop that initializes a beginning sequence of random values. Replacing the call to rand() with i*i changes the character of the sound in a plausible way (that is, it sounds like the synthesis is imitating a different member of the same instrument family). i*i*i and i*i*i*i give other sound qualities, though each one gets closer to sounding like rand(). A value like i*327584 or i*571, on the other hand, sounds quite different (and less like an imitation of something real).

Another minor variation of the same function comes even closer to another instrument, or at least it does to my ear.
void g(signed short *array, int* length)
{
    int i;

    *length = 44100 * 6;
    for (i = 0 ; i < 337 ; ++i)
        array[i] = rand();
    for ( ; i < *length ; ++i)
        array[i] = (array[i - 337] + array[i - 1]) * 32555 / 65536;
}

Edited to Add:  I hadn't been treating this as a code golf question, since it's not flagged as such (beyond the 1500-char limit), but since it's been brought up in the comments, here's a golfed version of the above (96 characters):
g(short*a,int*n){int i=0;for(*n=1<<18;i<*n;++i)
a[i]=i>336?32555*(a[i-337]+a[i-1])/65536:rand();}

(I could get it down below 80 characters if I could change the function interface to use global variables.)

Karplus-Strong string. Sounds like a steel string to me.

@PeterTaylor my thought exactly. The bottom variant, on the other hand, sounds to me exactly like the gut (or nylon) string of a harpsichord. It just needs the thunk of the returning quill afterwards to complete the illusion.

After removing the whitespace and shortening array, length, void and signed in the second code I got the score: 113 bytes. Very nice try. And the sound is rather good.


text:
Tips for golfing in AWK
What general tips do you have for golfing in AWK? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to AWK. Please post one tip per answer.

These are not in any particular order, and some of them might even apply to other languages too, but not to a lot of them I think.

You can sometimes use awk's simple string concatenation to assemble numbers
z=x*10+y and a=b*10
become
z=x y and a=b 0
You can use the ~ operator (match pattern on the right side) to compare numbers or strings if you know that the two parts meet certain conditions
for instance if you know that a will always be smaller than or equal to b, you can replace
a==b
with
a~b
or if you want to check for an empty string s (which means that s isn't allowed to be "0" either), and you haven's changed the variable X before, so that it is still undefined, you could use
X~s
instead of
s==""
if you want to check if i is an integer you can use
i!~/\./ (i doesn't contain a dot)
instead of
i==int(i)
You can swap two numbers in a single command
t=a;a=b;b=t
becomes
a+=b-(b=a)
saving one character
If you don't need them as input anymore, you can use the input variables $1, $2, $3, ... as an array. So instead of writing a[n] you can just write $n. Sometimes even while reading the input from these you can use the already handled ones as a stack for something.
You can make good use of the built-in separators FS (space, if not changed by you) and RS (newline) when concatenating strings
a=$1" "$2
becomes
a=$1FS$2
or even better
a=$1"\n"$2
becomes
a=$1RS$2
If there is no input and you use the BEGIN block, you can try to use the END block instead. Depending on the judge it works. If you test it, you have to press Ctrl-D (end of input) to access the END block.
If you want to skip the first line, you can use
C++
instead of
NR>1
if you won't be using C anywhere in your program.

Techniques

Thanks to Peter Taylor for pointing out the language-generic version of this question for which I did not bother to search. I'll try to limit this answer to things that are not available in other C-like languages.
The frequently accessed builtin variables are 2 characters long. Find the break-even point for assigning to a temp variable. a=$1; is five characters, so it breaks even after five uses of $1;
Remember that the default action for a matching pattern is print $0, so if you get what you want printed into $0, just use
1

Getting creative with operator ordering can save you some parentheses or extra statements
for(i=1;i<=NF;i++)print$i;

vs
for(;i<NF;)print$++i;

Examples

A solution to Do We Sink or Swim? in 70 characters:
n{for(;NF;NF--)s+=$NF;n--}NR==1{n=$1;p=$3}END{print p<s?"Swim":"Sink"}

A solution to The Floating Horde in 44 characters:
{for(i=NF;i>1;){n=int($i/2);$i%=2;$--i+=n}}1

Summary
awk will probably never outgolf APL, Golfscript, J, or K, but you can quite consistently beat other high level languages.

The question asks for tips which are somewhat specific to Awk. The ternary operator is included in the tips for all languages.

@laindir : for(;i<NF;)print$++i; can become NF=NF OFS='\n'

To read and process a number on each line:
{
    n=$1;
    print(n*n);
    // OR printf("%d\n",n*n);
}

Compressed form (Length = 14):
{print($1*$1)}       // thanks due to @manatwork

Shorter Code (Length = 7)
1,$0^=2              // thanks due to @llhuii

When compiled and run in gawk with inputs:
1
2
3

Output:
1
4
9

Why the variable? And why the parenthesis? {print$1*$1} is shorter.

1,$0^=2 is shorter

For any input different from 0 or null, $0^=2 does the same. Careful that when using 1,$0^=2, blank lines return 0.

@PedroMaimere : this solves it `echo "1\n2\n3\n\n4\n5" | mawk '!NF || ($!^=2)^'
1
4
9
16
25…. or not write any numbers at allmawk '!NF || ($!*=$!)^_'`

@PedroMaimere : better yet : `echo "0\n1\n2\n3\n\n4\n5" | mawk '!NF || ($!^=++NF)^'
0
1
4
9
16
25- actual input lines containing a zero will print out zero squared, while blank lines remain as such. u can directly square hexes withmawk:echo 0x4F0FFF9 | mawk '($!^=++NF)^' CONVFMT='%.f'
6872912880599089`

awk '!NF++||($_^=NF)_' this handles both 0 and blank line inputs just fine

Truthy and falsey values
Boolean evaluation is somehow flexible in AWK, and this is awesome. Remember: AWK's basis is pattern{action}; when pattern is true, it executes action.
Besides doing their business, some built-in functions return values, e.g., split(), gsub(). They are also useful as a pattern when manipulating the input.
Examples of truthy and falsey variables
I tried to come up with valuable examples of how to exploit truthy/falsey variables. This is non-exhaustive. Anyone is encouraged to share more examples, and I would add them to this list.
Try it online!
"strings are truthy"{print 1}  # truthy; strings are always truthy, except for the null string

-0xF3e10{print 2} # truthy; numbers different from zero are truthy

0{print 3}  # falsey; zeroes are false: 0, -0, +0, 0x0, 0000... expect for "0", which is a string
0 b{print 4}  # truthy; now the number 0 is concatenated to a null string (a variable still not assigned), thus converting it to "0"
""{print 5} # falsey; null string
b{print 6}  # falsey; b is null (a variable not assigned)

a=@/x/{print 7} # truthy; defining a strongly typed regex constant. Different from a /x/ pattern
/x/{print 8}  # falsey; /x/ does not match the input

c["test"]{print 9}   # falsey; undefined item of array, null
c["test"]++{print 10} # falsey; variable is evaluated before increment
c["test"]{print 11}   # truthy; now, c["test"] equals 1
c["test2"]{print 12}  # falsey; although the c array now exists, the "test2" element does not

Result:
1
2
4
7
11

one of the great things about awk's sigils $ is that string concat can be even more condensed than having to use the built-ins as buffer zones - say, u wanna prepend a zero to the full row:

 _=0
$_=_$_

jot -c 8 75  | gawk '$_=+_$_'

0K
0L
0M
0N
0O
0P
0Q
0R

and you wanna make patterns out of it ?
jot -c 8 75  | gawk '$_=_++$_'  # integers

0K
L 1
M  2
N   3
O    4
P     5
Q      6
R       7

jot -c 8 75  | gawk '$_=_++$++_' # even numbers

K 0
L   2
M     4
N       6
O         8
P           10
Q             12
R               14

jot -c 8 75  | gawk '$_=++_$++_'  # odd numbers

K 1
L   3
M     5
N       7
O         9
P           11
Q             13
R               15

And honestly, what language can repeat stings THIS easily :
jot 20 | mawk 'NF=OFS=$_'

1
22
333
4444
55555
666666
7777777
88888888
999999999
10101010101010101010
1111111111111111111111
121212121212121212121212
13131313131313131313131313
1414141414141414141414141414
151515151515151515151515151515
16161616161616161616161616161616
1717171717171717171717171717171717
181818181818181818181818181818181818
19191919191919191919191919191919191919
2020202020202020202020202020202020202020

or can decode arbitrary precision hex with this few keystrokes :
echo 0xEDCFAB12EDCFAB127659438976594389EDCFAB |

gawk -nM '$_=+$_'

5303367068685265828195859270035065456131166123


text:
How many times is rectangular array A embedded in rectangular array B?
Given two rectangular arrays, A and B, let's say that A is embedded in B if A can be obtained from B by deleting some (or none) of the rows and columns of B.
Write a program with the following I/O:
Input: two arbitrary rectangular arrays of letters (a-z), as a string from stdin.
Output: the number of embeddings of the first array in the second array, followed by a "text picture" of each embedding (showing deleted elements replaced by dots).
(This is a two dimensional generalization of my old question Is string X a subsequence of string Y?)
Example:
input:
abb
aba

ababb
aabba
babab
abbaa

output  (if I haven't missed any):
5

a..bb
a..ba
.....
.....

ab.b.
.....
.....
ab.a.

ab..b
.....
.....
ab..a

.....
a.bb.
.....
a.ba.

.....
.abb.
.aba.
.....

The winner is the shortest such program (least number of characters).

There are only 5 embeddings. Your first one is the same as your fourth one.

APL (160)
{∆,⍨⍴∆←⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨⊃¨∘.∧/¨∆/⍨⍺∘≡¨⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆←,⊃∘.,/⊂¨¨K{⍵=0:⊂⍺/1⋄~(⍳⍺)∘∊¨⍵{⍺=1:(⍳⍵)⋄∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵}⍺}¨(K←⍴⍵)-⍴⍺}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬

Output:
      {∆,⍨⍴∆←⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨⊃¨∘.∧/¨∆/⍨⍺∘≡¨⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆←,⊃∘.,/⊂¨¨K{⍵=0:⊂⍺/1⋄~(⍳⍺)∘∊¨⍵{⍺=1:(⍳⍵)⋄∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵}⍺}¨(K←⍴⍵)-⍴⍺}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬
abb
aba

ababb
aabba
babab
abbaa

 5  .....  .....  ab..b  ab.b.  a..bb
    a.bb.  .abb.  .....  .....  a..ba
    .....  .aba.  .....  .....  .....
    a.ba.  .....  ab..a  ab.a.  .....

Explanation:

{...}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬: read the two arrays from the keyboard, and return them as two matrices. Reduce the following function over the list of the two matrices.
∆{...}¨(∆←⍴⍵)-⍴⍺: get the height and width of each of the matrices. In both the width and the height, get a list of possible lines to drop.

⍵=0:⊂⍺/1: if the matrices are the same length in a dimension, never drop any lines from that dimension. Otherwise:
⍺=1:(⍳⍵)⋄: If the difference is one, try to drop each line
∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵: otherwise, drop each possible combination of ⍺ lines.

∆←,⊃∘.,/⊂¨¨: combine each height mask with each width mask, giving all possible combinations to make the second list the size of the first.
⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆: for each possible combination, remove those lines from the second matrix.
∆/⍨⍺∘≡¨: drop all the ones that are not equal to the first matrix, giving the solutions.
⊃¨∘.∧/¨: for each of the possible solutions, make a matrix with 0 where a dot should go and 1 where the corresponding character from the first matrix should go.
⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨: for each of these, flatten both the second matrix (,⍵) and the matrix of dots (,⍺), and take either the character or a dot for each position ({⍺:⍵⋄'.'}¨). Then reshape it to the shape it had before ((⍴⍵)⍴).
∆,⍨⍴∆: give the amount of solution, and each solution.

Thanks for the explanation! To someone unacquainted with APL, it would also be useful to know what exactly is to be typed for input via the keyboard. (I'd like to run your program with an online interpreter.)

@r.e.s. It will not run in ngn/apl, because it lacks support for some functions that are used. I use Dyalog APL (http://www.dyalog.com), if you're on Windows you can download a free version and then you can just paste this line in its command window and then type the arrays in the same format as in the question (i.e., array, blank line, array, blank line). Note: if you do this, do not paste them because the Dyalog interpreter seems to have a bug and will eat the blank lines. [1/2]

@r.e.s. If you want to try it without installing anything, everything but the input routine will run on TryAPL (http://www.tryapl.com). To make that work, you have to define your two matrices first (i.e. type a←2 3⍴'abbaba', enter, b←4 5⍴'ababbaabbababababbaa', enter). Then remove the part that does input ({×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬) at the end and put a b after the /. [2/2]

The fact that this APL program is so long frightens me

@Claudiu: APL frightens me in general.

I know I am late as heck here, but do you need parentheses around ⍳⍵?

@Zacharý Even later: No you don't.

Mathematica, 186 chars
{a,b}=Characters/@StringSplit@InputString[]&~Array~2;{Length@#,Grid/@#}&[ReplacePart[b,Except[$|##&@@Tuples@#,{_,_}]->"."]&/@Select[Tuples[Subsets/@Range/@Dimensions@b],b[[##]]&@@#==a&]]

Example:
In[1]:= {a,b}=Characters/@StringSplit@InputString[]&~Array~2;{Length@#,Grid/@#}&[ReplacePart[b,Except[$|##&@@Tuples@#,{_,_}]->"."]&/@Select[Tuples[Subsets/@Range/@Dimensions@b],b[[##]]&@@#==a&]]
? abb aba
? ababb aabba babab abbaa

Out[1]= {5, {a . . b b, a b . b ., a b . . b, . . . . ., . . . . .}}
             a . . b a  . . . . .  . . . . .  . a b b .  a . b b .
             . . . . .  . . . . .  . . . . .  . a b a .  . . . . .
             . . . . .  a b . a .  a b . . a  . . . . .  a . b a .

What world are we living in where Mathematica almost beat APL?

@Claudiu: one in which Mathematica has built-ins for just about anything, but their names are very long.

Python 2 with Numpy, 342 chars
from numpy import*
from itertools import*
import sys
S=str.split
C=combinations
R=range
a,b=[mat(map(list,S(x)))for x in S(sys.stdin.read(),'\n\n')]
n,m=b.shape
o,p=a.shape
z=[]
for i in product(C(R(n),o),C(R(m),p)):
 i=ix_(*i);e=b[i]
 if all(a==e):f=copy(b);f[:]='.';f[i]=e;z+=[f]
print len(z)
for x in z:print'\n'.join(map(''.join,x))+'\n'

Output Example
5
a..bb
a..ba
.....
.....

ab.b.
.....
.....
ab.a.

ab..b
.....
.....
ab..a

.....
.abb.
.aba.
.....

.....
a.bb.
.....
a.ba.

Haskell, 364 chars
m=map
l=length
u=unlines
v=reverse
z=zip[0..]
q s=p(lines s)[]
e i a=[a!!j|j<-i]
main=g.w.q=<<getContents
g x=(print.l)x>>(putStr.u.m u)x
c 0=[[]];c n=let x=m(m(1+))$c(n-1)in x++m(0:)x
p(c:x) a|c==""=(v a,fst$p x[])|1<2=p x(c:a);p[]a=(v a,[])
w(a,b)=[m(\(p,r)->m(\(q,x)->if(elem p i&&elem q j)then(b!!p!!q)else '.')$z r)$z b|i<-c.l$b,j<-c.l$b!!0,a==(m(e j).e i)b]

Ungolfed Version, 716 chars
parse (c:x) a | c == "" = (reverse a, fst$parse x [])
              | otherwise = parse x (c:a)
parse [] a = (reverse a, [])
readMat s = parse (lines s) []

choose 0 = [[]]
choose n = let
  x = map (map (1+))$choose (n-1)
  in x ++ map (0:) x

select ix a = [a!!i | i<-ix]

for = flip map
make b (ix, jx) =
  for (zip [0..] b) (\(i,r) ->
    for (zip [0..] r) (\(j,x) ->
      if elem i ix && elem j jx
      then b!!i!!j
      else '.'
    )
  )

main = do
  s <- getContents
  let (a, b) = readMat s
      (n, m) = (length b, length.head$ b)
  let ans = [make b (ix, jx) | ix <- choose n, jx <- choose n,
              a == (map (select jx).select ix$ b)]
  print$ length ans
  putStrLn$unlines.map unlines$ ans

Ruby 448
class Array
alias t transpose
alias z size
alias e each
alias s select
end

def x
v=[]
while(w=gets.chop).size>0 do
v<<w.split('')
end
v
end

def w(i,j)(0...i).to_a.combination(i-j).to_a end

a=x
n=a.z
a=a.t
o=a.z
b=x
q=b.z
r=b[0].z
w=['.']
y=w*r
z=w*q
f=[]
w(q,n).e{|u|w(r,o).e{|v|
h=b.dup
u.e{|i|h[i]=y}
h=h.t
v.e{|j|h[j]=z}
h=h.t
f<<h if(h.s{|i|i!=y}.t.s{|i|i!=w*n})==a}}
p f.z
puts
f.e{|b|b.e{|i|k='';i.e{|j|(k<<' ')if k.size>0;k<<j}
puts k}
puts}


text:
Download all google results for given Query
The Task
Write a program to take a query from STDIN and then download the first 20 search results of that query from google and save them in a folder named Search as html files. Or if google points to a non-html file (like PDF), save whatever it is. Type of results may depend on the programmer, but the first 20 results should be matched. Ads etc. can also be counted as results.
Scoring
This is code-golf ; shortest code wins.

You mean, retrieve the contents of whatever google points to? How should the files be named?

Yes, i mean the same. The files can be named anything.

Can we provide the radius of the earth in microns?

No, You have to use SI units. Edited question.

OK, I've already got two lines of my code: require'net/http' require'nokogiri'

You know that this probably violates googles TOS?

@JohannesKuhn how come? I can't find anything where Google forbids automated access or requires that the content be displayed to the browser.

Is the .html extension required, or only the file format?

There are a couple of problems with this as it stands, not including the pointless scaling of the scoring system. "Search results" is somewhat ambiguous given the number of types of search results that Google will now give in response to a query. The instruction to "save as HTML" files is somewhat odd: surely the idea should be to save whatever the resource is, and it might not be an HTML file.

True - what if Google points to a non-HTML?

Another issue is that, apparently, some servers don't like my user agent (and no, I'm not embedding a "real" user agent in my code)

@JohannesKuhn how come this is not a code golf? The score is proportional to the code length...

"objective criterion other than code size" = score.

@JanDvorak HTML extension is not required.

@PeterTaylor I edited the question.

What are we supposed to do if some results fail downloading? Die spectacularly? Shrug and move on? Fetch a replacement result? I'd most preferably die spectacularly

If a result fails, then you have to move on and get the others.

Ruby, 260 256 characters
require'net/http';require'nokogiri';i=0;`mkdir Search`;`cd Search`;N=Net::HTTP
Nokogiri::HTML.parse(N.get"www.google.cz","/search?"+URI.encode_www_form(q:gets,num:20)).css(".r a").each{|e|File.open("#{i+=1}",?w)<<N.get(URI e['href'][/q=(.*?)&/,1])rescue 0}

Note: when testing this multiple times, be sure to add `cd ..` between each test to reset the current working directory lest you end up with whatever/Search/Search/Search/Search...
If we are allowed to fail on first unsuccessful result, we can drop rescue 0 at the end of the second line and save 8 characters.
if we may assume input is alphanumeric and a single word, we can skip encoding and shave off some more characters. (235 chars with error recovery, 227 without)
require'net/http';require'nokogiri';i=0;`mkdir Search`;`cd Search`;N=Net::HTTP
Nokogiri::HTML.parse(N.get"www.google.cz","/search?num=20&q="+gets).css(".r a").each{|e|File.open("#{i+=1}",?w)<<N.get(URI e['href'][/q=(.*?)&/,1])}

Wait, is www.google.cz not the czech google? You have to use the english google, www.google.com.

Who said I have to use the english domain for Google? Does the inline link in your question count as normative? They point to the same machines with the same behavior and search results. If .com isactually required, count my solution as 261 characters. (actually, 260. I'm going to post a one-character improvement once I get to desktop and test its correctness)

Are you running this on Windows?

yes. Does it fail on Unix? Access rights? Unfortunately, I can't test on Linux.

No, the  \cd Search`is pointless: the backticks are starting a child process and the directory will be changed in that – which not affects the parent process, theruby` one.

@manatwork from my testing, it writes to the child directory on Windows. Should I change to Dir.chdir for Unix?

If you make it cross-platform by changing to Dir.chdir, then better edit your note too: the cd .. between runs is only needed on Windows. But if you are not making it cross-platform, then you can spare 3 characters by changing mkdir Search to md Search.

Bash
mkdir Search;cd Search;wget -U msie -rl 1 -e robots=off -d http://www.google.com http://www.google.com/search?q=`cat`&num=20

Because wget is the right way to do that.

wait, does this work if the user enters a search string containing &? Shouldn't you escape the user input?

Maybe I should.

Will you... probably not - too many extra characters.

@LegoStormtroopr right.


text:
Efficiently packing rectangles on a strip of paper
Algorithm for nesting submited jobs to reduce paper roll usage.
Working with a 36" large format printer, with paper roll as source (150feet=45meters).
With a delay loop on print server queue: waiting 30 seconds before printing in case another job are comming too.
At begining of (perl) print script, it do a list of paper sizes as an output from gs -sDEVICE=bbox, with all pages of all jobs in last 30 seconds and return only one indexed list of page sizes, like:
Input sample
 0:807.4780x562.6371
 1:562.6370x807.4780
 2:1700.0000x4251.0000
 3:550.6150x786.1020
 4:594.0000x840.9060
 5:504.7200x761.0000
 6:368.3280x761.0000
 7:1193.0000x1685.0000

All values are in 1/72 inches (postscript dot).
The roll is 36 x 72 = 2592 dot with but have 15dot margin.
The orientation of roll is: Y=<width; max 2562 dots> and X=<length: max not specified but ~127Kdots>. So when start printing, the top-left corner is one right side of printer and sheet is going out from the top of postscript page.

The goal of the challenge is to build the quicker algorithm to choose the smallest paper length to cut out from the roll and the way of nesting all pages on this paper sheet (adding a little fixed space between plots for cutter)... and having smallest number of cut (see drawing: reducing cut).
Fixed Variables
ROLL WIDTH        = 36 x 72
PRINTER MARGIN    = 15 x 2
PLOT SEPARATION   = 15

Important: The pages may have to be re-ordered and rotated in order to find the best arrangment.
Desired output: First paper length alone on first line, than all page, one by line, in format: <Index>:<X offset>x<Y offset><Rotation flag (R)
Output sample
4281
0:1715x0
1:1715x577R
2:0x0
3:1715x1400R
...

Note: This sample may be wrong: I'm not sure now if R are rightly placed or have to be inversed. That's doesn't matter in that:

R stand for rotation and is a flag. But his meaning stay free it could be used to say to rotate or to not rotate (the rotation angle could be 90° or 270°, as you prefer;-).

Number of cuts
This have to be calculated only for separating plots, not do finalize margins. This mean: One separation = one cut, not two. But the rush have to be dropped!
In others word: border added could be separator/2 to plotter margin.
A cut have to be straight and end to end on a dimension of a sheet or already cutted sheet.
Goal:
The winner will be the first to offer a full useable implementation of its algorithm able to process upto 20 rectangles in less than 30 seconds. (With shebang or command line sample). Any language commonly used in production is acceptable.  (meaning: no brainf@#k, but lisp could be accepted.)
Bonus if in case of one fixed size of paper length due to one big plot, all other jobs are placed in the meaning of reducing number of paper cut.

Is there a scoring system/is the winning answer determined by popularity?

The title might read more clearly as: "Efficiently packing rectangles on a strip of paper".  "Nesting rectangles" suggests placing rectangles within rectangles that are within rectangles that are within….

Could you please clarify the scoring? Is the goal just to output "a" paperlength and some arrangement? Or the "best" arrangement? In what sense? And could you explain how the number of paper cuts is calculated (maybe using your example)?

Rectangle bin packing is not for the faint of heart.  See http://clb.demon.fi/files/RectangleBinPack.pdf

I thought I could find beefy people, on Programming Puzzles & Code Golf ;-)

Isn't this one of the millennial prize problems? The unsolvable math problems, like the pattern of primes. Rectangle packaging is a crazy hard problem because the answer is never intuitive, the example you show isn't even the most efficient way to pack. :o

@AlbertRenshaw I think no: It's solvable be successive tries, (also a little expensive). And you're right: it's never intuitive and yes, I think my example is not perfect.


text:
Find the optimal set of weights to add to a certain set of weights
In this challenge, you will recieve a comma-separated list of weights as input, such as
1,3,4,7,8,11

And you must output the smallest amount of weights that can add to that set. For example, the output for this set would be
1,3,7

Because you could represent all of those weights with just those three:
1     = 1
3     = 3
1+3   = 4
7     = 7
1+7   = 8
1+3+7 = 11

There may be more than one solution. For example, your solution for the input 1,2 could be 1,1 or 1,2. As long as it finds the minimum amount of weights that can represent the input set, it is a valid solution.
Weights may not be used more than once. If you need to use one twice, you must output it twice. For example, 2,3 is not a valid solution for 2,3,5,7 because you can't use the 2 twice for 2+2+3=7.
Input is guaranteed not to have duplicated numbers.
This is code-golf so shortest code by character count wins.
Network access is forbidden (so none of your "clever" wget solutions @JohannesKuhn cough cough) ;)
Simpleest cases:
1,5,6,9,10,14,15               => 1,5,9
7,14,15,21,22,29               => 7,14,15
4,5,6,7,9,10,11,12,13,15,16,18 => 4,5,6,7
2,3,5,7                        => 2,2,3 or 2,3,7

And some trickier ones:
10,16,19,23,26,27,30,37,41,43,44,46,50,53,57,60,61,64,68,71,77,80,84,87
  => 3,7,16,27,34
20,30,36,50,56,63,66,73,79,86
  => 7,13,23,43
27,35,44,46,51,53,55,60,63,64,68,69,72,77,79,81,86,88,90,95,97,105,106,114,123,132
  => 9,18,26,37,42

very similar to http://codegolf.stackexchange.com/questions/12399/create-sets-with-a-goldbach-like-property/12402

@Jan, one significant difference is that the challenge you cite called for a set, whereas this one permits duplicates (e.g., 7,7,7,8 above), which increases complexity manyfold.

Can we assume the input weights are unique (so we don't have to remove dups, simple as that would be)?  Also, you may consider requiring that solutions be able to solve a given test case; otherwise the shortest solution may be a brute-force enumerator that can only deal with tiny problems (e.g., if there are n inputs weights and m is the largest, enumerate all subsequences of (1..m) and for each subsequence, enumerate every combination of between 1 and n instances of each element of the sequence.)

@CarySwoveland Edited for the "unique" part. I already have test cases.

How can {7,7,7,8} be a solution? 8 is not in the input set.

@David, you may be right, but "smallest amount of weights that can add to that set" does not necessarily mean that those weights are limited to those in the list.  "Weights" may not the best term; "postive integers" might be better.  Doorknob will let us know.

OK, dn, I guess the term "test cases" is pretty clear: solutions must be capable of solving all of them.  Initially, I thought they might just be examples to help clarify the question.

These test cases might be too trivial: all of them can be solved without testing for optimality. Pseudo code: n=[]; for (value in values) { if (value not in possible_sums(n)) n.push(value)}; print n

@Primo, the problem is pretty uninteresting if the weights to be added must be from the list given as input.  I think we need to assume the weights must simply be (possibly multiple copies of) positive integers. Note that one of the test cases is consistent with this interpretation.  Clarification, please, Doorknob.

@CarySwoveland my point is only that such an implementation would pass all of the given test cases. Python code: http://codepad.org/1ErSQCmX

This is probably obvious, but perhaps worth a mention. Suppose the input list is an array a and g is a "generator" array. If, say, a.max = 23, g = [1,2,4,8,16] is one possible solution, so we don't have to consider g for g.size > 5 (or g.size > a.size). More generally, g.size <= [Math.log2(m).ceil, a.size].min

@CarySwoveland Your second last comment is correct. Not sure what you're trying to say with your last comment... anyway, updating question to clarify

@primo How about my new testcase? Is that better?

Knob, my last comment is for the possible benefit of anyone attempting a solution-no need to consider generator arrays greater than the indicated size.

@Doorknob yes, much better. The 'greedy' solution I posted above produces a set of length 9: [10, 16, 19, 23, 27, 30, 41, 44, 61]

[1,2,4,8,16,32,64].size > [3,7,16,27,34].size as well.

Mathematica 80 75
Update: See at bottom an update on Doorknob's challenging last test, added on Nov.5

This passes all but the last test. However, it does not attempt to use a digit more than once.  And it only searches from solutions that are subsets of the larger data set.
The function generates all of the subsets of the input data set and then tests which subsets can be used to construct the complete set. After the viable subsets are found, it chooses the smallest sets.
s=Subsets
f@i_:=GatherBy[Select[s@i,Complement[i, Total /@ s@#]=={}&],Length]〚1〛

Tests
f[{1, 3, 4, 7, 8, 11}]

{{1, 3, 7}}

f[{1, 5, 6, 9, 10, 14, 15}]

{{1, 5, 9}}

f[{7, 14, 15, 21, 22, 29}]

{{7, 14, 15}}

f[{4, 5, 6, 7, 9, 10, 11, 12, 13, 15, 16, 18}]

{{4, 5, 6, 7}}

f[{2, 3, 5, 7}]

{{2, 3, 5}, {2, 3, 7}}

Update
Below I'll provide an initial analysis that may help get started toward a solution.
The data:
data = {10, 16, 19, 23, 26, 27, 30, 37, 41, 43, 44, 46, 50, 53, 57, 60, 61, 64, 68, 71, 77, 80, 84, 87};

Differently from the earlier approach, we want to consider, in the solution set, numbers that do NOT appear in the data set.
The approach makes use of absolute differences between pairs of numbers in the data set.
g[d_] := DeleteCases[Reverse@SortBy[Tally[Union[Sort /@ Tuples[d, {2}]] /. {a_, b_} :> Abs[a - b]], Last], {0, _}]

Let's look at the number of times each difference appears; we'll only grab the first 8 cases, starting from the most common difference].
g[data][[1;;8]]

{{7, 14}, {27, 13}, {34, 12}, {3, 11}, {20, 10}, {16, 10}, {4,
    10}, {11, 9}}

14 pairs differed by 7; 13 pairs differed by 27, and so on.
Now let's test subsets starting with {difference1},{difference1, difference2}, and so on, until we can hopefully account for all the original elements in the data set.
h reveals those numbers from the original set that cannot be constructed by composing sums from the subset.
h[t_] := Complement[data, Total /@ Subsets@t]

By the fifth try, there are still 10 elements that cannot be formed from {7, 27, 34, 3, 20}:
h[{7, 27, 34, 3, 20}]

{16, 19, 26, 43, 46, 53, 60, 77, 80, 87}

But on the next try, all numbers of the data set are accounted for:
h[{7, 27, 34, 3, 20, 16}]

{}

This is still not as economical as {3,7,16,27,34}, but it's close.

There are still some additional things to take into account.

If 1 is in the data set, it will be required in the solution set.
There may well be some "loners" in the original set that cannot be composed from the most common differences. These would need to be included apart from the difference tests.

These are more issues than I can handle at the moment. But I hope it sheds some light on this very interesting challenge.

hmm... currently devising testcase that requires duplicates :P

I'll leave my solution posted for now and see if I can add a condition to test duplicates.

If a solution exists where a weight w is repeated, then the same solution with one of the ws changed to 2 * w also works, because you can use the 2 * w everywhere you used w + w before.  This can be repeated until the solution has no repeats.  Therefore, you need not attempt to use repeats.

You don't really need the parenthesis. Get the s=Subsets; out of the function

Right about the parentheses.

I added a tricky testcase (:)), what does this output for it?

Great test.  I can see the careful planning so as to require use of elements outside the original data.The list is too long for my first program; it struggled for 2 hours before I put it out of its misery.  I added some notes on another possible approach.

Ruby 289
This is a straight enumeration, so it will obtain minimal solutions, but it may take years--possibly light years--to solve some problems.  All the "simplest cases" solve in at most a few seconds (though I got 7,8,14 and 1,2,4 for the 3rd and 5th cases, respectively).  Tricky #2 solved in about 3 hours, but the other two are just too big for enumeration, at least for the way I've gone about it.
An array of size n that generates the given array by summing subsets of its elements is of minimal size if it can be shown that there is no array of size < n that does that.  I can see no other way to prove optimality, so I start the enumeration with subsets of size m, where m is a known lower bound, and then increase the size to m+1 after having enumerated subsets of size m and shown they none of those "span" the given array, and so on, until I find an optimum.  Of course, if I have enumerated all subsets up to size n, I could use a heuristic for size n+1, so that if I found a spanning array of that size, I would know it is optimal.  Can anyone suggest an alternative way to prove a solution is optimal in the general case?
I've included a few optional checks to eliminate some combinations early on.  Removing those checks would save 87 characters.  They are as follows (a is the given array):

an array of size n can generate at most 2^n-1 distinct positive numbers; hence, 2^n-1 >= a.size, or n >= log2(a.size).ceil (the "lower bound" I referred to above).
a candidate generating array b of size n can be ruled out if:

b.min > a.min
sum of elements of b < a.max or
b.max < v, where v = a.max.to_f/n+(n-1).to_f/2.ceil (to_f being conversion to float).

The last of these, which is checked first, implements
sum of elements of b <= sum(b.max-n+1..b.max) < a.max

Note v is constant for all generator arrays of size n.
I've also made use of @cardboard_box's very helful observation that there is no need to consider duplicates in the generating array.
In my code,
(1..a.max).to_a.combination(n)

generates all combinations of the numbers 1 to a.max, taken n at a time (where a.max = a.last = a[-1]).  For each combination b:
(1...2**n).each{|j|h[b.zip(j.to_s(2).rjust(n,?0).split('')).reduce(0){|t,(u,v)|t+(v==?1?u:0)}]=0}

fills a hash h with all numbers that are sums over non-empty subsets of b.  The hash keys are those numbers; the values are arbitrary. (I chose to set the latter to zero.)
a.all?{|e|h[e]}}

checks whether every element of the given array a is a key in the hash (h[e] != nil, or just h[e]).
Suppose
n = 3 and b=[2,5,7].

Then we iterate over the range:
(1...2**8) = (1...8) # 1,2,..,7

The binary representation of each number in this range is used to stab out the elements of b to sum.  For j = 3 (j being the range index),
3.to_s(2)                  # =>  "11"
"11".rjust(3,?0)           # => "011"
"011".split('')            # => ["0","1","1"]
[2,5,7].zip(["1","0","1"]) # => [[2,"0"],[5,"1"],[7,"1"]]
[[2,"0"],[5,"1"],[7,"1"]].reduce(0){|t,(u,v)|t+(v==?1?u:0)}]=0 # => t = 0+5+7 = 12

The code:
x=a[-1]
n=Math.log2(a.size).ceil
loop do
v=(1.0*x/n+(n-1)/2.0).ceil
(1..x).to_a.combination(n).each{|b|
next if b[-1]<v||b[0]>a[0]||b.reduce(&:+)<x
h={}
(1...2**n).each{|j|h[b.zip(j.to_s(2).rjust(n,?0).split('')).reduce(0){|t,(u,v)|t+(v==?1?u:0)}]=0}
(p b;exit)if a.all?{|e|h[e]}}
n+=1
end


text:
Shortest code for longest output
This one is pretty simple.
Write the shortest program you can, while generating the most output.
To make it fun, programs that produce infinite output will be disqualified.
The winner is the program with the largest output size/code size ratio.
The results are based on what works on my computer, which is a Mac running Mac OS X 10.7.5 with an Intel Core i5 and 8GB of memory.

It's not clear exactly what you're asking. Should answers assume unbounded memory, unbounded index sizes, etc?

@PeterTaylor I fixed that.

Be blowed if I can figure it out, but I'm sure there is a way to have some interpretter interpret an empty file and produce any content - which would also give an infinite ratio.

@LegoStormtroopr GolfScript fits the bill. Executing an empty script will produce exactly one character of output: \n

Also, it is more or less a more general version of http://codegolf.stackexchange.com/q/12655/1490.

What do you mean by "what works on my computer"? If a huge number is computable (in principle) using less than 8 GB memory, but requires an infeasible execution time, does that "work"?

@r.e.s. I interpret "works" to mean that, given enough time, the code would eventually produce output (actual output) of the claimed length, while not consuming more than 8GB of system memory. Although, others seem to have a more liberal interpretation: both for the term "working", and for the term "program."

@primo - What is "actual" output? Would it "work" if a program requires less than 8 GB of memory and eventually halts, but needs an amount of time exceeding the age of the universe and/or prints more characters than there are atoms in the known universe?

@r.e.s. By "actual" output, I mean that the "program", as it were, should contain a statement which actually outputs something, rather than just evaluating an expression which would have the claimed length if actually output. Whether the program is allowed to take longer than the theoretical lifespan of the computer it's running on is a question that needs to be answered by the OP.

Mac? Then my bluescreen idea won't work :(

@anustart My mother's Mac had a bluescreen once.  It only happened once, but was the same color blue as Windows.

I read that Befunge can produce infinite output with the character '.' (period).  Does that count?

@user2509848 no, because, like I said, infinite output does not count.

Python: 8 chars code, 387420489 chars output -- Ratio: 48427561.125 : 1
'a'*9**9

We can have the ratio tend to infinity by adding more **9s:
'a'*9**9**9
'a'*9**9**9**9
etc.

For example:
'a'*9**9**9**9**9**9

which has a ratio of ~10101010108.568 (unimaginably large number).

Better than the other one...

@tbodt Why? O_o @arshajii If you add enough **9s, wouldn't it eventually become Infinity?

@Doorknob Sorry, I don't know everything about python. Now the challenge is: Figure out the maximum number of **9s you can put before the output becomes Infinity.

@Doorknob Python ints have arbitrary precision.

@tbodt See the comment above.

ah, so now the challenge is "figure out when Python errors or the computer crashes" :P

Well that would depend on the computer, of course :P I'm sure we could imagine a hypothetical computer for which all of this works (i.e. any number of 9s). Based on Python's specification, this should work indeed.

@Doorknob (among others): Things are happening pretty fast here, and it is hard to keep up.

@tbodt You could just upvote both answers (you shouldn't accept answers early - it discourages further answers).

It would be much bigger if you replace that last 9 by 99. (9**99 )/9.0= 3.279185047850306e+93

So, these are all good programs that produce lots of output with very little code, but none of them are really short...
brainfuck, 5 characters, 255 bytes of output
-[.-]

I think this is the only use case where brainfuck really excels. I know this one isn't going to win, but I don't think we can possibly do better than the Python example. Not only that, but...
brainfuck, 4 characters, infinite output
-[.]

I conjecture that this is the shortest infinite-output program out there.
Actually, hold on, my mate's just come up with a really good one.
Python, 80 bytes, unknown amount of output
from datetime import datetime
while datetime.now()!=datetime.max()
 print "This will probably get disqualified"

This program will definitely halt eventually, but will only do so after roughly 8,000 years. The exact number of characters output depends on the rate at which your computer can produce characters.

I like the python one :D

"I conjecture that this is the shortest infinite-output program out there" nope, this is where Befunge's implicit loop (via wraparound) comes handy: . outputs an infinite stream of 0 characters.

Perl - 19 bytes, 187200000000000000 bytes output (9852631578947368.42 : 1)
print+($]x9e7)x26e7

166 petabyes with a single print statement, using no more than 1.7GB of memory.
There's a few things that made this challenge more interesting that I thought it would be. Perl seems to refuse to allocate more than 1GB of memory to any single list. Hence, the 4-byte scalar reference to the inner string may only be repeated 26e7 ≈ 228 times. $] is the 'old perl version' number which, as a string, is 8 bytes long, resembling 5.016002.
With more system memory, it should be able to go higher. Assuming the full 8GB were actually available, you should be able to use $]x9e8 for the inner string instead, which would output 1.62 exabytes.

"If you give a 1,000,000 monkeys 1,000,000 typewriters, and give them 1,000,000 years to write stuff, one monkey will eventual write a Java program.  The others just produce Perl scripts." That's what I thought when I saw this :P source

Ruby and Python, 13 chars, 599994 char output, ~46153:1 ratio
999999**99999

Simply raises a very large number to the power of another very large number. Takes about 20 seconds to run. I can't increase the numbers because that would make the number become Infinity.
(I did this earlier, I am currently working on making a loop for even longer output)
Edit: I did it!
Ruby, 28 chars, 6e599999 char output, ~6e599998 ratio (I think)
a=999999**99999;a.times{p a}

Untested (for obvious reasons), but I'm pretty sure the first number is about 1e599994, which multiplied by 599994 is about 6e599999. Theoretically it would work, but I'm not sure if it would crash your computer, so disclaimer: I am not responsible if it harms your computer in any way :P
Of course, you can keep going:
Ruby, 37 chars, 6e359992800041 char output, ~6e359992800040 ratio
a=999999**99999;a.times{a.times{p a}}

And so on, but I doubt any computer can handle that :P

That's really a polyglot...

@tbodt Hehe, right! When I add my changes it won't be though

If infinite input was allowed,
cat /dev/random

Since it's not,
head -99 /dev/random

(25128 output : 20 input = 1256.4:1)
I'm not on a Linux box, but I imagine you could do something like
timeout 99d cat /dev/random

and get a huge output. (via GigaWatt's response)

You can substitute one character and make your output 8562 times longer:  timeout 99d.  Yep, 99 day runtime.
Also, I'm not certain on this, but eventually you'll empty the entropy pool with /dev/random and it'll block, so /dev/urandom may be more appropriate.  (I managed to get 40 MB/s with urandom and only 128 KB/s with random)

@GigaWatt that is awesome.

HQ9+, 11471
9

Actual character count varies depending on the interpreter, but probably around 10000 would be right?

What is HQ9+? I've never heard of it.

Ahh, sorry, it was mostly a joke since it's not a 'real' programming language, but:
http://esolangs.org/wiki/HQ9%2B

C#: 108 chars. Ratio: 742123445489230793057592 : 1
for(ulong i=0;i<ulong.MaxValue;i++){Console.Write(new WebClient().DownloadString(@"http://bit.ly/dDuoI4"));}

It just downloads and prints the wikipedia's List of law clerks of the Supreme Court of the United States (4344904 chars) 18446744073709551615 times.

That requires a URL shortener. I'm not sure about that.

Ok. And what about this: for(ulong i=0;i<ulong.MaxValue;i++){Console.Write(new string('a',int.MaxValue));} 2147483647 chars * 18446744073709551615 times = 39614081238685424720914939905 / 81 => Ratio: 489062731341795366924875801

Much better. No URL shortener required.

~-~! - Ratio: (6444464)/154 ~= 10101010101.583328920493678
'=~~~~,~~~~,~~~~:''=|*<%[%]'=',',',':''&*-~|:'''=|*<%[%]''&',',',':'''&*-~|:''''=|*<%[%]'''&',',',':''''&*-~|:''''&':''=|*<%[%]@~~~~,~~~~,~~:''&*-~|:''&':

How it works: First, it sets ' to 4^3, or 64. Then, it makes '' a function which sets ' to '^4 * times (where * is it's input). ''' is then made a function which calls '' with the input as '^4. Then, '''' is made a function which calls ''' with '^4 as it's input. '''' is then called with an input of 64. Finally, '' is changed to a function which prints a space * times; this is then called with an input of '.
Turns out, in the end, ' is  6444464, and my program's length is 154; punch that into Wolfram|Alpha and it spits out 10101010101.583328920493678, which it doesn't even bother to calculate. I don't even know how many digits it contains, but 6444 contains 463. Pretty nice for a language that only supports unary explicit numbers and doesn't have an exponent function ;3
I could have made this a lot larger, but, overkill.

C: 48 chars, approx. (2^32 - 1)*65090 bytes output
main(){for(int i=1<<31;i<~0;)puts("!");main();}

Note that the 65090 is not exact, and depends on stack size. The program will eventually stop when it crashes. Also, I could just put a longer and longer string in puts() to make the ration approach infinity, but that seems rather cheaty.

that's an infinite loop

Ouch, you're right, I think. I'll see if I can figure how to fix that.

ruby, 283 96 44 chars
a=1e99.times;a{a{a{a{a{puts'a'*99}}}}}}}}}}

Not very short, but it compensates for it in output, which is so much I haven't yet been able to measure it.

by my calculations this would be about 1e127 chars output. anyway, assigning to a variable would cut the code size about in half. also, 1e99 is a bigger number that takes less space. also, use map instead of each, use puts instead of print, remove extra whitespace between print and "ier.... You could also replace that big string with 'a'*999 (or even ?a*999) which is a longer string that takes less space. summary: this is not golfed at all

@Doorknob Thanks. I know nothing about ruby, except chapter 3 of why's poignant guide to ruby.

yeah, why don't you just assign (0..1e99).map to a variable? like a=(0...1e99).map;a{a{a{a{a{puts'a'*99}}}}}

My Ruby interpretter ran out of memory evaluating a=(0...1e99).map. You might want to tone that back a bit. 0..1e9 would use about 4GB.

Mathematica 9 chars  Ratio: ~ 4564112 : 1
The following is a picture of Mathematica input.  I haven't figured how to render it in SE.

Here's a screen shot showing the number of digits in the output. IntegerDigits converts the output to a list of digits. Length counts the number of digits.

Keystrokes to enter: 9, ctrl6, 9, ctrl6, 9, ctrl6, 9, ctrl6, 9....

What? You can type that into Mathematica?

Yes, this is legitimate input to Mathematica.

And what keystrokes are required?

@tbodt Keystrokes are now shown in the answer.

If you would like to use text instead of an image, then just add this code to your answer: 999999999

Thanks. I tried that but the font size becomes illegible.  If there were a way to do that while keeping the text readable, I'd do so.

I don't know if you would have to specify order, but you would want to have it calculate top down: (9^9)^9 is a 78 digit number, but 9^(9^9) is a 369,693,100 digit number (thanks, wolframalpha)

Good point. Mathematica defaults to the second order, so the FullForm of a^b^c  is Power[a,Power[b,c]].

Wow. I'd really love a copy of Mathematica right now.

You can download a trial version: http://www.wolfram.com/mathematica/ But it tends to be pricey unless you are a student or educator.

Javascript: 27 chars; 260,431,976 char output; 9,645,628.74 ratio
for(s=i=61;s=btoa(s),i--;)s

This code recursively encodes the input 61 to Base64 61 times. Encoding any input of length n to Base64 produces an output of length n * 8/6, rounded up to a multiple of 4.
This must be run from a JavaScript console environment that natively supports the Base64-encoding function btoa. (Any modern browser, but not Node.js.) Note Chrome cannot run higher than i=61, while Firefox can only reach i=60. Note also that Chrome's console cannot actually display the output because it is too large, but you can verify the result size by running
for(s=i=61;s=btoa(s),i--;)s.length

If this program were allowed to run for the maximum i=99, it would produce a hypothetical output of size 14,566,872,071,840 (14.5 trillion, 14.5e12) chars, for a hypothetical ratio of around 540 billion (5.39e11).

Befunge-93: 48 characters, about ((2^32)^2)*10  characters output
Befunge's stack is theoretically infinite,  but the numbers that stack stores are limited to the size of an unsigned long integer (here  assumed to be 32 bits). Thus,  to a Befunge  interpreter, (x+1)>x  is false for the proper value of x.  We use this fact to first push all values from zero to the maximum (twice, with a one every third number),  and  then for each value on the  stack,  we output and decrement it,  then pop it when it reaches zero. Eventually the stack empties and the program terminates. I may be a bit off on the output size, but it should be somewhere in that ballpark.
>::1# + #1\`# :# _> #- #1 :# :# .# _# .# :# _@

Ruby, 23 characters - ~500000000000000 (5e14) Output
while rand
puts 0
end

Ti-Basic 84, 13 characters - ~3000 Output
:Disp 1
:prgmA

Name the program prgmA

Python 3, 115 bytes, runs for 7983 years (unknown # of chars)
EDIT: ymbirtt beat me to it ._.
I know, this isn't really short, and I know that the other Python answer is much longer, But I decided to give this a shot.
The program runs for about 8000 years, which, as you know, is a pretty long time.
What it does is continuously get the current time using the datetime.datetime.now() function, and it compares it to 9999-12-31 24:59:59.999999, which is as far as I know the maximum date in Python.
If is is equal, the program stops. If it isn't, it continously outputs a.
import datetime
while 1:
    if str(datetime.datetime.now())=="9999-12-31 24:59:59.999999":exit
    else:print("a")

What if you miss that moment?

@C5H8NNaO4 If you leave it on for all 7983 years, you hopefully won't miss it.

java(131): unknown but finite amount
class A{public static void main(String[] args){while(Math.random()>0){for(long l=0;l!=-1;l++){System.out.println("1234567890");}}}}

Using the low chance of Math.random() to get to 0 in a loop and then goin 2^64-1 loops thru a foreach with the output 1234567890;