I tried to solve the Ruby bonus drink problem (there is an example of the answer)

Introduction

"Introduction to Ruby for those who want to become a professional" I am a programming beginner after learning the so-called cherry book. When I wanted to move my hands and put into practice what I input, I found an article by the author. "If you have trouble with output material !? I collected programming problems for Ruby beginners (10 questions in total)"

I tried to solve this fourth problem.

Click here for other issues First question: Calendar creation problem (fun Ruby practice problem) Second question: Karaoke machine creation problem Third question: Bingo card creation problem Fourth question: Bonus drink problem Fifth question: Phonebook creation problem

problem

For details from here

When you buy a drink at a candy store, you will get a new drink with 3 empty bottles. Create a program that calculates the total number of drinks you can drink from the number of drinks you purchased first. Also, if you purchase 100 bottles for the first time, how many bottles can you drink in total?

** Remarks ** This problem is based on the math problem in the third grade of elementary school.

** Example **

|Number of purchases|Number of drinks| |--:|--:| | 0 | 0 | | 1 | 1 | | 3 | 4 | | 11 | 16 | | 100 | (Calculate by program) |

Answer example

It turned out to be something like this

class BonusDrink
  def self.total_count_for(amount)
    if amount.zero?
      0
    elsif amount.odd?
      3 * amount / 2
    elsif amount.even?
      3 * (amount - 1) / 2 + 1
    end
  end
end

Here is the test code.

require_relative '../Bonus_drink/drink'

RSpec.describe BonusDrink do
  it "total_count_for" do
    expect(BonusDrink.total_count_for(0)).to eq 0
    expect(BonusDrink.total_count_for(1)).to eq 1
    expect(BonusDrink.total_count_for(3)).to eq 4
    expect(BonusDrink.total_count_for(11)).to eq 16
  end
end

Commentary

I think that it is established as a program, but there is a slight feeling that this solution was good as the purpose of the programming problem. (Mostly I moved the paper and pen to solve it mathematically.)

First

As you can see in the problem, you can get a " exchange 3 empty bottles for a new one ". The essence of this problem is that even one new bottle that you exchange and receive will be subject to exchange.

So

Number of purchased: 3 Number of newly exchanged:1 Total number of drinks: 4

However, if you add the bottles you received and reach 3 bottles, you can exchange another one. For example

Number of purchased: 5 Number of newly exchanged:1 Additional books exchanged: 1 Total number of drinks: 7

It means that. Therefore, as the number of purchases increases, additional exchanges will be repeated many times.

I thought that it was a problem to express this by programming and repeatedly substitute the total number of bottles and the number of replaced bottles to get closer to the maximum total number, but I could not think of it and gave up. I would appreciate it if you could let me know in the comments if you have any examples of answers.

Explanation from here

So how did I solve it? I wrote down the number of bottles I bought and the number of bottles I could drink.

Number of purchases Number of drinks
0 0
1 1
2 2
3 4
4 5
5 7
6 8
7 10
8 11
9 13
10 14
11 16

Then, *** "When the number of purchased bottles n is odd, the value of (n * 3) matches the total number of drinkable bottles at n and the number of drinkable bottles at (n + 1)" *** I found out. By the way, when it is 0, it does not hold. (There are various other rules, but this time I will use this equation.) In particular,

Number of purchases Number of drinks
5 7
6 8
5 * 3 = 15
7 + 8 = 15

It will be! In other words, *** "If you divide n by 3 and divide it by 2, you can find the number of drinks you can drink" ***. If you translate this into programming,

#When odd
3 * amount / 2
#When it is an even number, it is calculated from the previous odd number.
3 * (amount - 1) / 2 + 1

[Example of the above answer](#Example of answer) is a summary of the above contents.

at the end

I understand that such a law does not hold, but I don't quite understand ** "Why this happens" **. If you can explain in an easy-to-understand manner, I would like to ask you to teach with embarrassment.

Thank you!

Recommended Posts

I tried to solve the Ruby bonus drink problem (there is an example of the answer)
I tried to solve the Ruby karaoke machine problem (there is an example of the answer)
I tried to solve the Ruby bingo card creation problem (there is an example of the answer)
I tried to solve the problem of "multi-stage selection" with Ruby
[Beginner's point of view] I tried to solve the FizzBuzz problem "easily" with Ruby!
I tried to solve the problem of Google Tech Dev Guide
I tried to solve the tribonacci sequence problem in Ruby, with recursion.
I tried to solve the tribonatch sequence problem in Ruby (time limit 10 minutes)
I tried to summarize the basic grammar of Ruby briefly
I tried to solve the paiza campaign problem "Challenge from Kaito 813"
I want to make the frame of the text box red when there is an input error
I tried to make full use of the CPU core in Ruby
I tried to summarize the state transition of docker
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I want to know the answer of the rock-paper-scissors app
Offline real-time how to write Implementation example of the problem in E05 (ruby, C11)
Since the argument of link_to is nil (null) and an unexpected link was generated, I tried to verify it
I tried to summarize the basics of kotlin and java
[Swift] I tried to implement the function of the vending machine
Since the reading of JdbcCodeList of TERASOLUNA is slow, I tried to register multiple at once.
I tried to build the environment of WSL2 + Docker + VSCode
I tried the FizzBuzz problem
[Ruby] I want to reverse the order of the hash table
I want to solve the N + 1 problem where the data is collated excessively and the operation becomes heavy.
I tried to build the environment of PlantUML Server with Docker
[Ruby] Tonight, I tried to summarize the loop processing [times, break ...]
Want to know what Ruby n is the power of 2? (Power judgment of 2)
How to output the value when there is an array in the array
I tried to understand how the rails method "redirect_to" is defined
I tried to check the operation of gRPC server with grpcurl
I tried to understand how the rails method "link_to" is defined
I tried to summarize the methods of Java String and StringBuilder
I tried to make Numeron which is not good in Ruby
I want to change the value of Attribute in Selenium of Ruby
I tried to explain the method
I tried to make a sample program using the problem of database specialist in Domain Driven Design
I tried to make a parent class of a value object in Ruby
I tried to summarize the stumbling points when developing an Android application
I tried to summarize the key points of gRPC design and development
[Ruby] I tried to diet the if statement code with the ternary operator
[Ruby] I want to extract only the value of the hash and only the key
[Introduction to Java] I tried to summarize the knowledge that I think is essential
Get the type of an array element to determine if it is an array
How to solve the local environment construction of Ruby on Rails (MAC)!
I tried to visualize the access of Lambda → Athena with AWS X-Ray
[Ruby] I tried to summarize the methods that frequently appear in paiza
[Ruby] I tried to summarize the methods that frequently appear in paiza ②
I tried to measure and compare the speed of GraalVM with JMH
There is LSP and I tried to create an environment to write Java with Vim (NeoVim), but after all I could not beat the IDE ...
I tried a calendar problem in Ruby
I tried to summarize the methods used
Since the du command used when the capacity is full is difficult to use, I tried wrapping it with ruby
I tried to implement the Iterator pattern
I tried to summarize the Stream API
What is Docker? I tried to summarize
I tried to build Ruby 3.0.0 from source
Use hashes well in Ruby to calculate the total amount of an order
Ruby: I tried to find out where Nokogiri goes to see the encoding himself
What I tried when I wanted to get all the fields of a bean
I tried to compare the infrastructure technology of engineers these days with cooking.