Code-golf: Output multiplication table to the Console
Asked Answered
E

40

18

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!

Embarkation answered 5/8, 2010 at 7:52 Comment(14)
I can write any program in one line of code :)Meneses
You possibly could get it down to one really long line of code (if you decide to not count the extension methods you write) but you'd surely sacrifice readabilityMisalliance
You can write it in one line and still be readable. hint: Console.Write("01 02 03 04...Houseleek
code-golf is usually language-agnosticHouseleek
I do think it's cute that C# people like to talk about smallest number of lines. code-golf is about smallest number of charactersHouseleek
@Meneses Even in VB6?Sanitize
Hm... I thought the multiplication tables usually ended in x*10? At least all the ones I saw during elementary school and such did.Squire
@Svish: my elementary school times tables ended at 9, now I feel totally gypped.. How was I ever supposed to know what 10 times anything was?? Man I sure dodged a bullet on that one figuring it out on my own..Snippy
@Squire - Would it be a better solution if those extents were configurable? But creating those variables means more codeEmbarkation
@Jimmy: haha, didn't mean it like that. Just looked weird to me. I have no strong feelings about this :p @fletcher: nah. it was mostly just an observation :pSquire
What are those c# and .net doing there together language-agnostic? Those two language-specific tags should be removed.Morrismorrison
When I was at school we went up to 12 times. I still haven't figured out what is beyond 12x12=144Scud
@Sanitize The tag has been changed since I made that comment :) It said C# before.Meneses
I had to learn up to 14 :) But I suck(ed) at arithmetic.Amethist
S
41

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 
Sanitize answered 5/8, 2010 at 7:52 Comment(16)
Well, I could space it a bit, that would give J a bit of a handicap for code-golf...Sanitize
This is the worst C# I've ever seenSnippy
@Jimmy Hoffa: I'm of the code-agnostic allegiance for code-golf :)Sanitize
@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 coldSnippy
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!)Thessa
@Jason Ah, nice! *"_ 0 just makes the multiplication in 2 dimensions against itself. Granted `*` is more elegant.Sanitize
earl posted the same answer 3 hours earlier but deleted it for some reasonHouseleek
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).Thessa
@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."Sanitize
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 :)Sarene
It doesn't do the 0 padding, though :(Maag
@Robert: Are you using J5 or J6? This seems fit for J6 only.Sanitize
@MPelletier: j602a, downloaded yesterday. The output in the post is the output I got from running it on that version.Maag
How come it has so many upvotes even if it does not follow the output spec? (leading 0 for single-digit numbers)Klusek
@Kenny, pretty typical in code-golf on SO. We can only wonder why :)Houseleek
@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).Houseleek
A
16

MATLAB - 10 characters

a=1:9;a'*a

... or 33 characters for stricter output format

a=1:9;disp(num2str(a'*a,'%.2d '))
Atherton answered 5/8, 2010 at 7:52 Comment(5)
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.Satinet
@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 '))Atherton
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.Houseleek
@gnovice: to be exact, the formatting string should be '%02d 'Hereat
@Amro: True, but for integer values the two give identical results.Atherton
S
15

Brainf**k - 185 chars

>---------[++++++++++>---------[+<[-<+>>+++++++++[->+>>---------[>-<++++++++++<]<[>]>>+<<<<]>[-<+>]<---------<]<[->+<]>>>>++++[-<++++>]<[->++>+++>+++<<<]>>>[.[-]<]<]++++++++++.[-<->]<+]
Seurat answered 5/8, 2010 at 7:52 Comment(8)
This looks like a timeline of a dagger mating with a fish corpse.Basrhin
@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 possibleGuyenne
Actually, after going through the meta post on it 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 flagsGuyenne
hmm..beating COBOL by a fair whackHouseleek
@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?Afc
@Afc 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 thingGuyenne
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 thoCarhart
A point as to why people hate it; words have meanings, and this one's meaning is particularly bad.Selfservice
R
14

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 *

Rehabilitate answered 5/8, 2010 at 7:52 Comment(2)
ROFL, I never thought of that for static things like thisHellas
+1 because this should be the benchmark. Any language that can't beat this should not even bother to apply.Phil
C
8

Python - 61 chars

r=range(1,10)
for y in r:print"%02d "*9%tuple(y*x for x in r)
Counterfeit answered 5/8, 2010 at 7:52 Comment(2)
@Jimmy Hoffa: You misspelled "Perl".Luellaluelle
@Jimmy, sorry i should have explained print is kinda like Console.WriteHouseleek
W
7

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?

Wield answered 5/8, 2010 at 7:52 Comment(9)
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..Snippy
what language is that? pls indicate in titleMohn
amazing how you were able to get these TWO lines into a SINGLE one :>Tarah
Using Enumerable.Range(1, 9) might make it a bit shorter.Wilen
@Wilen you would still have to add .ToList() because ForEach only works on IList and no on IEnumerableWield
@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(). :)Wilen
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 :)Sufferance
@Andrew I think you have 2 extra chars in there. Why not chain the .ToList().ForEach() and save the ;mWield
@Wield 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.Sufferance
S
6

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.

Sarene answered 5/8, 2010 at 7:52 Comment(4)
"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 KAgra
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.Sarene
And this also doesn't do the leading 0's. :(Maag
Prepend -1',/'(|" ",2#|"00",$:)'' (26 chars) to produce output with zero-padded values.Sarene
C
6

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
Counterfeit answered 5/8, 2010 at 7:52 Comment(1)
This is also F90, even maybe F77.Karenkarena
D
5

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);
}
Dilettante answered 5/8, 2010 at 7:52 Comment(20)
Does not compile. Message: A namespace does not directly contain members such as fields or methods.Giavani
Make sure you included using System.Linq; and that the above code is inside of a method body.Dilettante
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};.Giavani
Those are some really big words. Is C# trying to replace COBOL?Satinet
@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.Dilettante
@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.Dilettante
@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.Giavani
The whitespace in ' ' should be a tab and not a space... but it looks like the editor on here is messign with me.Dilettante
for(int i=1;i<10;i++)Console.WriteLine(Enumerable.Range(1,9).Aggregate("",(w,t)=>w+(i*t).ToString("00 "))); 107Giavani
Sweet. You should post that as your own answer.Dilettante
@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.Giavani
@Nick, well I found a shorter version based on your idea and posted it above. :o)Dilettante
You can shave a character off by incrementing y during the multiplication instead of in the for structure!Giavani
@Matthew Whited: sorry for hijacking your answer, I found another character.Giavani
I'm thinking there has to be a way to use Console.Write(...), I just cannot figure it out.Giavani
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.Dilettante
you can skip \r and just use \n, but it is still longer obviouslyGiavani
True, it wouldn't be technically correct for Windows, but it would match the spec.Dilettante
If you can move the math to the for structure, you can remove the parenthesis on the top version.Giavani
Finally got rid of that pesky string!Giavani
L
5

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)
Licastro answered 5/8, 2010 at 7:52 Comment(2)
Nice, you can do it 1 char shorter by replacing 'rownum' with 'level'.Corene
@TTT: and even many characters shorter with trimming of unnecessary space!Ref
C
4

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.
Counterfeit answered 5/8, 2010 at 7:52 Comment(3)
I can't quite put my finger on it, but for some reason this is my favorite.Giavani
@belisarius, thanks .. can't believe this has more votes than fortran though :)Houseleek
In "my" compiler the {Begin} is not needed. Check yours :D - Ha! Cobol in a code-golf ... you are a hero!Centeno
C
3

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(" ")}
Counterfeit answered 5/8, 2010 at 7:52 Comment(4)
Nice reductions. I feel like the map{|x|x*y} could be done away with if only Ruby had some nice currying stuff...Terebinthine
If you're a little lenient on the spec, you can do 42 chars using puts"%3d".Terebinthine
@jtbandes, looks like hobb's perl is taking that shortcut, so i guess i'm really beating perl by 2 chars...Houseleek
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...Terebinthine
E
3

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]
Era answered 5/8, 2010 at 7:52 Comment(4)
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<-rHectograph
@Landei: Thanks. But it can only save 1 char.Klusek
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. :)Samarium
I love the use of list comprehensions!Depository
A
3

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(); });

Amylene answered 5/8, 2010 at 7:52 Comment(2)
+1 for Enumerable.Range. Combine that with Sruly's .ForEach and inline it all for the ultimate horror! ;-)Penis
Enumreable doesn't have .ForEach, you would have to call .ToList() firstWield
A
2

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 
Antheridium answered 5/8, 2010 at 7:52 Comment(1)
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));Bohr
B
2

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
Baird answered 5/8, 2010 at 7:52 Comment(0)
D
2

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}
Descriptive answered 5/8, 2010 at 7:52 Comment(4)
oh c'mon you can't even beat Fortran? :)Houseleek
Nope. You've got implicit loops and an especially clever output formatter built into the language ;)Descriptive
And it doesn't print the leading 0's. >_>Maag
A small fix to make it work to spec: for$n(1..9){printf"%02d "x9 .$/,map$n*$_,1..9}Maag
A
2

