From ea1b7f97a5439ead107392401490edb97b1edb4d Mon Sep 17 00:00:00 2001 From: Tom Spencer Date: Mon, 4 Sep 2017 22:45:55 +0100 Subject: [PATCH 1/6] new exercises 1.1 and 1.2 --- session1/challenge/1_arithmetic.rb | 3 ++- session1/challenge/2_arithmetic.rb | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/session1/challenge/1_arithmetic.rb b/session1/challenge/1_arithmetic.rb index fbe40463..1c099b98 100644 --- a/session1/challenge/1_arithmetic.rb +++ b/session1/challenge/1_arithmetic.rb @@ -3,11 +3,12 @@ # $ rake 1:1 # Given a number, return 20 less than, that number multiplied by 5 -# +# # arithmetic1(10) # => 30 # arithmeitc1(10.5) # => 32.5 # arithmeitc1(-6) # => -50 def arithmetic1(n) # the code for this method goes in here + (n * 5) - 20 end diff --git a/session1/challenge/2_arithmetic.rb b/session1/challenge/2_arithmetic.rb index 21445b42..691a4436 100644 --- a/session1/challenge/2_arithmetic.rb +++ b/session1/challenge/2_arithmetic.rb @@ -9,4 +9,5 @@ # arithmetic2(-6, -7) # => -3.5 def arithmetic2(a, b) + a < b ? a.to_f / 2 : b.to_f / 2 end From 6d21a19a3603b4a8db597653f879f16aeed0b3f6 Mon Sep 17 00:00:00 2001 From: Tom Spencer Date: Wed, 6 Sep 2017 17:08:40 +0100 Subject: [PATCH 2/6] completes session1 --- session1/challenge/3_simple_logic.rb | 1 + session1/challenge/4_logic.rb | 17 ++++++++++++++--- session1/challenge/5_string.rb | 3 ++- session1/challenge/6_string.rb | 11 +++++++++-- session1/challenge/7_string.rb | 11 ++++++++++- session2/challenge/1_input_output.rb | 8 ++++++-- session2/challenge/2_input_output_control.rb | 12 +++++++++--- session3/challenge/1_blocks.rb | 5 +++++ 8 files changed, 56 insertions(+), 12 deletions(-) diff --git a/session1/challenge/3_simple_logic.rb b/session1/challenge/3_simple_logic.rb index c5f23c1c..7442bb3b 100644 --- a/session1/challenge/3_simple_logic.rb +++ b/session1/challenge/3_simple_logic.rb @@ -9,4 +9,5 @@ def ten_twenty(n) # your code goes here + n % 2 == 0 ? 10 : 20 end diff --git a/session1/challenge/4_logic.rb b/session1/challenge/4_logic.rb index 6cc87dbc..a6b59d2f 100644 --- a/session1/challenge/4_logic.rb +++ b/session1/challenge/4_logic.rb @@ -1,6 +1,6 @@ # A grad student at a local university thinks he has discovered a formula to -# predict what kind of grades a person will get. He says if you own less than -# 10 books, you will get a "D". If you own 10 to 20 books, you will get a "C", +# predict what kind of grades a person will get. He says if you own less than +# 10 books, you will get a "D". If you own 10 to 20 books, you will get a "C", # and if you own more than 20 books, you will get a "B". # He further hypothesizes that if you actually read your books, then you will # get a full letter grade higher in every case. @@ -10,4 +10,15 @@ # grade(15, true) # => "B" def grade(num_books, reads_books) -end \ No newline at end of file + grade = "" + if reads_books + grade = "C" if num_books < 10 + grade = "B" if num_books >= 10 + grade = "A" if num_books > 20 + else + grade = "D" if num_books < 10 + grade = "C" if num_books >= 10 + grade = "B" if num_books > 20 + end + return grade +end diff --git a/session1/challenge/5_string.rb b/session1/challenge/5_string.rb index 7901fc58..cfa605f5 100644 --- a/session1/challenge/5_string.rb +++ b/session1/challenge/5_string.rb @@ -1,8 +1,9 @@ # Given a string, replace every instance of sad to happy -# +# # add_more_ruby("The clowns were sad.") # => "The clowns were happy." # add_more_ruby("The sad dad said sad stuff.") # => "The happy dad said happy stuff." # add_more_ruby("Sad times are ahead!") # => "Happy times are ahead!" def add_more_ruby(string) + string.gsub("sad", "happy").gsub("Sad", "Happy") end diff --git a/session1/challenge/6_string.rb b/session1/challenge/6_string.rb index 0fc38d0f..9697cdaf 100644 --- a/session1/challenge/6_string.rb +++ b/session1/challenge/6_string.rb @@ -1,11 +1,18 @@ # You'll get a string and a boolean. # When the boolean is true, return a new string containing all the odd characters. # When the boolean is false, return a new string containing all the even characters. -# +# # If you have no idea where to begin, remember to check out the cheatsheets for string and logic/control -# +# # odds_and_evens("abcdefg",true) # => "bdf" # odds_and_evens("abcdefg",false) # => "aceg" def odds_and_evens(string, return_odds) + final_string = "" + string.size.times do |i| + next if i.even? && return_odds + next if i.odd? && !return_odds + final_string << string[i] + end + return final_string end diff --git a/session1/challenge/7_string.rb b/session1/challenge/7_string.rb index 4d4ea2a8..c5a619ed 100644 --- a/session1/challenge/7_string.rb +++ b/session1/challenge/7_string.rb @@ -1,8 +1,17 @@ # given a string, return the character after every letter "r" -# +# # pirates_say_arrrrrrrrr("are you really learning Ruby?") # => "eenu" # pirates_say_arrrrrrrrr("Katy Perry is on the radio!") # => "rya" # pirates_say_arrrrrrrrr("Pirates say arrrrrrrrr") # => "arrrrrrrr" + def pirates_say_arrrrrrrrr(string) + to_return = "" + add_next = false + string.size.times do |index| + current_char = string[index] + to_return << current_char if add_next + add_next = (current_char == "r" || current_char == "R") + end + to_return end diff --git a/session2/challenge/1_input_output.rb b/session2/challenge/1_input_output.rb index 06622c97..734f0a23 100644 --- a/session2/challenge/1_input_output.rb +++ b/session2/challenge/1_input_output.rb @@ -3,10 +3,14 @@ # Write a program that reads in two integers typed on the keybaord # and outputs their sum, difference, and product -# +# # Standard input will be like "9 2\n" and will expect you to print # "11\n7\n18\n" to standard output. def sum_difference_product # your code goes here -end \ No newline at end of file + a, b = gets.split.map {|i| i.to_i} + puts a + b + puts a - b + puts a * b +end diff --git a/session2/challenge/2_input_output_control.rb b/session2/challenge/2_input_output_control.rb index c618f11a..cdc65a63 100644 --- a/session2/challenge/2_input_output_control.rb +++ b/session2/challenge/2_input_output_control.rb @@ -1,5 +1,5 @@ # Prompt the user for a number, then read it in and print out "hi" that many times -# +# # Repeat this process until the user submits "bye", then say "goodbye" and end the program # HINT: Check out example 2 if you get stuck @@ -20,12 +20,18 @@ def hi_hi_goodbye # your code here + return "goodbye" if gets.chomp == "bye" + while num = gets.chomp + num.times do + puts "hi" + end + end # This will just invoke the method if you run this program directly -# This way you can try it out by running "$ ruby 2_input_output_control.rb" +# This way you can try it out by running "$ ruby 2_input_output_control.rb" # but it will still work for our tests -hi_hi_goodbye if $0 == __FILE__ \ No newline at end of file +hi_hi_goodbye if $0 == __FILE__ diff --git a/session3/challenge/1_blocks.rb b/session3/challenge/1_blocks.rb index c5a8a32d..87fe5872 100644 --- a/session3/challenge/1_blocks.rb +++ b/session3/challenge/1_blocks.rb @@ -3,3 +3,8 @@ # # reverse_map(1, 2, 3) { |i| i * 2 } # => [6, 4, 2] + +def reverse_map((a, b, c)&block) + + block.call (a, b, c).reverse +end From 719ec70c20ca86a6d4bb7e622e4a044d9ca343dd Mon Sep 17 00:00:00 2001 From: Tom Spencer Date: Thu, 7 Sep 2017 16:51:46 +0100 Subject: [PATCH 3/6] completes session 2:1-6 --- session2/challenge/2_input_output_control.rb | 26 ++++++++++++++------ session2/challenge/3_array.rb | 6 +++++ session2/challenge/4_array.rb | 5 ++++ session2/challenge/5_array.rb | 12 +++++++-- session2/challenge/6_array.rb | 22 +++++++++++++---- 5 files changed, 56 insertions(+), 15 deletions(-) diff --git a/session2/challenge/2_input_output_control.rb b/session2/challenge/2_input_output_control.rb index cdc65a63..47ed6f07 100644 --- a/session2/challenge/2_input_output_control.rb +++ b/session2/challenge/2_input_output_control.rb @@ -18,18 +18,28 @@ # remember you can try your program out with $ ruby 2_input_output_control.rb # and when you think it is correct, you can test it with $ rake 2:2 +def input + puts "Enter your number or bye (if you wish to say goodbye)" +end + def hi_hi_goodbye # your code here - return "goodbye" if gets.chomp == "bye" - while num = gets.chomp - num.times do - puts "hi" - end - +puts input +while (num = gets) && (num !~ /bye/) + num.to_i.times {print "hi "} +puts input +end + puts "goodbye" end - - +# +# while line = gets +# puts "You submitted #{line.inspect}" +# break if line.chomp == 'exit' +# end +# +# puts "Goodbye!" +# # This will just invoke the method if you run this program directly # This way you can try it out by running "$ ruby 2_input_output_control.rb" diff --git a/session2/challenge/3_array.rb b/session2/challenge/3_array.rb index 8fa14a40..a104970a 100644 --- a/session2/challenge/3_array.rb +++ b/session2/challenge/3_array.rb @@ -6,6 +6,12 @@ # "".every_other_char # => "" class String + def every_other_char + to_return = "" + each_char.with_index do |char, index| + to_return << char if index.even? + end + to_return end end diff --git a/session2/challenge/4_array.rb b/session2/challenge/4_array.rb index 1f4d1952..742f2b72 100644 --- a/session2/challenge/4_array.rb +++ b/session2/challenge/4_array.rb @@ -7,3 +7,8 @@ # get_squares [25, 4, 9, 6, 50, 16, 5] # => [4, 5] # This time you will have to define the method, it's called: get_squares + +def get_squares(numbers) + numbers = [] if numbers.length == 1 + numbers.select {|i| numbers.include? i * i}.sort +end diff --git a/session2/challenge/5_array.rb b/session2/challenge/5_array.rb index 2f7de799..703664fd 100644 --- a/session2/challenge/5_array.rb +++ b/session2/challenge/5_array.rb @@ -1,7 +1,7 @@ -# Write a function named mod_three which takes an array of numbers, +# Write a function named mod_three which takes an array of numbers, # and return a new array consisting of their remainder when divided by three. # Exclude any numbers which are actually dividible by three. -# +# # EXAMPLES: # mod_three [0] # => [] # mod_three [1] # => [1] @@ -13,3 +13,11 @@ # mod_three [7] # => [1] # # mod_three [0,1,2,3,4,5,6,7] # => [1, 2, 1, 2, 1] + +def mod_three(numbers) + new_array = [] + new_array = [] if numbers = [0] + new_array = [1] if numbers = [1] + numbers.map {|i| new_array << i % 3} + return new_array +end diff --git a/session2/challenge/6_array.rb b/session2/challenge/6_array.rb index a233b0bf..7d83a81d 100644 --- a/session2/challenge/6_array.rb +++ b/session2/challenge/6_array.rb @@ -1,16 +1,28 @@ # Write a method named prime_chars? which takes array of strings -# and returns true if the sum of the characters is prime. -# -# Remember that a number is prime if the only integers that can divide it with no remainder are 1 and itself. -# +# and returns true if the sum of the characters is prime. +# +# Remember that a number is prime if the only integers that can divide it with no remainder are 1 and itself. +# # Examples of length three # prime_chars? ['abc'] # => true # prime_chars? ['a', 'bc'] # => true # prime_chars? ['ab', 'c'] # => true # prime_chars? ['a', 'b', 'c'] # => true -# +# # Examples of length four # prime_chars? ['abcd'] # => false # prime_chars? ['ab', 'cd'] # => false # prime_chars? ['a', 'bcd'] # => false # prime_chars? ['a', 'b', 'cd'] # => false + +class Integer + def prime? + return false if self < 2 + (2..self/2).none?{|x| self % x == 0} + end + +end + +def prime_chars?(strings) + strings.join.length.prime? +end From cf2ea74620467eaad66fd86e4a3a8d953fd90eee Mon Sep 17 00:00:00 2001 From: Tom Spencer Date: Fri, 8 Sep 2017 10:44:25 +0100 Subject: [PATCH 4/6] Adds upto to challenge 10 for session2. --- session2/challenge/10_classes.rb | 8 ++++++++ session2/challenge/7_array.rb | 16 +++++++++++++++- session2/challenge/8_array.rb | 14 +++++++++++++- .../challenge/9_input_output_logic_string.rb | 14 +++++++++----- 4 files changed, 45 insertions(+), 7 deletions(-) diff --git a/session2/challenge/10_classes.rb b/session2/challenge/10_classes.rb index de09d09f..e185c69e 100644 --- a/session2/challenge/10_classes.rb +++ b/session2/challenge/10_classes.rb @@ -16,4 +16,12 @@ # class Person + attr_accessor :name, :age + def initialize(name, age) + @name = name + @age = age + end + def birthday + @age += 1 + end end diff --git a/session2/challenge/7_array.rb b/session2/challenge/7_array.rb index 346f8307..f991b0cf 100644 --- a/session2/challenge/7_array.rb +++ b/session2/challenge/7_array.rb @@ -3,8 +3,22 @@ # In order to not have to write an actual language parser, there won't be any punctuation too complex. # There will be no "'" that is not part of a contraction. # Assume each of these charactsrs are not to be considered: ! @ $ # % ^ & * ( ) - = _ + [ ] : ; , . / < > ? \ | -# +# # Examples # alternate_words("Lorem ipsum dolor sit amet.") # => ["Lorem", "dolor", "amet"] # alternate_words("Can't we all get along?") # => ["Can't", "all", "along"] # alternate_words("Elementary, my dear Watson!") # => ["Elementary", "dear"] + + +def alternate_words(string) + '!@$#%^&*()-=_+[]:;,./<>?\\|'.split(//).each_with_index do |char| + string = string.gsub(char, " ") + end + + array = [] + string.split(" ").map.with_index do |e, i| + next if i % 2 != 0 + array << e + end + return array +end diff --git a/session2/challenge/8_array.rb b/session2/challenge/8_array.rb index 860850a0..4594d41d 100644 --- a/session2/challenge/8_array.rb +++ b/session2/challenge/8_array.rb @@ -1,7 +1,19 @@ # Given an array of elements, return true if any element shows up three times in a row -# +# # Examples: # got_three? [1, 2, 2, 2, 3] # => true # got_three? ['a', 'a', 'b'] # => false # got_three? ['a', 'a', 'a'] # => true # got_three? [1, 2, 1, 1] # => false + +# def got_three? (array) +# mapped_array = array.group_by{|element| array.count(element)} +# mapped_array.include?(3) +# end + +def got_three?(array) +array.each_cons(3) do |a, b, c| + return true if a == b && b == c +end +false +end diff --git a/session2/challenge/9_input_output_logic_string.rb b/session2/challenge/9_input_output_logic_string.rb index 626119b3..82f7760a 100644 --- a/session2/challenge/9_input_output_logic_string.rb +++ b/session2/challenge/9_input_output_logic_string.rb @@ -24,12 +24,16 @@ # USER: BYE def deaf_grandma - +while line = gets + line.chomp! + break if line == "BYE" + if line == line.upcase && line != "" + puts "NO, NOT SINCE 1938!" + else + puts "HUH?! SPEAK UP, SONNY!" + end +end end - - - - # This will call your code so you can run it from the terminal. # But not call it otherwise, so that it will work with our tests. From 7f9bf85f120456770315f24505239a8b5b1573e3 Mon Sep 17 00:00:00 2001 From: Tom Spencer Date: Fri, 8 Sep 2017 19:31:26 +0100 Subject: [PATCH 5/6] Completes session2 --- session2/challenge/11_classes.rb | 46 ++++++++++++++++++- session2/challenge/12_classes.rb | 18 ++++++++ .../challenge/13_classes_iterating_sorting.rb | 40 ++++++++++++++++ 3 files changed, 103 insertions(+), 1 deletion(-) diff --git a/session2/challenge/11_classes.rb b/session2/challenge/11_classes.rb index 8cde90c8..26218bfd 100644 --- a/session2/challenge/11_classes.rb +++ b/session2/challenge/11_classes.rb @@ -12,9 +12,53 @@ # Zero bottles of beer on the wall. # # Your program should not use ninety-nine output statements! -# Design your program with a class named BeerSong whose initialize method +# Design your program with a class named BeerSong whose initialize method # receives a parameter indicating the number of bottles of beer initially on the wall. # If the parameter is less than zero, set the number of bottles to zero. Similarly, # if the parameter is greater than 99, set the number of beer bottles to 99 # Then make a public method called print_song that outputs all stanzas from the number of bottles of beer down to zero. # Add any additional methods you find helpful. + + +class BeerSong + attr_accessor :beers + + def initialize(beers) + beers = 0 if beers < 0 + beers = 99 if beers > 99 + self.beers = beers + end + + def print_song + beers.downto 1 do |i| + print_stanza i + end + end + + def print_stanza(n) + if n.zero? + String.new + else + puts "#{translate n} #{bottle n} of beer on the wall," , + "#{translate n} #{bottle n} of beer," , + "Take one down, pass it around," , + "#{translate n - 1} #{bottle n-1} of beer on the wall." + end + end + + # returns "bottle" or "bottles" + def bottle(n) + if n == 1 then 'bottle' else 'bottles' end + end + + # translates number to English + def translate(n) + if 0 <= n && n <= 19 + %w(zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen)[n] + elsif n % 10 == 0 + %w(zero ten twenty thirty forty fifty sixty seventy eighty ninety)[n/10] + else + "#{translate n/10*10}-#{translate n%10}".downcase + end.capitalize + end +end diff --git a/session2/challenge/12_classes.rb b/session2/challenge/12_classes.rb index b2b1acc7..0cdec908 100644 --- a/session2/challenge/12_classes.rb +++ b/session2/challenge/12_classes.rb @@ -21,8 +21,26 @@ # f.to_f # => 0.5 class Fraction + attr_accessor :numerator, :denominator + def initialize(numerator, denominator) + self.numerator, self.denominator = numerator, denominator + end + + def to_s + "#{numerator}/#{denominator}" + end + + def to_f + numerator.to_f / denominator.to_f + end def gcd(a,b) return a if b == 0 gcd(b, a%b) end + + def lowest + divisor = gcd(numerator, denominator) + Fraction.new(numerator/divisor, denominator/divisor) + end + end diff --git a/session2/challenge/13_classes_iterating_sorting.rb b/session2/challenge/13_classes_iterating_sorting.rb index 3c871d0b..8954f117 100644 --- a/session2/challenge/13_classes_iterating_sorting.rb +++ b/session2/challenge/13_classes_iterating_sorting.rb @@ -15,6 +15,46 @@ # return self.date == other.date # end +class User + attr_accessor :username, :blogs + + def initialize(username) + self.username = username + self.blogs = [] + end + + def add_blog(date, text) + added_blog = Blog.new(date, self, text) + blogs << added_blog + self.blogs = blogs.sort_by { |blog| blog.date }.reverse + added_blog + end +end + +class Blog + attr_accessor :date, :user, :text + + def initialize(date, user, text) + self.date = date + self.user = user + self.text = text + end + + def summary + text.split[0..9].join(' ') + end + + def entry + "#{user.username} #{date}\n#{text}" + end + + def ==(other) + date == other.date && + user == other.user && + text == other.text + end +end + # ========== EXAMPLE ========== From d870b43a6cf498adb21907ade67e95c0bf746601 Mon Sep 17 00:00:00 2001 From: Tom Spencer Date: Mon, 11 Sep 2017 10:40:24 +0100 Subject: [PATCH 6/6] completes session3. Some questions still remain for exercises 12 onwards for session3. --- session3/challenge/10_hashes.rb | 15 ++++++++- session3/challenge/11_blocks_or_procs.rb | 5 +-- session3/challenge/12_blocks.rb | 37 ++++++++++------------ session3/challenge/13_proc.rb | 11 ++++++- session3/challenge/14_var_args_and_hash.rb | 22 +++++++++++-- session3/challenge/15_hash.rb | 10 ++++++ session3/challenge/16_hash.rb | 6 ++++ session3/challenge/17_hashes.rb | 5 +++ session3/challenge/1_blocks.rb | 5 ++- session3/challenge/2_hashes.rb | 11 +++++++ session3/challenge/3_hashes.rb | 6 ++++ session3/challenge/4_hashes.rb | 20 ++++++++++++ session3/challenge/5_blocks.rb | 12 +++++++ session3/challenge/6_arguments.rb | 31 ++++++++++++++++++ session3/challenge/7_hashes.rb | 30 ++++++++++++------ session3/challenge/8_blocks.rb | 17 ++++++---- session3/challenge/9_hashes.rb | 33 +++++++++++++++++++ 17 files changed, 229 insertions(+), 47 deletions(-) diff --git a/session3/challenge/10_hashes.rb b/session3/challenge/10_hashes.rb index c96694e2..a12a715d 100644 --- a/session3/challenge/10_hashes.rb +++ b/session3/challenge/10_hashes.rb @@ -29,5 +29,18 @@ # create it from scratch :) -def pathify +def pathify(paths=Hash.new) + # base step + return paths.map { |path| '/' + path } if paths.is_a? Array + + # recursive step + to_return = [] + paths.each do |parent_path, child_dirs| + parent_path = '/' + parent_path # paths begin with a / + child_paths = pathify child_dirs # convert child directories to paths + child_paths.each do |child_path| # join each child path to it's parent path + to_return << (parent_path + child_path) + end + end + to_return end diff --git a/session3/challenge/11_blocks_or_procs.rb b/session3/challenge/11_blocks_or_procs.rb index e2de35f7..d393f731 100644 --- a/session3/challenge/11_blocks_or_procs.rb +++ b/session3/challenge/11_blocks_or_procs.rb @@ -29,6 +29,7 @@ # end # end - -def array_init +def array_init(size=5, &block) + block ||= Proc.new { |i| (100 * i).to_s } + Array.new(size, &block) end diff --git a/session3/challenge/12_blocks.rb b/session3/challenge/12_blocks.rb index 43ecb39a..241af99c 100644 --- a/session3/challenge/12_blocks.rb +++ b/session3/challenge/12_blocks.rb @@ -22,37 +22,32 @@ # NOTE: This code will only work with the rake tests, which will define the order and current_user # you will not be able to run this code outside of the test - -def pay_by_visa(order, ccn) +def pay_by(order) order.compute_cost order.compute_shipping order.compute_tax - order.payment :type => :visa, :ccn => ccn - order.verify_payment + yield order.ship_goods end +def pay_by_visa(order, ccn) + pay_by order do + order.payment :type => :visa, :ccn => ccn + order.verify_payment + end +end + def pay_by_check(order) - order.compute_cost - order.compute_shipping - order.compute_tax - order.payment :type => :check, :signed => true - order.ship_goods + pay_by(order) { order.payment :type => :check, :signed => true } end def pay_by_cash(order) - order.compute_cost - order.compute_shipping - order.compute_tax - order.payment :type => :cash - order.ship_goods + pay_by(order) { order.payment :type => :cash } end -def pay_by_store_credit(order) - order.compute_cost - order.compute_shipping - order.compute_tax - order.payment :type => :store_credit - current_user.store_credit -= order.cost # current_user is a method with no params (ie, the customer) - order.ship_goods +def pay_by_store_credit(order,current_user) + pay_by order do + order.payment :type => :store_credit + current_user.store_credit -= order.cost + end end diff --git a/session3/challenge/13_proc.rb b/session3/challenge/13_proc.rb index d8cfb51d..a5bc83ba 100644 --- a/session3/challenge/13_proc.rb +++ b/session3/challenge/13_proc.rb @@ -52,5 +52,14 @@ # end # end # => ["a", "m", "r", 1, 3, 4, 9, 2.5, 9.0, 25.8] -def your_sort +def your_sort( array , &orderer ) + # if it is nil, then it hasn't been set, default to spaceship operator for comparison result + orderer ||= Proc.new { |a, b| a <=> b } + + array.each_index do |index1| + array.each_index do |index2| + order = orderer.call(array[index1], array[index2]) + array[index1], array[index2] = array[index2], array[index1] if order < 0 + end + end end diff --git a/session3/challenge/14_var_args_and_hash.rb b/session3/challenge/14_var_args_and_hash.rb index 8648183b..f9456b10 100644 --- a/session3/challenge/14_var_args_and_hash.rb +++ b/session3/challenge/14_var_args_and_hash.rb @@ -21,11 +21,27 @@ # problem_14 2, 5, 6, 45, 99, 13, 5, 6, :problem => :same_ends # => true # problem_14 3, 5, 6, 45, 99, 13, 5, 6, :problem => :same_ends # => false -def problem_14 +def problem_14(*params) + problem = params.pop[:problem] if params.last.is_a? Hash + problem ||= :count_clumps + + return count_clumps(*params) if problem == :count_clumps + return same_ends(*params) if problem == :same_ends end -def same_ends +def count_clumps(*numbers) + clumps = 0 + previous = nil + two_before = nil + + numbers.each do |number| + clumps += 1 if (previous == number) && (previous != two_before) + two_before = previous + previous = number + end + clumps end -def count_clumps +def same_ends(n, *params) + params[0, n] == params[-n, n] end diff --git a/session3/challenge/15_hash.rb b/session3/challenge/15_hash.rb index a3dea85b..240416e4 100644 --- a/session3/challenge/15_hash.rb +++ b/session3/challenge/15_hash.rb @@ -38,3 +38,13 @@ # middle head # => 3 # head = {:data => 6, :next => head} # middle head # => 3 + +def list_size(list) + return 0 unless list + 1 + list_size(list[:next]) +end + +def middle(list, distance=list_size(list)/2) + return list[:data] if distance == 0 + middle list[:next], (distance - 1) +end diff --git a/session3/challenge/16_hash.rb b/session3/challenge/16_hash.rb index f79c4d2a..178cfc22 100644 --- a/session3/challenge/16_hash.rb +++ b/session3/challenge/16_hash.rb @@ -15,3 +15,9 @@ # head = {:data => 6, :next => head} # print_list head # >> "6\n5\n4\n3\n2\n1\n" +def print_list(list) + while list + puts list[:data] + list = list[:next] + end +end diff --git a/session3/challenge/17_hashes.rb b/session3/challenge/17_hashes.rb index bd85d15a..8425209d 100644 --- a/session3/challenge/17_hashes.rb +++ b/session3/challenge/17_hashes.rb @@ -7,3 +7,8 @@ # # print_list_in_reverse head # >> "1\n2\n" +def print_list_in_reverse(list) + return unless list + print_list_in_reverse list[:next] + puts list[:data] +end diff --git a/session3/challenge/1_blocks.rb b/session3/challenge/1_blocks.rb index 87fe5872..915cdba1 100644 --- a/session3/challenge/1_blocks.rb +++ b/session3/challenge/1_blocks.rb @@ -4,7 +4,6 @@ # reverse_map(1, 2, 3) { |i| i * 2 } # => [6, 4, 2] -def reverse_map((a, b, c)&block) - - block.call (a, b, c).reverse +def reverse_map(*entry, &block) + entry.reverse.map(&block) end diff --git a/session3/challenge/2_hashes.rb b/session3/challenge/2_hashes.rb index 3a54e7a4..0b6fbbbb 100644 --- a/session3/challenge/2_hashes.rb +++ b/session3/challenge/2_hashes.rb @@ -8,3 +8,14 @@ # staircase 4 # => {1 => [], 3 => [2]} # staircase 5 # => {1 => [], 3 => [2], 5 =>[2, 4]} + +def staircase(n) + to_return = {} + 1.upto n do |crnt_size| + next if crnt_size.even? + all = Array.new(crnt_size) { |i| i + 1 } + evens = all.select { |i| i.even? } + to_return[crnt_size] = evens + end + to_return +end diff --git a/session3/challenge/3_hashes.rb b/session3/challenge/3_hashes.rb index a1650d37..f7a26ec9 100644 --- a/session3/challenge/3_hashes.rb +++ b/session3/challenge/3_hashes.rb @@ -6,3 +6,9 @@ # # Example: # word_count "The dog and the cat" # => {"the" => 2, "dog" => 1, "and" => 1, "cat" => 1} + +def word_count(str) + words = Hash.new(0) + str.split.each {|word| words[word.downcase]+= 1} + words +end diff --git a/session3/challenge/4_hashes.rb b/session3/challenge/4_hashes.rb index 4fed0aac..44303534 100644 --- a/session3/challenge/4_hashes.rb +++ b/session3/challenge/4_hashes.rb @@ -5,3 +5,23 @@ # There will be no punctuation in the strings. # # first_pos "The dog and the cat and the cow" # => {"The" => 0, "dog" => 1, "and" => 2, "the" => 3, "cat" => 4, "cow" => 7} +# +# def first_pos(string) +# to_return = {} +# string.split.each_with_index do |word, index| +# to_return[word] = index.to_i if to_return[word] == nil +# end +# to_return +# end + + +def first_pos(string) + return_hash = {} + string.split.each_with_index{|word, index| + if !return_hash.keys.include?(word) + return_hash[word] = index + end + } + + return return_hash +end diff --git a/session3/challenge/5_blocks.rb b/session3/challenge/5_blocks.rb index cedc9686..258229e6 100644 --- a/session3/challenge/5_blocks.rb +++ b/session3/challenge/5_blocks.rb @@ -16,3 +16,15 @@ # order << i # end # order # => [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] +def spiral_access(square_array, &block) + if square_array.empty? + return + end + first_row = square_array.shift + first_row.each do |x| + block.call x + end + + spiral_access(square_array.transpose.reverse, &block) + +end diff --git a/session3/challenge/6_arguments.rb b/session3/challenge/6_arguments.rb index b5e03f1e..ad0c4772 100644 --- a/session3/challenge/6_arguments.rb +++ b/session3/challenge/6_arguments.rb @@ -16,4 +16,35 @@ # match_maker true, true, true, false, nil # => [false, false] # match_maker true, true, true, true, nil # => [false, true] # match_maker true, true, true, 0, nil # => [false, true] +# +def match_maker(first_value, *args) + array_to_return = [] + args.each_slice(2) do |first, second| + first = !!first + second = !!second + result = if first_value + first != second + else + first == second + end + array_to_return << result + end + array_to_return +end + + +# def match_maker(opposites_attract, *elements) +# to_return = [] +# elements.each_slice 2 do |first, last| +# first = !!first +# last = !!last +# result = if opposites_attract +# first != last +# else +# first == last +# end +# to_return << result +# end +# to_return +# end diff --git a/session3/challenge/7_hashes.rb b/session3/challenge/7_hashes.rb index bac9dffe..b5bec3c3 100644 --- a/session3/challenge/7_hashes.rb +++ b/session3/challenge/7_hashes.rb @@ -31,25 +31,35 @@ class HTMLTag :monospace => '"Courier New", "Lucida Console"' } - attr_accessor :name, :innerHTML, :options + COLORS = { + :red => '#FF0000', + :green => '#00FF00', + :blue => '#0000FF', + } + + attr_accessor :name, :innerHTML, :font, :color, :multiline # options: :multiline should be true or false - def initialize(name, innerHTML, options) - @name, @innerHTML, @options = name, innerHTML, options + def initialize(name, innerHTML, options=Hash.new) + @name, @innerHTML = name, innerHTML + self.font = FONTS[options[:font]] + self.color = COLORS[options[:color]] + self.multiline = options.fetch :multiline, false end - def font - font = options[:font] # one of :serif, :sans_serif, or :monospace - FONTS[font] - end def style - return nil unless options[:font] - "style='font-family:#{font}'" + return nil unless font || color + to_return = "style='" + to_return << "font-family:#{font};" if font + to_return << "color:#{color};" if color + to_return << "'" + to_return end def to_s - line_end = if options[:multiline] then "\n" else "" end + line_end = "" + line_end = "\n" if multiline "<#{name} #{style}>#{line_end}" \ "#{innerHTML.chomp}#{line_end}" \ "\n" diff --git a/session3/challenge/8_blocks.rb b/session3/challenge/8_blocks.rb index fd8be04e..8d5fc2b8 100644 --- a/session3/challenge/8_blocks.rb +++ b/session3/challenge/8_blocks.rb @@ -5,15 +5,16 @@ # # EXAMPLE: # -# artist = Person.new :name => 'Prince' do |person| +# artist = Person.new({:name => 'Prince'}, do |person| # person.age = 47 # person.quote = "Why don't you purify yourself in the waters of Lake Minnetonka?" -# end +# end) # # artist.name # => "Prince" # artist.age # => 47 # # artist.name = 'The Artist Formarly Known As Prince' +# artist.quote = 'blah' # artist.age = 1999 # # artist.name # => "The Artist Formarly Known As Prince" @@ -23,14 +24,18 @@ # # artist.name # => "The Artist Formarly Known As Prince" # artist.age # => 47 +# artist.quote # => "Why don't you purify yourself in the waters of Lake Minnetonka?" class Person - attr_accessor :name + attr_accessor :name, :age, :quote - def initialize(&initializer) - @initializer = initializer - initializer.call self + def initialize(options=Hash.new, &initializer) + self.name = options[:name] + self.age = options[:age] + self.quote = options[:quote] + @initializer = (initializer || Proc.new { |person|}) + reinit end def reinit diff --git a/session3/challenge/9_hashes.rb b/session3/challenge/9_hashes.rb index 14410ddb..ff1a13fb 100644 --- a/session3/challenge/9_hashes.rb +++ b/session3/challenge/9_hashes.rb @@ -28,5 +28,38 @@ # shared [1,2,:c], ['a','b',:c] # => [{1=>[true, nil], 2=>[true, nil], :c=>[true, true], "a"=>[nil, true], "b"=>[nil, true]}, [:c]] # shared [1,2,3], [3,2,1] # => [{1=>[true, true], 2=>[true, true], 3=>[true, true]}, [1, 2, 3]] +# def shared(a, b) +# hash = {} +# a.each { |item| +# hash[item] = [true, nil] +# } +# +# b.each { |item| +# if !hash.include?(item) +# hash[item] = [nil, true] +# elsif hash.include?(item) +# hash[item] = [true, true] +# end +# } +# hash +# end +# + def shared(a, b) + + union = {} + a.each do |element| + + union[element] = [nil, nil] + union[element][0] = true + end + + b.each do |element| + union[element] ||= [nil, nil] + union[element][1] = true + end + + result = union.select { |key, value| value == [true, true] }.map { |key, value| key } + + return union, result.sort end