From d6249c522c29e7504be47d5385a629616d488ffe Mon Sep 17 00:00:00 2001 From: mardav Date: Tue, 7 Feb 2023 12:08:51 +0530 Subject: [PATCH] week2 tasks --- week_2/pet.rb | 27 ++++++++++++++++++++++----- week_2/prime_numbers.rb | 18 +++++++++++++++++- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/week_2/pet.rb b/week_2/pet.rb index 954a713b..ecc6f434 100644 --- a/week_2/pet.rb +++ b/week_2/pet.rb @@ -46,7 +46,11 @@ def initialize(name: , animal_type_id: , food_consumed_per_day:) # Return the habitat of the pet def habitat - raise NotImplementedError # TODO + for (key, value) in HABITATS + if value.include?(animal_type_id) + return key + end + end end # Returns the cost of food required to feed the animal @@ -66,7 +70,7 @@ def food_cost_per_day # cat = Pet.new(name: 'cat', animal_type_id: 6, food_consumed_per_day: 0.4) # cat.food_required(28) = 11.2 (0.4 * 28) def food_required(days) - raise NotImplementedError # TODO + return food_consumed_per_day * days end # This function takes the number of `days` as the input @@ -76,7 +80,7 @@ def food_required(days) # cat = Pet.new(name: 'cat', animal_type_id: 6, food_consumed_per_day: 0.4) # cat.food_cost(28) = 8960 def food_cost(days) - raise NotImplementedError # TODO + return food_cost_per_day * days end # This function takes an array of pets and the `days` @@ -90,7 +94,11 @@ def food_cost(days) # snake = Pet.new(name: 'python', animal_type_id: 4, food_consumed_per_day: 0.3) # Pet.cost_to_feed([cat, dog, fish, snake], 6) will return 6180.0 def self.cost_to_feed(pets, days) - raise NotImplementedError # TODO + cost = 0 + for pet in pets + cost += pet.food_cost(days) + end + return cost end # This function takes an array of pets as input @@ -110,6 +118,15 @@ def self.cost_to_feed(pets, days) # # Note - Order is not important def self.group_by_animal_type(pets) - raise NotImplementedError # TODO + obj = Hash.new() + for pet in pets + if !obj[pet.animal_type_id] + obj[pet.animal_type_id] = [pet.name] + else + obj[pet.animal_type_id].push(pet.name) + end + end + return obj end + end diff --git a/week_2/prime_numbers.rb b/week_2/prime_numbers.rb index 777a8cf5..2779d39b 100644 --- a/week_2/prime_numbers.rb +++ b/week_2/prime_numbers.rb @@ -13,6 +13,22 @@ # If the user gives a invalid input like -4 # We will raise an `ArgumentError` exception to let the caller know that # their function arguments were incorrect. + def prime_numbers(n:) - raise NotImplementedError # TODO + raise ArgumentError, "n must be positive int" if n <= 0 + primes = Array.new() + + for i in 2..n + is_prime = true + for j in 2..(i - 1) + if i % j == 0 + is_prime = false + break + end + end + primes << i if is_prime + i+=1 + end +return primes end +