"Buying a car" Ruby codewars - ruby

I am trying to do Ruby codewars challenge and I am stuck since I pass sample tests but can't pass final one. I am getting error Expected: [8, 597], instead got: [8, 563].
Instructions :
A man has a rather old car being worth $2000. He saw a secondhand car
being worth $8000. He wants to keep his old car until he can buy the
secondhand one.
He thinks he can save $1000 each month but the prices of his old car
and of the new one decrease of 1.5 percent per month. Furthermore the
percent of loss increases by a fixed 0.5 percent at the end of every
two months.
Example of percents lost per month:
If, for example, at the end of first month the percent of loss is 1,
end of second month percent of loss is 1.5, end of third month still
1.5, end of 4th month 2 and so on ...
Can you help him? Our man finds it difficult to make all these
calculations.
How many months will it take him to save up enough money to buy the
car he wants, and how much money will he have left over?
def nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth)
months = 0
leftover = 0
currentSavings = 0
until (currentSavings + startPriceOld) >= (startPriceNew)
months += 1
months.even? ? percentLossByMonth = percentLossByMonth + 0.5 : percentLossByMonth
startPriceNew = startPriceNew * (1 - (percentLossByMonth/100))
startPriceOld = startPriceOld * (1 - (percentLossByMonth/100))
currentSavings = currentSavings + savingperMonth
end
leftover = currentSavings + startPriceOld - startPriceNew
return [months, leftover.abs.to_i]
end
I don't want to look at solutions and I don't need one here just a nudge in the right direction would be very helpful.
Also, I get that code is probably sub-optimal in a lot of ways but I have started coding 2 weeks ago so doing the best I can.
Tnx guys

Your algorithm is good. But you have two coding errors:
1) percentLossByMonth needs to be converted to float before dividing it by 100 ( 5 / 100 = 0 while (5.to_f) / 100 = 0.05 )
2) It's said in the instructions that you need to return the nearest integer of the leftover, which is leftover.round
def nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth)
months = 0
leftover = 0
currentSavings = 0
until (currentSavings + startPriceOld) >= (startPriceNew)
months += 1
percentLossByMonth += months.even? ? 0.5 : 0
startPriceNew = startPriceNew * (1 - (percentLossByMonth.to_f/100))
startPriceOld = startPriceOld * (1 - (percentLossByMonth.to_f/100))
currentSavings += savingperMonth
end
leftover = currentSavings + startPriceOld - startPriceNew
return [months, leftover.round]
end

The problem with your code has been identified, so I will just offer an alternative calculation.
r = 0.015
net_cost = 8000-2000
n = 1
months, left_over = loop do
r += 0.005 if n.even?
net_cost *= (1-r)
tot = n*1000 - net_cost
puts "n=#{n}, r=#{r}, net_cost=#{net_cost.to_i}, " +
"savings=#{(n*1000).to_i}, deficit=#{-tot.to_i}"
break [n, tot] if tot >= 0
n += 1
end
#=> [6, 766.15...]
months
#=> 6
left_over
#=> 766.15...
and prints
n=1, r=0.015, net_cost=5910, savings=1000, deficit=4910
n=2, r=0.020, net_cost=5791, savings=2000, deficit=3791
n=3, r=0.020, net_cost=5675, savings=3000, deficit=2675
n=4, r=0.025, net_cost=5534, savings=4000, deficit=1534
n=5, r=0.025, net_cost=5395, savings=5000, deficit=395
n=6, r=0.030, net_cost=5233, savings=6000, deficit=-766

Related

Ruby - Get time at start of next minute

