Section 1

Preview this deck

In this exercise, I'd like you to write a method num_to_s(num, base), which will convert a number to a string in a different base. For instance, num_to_s(123, 10) == "123" and num_to_s(4, 2) == 100. It should work for bases up to 16 (hexadecimal).

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (21)

Section 1

(21 cards)

In this exercise, I'd like you to write a method num_to_s(num, base), which will convert a number to a string in a different base. For instance, num_to_s(123, 10) == "123" and num_to_s(4, 2) == 100. It should work for bases up to 16 (hexadecimal).

Front

def num_to_s(num, base) end def array_base(num, base) arr = [] while num != 0 && num != 1 digit = num%base num = num/base arr.unshift(digit) end if num == 1 arr.unshift(1) end arr end

Back

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

Front

def prime?(num) if num = 1 || num = 2 || num = 3 return true end (4...num).each {|x| return false if num % x == 0} true end def factor?(x, y) if y % x == 0 return true end false end def largest_prime(number) #debugger # must be prime, must be factor current_largest_prime = 1 current_largest_product = 1 x = 1 while current_largest_product < number && x <= (number/2) #program will run too long if we check every number till entered # if prime?(x) && factor?(x, number) current_largest_prime = x current_largest_product *= current_largest_prime end x+=1 end current_largest_prime end

Back

#sum of multiples of 3 and 5 below 1000

Front

y = 0 (0...1000).each {|x| y = x+y if (x%3 == 0) || (x%5 == 0)} puts y

Back

# Write a function, `nearest_larger(arr, i)` which takes an array and an # index. The function should return another index, `j`: this should # satisfy: # # (a) `arr[i] < arr[j]`, AND # (b) there is no `j2` closer to `i` than `j` where `arr[i] < arr[j]`. # # In case of ties (see example below), choose the earliest (left-most) # of the two indices. If no number in `arr` is larger than `arr[i]`, # return `nil`.

Front

def nearest_larger(arr, idx) diff = 1 loop do left = idx - diff right = idx + diff if (left >= 0) && (arr[left] > arr[idx]) return left elsif (right < arr.length) && (arr[right] > arr[idx]) return right elsif (left < 0) && (right >= arr.length) return nil end diff += 1 end end def nearest_larger(arr, idx) # arr[i] < arr[j] # there is no j2 closer to i than j where arr[i] < arr[j] #in ties choose earliest #if no larger return nil i = idx if i == 0 n = i+1 while n < arr.length if arry[n] > arr[i] return n end n+1 end if i == arr.length-1 n = i-1 while n >= 0 if arr[n] > arr[i] return n end n-1 end end else low = i-1 high = i+1 while low >=0 || high < arr.length if low >= 0 if arr[low] > arr[i] return low end end if high < arr.length if arr[high] > arr[i] return high end end low -= 1 high += 1 end end return "boo" end

Back

Catsylvanian money is a strange thing: they have a coin for every # denomination (including zero!). A wonky change machine in # Catsylvania takes any coin of value N and returns 3 new coins, # valued at N/2, N/3 and N/4 (rounding down). # # Write a method `wonky_coins(n)` that returns the number of coins you # are left with if you take all non-zero coins and keep feeding them # back into the machine until you are left with only zero-value coins. #

Front

def wonky_coins(n) return 1 if n == 0 # call wonky_coins from inside itself. This is called recursion. return wonky_coins(n / 2) + wonky_coins(n / 3) + wonky_coins(n / 4) end

Back

# Write a function `bubble_sort(arr)` which will sort an array of # integers using the "bubble sort" # methodology. (http://en.wikipedia.org/wiki/Bubble_sort) #

Front

def bubble_sort(arr) sorted = false until sorted sorted = true (arr.count - 1).times do |i| print i if arr[i] > arr[i + 1] arr[i], arr[i + 1] = arr[i + 1], arr[i] sorted = false end end end arr end

Back

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Front

def largest_divisible_by_20() x = 2357911131517*19 y = 234567891011121314151617181920 range = Array.new range = (2..20).to_a while x < y if range.all? {|num| x % num == 0} return x end x+=10 end end

Back

"Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"."

Front

arr = (1...100).map do |x| if x % 3 == 0 && x % 5 == 0 x = "FizzBuzz" elsif x % 3 == 0 x = "Fizz" elsif x % 5 == 0 x = "Buzz" else x = x end end

Back

# Build a function, `morse_encode(str)` that takes in a string (no # numbers or punctuation) and outputs the morse code for it. See # http://en.wikipedia.org/wiki/Morse_code. Put two spaces between # words and one space between letters. # # You'll have to type in morse code: I'd use a hash to map letters to # codes. Don't worry about numbers. # # I wrote a helper method `morse_encode_word(word)` that handled a # single word.

Front

def morse_encode(str) words = str.split(" ") encoded_words = words.map { |word| morse_encode_word(word) } encoded_words.join(" ") end def morse_encode_word(word) letters = word.split("") codes = letters.map { |l| MORSE_CODE[l] } codes.join(" ") end

Back

# Write a function, `letter_count(str)` that takes a string and # returns a hash mapping each letter to its frequency. Do not include # spaces. #

Front

def letter_count(str) counts = {} str.each_char do |char| next if char == " " counts[char] = 0 unless counts.include?(char) counts[char] += 1 end counts end

Back

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Front

def fib(num) fib = [1, 2] n = 0 p = n+1 while fib[n]+fib[p] <= num fib << (fib[n]+fib[p]) n += 1 p = n+1 end evens = fib.select {|x| x.even? } final = evens.inject {|sum, x| sum+x} final end

Back

