-
Notifications
You must be signed in to change notification settings - Fork 0
/
kata.js
79 lines (56 loc) · 2.25 KB
/
kata.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
function graph(arr) {
if (arr.length === 0) return '';
if (arr.length === 1 && arr[0] === 0) return " ____ ^ 0"
let arrSort = [...arr].sort((a, b) => a - b);
let arrMax = arrSort[arr.length - 1];
/*
............ ____ ............ ^ 5\n
............| | ____ ...... | 4\n
...... ____ | || |...... | 3\n
......| || || |...... | 2\n
____ | || || | ____ | 1\n
| || || || || | | 0
*/
let graph = [];
for (let j = 0; j <= arrMax; j++) {
if (j === 0) {
graph.push(` | ${j}`);
} else if (j < arrMax) {
graph.push(` | ${j}\n`);
} else {
graph.push(` ^ ${j}\n`);
}
for (let i = arr.length; i >= 0; i--) {
if (arr[i] > j) {
graph.push('| |');
}
if (arr[i] === j) {
graph.push(' ____ ');
}
if (arr[i] < j) {
graph.push('......')
}
}
}
return graph.reverse().join('');
}
// BEST
/*
const graph = arr =>
(h = Math.max(...arr),
Array.from({length: h + 1}, (_, x) =>
arr.reduce((a,b,i) => (a += b === x ? ' ____ ' : b < x ? '......' : '| |', a), '')
+ ` ${(x === h ? '^' : '|')} ${x}`)
.reverse()
.join('\n'));
*/
console.log(graph([1, 3, 5, 4, 1]));
// "............ ____ ............ ^ 5\n............| | ____ ...... | 4\n...... ____ | || |...... | 3\n......| || || |...... | 2\n ____ | || || | ____ | 1\n| || || || || | | 0");
console.log(graph([1, 4, 2]));
// "...... ____ ...... ^ 4\n......| |...... | 3\n......| | ____ | 2\n ____ | || | | 1\n| || || | | 0");
console.log(graph([10, 5, 3, 1, 4]));
// " ____ ........................ ^ 10\n| |........................ | 9\n| |........................ | 8\n| |........................ | 7\n| |........................ | 6\n| | ____ .................. | 5\n| || |............ ____ | 4\n| || | ____ ......| | | 3\n| || || |......| | | 2\n| || || | ____ | | | 1\n| || || || || | | 0");
console.log(graph([]));
// "");
console.log(graph([0]));
// " ____ ^ 0");