I'm looking for a concise way to get a Ruby Time object representing the top of the next minute (and hour/day/month/year, if possible). I want this to work in a pure Ruby environment, so the Rails function Time.change or similar doesn't fit the bill.
At first this seems simple - just add 1 to Time.now, but there are edge cases where if, for example, you try to instantiate a Time object with Time.now.min + 1 when the current minute is 59, you get an ArgumentError: min out of range. This goes for hour, day, and month as well.
I have some lengthy code that does the job. It's ugly, but I'm just experimenting:
def add_minute
now = Time.local
year = now.year
month = now.month
day = now.day
hour = now.hour
min = now.min
if now.min == 59
if now.hour == 23
if now.day == Date.civil(now.year, now.month, -1).day
if month == 12
year = year + 1
month = 1
day = 1
hour = 0
min = 0
else
month = now.month + 1
day = 1
hour = 0
min = 0
end
else
day = now.day + 1
hour = 0
min = 0
end
else
hour = now.hour + 1
min = 0
end
else
min = now.min + 1
end
Time.local year, month, day, hour, min, 0
end
This seems absurdly verbose for what seems like it should be a simple or built-in task, but I haven't found a native Ruby solution. Does one exist?
You could convert the Time object to UNIX epoch time (seconds since 1970) using #to_i, add 60 s, and then convert back to a Time object.
time_unix = Time.now.to_i
time_unix_one_min_later = time_unix + 60
time_one_min_later = t = Time.at(time_unix_one_min_later)
time_one_min_later_rounded_down = Time.new(t.year, t.month, t.day, t.hour, t.min)
EDIT: Even shorter - you can just add integer seconds to Time.now directly:
time_one_min_later = t = Time.now + 60
time_one_min_later_rounded_down = Time.new(t.year, t.month, t.day, t.hour, t.min)
EDIT 2: One-liner - just subtract Time.now.sec:
time_one_min_later_rounded_down = Time.now + 60 - Time.now.sec
Other option, given one second to midnight:
require 'time'
now = Time.strptime('2018-12-31 23:59:59', '%Y-%m-%d %H:%M:%S')
Within one minute:
Time.at(now + 60) #=> 2019-01-01 00:00:59 +0100
Time.at(now + 60 - now.sec) #=> 2019-01-01 00:00:00 +0100
You get: # HAPPY NEW YEAR!
Ruby has built in methods for adding months (>>) and days (+). A year is 12 months, and an hour is 1/24th of a day.
require 'date'
def add_time(time, year: 0 ,month: 0, day: 0, hour: 0, minute: 0)
time >>= 12*year
time >>= month
time += day
time += Rational(hour,24) # or (hour/24.0) if you dislike rationals
time += Rational(minute, 24*60) # (minute/24.0*60) if you dislike rationals
end
p t = DateTime.now
p add_time(t, year: 1, minute: 30)
Not that clean without ActiveSupport:
new_date = (DateTime.now + 1.to_f / (60*24))
DateTime.new(new_date.year, new_date.month, new_date.day, new_date.hour, new_date.minute)
We can make this calculation easier to understand by getting the current number of seconds we are through the day. (optional)
DateTime.current.to_i gives us the number of seconds since 1970
DateTime.current.to_i - DateTime.current.beginning_of_day.to_i gives us the number of seconds since the start of the day.
(((number_of_seconds_through_the_day + 60)/60) * 60) gives us the number of seconds we will be at when the next minute starts
Then we subtract the two to give us the number of seconds until the top of the next minute.
If we want the exact time at start of the next minute then we can do:
DateTime.current + seconds_until_start_of_the_next_minute.seconds
def seconds_until_start_of_the_next_minute
number_of_seconds_through_the_day = DateTime.current.to_i - DateTime.current.beginning_of_day.to_i
number_of_seconds_through_the_day_at_next_minute = (((number_of_seconds_through_the_day + 60)/60) * 60)
seconds_until_next_minute_starts = number_of_seconds_through_the_day_at_next_minute - number_of_seconds_through_the_day
return seconds_until_next_minute_starts
end

Ruby algorithms loops codewars

