views:

1850

answers:

39

Hi,

I recently pointed a student doing work experience to an article about dumping a multiplication table to the console. It used a nested for loop and multiplied the step value of each.

This looked like a .NET 2.0 approach. I was wondering, with the use of Linq and extension methods,for example, how many lines of code it would take to achieve the same result.

Is the stackoverflow community up to the challenge?

The challenge: In a console application, write code to generate a table like this example:

01 02 03 04 05 06 07 08 09
02 04 06 08 10 12 14 16 18
03 06 09 12 15 18 21 24 27
04 08 12 16 20 24 28 32 36
05 10 15 20 25 30 35 40 45
06 12 18 24 30 36 42 48 54
07 14 21 28 35 42 49 56 63
08 16 24 32 40 48 56 64 72
09 18 27 36 45 54 63 72 81

As this turned into a language-agnostic code-golf battle, I'll go with the communities decision about which is the best solution for the accepted answer.

There's been alot of talk about the spec and the format that the table should be in, I purposefully added the 00 format but the double new-line was originally only there because I didn't know how to format the text when creating the post!

+3  A: 

Not really a one-liner, but the shortest linq i can think of:

var r = Enumerable.Range(1, 9);
foreach (var z in r.Select(n => r.Select(m => n * m)).Select(a => a.Select(b => b.ToString("00 "))))
{
    foreach (var q in z)
        Console.Write(q);
    Console.WriteLine();
}

In response to combining this and SRuly's answer

Enumberable.Range(1,9).ToList.ForEach(n => Enumberable.Range(1,9).ToList.ForEach(n2 => Console.Write((n * n2).ToString("00 "))); Console.WriteLine(); });

Oliver
+1 for Enumerable.Range. Combine that with Sruly's `.ForEach` and inline it all for the ultimate horror! ;-)
Dan Puzey
Enumreable doesn't have .ForEach, you would have to call .ToList() first
Sruly
@Sruly even better then!
msarchet
+8  A: 

C#

This is only 2 lines. It uses lambdas not extension methods

 var nums = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 nums.ForEach(n => { nums.ForEach(n2 => Console.Write((n * n2).ToString("00 "))); Console.WriteLine(); });

and of course it could be done in one long unreadable line

 new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.ForEach(n => { new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.ForEach(n2 => Console.Write((n * n2).ToString("00 "))); Console.WriteLine(); });

all of this is assuming you consider a labmda one line?

Sruly
personally a fan of String.Format("{0} ", n * n2) as opposed to .ToString with the format, otherwise I'm at a loss for another calculation method than this basic recursion with a multiplier..
Jimmy Hoffa
what language is that? pls indicate in title
Nas Banov
amazing how you were able to get these TWO lines into a SINGLE one :>
atamanroman
Using `Enumerable.Range(1, 9)` might make it a bit shorter.
GeReV
@GeReV you would still have to add .ToList() because ForEach only works on IList and no on IEnumerable
Sruly
@Sruly, I'm not sure, but you might be able to use some LINQ extension instead, like `Aggregate` maybe... But there's already an answer with `Enumerable.Range()`. :)
GeReV
`var m=Enumerable.Range(1,9).ToList();m.ForEach(n=>{m.ForEach(o=>Console.Write("{0:00} ",(n*o)));Console.WriteLine();});` is a whole 119 characters :)
Andrew Koester
@Andrew I think you have 2 extra chars in there. Why not chain the .ToList().ForEach() and save the ;m
Sruly
@Sruly Because m is used again inside the ForEach, and doing that would prevent a value being returned to store in m to be used inside the first loop.
Andrew Koester
+8  A: 

Python - 61 chars

r=range(1,10)
for y in r:print"%02d "*9%tuple(y*x for x in r)
gnibbler
@Jimmy Hoffa: You misspelled "Perl".
Javier Badia
@Jimmy, sorry i should have explained `print` is kinda like `Console.Write`
gnibbler
Oh, Python 62 is already released. ;)
KennyTM
@Kenny heh..it was late
gnibbler
@Javier-Badia: Oops, my mind must have transposed the words
Jimmy Hoffa
+6  A: 