C - 97 79 characters

#define f(i){int i=0;while(i++<9)
main()f(x)f(y)printf("%.2d ",x*y);puts("");}}
Afc answered 5/8, 2010 at 7:52 Comment(0)
A
2

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);});
Aposiopesis answered 5/8, 2010 at 7:52 Comment(0)
A
2

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"")
Altonaltona answered 5/8, 2010 at 7:52 Comment(0)
M
1

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));
 }
}
Morrismorrison answered 5/8, 2010 at 7:52 Comment(5)
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.Uretic
@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.Morrismorrison
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.Uretic
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.Uretic
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.Morrismorrison
E
1

PHP, 62 chars

for(;$x++<9;print"\n",$y=0)while($y++<9)printf("%02d ",$x*$y);
Eads answered 5/8, 2010 at 7:52 Comment(0)
E
1

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
Ecdysis answered 5/8, 2010 at 7:52 Comment(0)
H
1

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)}
Hectograph answered 5/8, 2010 at 7:52 Comment(0)
G
1

Ruby - 56 chars :D

9.times{|a|9.times{|b|print"%02d "%((a+1)*(b+1))};puts;}
Gynecic answered 5/8, 2010 at 7:52 Comment(0)
G
1

PostgreSQL: 81 74 chars

select array(select generate_series(1,9)*x)from generate_series(1,9)as x;
Gossoon answered 5/8, 2010 at 7:52 Comment(1)
@Jay Adams: +1: Removed some extraneous whitespace for you. Your original count was off by 3 chars... new lines perhaps?Arriviste
F
1

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);
Florance answered 5/8, 2010 at 7:52 Comment(1)
I like this. I think this meets the original spec fully.Embarkation
C
1

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("");}}
Counterfeit answered 5/8, 2010 at 7:52 Comment(4)
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).Afc
@dreamlax, under the rules of code-golf, it if compiles and runs it's ok :) Tested with gcc-4.4.3 btwHouseleek
Fails to compile with clang however test.c:2:1: error: second argument of 'main' should be of type 'char **'Afc
@dreamlax, I have a better answer now anyway :)Houseleek
G
0

C++ RANKING IN AT 99999TH PLACE (76 chars)

for(int i=1;i<=9;++i){cout<<i<<" "<<i+1<<i+2<<i+3<<i+4<<i+5<<i+6<<i+7<<i+8;}
Gravy answered 5/8, 2010 at 7:52 Comment(0)
S
0

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)
Sheilasheilah answered 5/8, 2010 at 7:52 Comment(0)
N
0

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
Nog answered 5/8, 2010 at 7:52 Comment(0)
S
0

BASH 53

for((i=1;i<10;i++));do seq -s' ' $i $i $((9*i));done
Spiritualize answered 5/8, 2010 at 7:52 Comment(0)
D
0

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
Diathesis answered 5/8, 2010 at 7:52 Comment(0)
S
0

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 "))));
Scad answered 5/8, 2010 at 7:52 Comment(0)
A
0

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)

Amethist answered 5/8, 2010 at 7:52 Comment(2)
This just looks like gobbledygook. :) Would maybe be cool to explain it a bit.Hhd
Heh your comment made me look at my code again. Almost threw up. Might retry building an interpreter for it, maybe not using unicode either :p Also, the reference but tbf it doesn't explain how a stack based language works.Amethist
T
0

PHP, 67 characters

while(++$x<10){$y=0;while(++$y<10)printf("%02d ",$x*$y);print"\n";}
Theresatherese answered 5/8, 2010 at 7:52 Comment(0)
P
0

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))))
Paperboy answered 5/8, 2010 at 7:52 Comment(0)
E
0

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.

Ellissa answered 5/8, 2010 at 7:52 Comment(1)
For Wolfram Alpha, 9times tables is 13 characters and will give the same output as multiplication table 9.Seurat
T
0

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.)

Terebinthine answered 5/8, 2010 at 7:52 Comment(2)
thanks, i pinched your idea of putting the range in a variable :)Houseleek
really you need "%02d" to meet the specHouseleek
A
0

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()));
Antiparallel answered 5/8, 2010 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.