-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem.js
More file actions
90 lines (75 loc) · 1.89 KB
/
problem.js
File metadata and controls
90 lines (75 loc) · 1.89 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
/*
John Kusner
jjk320@lehigh.edu
CSE 264
Final Project
*/
const { randInt, randChoice } = require('./random');
const OPERATIONS = ['+', '-', '*'];
function randOperand(makeProblem=false) {
if (makeProblem) {
return Problem.generate(false);
}
return randInt(6) * (Math.random() > .8 ? -1 : 1);
}
function randOperator() {
return randChoice(OPERATIONS);
}
class Problem {
constructor(a, b, op) {
this.a = a;
this.b = b;
this.op = op;
this.solution = this.solve();
this.str = this.toString();
}
solve() {
let a = Problem.sln(this.a);
let b = Problem.sln(this.b);
if (this.op === '+') {
return a + b;
} else if (this.op === '-') {
return a - b;
} else if (this.op === '*') {
return a * b;
} else {
throw 'OPERATOR ' + this.op + ' UNKNOWN!';
}
}
toString() {
let result = '';
if (this.a instanceof Problem) {
result += '(' + this.a.toString() + ')';
} else {
result += this.a;
}
result += ' ' + this.op + ' ';
if (this.b instanceof Problem) {
result += '(' + this.b.toString() + ')';
} else {
result += this.b;
}
// Avoid weird -0 result
if (result === 0) result = 0;
return result;
}
static generate(nest=true) {
let a = randOperand(nest && Math.random() > .5);
let b = randOperand();
// flip a and b
if (Math.random() > .5) {
let temp = a;
a = b;
b = temp;
}
let op = randOperator();
return new Problem(a, b, op);
}
static sln(p) {
if (p instanceof Problem) {
return p.solution;
}
return p;
}
}
module.exports = Problem