I'm trying to sort columns from left to right based on dates, here is an example of the issue that I'm facing:
https://docs.google.com/spreadsheets/d/1CuDW-VRZxrwXXjyBj4BeUleMFqL8DUQrW3sku6WjMh0/edit?usp=sharing
I'm sorting from column E to N based on the dates in row 6. The script that I'm currently using works okay as far as cell E6 has a date and there is no empty columns in between the full ones, otherwise the script won't work.
Here's the script that I'm using:
function sortLToR() {
//Defining the spreadsheet variables and setting ranges
var sheet = SpreadsheetApp.getActive().getSheetByName("Sort");
var range3 = sheet.getRange(5, 5, 88,sheet.getLastColumn()-4)
var range = sheet.getRange(5, 5, 88,sheet.getLastColumn()-4).getValues();
Logger.log(sheet.getLastColumn())
//Defining a blank array that can hold the result
var trans = [];
//transpose the data stored in range variable
for(var column = 0; column < range[0].length; column++){
trans[column] = [];
for(var row = 0; row < range.length; row++){
trans[column][row] = range[row][column];
}
}
function sortByDate(a, b) {
return new Date(b[1]).getTime() - new Date(a[1]).getTime();
}
var range2 = trans.sort(sortByDate);
var trans2 = [];
//transpose the data stored in range variable
for(var column = 0; column < range2[0].length; column++){
trans2[column] = [];
for(var row = 0; row < range2.length; row++){
trans2[column][row] = range2[row][column];
}
}
range3.setValues(trans2);
}
Any ideas how to fix this?
Thanks
Sort Columns by date and move blank columns to right so that data always starts in Column E
This version puts the blank columns to the right and always starts at E
function sortLToR() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const rg = sh.getRange(5, 5, sh.getLastRow() -4, sh.getLastColumn() - 4)
const vs = rg.getValues();
let b = transpose(vs);
b.sort((a,b) => {
if(a[1] && b[1]) {
return new Date(a[1]).valueOf() - new Date(b[1]).valueOf();
} else if(a[1] && !b[1]){
return -1;
} else if(!a[1] && b[1]) {
return +1
}
});
let c = transpose(b)
rg.setValues(c);
}
Demo:
Before Sort:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
COL2
COL3
COL4
COL5
COL6
COL7
COL8
COL9
COL10
5/19/2022
5/18/2022
5/17/2022
5/16/2022
5/15/2022
5/14/2022
5/13/2022
5/12/2022
5/11/2022
3
4
5
6
7
8
9
10
11
4
5
6
7
8
9
10
11
12
5
6
7
8
9
10
11
12
13
6
7
8
9
10
11
12
13
14
7
8
9
10
11
12
13
14
15
8
9
10
11
12
13
14
15
16
9
10
11
12
13
14
15
16
17
10
11
12
13
14
15
16
17
18
11
12
13
14
15
16
17
18
19
12
13
14
15
16
17
18
19
20
13
14
15
16
17
18
19
20
21
14
15
16
17
18
19
20
21
22
15
16
17
18
19
20
21
22
23
16
17
18
19
20
21
22
23
24
17
18
19
20
21
22
23
24
25
18
19
20
21
22
23
24
25
26
19
20
21
22
23
24
25
26
27
20
21
22
23
24
25
26
27
28
21
22
23
24
25
26
27
28
29
After Sort:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
COL10
COL9
COL8
COL7
COL6
COL5
COL4
COL3
COL2
5/11/2022
5/12/2022
5/13/2022
5/14/2022
5/15/2022
5/16/2022
5/17/2022
5/18/2022
5/19/2022
11
10
9
8
7
6
5
4
3
12
11
10
9
8
7
6
5
4
13
12
11
10
9
8
7
6
5
14
13
12
11
10
9
8
7
6
15
14
13
12
11
10
9
8
7
16
15
14
13
12
11
10
9
8
17
16
15
14
13
12
11
10
9
18
17
16
15
14
13
12
11
10
19
18
17
16
15
14
13
12
11
20
19
18
17
16
15
14
13
12
21
20
19
18
17
16
15
14
13
22
21
20
19
18
17
16
15
14
23
22
21
20
19
18
17
16
15
24
23
22
21
20
19
18
17
16
25
24
23
22
21
20
19
18
17
26
25
24
23
22
21
20
19
18
27
26
25
24
23
22
21
20
19
28
27
26
25
24
23
22
21
20
29
28
27
26
25
24
23
22
21
I'm not sure if this is a viable solution, but you could just add another sheet or use a range in columns to the right, I think you could accomplish what you want.
=transpose(sort(TRANSPOSE(filter(F:N,F:F<>"")),6,true))
See example here of before and after.
Updated to account for potential breaks in data:
=transpose(sort(TRANSPOSE(filter(Before!E:N,Row(Before!E:E)<=max(arrayformula(--NOt(ISBLANK(Before!E:N))*row(Before!E:N))))),6,true))
One could then leverage this formula in an appscript to overwrite the data with something like this:
function makeRange(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const yourSheetName = "Before"; //sheet name with data
const zFormula = "=transpose(sort(TRANSPOSE(filter('zzzzz'!E:N,Row('zzzzz'!E:E)<=max(arrayformula(--NOt(ISBLANK('zzzzz'!E:N))*row('zzzzz'!E:N))))),6,true))";//
var newSheet = ss.insertSheet();
var newFormula = zFormula.replace(/zzzzz/g,yourSheetName)
newSheet.getRange("E1").setFormula(newFormula);
var newValues = newSheet.getRange("E:N").getValues();
ss.getSheetByName(yourSheetName).getRange("E:N").setValues(newValues);
ss.deleteSheet(newSheet);
}
I have a spreadsheet with multiple sheets each sheet has the same layout with Date in column "A" and Time Elapsed in column "P" I need to calculate days between column A and today on all four sheets. If checkbox in column "N" is set to true then instead calculate column "O" from "A".
So far I have been able to code this bit but, need help getting over the hurdle.
function getDateDifference(event) {
var ss = event.source;
var s = ss.getSheetByName('Alpha'); // I need this to run on all four pages
var r = event.source.getActiveRange();
var startDate = sheet.getRange(3,1).getValue();
var endDate = new Date();
var duration = (endDate - startDate)
var r = event.source.getActiveRange();
if (r.getColumn() == 14 && r.getValue() == true) {
var endDate = sheet.getRange(3, 15);
var duration = (endDate - startDate);
sheet.getRange(3, 16).setValue(duration);
}
else {sheet.getRange(3, 16).setValue(duration);}
}
Example sheet for reference
https://docs.google.com/spreadsheets/d/1OKFoS17le-Y5SAOecoLE4EJxiKqKVjRLRHtMzwHNwxM/edit?usp=sharing
Calculate Diff in Days for selected sheets
function calcdiffindays() {
const ss = SpreadsheetApp.getActive();
const incl = ['Alpha', 'Sheet2', 'Sheet3'];//Add the desired sheet names
const dt = new Date();
const dtv = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
ss.getSheets().filter(sh => ~incl.indexOf(sh.getName())).forEach(s => {
s.getRange(3, 1, s.getLastRow() - 2, s.getLastColumn()).getValues().forEach((r, i) => {
if (r[13] == true) {
let d = new Date(r[0]);
let dv = new Date(d.getFullYear(), d.getMonth(), d.getDate());
s.getRange(i + 3, 15).setValue(DiffInDays(dtv, dv));
}
})
})
}
function DiffInDays(Day1,Day2) {
if(Day1 && Day2 && (Object.prototype.toString.call(Day1) === '[object Date]') && (Object.prototype.toString.call(Day2) === '[object Date]')) {
var day=86400000;
var t1=new Date(Day1).valueOf();
var t2=new Date(Day2).valueOf();
var d=Math.abs(t2-t1);
var days=Math.floor(d/day);
//Logger.log(days);
return days;
} else {
throw 'Invalid Inputs';
}
}
Test Sheet:
COL1
COL2
COL3
COL4
COL5
COL6
COL7
COL8
COL9
COL10
COL11
COL12
COL13
COL14
COL15
7/1/2022
2
3
4
5
6
7
8
9
10
11
12
13
TRUE
3
7/2/2022
3
4
5
6
7
8
9
10
11
12
13
14
TRUE
4
7/3/2022
4
5
6
7
8
9
10
11
12
13
14
15
TRUE
5
7/4/2022
5
6
7
8
9
10
11
12
13
14
15
16
TRUE
6
7/5/2022
6
7
8
9
10
11
12
13
14
15
16
17
TRUE
7
7/6/2022
7
8
9
10
11
12
13
14
15
16
17
18
TRUE
8
7/7/2022
8
9
10
11
12
13
14
15
16
17
18
19
TRUE
9
7/8/2022
9
10
11
12
13
14
15
16
17
18
19
20
TRUE
10
7/9/2022
10
11
12
13
14
15
16
17
18
19
20
21
TRUE
11
7/10/2022
11
12
13
14
15
16
17
18
19
20
21
22
TRUE
12
7/11/2022
12
13
14
15
16
17
18
19
20
21
22
23
TRUE
13
7/12/2022
13
14
15
16
17
18
19
20
21
22
23
24
TRUE
14
7/13/2022
14
15
16
17
18
19
20
21
22
23
24
25
TRUE
15
7/14/2022
15
16
17
18
19
20
21
22
23
24
25
26
TRUE
16
7/15/2022
16
17
18
19
20
21
22
23
24
25
26
27
FALSE
7/16/2022
17
18
19
20
21
22
23
24
25
26
27
28
TRUE
18
7/17/2022
18
19
20
21
22
23
24
25
26
27
28
29
FALSE
7/18/2022
19
20
21
22
23
24
25
26
27
28
29
30
TRUE
20
7/19/2022
20
21
22
23
24
25
26
27
28
29
30
31
FALSE
7/20/2022
21
22
23
24
25
26
27
28
29
30
31
32
TRUE
22
You appeared to be attempting to use a trigger. However, you did not specify a trigger and there were no triggers defined in your spreadsheet. So I went without triggers.
An onEdit Version:
function onEdit(e) {
const sh = e.range.getSheet();
const incl = ['Alpha', 'Sheet2', 'Sheet3'];//Add the desired sheet names
const idx = incl.indexOf(sh.getName())
if (~idx && e.range.columnStart == 14 && e.range.rowStart > 2 && e.value == "TRUE") {
const dt = new Date();
const dtv = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
let d = new Date(sh.getRange(e.range.rowStart, 1).getValue());
let dv = new Date(d.getFullYear(), d.getMonth(), d.getDate());
e.range.offset(0, 1).setValue(DiffInDays(dtv, dv));
}
}
To insert timestamps in column O when the checkboxes in column N are ticked, use a timestamping script such as yetAnotherTimestamp_ with these parameters:
// [START modifiable parameters]
{
sheetName: /^(Alpha|Beta|Charlie|Delta)$/i,
watchColumn: ['N'],
stampColumn: ['O'],
watchRowStart: 3,
watchRowEnd: +Infinity,
timestampFormat: 'yyyy-MM-dd',
overwriteTimestamp: true,
eraseTimestampOnDelete: true,
},
// [END modifiable parameters]
Then put this formula in cell P2:
=arrayformula(
{
"Days Elapsed";
if( N3:N = "Yes", O3:O - A3:A, iferror(1/0) )
}
)
The formula will give the number of days between the timestamp and the form submission in the rows where a checkbox is ticked.
I make this program to practice cudaMemcpy3D() and Texture Memory.
Here comes the questions,when I print out tex3D data,it is not same as initial data.The value I get is ncrss times the initial value, and there are ncrss interval numbers which equal to 0 between each other. If I set nsubs to 2 or other bigger one, the time should be ncrss*nsubs and interval will be ncrss*nsubs.
Can you piont out where I made the mistakes. I think it probably is make_cudaPitchedPtr at line 61, or make_cudaExtent at line 56. And also may related with the way of array storaged.
So I come here for your help,appreciate for your comments and advices.
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<cuda_runtime.h>
4 #include<helper_functions.h>
5 #include<helper_cuda.h>
6 #ifndef MIN
7 #define MIN(A,B) ((A) < (B) ? (A) : (B))
8 #endif
9 #ifndef MAX
10 #define MAX(A,B) ((A) > (B) ? (A) : (B))
11 #endif
12
13 texture<float,cudaTextureType3D,cudaReadModeElementType> vel_tex;
14
15 __global__ void mckernel(int ntab)
16 {
17 const int biy=blockIdx.y;//sub
18 const int bix=blockIdx.x;//crs
19 const int tid=threadIdx.x;
20
21 float test;
22 test=tex3D(vel_tex,biy,bix,tid);
23 printf("test=%f,bix=%d,tid=%d\n",test,bix,tid);
24
25 }
26
27 int main()
28 {
29 int n=10;//208
30 int ntab=10;
31 int submin=1;
32 int crsmin=1;
33 int submax=1;
34 int crsmax=2;
35 int subinc=1;
36 int crsinc=1;
37
38 int ncrss,nsubs;
39 ncrss=(crsmax-crsmin)/crsinc + 1;
40 nsubs=(submax-submin)/subinc + 1;
41 dim3 BlockPerGrid(ncrss,nsubs,1);
42 dim3 ThreadPerBlock(n,1,1);
43
44 float vel[nsubs][ncrss][ntab];
45 int i,j,k;
46 for(i=0;i<nsubs;i++)
47 for(j=0;j<ncrss;j++)
48 for(k=0;k<ntab;k++)
49 vel[i][j][k]=k;
50 for(i=0;i<nsubs;i++)
51 for(j=0;j<ncrss;j++)
52 for(k=0;k<ntab;k++)
53 printf("vel[%d][%d][%d]=%f\n",i,j,k,vel[i][j][k]);
54
55 cudaChannelFormatDesc velchannelDesc=cudaCreateChannelDesc<float>();
56 cudaExtent velExtent=make_cudaExtent(nsubs,ncrss,ntab);
57 cudaArray *d_vel;
58 cudaMalloc3DArray(&d_vel,&velchannelDesc,velExtent);
59
60 cudaMemcpy3DParms velParms = {0};
61 velParms.srcPtr=make_cudaPitchedPtr((void*)vel,sizeof(float)*nsubs,nsubs,ncrss);
62 velParms.dstArray=d_vel;
63 velParms.extent=velExtent;
64 velParms.kind=cudaMemcpyHostToDevice;
65 cudaMemcpy3D(&velParms);
66
67 cudaBindTextureToArray(vel_tex,d_vel);
68
69 printf("kernel start\n");
70 cudaDeviceSynchronize();
71 mckernel<<<BlockPerGrid,ThreadPerBlock>>>(ntab);
72 printf("kernel end\n");
73
74 cudaUnbindTexture(vel_tex);
75 cudaFreeArray(d_vel);
76 cudaDeviceReset();
77 return 0 ;
78 }
Here comes the printf data,nsubs=1 and ncrss=2;
1 vel[0][0][0]=0.000000
2 vel[0][0][1]=1.000000
3 vel[0][0][2]=2.000000
4 vel[0][0][3]=3.000000
5 vel[0][0][4]=4.000000
6 vel[0][0][5]=5.000000
7 vel[0][0][6]=6.000000
8 vel[0][0][7]=7.000000
9 vel[0][0][8]=8.000000
10 vel[0][0][9]=9.000000
11 vel[0][1][0]=0.000000
12 vel[0][1][1]=1.000000
13 vel[0][1][2]=2.000000
14 vel[0][1][3]=3.000000
15 vel[0][1][4]=4.000000
16 vel[0][1][5]=5.000000
17 vel[0][1][6]=6.000000
18 vel[0][1][7]=7.000000
19 vel[0][1][8]=8.000000
20 vel[0][1][9]=9.000000
21 kernel start
22 kernel end
23 test=1.000000,bix=1,tid=0
24 test=3.000000,bix=1,tid=1
25 test=5.000000,bix=1,tid=2
26 test=7.000000,bix=1,tid=3
27 test=9.000000,bix=1,tid=4
28 test=1.000000,bix=1,tid=5
29 test=3.000000,bix=1,tid=6
30 test=5.000000,bix=1,tid=7
31 test=7.000000,bix=1,tid=8
32 test=9.000000,bix=1,tid=9
33 test=0.000000,bix=0,tid=0
34 test=2.000000,bix=0,tid=1
35 test=4.000000,bix=0,tid=2
36 test=6.000000,bix=0,tid=3
37 test=8.000000,bix=0,tid=4
38 test=0.000000,bix=0,tid=5
39 test=2.000000,bix=0,tid=6
40 test=4.000000,bix=0,tid=7
41 test=6.000000,bix=0,tid=8
42 test=8.000000,bix=0,tid=9
After a night thinking ,I find out the problem.
the cuda array load as M[fast][mid][low] while c array is M[low][mid][fast].
so dim3(),cudaExtent(),pitchedPtr()should be same to [low][mid][fast] or at least should be same as each other.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
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!
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
MATLAB - 10 characters
a=1:9;a'*a
... or 33 characters for stricter output format
a=1:9;disp(num2str(a'*a,'%.2d '))
Brainf**k - 185 chars
>---------[++++++++++>---------[+<[-<+>>+++++++++[->+>>---------[>-<++++++++++<]<[>]>>+<<<<]>[-<+>]<---------<]<[->+<]>>>>++++[-<++++>]<[->++>+++>+++<<<]>>>[.[-]<]<]++++++++++.[-<->]<+]
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 *
Python - 61 chars
r=range(1,10)
for y in r:print"%02d "*9%tuple(y*x for x in r)
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?
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.
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
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)
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);
}
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.
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(); });
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(" ")}
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]
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"")
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);});
C - 97 79 characters
#define f(i){int i=0;while(i++<9)
main()f(x)f(y)printf("%.2d ",x*y);puts("");}}
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}
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
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
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);
PostgreSQL: 81 74 chars
select array(select generate_series(1,9)*x)from generate_series(1,9)as x;
Ruby - 56 chars :D
9.times{|a|9.times{|b|print"%02d "%((a+1)*(b+1))};puts;}
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("");}}
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
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)}
PHP, 62 chars
for(;$x++<9;print"\n",$y=0)while($y++<9)printf("%02d ",$x*$y);
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));
}
}
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()));
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.)