-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlassStacking.java
More file actions
103 lines (91 loc) · 2.1 KB
/
GlassStacking.java
File metadata and controls
103 lines (91 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.util.*;
import java.io.*;
import java.math.*;
/**
* github: albaad
**/
class GlassStacking {
static Integer[] nbrglasses = { 1, 3, 6, 10, 15, 21, 28 };
public static String[] singleGlass(int offset) {
String[] glass = new String[4];
for (int i = 0; i < 4; i++) {
glass[i] = glassLine(i, offset);
}
return glass;
}
public static String glassLine(int i, int offset) {
String line = offset(offset);
switch (i) {
case 0:
line += " *** ";
break;
case 1:
case 2:
line += " * * ";
break;
case 3:
line += "*****";
break;
default:
break;
}
return line;
}
// n glasses with offset on this level
public static String[] multiGlass(int offset, int n) {
String[] glasses = new String[4];
for (int i = 0; i < 4; i++) {
glasses[i] = glassLine(i, offset);
for (int j = 1; j < n; j++) {
glasses[i] += " " + glassLine(i, 0);
}
glasses[i] += offset(offset);
}
return glasses;
}
public static String offset(int n) {
String off = "";
for (int i = 1; i <= n; i++) {
off += " ";
}
return off;
}
public static int determineGlasses(int N) {
if (N <= 0 || N >= 30) {
return -1;
}
while (Arrays.asList(nbrglasses).indexOf(N) == -1) {
N = N - 1;
}
return N;
}
// level starts from the ground = 0
public static int determineOffset(int level, int nbrlevels) {
int offset = 3 * level;
return offset;
}
public static int determineLevels(int N) {
return Arrays.asList(nbrglasses).indexOf(N) + 1;
}
public static void printGlass(String[] glass) {
for (int i = 0; i < glass.length; i++) {
System.out.println(glass[i]);
}
}
public static void glassStacking(int N) {
// Determine number of glasses of the pyramid
N = determineGlasses(N);
// Determine number of levels
int levels = determineLevels(N);
// Loop the levels and create each row
for (int i = 0; i < levels; i++) {
String[] glass = multiGlass(determineOffset(levels - i - 1, levels), i + 1);
printGlass(glass);
}
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
glassStacking(N);
}
}