Code-golf: Output multiplication table to the Cons

2019-03-14 15:35发布

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!

30条回答
趁早两清
2楼-- · 2019-03-14 16:16

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?

查看更多
虎瘦雄心在
3楼-- · 2019-03-14 16:17

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);
}
查看更多
Explosion°爆炸
4楼-- · 2019-03-14 16:17

C - 97 79 characters

#define f(i){int i=0;while(i++<9)
main()f(x)f(y)printf("%.2d ",x*y);puts("");}}
查看更多
成全新的幸福
5楼-- · 2019-03-14 16:17

Ruby - 56 chars :D

9.times{|a|9.times{|b|print"%02d "%((a+1)*(b+1))};puts;}
查看更多
叛逆
6楼-- · 2019-03-14 16:17

Python - 61 chars

r=range(1,10)
for y in r:print"%02d "*9%tuple(y*x for x in r)
查看更多
We Are One
7楼-- · 2019-03-14 16:18

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);});
查看更多
登录 后发表回答