#Experiment by writing a couple of short programs that will use Hashes to count objects by incrementing a key value.

Front

def count_objects(array) hash = {} #find values, make key when see again array.each_char do |char| next if char == " " hash[char] = 0 unless hash.includes?(char) hash[char] += 1 end hash end

Back

array of numbers: give the smallest and biggest #

Front

def small_big(array) small = arr[0] big = arr[0] (0...array.count).each do |x| if x > big big = x end if x < small small = x end end return small, big end

Back

Problem: you have 100 doors in a row that are all initially closed. you make 100 passes by the doors starting with the first door every time. the first time through you visit every door and toggle the door (if the door is closed, you open it, if its open, you close it). the second time you only visit every 2nd door (door #2, #4, #6). the third time, every 3rd door (door #3, #6, #9), etc, until you only visit the 100th door.

Front

#100 doors problem def switch(x) if x == 0 x = 1 else x = 0 end end def pass(num, array) array = array.map.with_index do |x, index| if (index+1) % num == 0 switch(x) else x = x end end array end def game(doors) line = [] doors.times do |i| line << 0 end #print line #print "
" n = 1 while n <= doors line = pass(n, line) #print line #print "
" n+= 1 end line end

Back

# Write a function, `no_repeats(year_start, year_end)`, which takes a # range of years and outputs those years which do not have any # repeated digits. # # You should probably write a helper function, `no_repeat?(year)` which # returns true/false if a single year doesn't have a repeat. #

Front

def no_repeats(year_start, year_end) no_repeats = [] (year_start..year_end).each do |yr| no_repeats << yr if no_repeat?(yr) end no_repeats end def no_repeat?(year) chars_seen = [] year.to_s.each_char do |char| return false if chars_seen.include?(char) chars_seen << char end return true end

Back

Suppose I have the following Array of tuples #[ ['a',1], ['b',2], ['c','3' ] #How can I convert this to a Hash? #{ 'a' => 1, 'b' => 2, 'c' => 3}

Front

def convert(array) arrayHash = Hash[array] arrayHash end

Back

Caesar Cipher Implement a Caesar cipher. Example: caesar("hello", 3) # => "khoor" Assume the text is all lower case letters. You'll probably want to map letters to numbers (so you can shift them). You can do this mapping yourself, but you may also want to use the ASCII codes, which are accessible through String#each_byte. You will probably also want to use String#ord and Fixnum#chr. Important point: ASCII codes are all consecutive! Lastly, be careful of the letters at the end of the alphabet, like "z"!

Front

def caesar(word, num) # split word to become array array = word.split("") #map word array to ascii codes codes = array.map {|c| c.ord } print codes #use map again to add num to each entry, caesar = codes.map do |c| if c==122 c=96+num else c+3 end end letters = caesar.map {|i| i.chr } letters.join end

Back

#Sort an array of strings by the length of the string in Ruby

Front

def sort_length(string) sorted = false array = string.split(' ') until sorted sorted = true (0...array.count-1).each do |word| if array[word].length > array[word+1].length array[word], array[word+1] = array[word+1], array[word] sorted = false end end end array.join(" ") end

Back

# Write a function, `rec_intersection(rect1, rect2)` and returns the # intersection of the two. # # Rectangles are represented as a pair of coordinate-pairs: the # bottom-left and top-right coordinates (given in `[x, y]` notation). # # Hint: You can calculate the left-most x coordinate of the # intersection by taking the maximum of the left-most x coordinate of # each rectangle. Likewise, you can calculate the top-most y # coordinate of the intersection by taking the minimum of the top most # y coordinate of each rectangle. #

Front

def rec_intersection(rect1, rect2) x_min = [rect1[0][0], rect2[0][0]].max x_max = [rect1[1][0], rect2[1][0]].min y_min = [rect1[0][1], rect2[0][1]].max y_max = [rect1[1][1], rect2[1][1]].min return nil if ((x_max < x_min) || (y_max < y_min)) return [[x_min, y_min], [x_max, y_max]] end

Back

Write a method, `ordered_vowel_words(str)` that takes a string of # lowercase words and returns a string with just the words containing # all their vowels (excluding "y") in alphabetical order. Vowels may # be repeated (`"afoot"` is an ordered vowel word). # # You will probably want a helper method, `ordered_vowel_word?(word)` # which returns true/false if a word's vowels are ordered. #

Front

def ordered_vowel_words(str) words = str.split(" ") ordered_vowel_words = words.select do |word| ordered_vowel_word?(word) end ordered_vowel_words.join(" ") end def ordered_vowel_word?(word) vowels = ["a", "e", "i", "o", "u"] letters_arr = word.split("") vowels_arr = letters_arr.select { |l| vowels.include?(l) } (0...(vowels_arr.length - 1)).all? do |i| vowels_arr[i] <= vowels_arr[i + 1] end end MYSOLUTION def ordered_values(str) str = str.split(' ') ordered = [] n = 0 while n < str.length if ordered_vowel_word?(str[n]) == true ordered << str[n] end n += 1 end return ordered.join(" ") end def ordered_vowel_word?(word) list = word.scan(/[aeiou]/) if list == list.sort return true end return false end

Back

# Write a function word_unscrambler that takes two inputs: a scrambled # word and a dictionary of real words. Your program must then output # all words that our scrambled word can unscramble to. # # Hint: To see if a string `s1` is an anagram of `s2`, split both # strings into arrays of letters. Sort the two arrays. If they are # equal, then they are anagrams.

Front

def word_unscrambler(str, words) str_letters = str.split("").sort anagrams = [] words.each do |word| word_letters = word.split("").sort anagrams << word if str_letters == word_letters end anagrams end

Back