I got stuck with below task and spent about 3 hours trying to figure it out.
Task description: A man has a rather old car being worth $2000. He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one.
He thinks he can save $1000 each month but the prices of his old car and of the new one decrease of 1.5 percent per month. Furthermore this percent of loss increases by 0.5 percent at the end of every two months. Our man finds it difficult to make all these calculations.
How many months will it take him to save up enough money to buy the car he wants, and how much money will he have left over?
My code so far:
def nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth)
dep_value_old = startPriceOld
mth_count = 0
total_savings = 0
dep_value_new = startPriceNew
mth_count_new = 0
while startPriceOld != startPriceNew do
if startPriceOld >= startPriceNew
return mth_count = 0, startPriceOld - startPriceNew
end
dep_value_new = dep_value_new - (dep_value_new * percentLossByMonth / 100)
mth_count_new += 1
if mth_count_new % 2 == 0
dep_value_new = dep_value_new - (dep_value_new * 0.5) / 100
end
dep_value_old = dep_value_old - (dep_value_old * percentLossByMonth / 100)
mth_count += 1
total_savings += savingperMonth
if mth_count % 2 == 0
dep_value_old = dep_value_old - (dep_value_old * 0.5) / 100
end
affordability = total_savings + dep_value_old
if affordability >= dep_value_new
return mth_count, affordability - dep_value_new
end
end
end
print nbMonths(2000, 8000, 1000, 1.5) # Expected result[6, 766])
The data are as follows.
op = 2000.0 # current old car value
np = 8000.0 # current new car price
sv = 1000.0 # annual savings
dr = 0.015 # annual depreciation, both cars (1.5%)
cr = 0.005. # additional depreciation every two years, both cars (0.5%)
After n >= 0 months the man's (let's call him "Rufus") savings plus the value of his car equal
sv*n + op*(1 - n*dr - (cr + 2*cr + 3*cr +...+ (n/2)*cr))
where n/2 is integer division. As
cr + 2*cr + 3*cr +...+ (n/2)*cr = cr*((1+2+..+n)/2) = cr*(1+n/2)*(n/2)
the expression becomes
sv*n + op*(1 - n*dr - cr*(1+(n/2))*(n/2))
Similarly, after n years the cost of the car he wants to purchase will fall to
np * (1 - n*dr - cr*(1+(n/2))*(n/2))
If we set these two expressions equal we obtain the following.
sv*n + op - op*dr*n - op*cr*(n/2) - op*cr*(n/2)**2 =
np - np*dr*n - np*cr*(n/2) - np*cr*(n/2)**2
which reduces to
cr*(np-op)*(n/2)**2 + (sv + dr*(np-op))*n + cr*(np-op)*(n/2) - (np-op) = 0
or
cr*(n/2)**2 + (sv/(np-op) + dr)*n + cr*(n/2) - 1 = 0
If we momentarily treat (n/2) as a float division, this expression reduces to a quadratic.
(cr/4)*n**2 + (sv/(np-op) + dr + cr/2)*n - 1 = 0
= a*n**2 + b*n + c = 0
where
a = cr/4 = 0.005/4 = 0.00125
b = sv/(np-op) + dr + cr/(2*a) = 1000.0/(8000-2000) + 0.015 + 0.005/2 = 0.18417
c = -1
Incidentally, Rufus doesn't have a computer, but he does have an HP 12c calculator his grandfather gave him when he was a kid, which is perfectly adequate for these simple calculations.
The roots are computed as follows.
(-b + Math.sqrt(b**2 - 4*a*c))/(2*a) #=> 5.24
(-b - Math.sqrt(b**2 - 4*a*c))/(2*a) #=> -152.58
It appears that Rufus can purchase the new vehicle (if it's still for sale) in six years. Had we been able able to solve the above equation for n/2 using integer division it might have turned out that Rufus would have had to wait longer. That’s because for a given n both cars would have depreciated less (or at least not not more), and because the car to be purchased is more expensive than the current car, the difference in values would be greater than that obtained with the float approximation for 1/n. We need to check that, however. After n years, Rufus' savings and the value of his beater will equal
sv*n + op*(1 - dr*n - cr*(1+(n/2))*(n/2))
= 1000*n + 2000*(1 - 0.015*n - 0.005*(1+(n/2))*(n/2))
For n = 6 this equals
1000*6 + 2000*(1 - 0.015*6 - 0.005*(1+(6/2))*(6/2))
= 1000*6 + 2000*(1 - 0.015*6 - 0.005*(1+3)*3)
= 1000*6 + 2000*0.85
= 7700
The cost of Rufus' dream car after n years will be
np * (1 - dr*n - cr*(1+(n/2))*(n/2))
= 8000 * (1 - 0.015*n - 0.005*(1+(n/2))*(n/2))
For n=6 this becomes
8000 * (1 - 0.015*6 - 0.005*(1+(6/2))*(6/2))
= 8000*0.85
= 6800
(Notice that the factor 0.85 is the same in both calculations.)
Yes, Rufus will be able to buy the car in 6 years.
def nbMonths(old, new, savings, percent)
percent = percent.fdiv(100)
current_savings = 0
months = 0
loop do
break if current_savings + old >= new
current_savings += savings
old -= old * percent
new -= new * percent
months += 1
percent += 0.005 if months.odd?
end
[months, (current_savings + old - new).round]
end

work out how many seconds have expired in total during game play

~Why the hell has this had down votes.... you people are weird!
Ok so this is a very simply HTML5 and jQuery and PHP game. Sorry to the people who have answered, I forgot to say this is a php script, i have updated here to reflect.
the first level takes 1 minute. Every level after that takes an extra 10 seconds than the last level. like so;
level 1 = 60 seconds
level 2 = 70 seconds
level 3 = 80 seconds
level 4 = 90 seconds
and so on infinitely.
I need an equation that can figure out what is the total amount of seconds played based on the users level.
level = n
i started with (n * 10) + (n * 60) but soon realized that that doesn't account for the last level already being 10 seconds longer than the last. I have temporarily fixed it using a function calling a foreach loop stopping at the level number and returning the value. but i really want an actual equation.
SO i know you wont let me down :-)
Thanks in advance.
this is what i am using;
function getnumberofsecondsfromlevel($level){
$lastlevelseconds = 60;
while($counter < $level){
$totalseconds = $lastlevelseconds+$totalseconds;
$lastlevelseconds = $lastlevelseconds + 10;
$counter++;
}
return $totalseconds;
}
$level = $_SESSION['**hidden**']['thelevel'];
$totaldureationinseconds = getnumberofsecondsfromlevel($level);
but i want to replace with an actual equation
like so;(of course this is wrong, this is just the example of the format i want it in i.e an equation)
$n = $_SESSION['**hidden**']['thelevel']; (level to get total value of
in seconds)
$s = 60; (start level)
$totaldureationinseconds = ($n * 10) + ($s * $n);
SOLVED by Gopalkrishna Narayan Prabhu :-)
$totalseconds = 60 * $level + 5* (($level-1) * $level);
var total_secs = 0;
for(var i = 1; i<= n ;i++){
total_secs = total_secs + (i*10) + 50;
}
for n= 1, total_secs = 0 + 10 + 50 = 60
for n= 2, total_secs = 60 + 20 + 50 = 130
and so on...
For a single equation:
var n = level_number;
total_secs = 60 * n + 5* ((n-1) * n);
Hope this helps.
It seems as though you're justing looking for the equation
60 + ((levelN - 1) * 10)
Where levelN is the current level, starting at 1. If you make the first level 0, you can get rid of the - 1 part and make it just
60 + (levelN * 10)
Thought process:
What's the base/first number? What's the lowest it can ever be? 60. That means your equation will start with
60 + ...
Every time you increase the level, you add 10, so at some point you'll need something like levelN * 10. Then, it's just some fiddling. In those case, since you don't add any on the first left, and the first level is level 1, you just need to subtract 1 from the level number to fix that.
You can solve this with a really simple mathematical phrase (with factorial).
((n-1)! * 10) + (60 * n)
n is the level ofcourse.

