4
\$\begingroup\$

This javascript code: for(x=1;x<6;x++)for(y=1;y<6;y++)console.log((y==1?'\n':'')+x+'*'+y+'='+x*y);

prints the following:

1*1=1
1*2=2
1*3=3
1*4=4
1*5=5

2*1=2
2*2=4
2*3=6
2*4=8
2*5=10

3*1=3
3*2=6
3*3=9
3*4=12
3*5=15

4*1=4
4*2=8
4*3=12
4*4=16
4*5=20

5*1=5
5*2=10
5*3=15
5*4=20
5*5=25 

2 questions:

  • Is there a smaller (in bytes) way to do the same?
  • What is the smallest code that can do the same without using 2 for statements?
\$\endgroup\$
8
  • 5
    \$\begingroup\$ Before the downvotes and close votes come in: this is on-topic \$\endgroup\$ Commented Sep 30, 2014 at 18:43
  • 2
    \$\begingroup\$ @MartinBüttner which doesn't change the fact that this is technically a language-specific challenge ;-) \$\endgroup\$ Commented Sep 30, 2014 at 18:47
  • 1
    \$\begingroup\$ Why are there two blocks of 1s, two blocks of 3s, and no block of 2s or 4s? I don't think that's what the code outputs... \$\endgroup\$ Commented Sep 30, 2014 at 18:49
  • 1
    \$\begingroup\$ At least in firebug console, the part (y==1?'\n':'') has no effect (no blank lines to separate runs). \$\endgroup\$
    – edc65
    Commented Sep 30, 2014 at 19:06
  • \$\begingroup\$ @edc65 That is because both Chrome and Firebug print the actual value instead of the string representation as Firefox does. \$\endgroup\$
    – Optimizer
    Commented Sep 30, 2014 at 19:14

1 Answer 1

4
\$\begingroup\$

Single for loop, 80 75 72 68 bytes

I will try to make the code smaller too, but as far as single for loop goes:

for(i=5;i<30;)console.log(k=i/5|0,"*",l=i%5+1,"=",k*l,++i%5?"":"\n")

Try it in your console! (Although IE gives the best results)

\$\endgroup\$
8
  • \$\begingroup\$ Don't forget to include the code length in the header \$\endgroup\$ Commented Sep 30, 2014 at 18:49
  • \$\begingroup\$ "Is there a smaller (in bytes) way to do the same?" -- so, it surely is code-golf \$\endgroup\$ Commented Sep 30, 2014 at 18:51
  • \$\begingroup\$ Should I add it? \$\endgroup\$ Commented Sep 30, 2014 at 18:52
  • \$\begingroup\$ There. It's tagged code-golf now. \$\endgroup\$ Commented Sep 30, 2014 at 18:53
  • \$\begingroup\$ Try in your MSIE console! In chrome and firefox and firebug the output is very different... (no problem for me, just to make it clear) \$\endgroup\$
    – edc65
    Commented Sep 30, 2014 at 19:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.