-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsortanimals.js
94 lines (80 loc) · 2.22 KB
/
sortanimals.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
function SortModel() {
var self = this;
self.prefix = 'xyz';
Model.call(self);
self.title("Blocky Sort Animals");
self.reverse = ko.observable(false);
self.problem = ko.computed(function() {
if (self.reverse()) {
return "Define an algorithm that sorts the array of animals below in descending order according to their weights:";
} else {
return "Define an algorithm that sorts the array of animals below in ascending order according to their weights:";
}
}, self);
self.checkSucceeded = function() {
var valid = true;
var rev = self.reverse();
for (var i=1; i<self.array().length; i++) {
var wi = self.animalsLookup[self.array()[i]];
var wimin = self.animalsLookup[self.array()[i-1]];
if ((!rev & wimin > wi) ||
(rev & wimin < wi) ) {
valid = false;
break;
}
};
self.succeeded(valid);
}
self.newProblem = function() {
self.seed(Math.ceil(Math.random() * 1000));
self.reset();
}
self.sortedProblem = function() {
self.seed(Math.ceil(Math.random() * 20) - 20);
self.reset();
}
self.invSortedProblem = function() {
self.seed(Math.ceil(Math.random() * 80) - 100);
self.reset();
}
self.animalsLookup = {
'Tiger': 303,
'Elephant': 2721,
'Turtle': 249,
'Pelican': 14,
'Mouse': 0.019,
'Dog': 68,
'Horse': 453
}
self.animals = Object.keys(self.animalsLookup);
self.weights = [];
for (var x in self.animals) {
self.weights.push(self.animalsLookup[self.animals[x]]);
}
self.reset = function() {
var seed = self.seed();
self.interpreter = null;
self.succeeded(false);
self.steps(0);
self.array.removeAll();
var keys = self.animals;
var ar = [];
var rng = new MersenneTwister(seed);
for (var i=0; i<self.n(); i++) {
ar.push(keys[Math.floor(rng.random() * keys.length)]);
}
if (seed < 0) {
if (seed > -20) {
ar.sort()
} else {
ar.sort(function(a,b) { b-a;});
}
}
self.array(ar);
}
self.newProblem();
}
SortModel.prototype = Object.create(Model.prototype);
SortModel.prototype.init = function() {
Object.getPrototypeOf(SortModel.prototype).init.call(this);
}