working with exponentiation of time

I have a string as follows:
"00:48:22"
From right to left, I am working with a power of 60, because I want to get the total number of seconds from hours, minutes, seconds.
This is what I have tried:
clock
=> "00:48:22"
i = 0
result = clock.split(":").reverse.reduce(0) do |acc, segment|
acc += segment.to_i + (60 ** i)
i += 1
acc
end
=> 3731
The result is off. It should be 2902. Any idea what I am doing wrong?
Your algorithm is a little messy and error prone.
This will give you the right answer:
clock = '00:48:22'
clock.split(':').map(&:to_i).reduce(0) do |acc, segment|
acc * 60 + segment
end
You are adding where you should be multiplying
acc += segment.to_i * (60 ** i)
require 'date'
d = Date.today
(Time.new(d.year,d.month,d.day,*str.split(':').map(&:to_i))-d.to_time).to_i
#=> 2902

Can this check digit method be refactored?

I have the following method for doing a check digit on a tracking number, but it just feels lengthy/sloppy. Can it be refactored and just generally cleaned up?
I'm running Ruby 1.8.7.
def is_fedex(number)
n = number.reverse[0..14]
check_digit = n.first.to_i
even_numbers = n[1..1].to_i + n[3..3].to_i + n[5..5].to_i + n[7..7].to_i + n[9..9].to_i + n[11..11].to_i + n[13..13].to_i
even_numbers = even_numbers * 3
odd_numbers = n[2..2].to_i + n[4..4].to_i + n[6..6].to_i + n[8..8].to_i + n[10..10].to_i + n[12..12].to_i + n[14..14].to_i
total = even_numbers + odd_numbers
multiple_of_ten = total + 10 - (total % 10)
remainder = multiple_of_ten - total
if remainder == check_digit
true
else
false
end
end
EDIT: Here are valid and invalid numbers.
Valid: 9612019950078574025848
Invalid: 9612019950078574025847
def is_fedex(number)
total = (7..20).inject(0) {|sum, i| sum + number[i..i].to_i * ( i.odd? ? 1 : 3 ) }
number[-1].to_i == (total / 10.0).ceil * 10 - total
end
I believe you should keep your code. While it's not idiomatic or clever, it's the one you will have the least trouble to understand a few months from now.
I'm not a ruby programmer, so if any of the syntax is off, I apologize but you should get the general idea. A few things I see: First, you don't need to slice the array, a single index should be sufficient. Second, Instead of splitting even and odd, you could do something like this:
total = 0
for i in (1..14)
total += n[i].to_i * ( i % 2 == 1 ? 1 : 3 )
end
Third, remainder could be simplified to 10 - (total % 10).
I realize you're running 1.8.7, but here's my attempt using each_slice and inject in conjunction, a 1.9.2 feature:
def is_fedex(number)
total = number.reverse[1..14].split(//).map(&:to_i).each_slice(2).inject(0) do |t, (e,o)|
t += e*3 + o
end
10 - (total % 10) == number[-1].to_i
end
It passes both tests
Give this a try:
#assuming number comes in as a string
def is_fedex(number)
n = number.reverse[0..14].scan(/./)
check_digit = n[0].to_i
total = 0
n[1..14].each_with_index {|d,i| total += d.to_i * (i.even? ? 3 : 1) }
check_digit == 10 - (total % 10)
end
> is_fedex("12345678901231") => true
edit incorporating simplified remainder logic as Kevin suggested
Something like this?
def is_fedex(number)
even_arr, odd_arr = number.to_s[1..13].split(//).map(&:to_i).partition.with_index { |n, i| i.even? }
total = even_arr.inject(:+) * 3 + odd_arr.inject(:+)
number.to_s.reverse[0..0].to_i == (total + 10 - (total % 10)) - total
end
If you can give me a valid and invalid number I can test if it works and maybe tweak it further :)
This function should to:
def is_fedex(number)
# sanity check
return false unless number.length == 15
data = number[0..13].reverse
check_digit = number[14..14].to_i
total = (0..data.length-1).inject(0) do |total, i|
total += data[i..i].to_i * 3**((i+1)%2)
end
(10 - total % 10) == check_digit
end
The arithmetic expression 3**((i+1)%2) might look a bit complex, but is essentially the same as (i.odd? ? 1 : 3). Both variants are correct, which you use is up to you (and might affect speed...)
Also note, that if you use Ruby 1.9, you can use data[i] instead of data[i..i] which is required for for Ruby 1.8.

Resources