Oracle SQL, 103 characters:

select n, n*2, n*3, n*4, n*5, n*6, n*7, n*8, n*9 from (select rownum n from dual CONNECT BY LEVEL < 10)
Mark Bannister
Nice, you can do it 1 char shorter by replacing 'rownum' with 'level'.
TTT
+42  A: 

J - 8 chars - 24 chars for proper format

*/~1+i.9

Gives:

1  2  3  4  5  6  7  8  9
2  4  6  8 10 12 14 16 18
3  6  9 12 15 18 21 24 27
4  8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81

This solution found by @earl:

'r(0)q( )3.'8!:2*/~1+i.9

Gives:

01 02 03 04 05 06 07 08 09 
02 04 06 08 10 12 14 16 18 
03 06 09 12 15 18 21 24 27 
04 08 12 16 20 24 28 32 36 
05 10 15 20 25 30 35 40 45 
06 12 18 24 30 36 42 48 54 
07 14 21 28 35 42 49 56 63 
08 16 24 32 40 48 56 64 72 
09 18 27 36 45 54 63 72 81 
MPelletier
............ O.o
Svish
Well, I could space it a bit, that would give J a bit of a handicap for code-golf...
MPelletier
Consider my mind blown.
Aistina
This is the worst C# I've ever seen
Jimmy Hoffa
@Jimmy Hoffa: I'm of the code-agnostic allegiance for code-golf :)
MPelletier
@MPelletier: The only reason I ever played golf was the beer carts they bring around to you, I don't really care what language they speak as long as it's cold
Jimmy Hoffa
For that matter, `*/~1+i.9` is only 8 characters. (To be honest I'm having some trouble figuring out what the `*"_ 0` part of yours is doing!)
Jason Orendorff
@Jason Ah, nice! `*"_ 0` just makes the multiplication in 2 dimensions against itself. Granted `*\` is more elegant.
MPelletier
earl posted the same answer 3 hours earlier but deleted it for some reason
gnibbler
Oh, I get it now: `_ 0` is the two-element array `(_, 0)`, so your original 11-character entry `*"_ 0~1+i.9` parses like `(1 + i. 9) *"(_,0) (1 + i. 9)`.
Jason Orendorff
@Jason: Exactly. I usually don't "string" my array elements together, I go straight for the array, even if `_ 0` is not the most obvious way to say "array of 2 elements composed of infinity and 0."
MPelletier
Yeah, I deleted the answer because I considered it off-topic for a C# code-golfing question. Seems the "language-agnostic" tag has been added since. My answer also contained an extended version doing zero padding: 'r(0)q( )3.' 8!:2 */~1+i.9. Feel free to upvote this comment if you want to give props :)
earl
It doesn't do the 0 padding, though :(
Robert P
@Robert: Are you using J5 or J6? This seems fit for J6 only.
MPelletier
Any other reason to learn J except beer? ;)
atamanroman
@fielding: If only there really was beer...
MPelletier
@MPelletier: j602a, downloaded yesterday. The output in the post is the output I got from running it on that version.
Robert P
How come it has so many upvotes *even if it does not follow the output spec?* (leading 0 for single-digit numbers)
KennyTM
@Kenny, pretty typical in code-golf on SO. We can only wonder why :)
gnibbler
@earl, I think you should post your J as a proper answer as it's the shortest code that meets the spec so far (re: leading zeros).
gnibbler
@Jimmy found you! :-)
aaa
+2  A: 

F# - 61 chars:

for y=1 to 9 do(for x=1 to 9 do printf"%02d "(x*y));printfn""

If you prefer a more applicative/LINQ-y solution, then in 72 chars:

[1..9]|>Seq.iter(fun y->[1..9]|>Seq.iter((*)y>>printf"%02d ");printfn"")
Brian
+3  A: 

Haskell — 85 84 79 chars

r=[1..9]
s x=['0'|x<=9]++show x
main=mapM putStrLn[unwords[s$x*y|x<-r]|y<-r]

If double spacing is required (89 81 chars),

r=[1..9]
s x=['0'|x<=9]++show x
main=mapM putStrLn['\n':unwords[s$x*y|x<-r]|y<-r]
KennyTM
No Haskell here to try it out, but shouldn't this work (would save 3 chars): Add a line r=[1..9] and write x<-r and y<-r
Landei
@Landei: Thanks. But it can only save 1 char.
KennyTM
You can shorten definition of s function if you declare it like s x=['0'|x<=9]++show x ... it may not be particulary nice and it takes one extra reduction step, but it is by 8 characters shorter. :)
Matajon
I love the use of list comprehensions!
trinithis
+2  A: 

c# - 125, 123 chars (2 lines):

var r=Enumerable.Range(1,9).ToList();
r.ForEach(n=>{var s="";r.ForEach(m=>s+=(n*m).ToString("00 "));Console.WriteLine(s);});
Chad
+16  A: 

Brainf**k - 185 chars

>---------[++++++++++>---------[+<[-<+>>+++++++++[->+>>---------[>-<++++++++++<]<[>]>>+<<<<]>[-<+>]<---------<]<[->+<]>>>>++++[-<++++>]<[->++>+++>+++<<<]>>>[.[-]<]<]++++++++++.[-<->]<+]
Nabb
This looks like a timeline of a dagger mating with a fish corpse.
Sam Pearson
I like how the word brain is censored, and not f**k.
dreamlax
@dreamlax Apparently three people so far find it offensive; I for one intend to start bowdlerizing the non-offensive parts of words as often as possible
Michael Mrozek
Actually, after going through [the meta post on it](http://meta.stackoverflow.com/questions/24079/is-the-language-brainf-ck-offensive) it looks like it should be censored just to avoid the arguing and triggering nanny filters, so I'll do it even though I pretty massively disagree with the practice. I flagged it for mod attention to hopefully clear the offensive flags
Michael Mrozek
hmm..beating COBOL by a fair whack
gnibbler
@Michael Mrozek: I don't understand, do we have 8 year old programmers browsing this site with a net nanny or who honestly won't know what two letters belong under those asterisks?
dreamlax
@dreamlax I guess the main concern is companies that block sites with those words, and avoiding arguments with people who do care about that sort of thing
Michael Mrozek
Sigh... it's a word. Offensive to robots and little minds in this context. Intercoursing sad. Kudos for writing that and keeping your brain intact tho
seanb
A point as to why people hate it; words have meanings, and this one's meaning is particularly bad.
RCIX
+5  A: 

C# - 117, 113, 99, 96, 95 89 characters

updated based on NickLarsen's idea

for(int x=0,y;++x<10;)
    for(y=x;y<x*10;y+=x)
        Console.Write(y.ToString(y<x*9?"00 ":"00 \n"));

99, 85, 82 81 characters ... If you don't care about the leading zeros and would allow tabs for alignment.

for(int x=0,y;++x<10;)
{
    var w="";
    for(y=1;++y<10;)
        w+=x*y+"    ";
    Console.WriteLine(w);
}
Matthew Whited
Does not compile. Message: `A namespace does not directly contain members such as fields or methods`.
NickLarsen
Make sure you included `using System.Linq;` and that the above code is inside of a method body.
Matthew Whited
I don't think a non compiling method body should count when other languages are full programs... but anyway, you can shave off a character with `int[] r={1,2,3,4,5,6,7,8,9};`.
NickLarsen
Those are some really big words. Is C# trying to replace COBOL?
phkahler
@nick, interesting... I think I tried that everyother way and couldn't find anything shorter (and that int[] looks to be the same length as the Enumerable version I have posted above.) As for just the method body, this is the way I have see most other C# code-golf so I went with it.
Matthew Whited
@phkahler, I don't know about that, I just used exiting framework methods to implment this method. I would have perfered shorter method and class names, but you gotta do what ya gotta do.
Matthew Whited
@Matthew Whited: you're right, its the same length. I just realized when I copied your code into VS, it expanded a space after the comma.
NickLarsen
The whitespace in `' '` should be a tab and not a space... but it looks like the editor on here is messign with me.
Matthew Whited
`for(int i=1;i<10;i++)Console.WriteLine(Enumerable.Range(1,9).Aggregate("",(w,t)=>w+(i*t).ToString("00 ")));` 107
NickLarsen
Sweet. You should post that as your own answer.
Matthew Whited
@Matthew Whited: I'd rather there be only one answer per concept/language, and it was just an improvement on yours. I tried to be super clever and increment `i` inside the loop, but I didn't realize it was double looped.
NickLarsen
@Nick, well I found a shorter version based on your idea and posted it above. :o)
Matthew Whited
Of course all the linq hotness is gone now :o(
Matthew Whited
You can shave a character off by incrementing `y` during the multiplication instead of in the `for` structure!
NickLarsen
@Matthew Whited: sorry for hijacking your answer, I found another character.
NickLarsen
I'm thinking there has to be a way to use `Console.Write(...)`, I just cannot figure it out.
NickLarsen
I tried about 20 different ways yesterday and couldn't get any shorter. The most I can think of on `Console.Write` is to either add `+"\r\n"` (which is longer than `Line`) or to use a formatter string... which will again cause it to explode.
Matthew Whited
you can skip `\r` and just use `\n`, but it is still longer obviously
NickLarsen
True, it wouldn't be technically correct for Windows, but it would match the spec.
Matthew Whited
If you can move the math to the for structure, you can remove the parenthesis on the top version.
NickLarsen
Finally got rid of that pesky string!
NickLarsen
+2  A: 

C - 97 79 characters

#define f(i){int i=0;while(i++<9)
main()f(x)f(y)printf("%.2d ",x*y);puts("");}}
dreamlax
+6  A: 

Fortran95 - 40 chars (beating perl by 4 chars!)

This solution does print the leading zeros as per the spec.

print"(9(i3.2))",((i*j,i=1,9),j=1,9);end
gnibbler
This is also F90, even maybe F77.
ldigas
+1  A: 

C - 66 Chars

This resolves the complaint about the second parameter of main :)

main(x){for(x=8;x++<89;)printf("%.2d%c",x/9*(x%9+1),x%9<8?32:10);}

C - 77 chars

Based on dreamlax's 97 char answer. His current answer somewhat resembles this one now :)

Compiles ok with gcc, and main(x,y) is fair game for golf i reckon

#define f(i){for(i=0;i++<9;)
main(x,y)f(x)f(y)printf("%.2d ",x*y);puts("");}}
gnibbler
Isn't this UB? If `main` is defined with two parameters, the second argument to `main` must be a `char **` or equivalent, (you've violated a *shall* clause in 5.1.2.2.1).
dreamlax
@dreamlax, under the rules of code-golf, it if compiles and runs it's ok :) Tested with gcc-4.4.3 btw
gnibbler
Fails to compile with clang however `test.c:2:1: error: second argument of 'main' should be of type 'char **'`
dreamlax
@dreamlax, I have a better answer now anyway :)
gnibbler
+5  A: 

COBOL - 218 chars -> 216 chars

PROGRAM-ID.P.DATA DIVISION.WORKING-STORAGE SECTION.
1 I PIC 9.
1 N PIC 99.
PROCEDURE DIVISION.PERFORM 9 TIMES
ADD 1 TO I
SET N TO I
PERFORM 9 TIMES
DISPLAY N' 'NO ADVANCING
ADD I TO N
END-PERFORM
DISPLAY''
END-PERFORM.

Edit

216 chars (probably a different compiler)

PROGRAM-ID.P.DATA DIVISION.WORKING-STORAGE SECTION.
1 I PIC 9.
1 N PIC 99.
PROCEDURE DIVISION.

  PERFORM B 9 TIMES
  STOP RUN.

B.
 ADD 1 TO I
 set N to I
 PERFORM C 9 TIMES
 DISPLAY''.

C.
 DISPLAY N" "NO ADVANCING
 Add I TO N.
gnibbler
I can't quite put my finger on it, but for some reason this is my favorite.
NickLarsen
just "PIC 9" for I and J ... two chars less .... Hurrah!! :D
belisarius
@belisarius, thanks .. can't believe this has more votes than fortran though :)
gnibbler
In "my" compiler the {Begin} is not needed. Check yours :D - Ha! Cobol in a code-golf ... you are a hero!
belisarius
@belisarius, you are correct. I am using `cobc`
gnibbler
well ... done with some @shortcuts@ >D
belisarius
+7  A: 

K - 12 characters

Let's take the rosetta-stoning seriously, and compare Kdb+'s K4 with the canonical J solution (*/~1+i.9):

  a*/:\:a:1+!9
1 2  3  4  5  6  7  8  9 
2 4  6  8  10 12 14 16 18
3 6  9  12 15 18 21 24 27
4 8  12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81

J's "table" operator (/) equals the K "each-left each-right" (/:\:) idiom. We don't have J's extremely handy "reflexive" operator (~) in K, so we have to pass a as both left and right argument.

earl
"so we have to pass a as both left and right argument" - this kind of code duplication is why I never could get too interested in K
pelotom
I also consider the purely tacit definition of J is more elegant in this case. But in general, K strikes a very nice balance with it's selection of built-ins. And just in case: a simple `R:{x[y;y]}` allows you to write the above tacitly as `R[*/:\:]1+!9`.
earl
And this also doesn't do the leading 0's. :(
Robert P
Prepend `-1',/'(|" ",2#|"00",$:)''` (26 chars) to produce output with zero-padded values.
earl
+16  A: 

MATLAB - 10 characters

a=1:9;a'*a

... or 33 characters for stricter output format

a=1:9;disp(num2str(a'*a,'%.2d '))
gnovice
Nice! utterly simple and to the point
Darknight
This is not a correct answer. It prints "ans =" and a blank line prior to showing the table which contains many extra spaces and no 0-padding. I doubt the formatting will be as compact as this. Still a good try.
phkahler
@phkahler: Admittedly, I took some liberties, since there didn't seem to be an explicit set of output rules, merely that it should generate a multiplication table. I don't like the zero padding because it makes the numbers a little harder to read, but here's a 33-character solution that generates output more like the example: `a=1:9;disp(num2str(a'*a,'%.2d '))`
gnovice
It turns out that the zero padding makes the question more interesting. For many of the more verbose languages, only one more char is required, but for the likes of J,K,MATLAB, there is a significant penalty.
gnibbler
@gnovice: to be exact, the formatting string should be `'%02d '`
Amro
@Amro: True, but for integer values the two give identical results.
gnovice
+1  A: 

C#, 135 chars, nice and clean:

var rg = Enumerable.Range(1, 9);
foreach (var rc in from r in rg 
                   from c in rg 
                   select (r * c).ToString("D2") + (c == 9 ? "\n\n" : " "))
    Console.Write(rc);
Rafe
I like this. I think this meets the original spec fully.
fletcher
+2  A: 

PostgreSQL: 81 74 chars

select array(select generate_series(1,9)*x)from generate_series(1,9)as x;
Joey Adams
@Jay Adams: +1: Removed some extraneous whitespace for you. Your original count was off by 3 chars... new lines perhaps?
sdolan
+3  A: 

Ruby - 42 Chars (including one linebreak, interactive command line only)

This method is two lines of input and only works in irb (because irb gives us _), but shortens the previous method by a scant 2 charcters.

1..9
_.map{|y|puts"%02d "*9%_.map{|x|x*y}}

Ruby - 44 Chars (tied with perl)

(a=1..9).map{|y|puts"%02d "*9%a.map{|x|x*y}}

Ruby - 46 Chars

9.times{|y|puts"%02d "*9%(1..9).map{|x|x*y+x}}

Ruby - 47 Chars

And back to a double loop

(1..9).map{|y|puts"%02d "*9%(1..9).map{|x|x*y}}

Ruby - 54 chars!

Using a single loop saves a couple of chars!

(9..89).map{|n|print"%02d "%(n/9*(x=n%9+1))+"\n"*(x/9)}

Ruby - 56 chars

9.times{|x|puts (1..9).map{|y|"%.2d"%(y+x*y)}.join(" ")}
gnibbler
Nice reductions. I feel like the `map{|x|x*y}` could be done away with if only Ruby had some nice currying stuff...
jtbandes
If you're a little lenient on the spec, you can do 42 chars using `puts"%3d"`.
jtbandes
@jtbandes, looks like hobb's perl is taking that shortcut, so i guess i'm really beating perl by 2 chars...
gnibbler
I added another method which only works in irb for its use of `_` instead of assigning a variable `a`, so it can get rid of the parentheses...
jtbandes
+1  A: 

Ruby - 56 chars :D

9.times{|a|9.times{|b|print"%02d "%((a+1)*(b+1))};puts;}
robbles
A: 

Another attempt using C#/Linq with GroupJoin:

Console.Write(
    String.Join(
        Environment.NewLine,
        Enumerable.Range(1, 9)
            .GroupJoin(Enumerable.Range(1, 9), y => 0, x => 0, (y, xx) => String.Join(" ", xx.Select(x => x * y)))
            .ToArray()));
Felix Ungman
+2  A: 

Perl, 44 chars

(No hope of coming anywhere near J, but languages with matrix ops are in a class of their own here...)

for$n(1..9){printf"%3d"x9 .$/,map$n*$_,1..9}
hobbs
oh c'mon you can't even beat Fortran? :)
gnibbler
Nope. You've got implicit loops *and* an especially clever output formatter built into the language ;)
hobbs
And it doesn't print the leading 0's. >_>
Robert P
A small fix to make it work to spec: `for$n(1..9){printf"%02d "x9 .$/,map$n*$_,1..9}`
Robert P
A: 

Ruby — 47 chars

puts (a=1..9).map{|i|a.map{|j|"%2d"%(j*i)}*" "}

Output

 1  2  3  4  5  6  7  8  9
 2  4  6  8 10 12 14 16 18
 3  6  9 12 15 18 21 24 27
 4  8 12 16 20 24 28 32 36
 5 10 15 20 25 30 35 40 45
 6 12 18 24 30 36 42 48 54
 7 14 21 28 35 42 49 56 63
 8 16 24 32 40 48 56 64 72
 9 18 27 36 45 54 63 72 81

(If we ignore spacing, it becomes 39: puts (a=1..9).map{|i|a.map{|j|j*i}*" "} And anyway, I feel like there's a bit of room for improvement with the wordy map stuff.)

jtbandes
thanks, i pinched your idea of putting the range in a variable :)
gnibbler
really you need `"%02d"` to meet the spec
gnibbler
A: 

Ruby, 49 chars

1.upto(9){|n|puts"%02d "*9%(n..81).step(n).to_a}

PS. With Wolfram Alpha it's 23 characters DS.

Jonas Elfström
For Wolfram Alpha, `9times tables` is 13 characters and will give the same output as `multiplication table 9`.
Nabb
+2  A: 

R (very similar to Matlab on this level): 12 characters.

> 1:9%*%t(1:9)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    1    2    3    4    5    6    7    8    9
[2,]    2    4    6    8   10   12   14   16   18
[3,]    3    6    9   12   15   18   21   24   27
[4,]    4    8   12   16   20   24   28   32   36
[5,]    5   10   15   20   25   30   35   40   45
[6,]    6   12   18   24   30   36   42   48   54
[7,]    7   14   21   28   35   42   49   56   63
[8,]    8   16   24   32   40   48   56   64   72
[9,]    9   18   27   36   45   54   63   72   81
Zack
+2  A: 

PHP, 71 chars

for($x=0;++$x<10;print"\n"){for($y=0;++$y<10;){printf("%02d ",$x*$y);}}

Output:

$ php -r 'for($x=0;++$x<10;print"\n"){for($y=0;++$y<10;){printf("%02d ",$x*$y);}}'
01 02 03 04 05 06 07 08 09 
02 04 06 08 10 12 14 16 18 
03 06 09 12 15 18 21 24 27 
04 08 12 16 20 24 28 32 36 
05 10 15 20 25 30 35 40 45 
06 12 18 24 30 36 42 48 54 
07 14 21 28 35 42 49 56 63 
08 16 24 32 40 48 56 64 72 
09 18 27 36 45 54 63 72 81 
Kevin
This is only 62 chars: _for(;$x++<9;print"\n")for($y=0;$y++<9;printf("%02d ",$x*$y));_ or 66 if you give $x a starting value. But the previous one works for me. _for($x=0;$x++<9;print"\n")for($y=0;$y++<9;printf("%02d ",$x*$y));_
Vili
+1  A: 

Scala - 77 59 58 chars

print(1 to 9 map(p=>1 to 9 map(q=>"%02d "format(p*q))mkString)mkString("\n"))

Sorry, I had to do this, the Scala solution by Malax was way too readable...

[Edit] For comprehension seems to be the better choice:

for(p<-1 to 9;q<-{println;1 to 9})print("%02d "format p*q)

[Edit] A much longer solution, but without multiplication, and much more obfuscated:

val s=(1 to 9).toSeq
(s:\s){(p,q)=>println(q.map("%02d "format _)mkString)
q zip(s)map(t=>t._1+t._2)}
Landei
First time i got punished for producing readable code. ;-)
Malax
A: 

Common Lisp, 79 characters (including whitespace):

(dotimes (i 9) (dotimes (j 9) (format t "~2,'0d " (* (1+ i) (1+ j)))) (terpri))

With something approaching a more traditional formatting:

(dotimes (i 9) 
  (dotimes (j 9) 
    (format t "~2,'0d " (* (1+ i) (1+ j)))) 
  (terpri))

Then there's a 106-character version showing off the power of the formatter:

(format t "~{~{~2,'0d~^ ~}~%~}"
        (loop for i from 1 to 9 
           collect (loop for j from 1 to 9 
                      collect (* i j))))
Vatine
A: 

PHP, 67 characters

while(++$x<10){$y=0;while(++$y<10)printf("%02d ",$x*$y);print"\n";}
Mark Trapp
+14  A: 

cat - 252 characters

01 02 03 04 05 06 07 08 09

02 04 06 08 10 12 14 16 18

03 06 09 12 15 18 21 24 27

04 08 12 16 20 24 28 32 36

05 10 15 20 25 30 35 40 45

06 12 18 24 30 36 42 48 54

07 14 21 28 35 42 49 56 63

08 16 24 32 40 48 56 64 72

09 18 27 36 45 54 63 72 81

Assuming that a trailing newline is wanted; otherwise, 251 chars.

* runs *

Thomas
ROFL, I never thought of that for static things like this
TheLQ
Best answeeer!!!
trinithis
+1 because this should be the benchmark. Any language that can't beat this should not even bother to apply.
slebetman
Like Cobol... :D
Thomas
A: 

Repent, 11, 10 chars

↓1⇄.⇄^↓↻*;

This is using my own toy language stack-based language Repent (which I will release soon, once it is up to scratch). I am sad to see J beating it, because I designed it only to beat J, Perl and Golfscript at code golf.

V_1v.v^↓↻*;

Interpreter (Alpha)

Language Reference (Alpha)

Callum Rogers
A: 

C# using aggregate, 118 characters

var r=Enumerable.Range(1,9).ToList();
r.ForEach(i=>Console.WriteLine(r.Aggregate("",(a,b)=>a+=(i*b).ToString("00 "))));
Jesper Palm
+1  A: 

XQuery 1.0 (96 bytes)

string-join(for$x in 1 to 9 return(for$y in 1 to 9 return concat(0[$x*$y<10],$x*$y,' '),'

'),'')

Run (with XQSharp) with:

xquery table.xq !method=text
Oliver Hallam
A: 

Bash, 59 chars

for i in `seq 9`;do seq -w $i $i 99|sed 9q;done|column -c80
01  02  03  04  05  06  07  08  09
02  04  06  08  10  12  14  16  18
03  06  09  12  15  18  21  24  27
04  08  12  16  20  24  28  32  36
05  10  15  20  25  30  35  40  45
06  12  18  24  30  36  42  48  54
07  14  21  28  35  42  49  56  63
08  16  24  32  40  48  56  64  72
09  18  27  36  45  54  63  72  81
cthom06
A: 

BASH 53

for((i=1;i<10;i++));do seq -s' ' $i $i $((9*i));done

NjuBee
A: 

PHP, 62 chars

for(;$x++<9;print"\n",$y=0)while($y++<9)printf("%02d ",$x*$y);
gms8994
+1  A: 

Java - 155 137 chars


  • Update 1: replaced string building by direct printing. Saved 18 chars.

class M{public static void main(String[]a){for(int x,y=0,z=10;++y<z;System.out.println())for(x=0;++x<z;System.out.printf("%02d ",x*y));}}

More readable format:

class M{
 public static void main(String[]a){
  for(int x,y=0,z=10;++y<z;System.out.println())
   for(x=0;++x<z;System.out.printf("%02d ",x*y));
 }
}
BalusC
By the way, I'll have to start doing this with Java code-golfs in the future: replace `public static void main(String[]a)` with `static`. You get an error but not until after the initializer is run, and the error is sent to stderr so technically your stdout is perfectly correct. That could get you down to 124.
Mark Peters
@Mark: I thought about `static` as well because no arguments are expected, but I couldn't get it to run in eclipse nor java in cmd.
BalusC
Really? Works fine for me in Eclipse and from the command line. From command line is Java 1.6.0_19-b04. As I said though, you do get the error afterward saying no main method could be found.
Mark Peters
Sorry, I was wrong in my first comment. I forgot to remove `s` when I calculated the first reduction. Using `System.out.printf` and `System.out.println` in place of concatenating to `s` gets you down to 137 characters, not 152. Then using static on top of that gets you down to 109.
Mark Peters
It indeed shows in stdout in Eclipse. But it won't run in cmd. Eclipse is by default configured to load the class (and run it if there's any `main` method) anyway regardless of the errors. I don't think that it's nice to have the IDE as dependency. I'll however update the printing as per your suggestions.
BalusC
A: 

Haskell (not list comprehensions) 71 after import

It's a shame haskell doesn't have printf in it's prelude library but after importing in ghci 71 chars,the other haskell program was using list comprehensions:

Prelude> :module Text.Printf
Prelude Text.Printf> let r=[1..9]
Prelude Text.Printf> mapM_(\y->(mapM_(\x->printf"%02d "(x*y))r)>>(putStrLn ""))r
01 02 03 04 05 06 07 08 09
02 04 06 08 10 12 14 16 18
03 06 09 12 15 18 21 24 27
04 08 12 16 20 24 28 32 36
05 10 15 20 25 30 35 40 45
06 12 18 24 30 36 42 48 54
07 14 21 28 35 42 49 56 63
08 16 24 32 40 48 56 64 72
09 18 27 36 45 54 63 72 81
cirons42
A: 

JavaScript - with console - 65 chars

for(i=0,a='';++i<10;a+='\n')for(j=0;++j<10;a+=i*j);console.log(a)

JavaScript - with html - 68 chars

for(i=0,a='';++i<10;a+='\n')for(j=0;++j<10;a+=i*j);document.write(a)
Topera