Fall 2024 Ruby Exam
Problem 1
Write a function peel
that accepts a string parameter that is surrounded by 0 or more matching pairs of parentheses ((...)
), square brackets ([...]
), curly braces ({...}
), or angle brackets (<...>
). It returns a new string in which the matching characters have been peeled off. Non-matching or non-surrounding characters are not removed. For example:
-
peel("(brunt)")
→"brunt"
-
peel("[[{A S A P!}]]")
→"A S A P!"
-
peel("<>")
→""
-
peel("{y()u}")
→"y()u"
-
peel("{heat]}")
→"heat]"
Problem 2
Define a function pivots
that accepts an array of integers. It returns a corresponding array of hashes. Each hash has three fields. Field pivot
is the integer from the original array. Field lessers
is an array of numbers less than the pivot in the order they appear in the original array. Field greaters
is an array of numbers greater than the pivot in the order they appear in the original array. For example:
> p pivots([3, 0, 7, 2])
[
{pivot: 3, lessers: [0, 2], greaters: [7]},
{pivot: 0, lessers: [], greaters: [3, 7, 2]},
{pivot: 7, lessers: [3, 0, 2], greaters: []},
{pivot: 2, lessers: [0], greaters: [3, 7]},
]
Don't use loops or each
.
Problem 3
Write class Flipper
that has a method flip
. The first time it is called, it returns true
. The second time false
. The third time true
. And so on.
Problem 4
Write function subtotal
that receives an array of pairs (which are arrays of 2 elements). The first element of pair is a symbol denoting a category. The second element is an amount. Return a hash that associates each category with its total amount. For example:
-
subtotal([[:food, 15], [:utilities, 62.43], [:food, 7.25]])
→{food: 22.25, utilities: 62.43}
-
subtotal([[:blue, 1], [:brown, 1], [:blue, 1], [:blue, 1]])
→{blue: 3, brown: 1}
Don't use loops or each
.
Problem 5
Write a script that receives an arbitrary number of non-negative integers as command-line arguments. It prints a histogram of the numbers with buckets of size 10 in the following manner:
> ruby histogram.rb 9 6 38 13
0-9: 2
10-19: 1
20-29: 0
30-39: 1
Empty buckets are not printed unless they are between non-empty buckets.
Problem 6
A round-robin iteration visits items in an established order and with equal attention. For example, a round-robin iteration of the items C, B, and A might visit items in the sequence A, B, C, A, B, C, A, B, C, A... Define class RoundRobin
to manage a collection of items you want to visit in a round-robin fashion. It has the following methods:
- a constructor that initializes the collection to be empty
-
add
, which accepts a new item as a parameter. It places the item in the collection, scheduling it so that it will be visited next. This method can be called at any time, including after visiting previously added items. -
visit
, which returns the next item in the collection.