-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolouredTriangles008.js
79 lines (51 loc) · 1.81 KB
/
colouredTriangles008.js
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
let row = "RGBG";
triangle(row);
function triangle(row) {
let prevLetters = "";
let rowLength = row.length; // so we can calculate how many times we must execute the algorithm
let triangle = [];
let result = "";
//Ean to row einai mono 1 gramma
if (rowLength === 1) {
result = row.slice(0);
console.log(" IF ", result);
}
//alliws
else {
//metra posa rows exoume
let newRowLength = rowLength;
//Outer For
for (let j = 0; j < rowLength - 1; j++) {
// Inner For
for (let i = 0; i < newRowLength - 1; i++) {
prevLetters = row.slice(i, i + 2); // Slice Start at i | end slice at possition i+2
result = result + calculateLastColor(prevLetters);
result = result.slice(-1); //Slice only the last character of result
}
newRowLength -= 1;
}
}
//console.log(triangle);
//console.log("Result: ", result);
return result;
}
function calculateLastColor(prevRow) {
let lastTwoDigits = prevRow.slice(-2); // The slice in this case, will select the last two digits in a string. If we put -1 will only select the last one etc https://stackoverflow.com/questions/3884632/how-to-get-the-last-character-of-a-string
if (lastTwoDigits.charAt(0) == lastTwoDigits.charAt(1)) return lastTwoDigits.charAt(0);
else {
switch (lastTwoDigits) {
case 'RG': return "B";
break;
case 'RB': return "G";
break;
case 'BR': return "G";
break;
case 'BG': return "R";
break;
case 'GR': return 'B';
break;
case 'GB': return 'R';
break;
}
}
}