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
103
104
105
106
107
108
109
110
111
112
113
|
# COMP-200: Intro to Computer Systems
## Assignment 1
### mo khan - 3431709
Choose ONE exercise each from Chapters 2 and 3
Chapter 2:
4. Write an algorithm that gets the price for item A plus the quantity
purchased. The algorithm prints the total cost, including 6% sales tax.
Pseudocode
```plaintext
Get values for `price` and `quantity`
Set the value of `tax` to 1.06
Set the value of `total` to `price` multiplied by `quantity` multiplied by `tax`
Print the value of `total`
```
Ruby code
```ruby
def calculate_total(price, quantity, tax = 0.06)
(price * quantity) * (1.0 + tax)
end
```
Chapter 3:
21. Use the binary search algorithm to decide whether 35 is in the following
list: `3, 6, 7, 9, 12, 14, 18, 21, 22, 31, 43`
Pseudocode
```plaintext
Get the list of numbers and assign to variable `items`
Get the target number and assign to variable `target`
Set variable `min` to 0
Set variable `max` to total # of `items`
Set variable `mid` to `max - min / 2`
Set variable `found` to No
while (mid > min && mid < max)
Set the variable `current` to `items` at index `mid`
if current = target
Set variable `found` to Yes
Set variable `mid` to `min - 1`
else if target > current
Set variable `min` to the value of `mid`
Set the variable `mid` to `((max-min) / 2) + min`
else
Set variable `max` to the value of `mid`
Set the variable `mid` to `((max-min) / 2) + min`
end
end of loop
If Found = Yes
print Found
else
print Not Found
stop
```
Ruby code
```ruby
def bsearch(target, items)
min = 0
max = items.size
mid = (max - min) / 2
while (mid > min && mid < max) do
current = items[mid]
if target == current
return true
elsif target > current
min = mid
else
max = mid
end
mid = ((max - min) / 2) + min
end
return false
end
```
What numbers will be compared with 35?
1. 14
| 00 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 |
| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
| 03 | 06 | 07 | 09 | 12 | 14 | 18 | 21 | 22 | 31 | 43 |
2. 22
| 00 | 01 | 02 | 03 | 04 |
| -- | -- | -- | -- | -- |
| 18 | 21 | 22 | 31 | 43 |
3. 31
| 00 | 01 |
| -- | -- |
| 31 | 43 |
4. 43
| 00 |
| -- |
| 43 |
|