Read sections 3.1-3.8 in chapter 3 of the textbook Explorations in Computing.
Write algorithms made up of instructions of the type shown above to draw each of the following pictures substituting in appropriate values for x, y, s and r in each instruction.
For each algorithm, the result of your last algorithmic step should be the final answer. NOTE: In the second computation, you should write only four instructions to generate the answer.
def lcm(x,y) p = x * y while y != 0 do temp = y y = x % y x = temp q = p / x end return q end
Show how this function computes lcm(24,32) by creating a table that shows the values of each variable at the end of each iteration of the loop. We have started the table for you with the initial values of the variables before the first iteration of the loop:
===================================== x y temp p q ===================================== 24 32 --- 768 --- =====================================
def lcm(x, y) return lcm2(x, y, x, y) end def lcm2(x, y, a, b) if (a == b) then return a end if (a < b) then return lcm2(x, y, a+x, b) end if (a > b) then return lcm2(x, y, a, b+y) end end
Show how lcm(24, 32) is computed recursively here by showing the chain of recursive calls that are made until an answer is found. We have started the chain for you below:
lcm(24, 32) --> lcm2(24, 32, 24, 32) --> lcm2(24, 32, 48, 32) -->
1. Set total equal to 0. 2. Set n equal to the length of the list. 3. Set i equal to 0. 4. While i is less than n, do the following: a. Add list[i] to total. b. Add 1 to i. 5. Return total / n.
def compute_average(list) end
def compute_average2(list) endHINT: Use the .each iterator operation.
codes.each{ |item| if item % 1111 == 0 then print item, "\n" end }
codes.delete_if { |x| x / 100 == x % 100 }
> s = "Penguins" => "Penguins" >> s.length => 8
Let dictionary represent an array of words stored as strings.
def sieve(n) numlist = Array(2..n) primes = [] while numlist.length > 0 do primes << numlist.first numlist.delete_if { |x| x % primes.last == 0 } end return primes end
def sieve2(n) numlist = Array(2..n) primes = [] while numlist.first < Math.sqrt(n) do primes << numlist.first numlist.delete_if { |x| x % primes.last == 0 } end return primes + numlist end
The return statement returns an array containing the values in primes followed by the values in numlist. Briefly explain why we need to do this.