-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathblocks.js
More file actions
102 lines (81 loc) · 1.9 KB
/
blocks.js
File metadata and controls
102 lines (81 loc) · 1.9 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
var Blocks = function(){
this.storage = [];
}
Blocks.prototype.init = function(size){
for (var i = 0; i < size; i++){
this.storage.push([i]);
}
}
Blocks.prototype.move = function(a, b){
if (a === b){
console.log('a is equal to b');
return;
}
var aAdd;
var bAdd;
this.storage.forEach(function(inArr){
if (!aAdd){
aAdd = inArr.indexOf(a) > -1 ? inArr : undefined;
}
if (!bAdd){
bAdd = inArr.indexOf(b) > -1 ? inArr : undefined;
}
})
// a and b info found;
if (aAdd === bAdd){
console.log('a in same stack as b');
return;
}
while (aAdd[aAdd.length - 1] !== a){
var temp = aAdd.pop();
this.storage[temp].push(temp);
}
while (bAdd[bAdd.length - 1] !== b){
var temp = bAdd.pop();
this.storage[temp].push(temp);
}
bAdd.push(aAdd.pop());
}
var test = new Blocks();
// test.init(8);
// test.move(7, 1);
// test.move(5, 1);
// test.move(1, 6);
// test.move(4, 3);
// test.move(1, 4);
// test.move(3, 1);
// test.move(5, 2);
// test.move(7, 5);
// test.move(4, 5);
var parser = function(work, text){
if (/^\d+$/.test(text)){
work.init(parseInt(text, 10));
} else if (text.slice(0, 4) === 'move'){
text = text.split(' ');
var a = parseInt(text[1], 10);
var b = parseInt(text[3], 10);
work.move(a, b);
} else {
work.storage.forEach(function(inArr, index){
if (inArr.length === 0){
console.log(index + ':');
} else {
var key = index + ': ';
var value = inArr.join(' ');
console.log(key + value);
}
})
}
}
parser(test, '8');
parser(test, 'move 7 onto 1');
parser(test, 'move 5 onto 1');
parser(test, 'move 1 onto 6');
parser(test, 'move 4 onto 3');
parser(test, 'move 1 onto 4');
parser(test, 'move 3 onto 1');
parser(test, 'move 5 onto 2');
parser(test, 'move 7 onto 5');
parser(test, 'move 4 onto 5');
parser(test, 'quit');
// console.log(test.storage);