-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchapter3.js
More file actions
74 lines (63 loc) · 1.35 KB
/
chapter3.js
File metadata and controls
74 lines (63 loc) · 1.35 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
console.log("Chapter 3 Exercise 1");
function min(a, b) {
if (a < b) return a;
else return b;
}
console.log(min(0, 10));
// → 0
console.log(min(0, -10));
// → -10
console.log(" ");
console.log(" ");
console.log(" ");
console.log("Chapter 3 Exercise 2");
function isEven(n) {
if (n >= 0) {
if (n == 0) return true;
else if (n == 1) return false;
else return isEven(n - 2);
} else {
return false;
}
}
// Books Solution
// function isEven(n) {
// if (n == 0) return true;
// else if (n == 1) return false;
// else if (n < 0) return isEven(-n);
// else return isEven(n - 2);
// }
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
console.log(" ");
console.log(" ");
console.log(" ");
console.log("Chapter 3 Exercise 3");
function countChar(string, char) {
let count = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] === char) count++;
}
return count;
}
function countBs(string) {
return countChar(string, "B");
}
console.log(countBs("BBC"));
// → 2
console.log(countChar("kakkerlak", "k"));
// → 4
/// Book Solution
// function countChar(string, ch) {
// let counted = 0;
// for (let i = 0; i < string.length; i++) {
// if (string[i] == ch) {
// counted += 1;
// }
// }
// return counted;
// }