Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf79bbc1

Browse files
refactor 59
1 parent56d2949 commitf79bbc1

File tree

2 files changed

+69
-3
lines changed

2 files changed

+69
-3
lines changed

‎src/main/java/com/fishercoder/solutions/_59.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,69 @@ public int[][] generateMatrix(int n) {
3838
returnmatrix;
3939
}
4040
}
41+
42+
publicstaticclassSolution2 {
43+
/**
44+
* My completely original solution on 10/12/2021.
45+
*/
46+
publicint[][]generateMatrix(intn) {
47+
intdirection =0;
48+
int[][]matrix =newint[n][n];
49+
intnum =1;
50+
inti =0;
51+
intj =0;
52+
inteastBoundary =n;
53+
intsouthBoundary =n;
54+
intwestBoundary =0;
55+
intnorthBoundary =0;
56+
intlimit =n *n;
57+
while (num <=limit) {
58+
if (direction %4 ==0) {
59+
//0 means going east
60+
for (;j <eastBoundary &&num <=limit;j++) {
61+
matrix[i][j] =num;
62+
num++;
63+
}
64+
j--;
65+
direction++;
66+
eastBoundary--;
67+
i++;
68+
}
69+
if (direction %4 ==1) {
70+
//1 means going south
71+
for (;i <southBoundary &&num <=limit;i++) {
72+
matrix[i][j] =num;
73+
num++;
74+
}
75+
i--;
76+
direction++;
77+
southBoundary--;
78+
j--;
79+
}
80+
if (direction %4 ==2) {
81+
//2 means going west
82+
for (;j >=westBoundary &&num <=limit;j--) {
83+
matrix[i][j] =num;
84+
num++;
85+
}
86+
j++;
87+
direction++;
88+
westBoundary++;
89+
i--;
90+
}
91+
if (direction %4 ==3) {
92+
//3 means going north
93+
for (;i >northBoundary &&num <=limit;i--) {
94+
matrix[i][j] =num;
95+
num++;
96+
}
97+
i++;
98+
direction++;
99+
northBoundary++;
100+
j++;
101+
}
102+
}
103+
returnmatrix;
104+
}
105+
}
41106
}

‎src/test/java/com/fishercoder/_59Test.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,17 @@
77

88
publicclass_59Test {
99
privatestatic_59.Solution1solution1;
10-
privatestaticint[][]matrix;
10+
privatestatic_59.Solution2solution2;
1111

1212
@BeforeClass
1313
publicstaticvoidsetup() {
1414
solution1 =new_59.Solution1();
15+
solution2 =new_59.Solution2();
1516
}
1617

1718
@Test
1819
publicvoidtest1() {
19-
matrix =solution1.generateMatrix(6);
20-
CommonUtils.print2DIntArray(matrix);
20+
CommonUtils.print2DIntArray(solution1.generateMatrix(6));
21+
CommonUtils.print2DIntArray(solution2.generateMatrix(6));
2122
}
2223
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp