I tried to solve the Ruby karaoke machine 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 second problem.

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, see Actual problem statement. If you know the problem, [Jump to answer example](# answer example).

Karaoke has a function to change the key. +1 will raise the key by one. -1 will lower the key by one. For example, if you raise the key of the melody "Dremifaso" by two, it becomes "Remifa #Sora". image.png Katakana like "Dremi Faso" is difficult to handle in the program, so let's replace it with the English reading, that is, the alphabet. Doremi Faso → C D E F G Remifa #Sora → D E F # G A

The melody of Kaeru no Uta is expressed by the following character strings. Change the key for the specified size such as (+6) or (-11).

"C D E F |E D C   |E F G A |G F E   |C   C   |C   C   |CCDDEEFF|E D C   "

The execution example looks like this.

melody = "C D E F |E D C |E F G A |G F E |C C |C C |CCDDEEFF|E D C " karaoke = KaraokeMachine.new(melody) karaoke.transpose(2)

=> "D E F# G |F# E D |F# G A B |A G F# |D D |D D |DDEEF#F#GG|F# E D "

karaoke.transpose(-1)

=> "B C# D# E |D# C# B |D# E F# G# |F# E D# |B B |B B |BBC#C#D#D#EE|D# C# B "

#1 octave(12 tones)You can change the above karaoke.transpose(14)

=> "D E F# G |F# E D |F# G A B |A G F# |D D |D D |DDEEF#F#GG|F# E D "


# Answer example
 It turned out to be something like this.

```ruby
class KaraokeMachine

  def initialize(melody)
    @melody = melody
  end

  def transpose(amount)
    scales = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
    @melody.split(/(\w#?)/).map{
            |m| /(\w#?)/.match?(m) ?
            scales[(scales.find_index(m) + amount) % scales.length] : m 
           }.join
  end
end

At first I thought it was completed with the code below, but

class KaraokeMachine

  def initialize(melody)
    @melody = melody
  end

  def transpose(amount)
    scales = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
    @melody.split("").map{
                |m| m == " " || m == "|" ?
                 m : scales[(scales.find_index(m) + amount) % scales.length]
               }.join
  end
end

In this case, I noticed that the alphabet and # were separated when the following melody came, and corrected it using a regular expression.

melody = "F# G# A# B |A# G# F#   |A# B C# D# |C# B A#   |F#   F#   |F#   F#   |F#F#G#G#A#A#BB|A# G# F#   "

Commentary

I will write it as my memorandum.

The scale in this problem is a repetition of "Dodo #Rele #Mifafa #Soso #Lara #Shi" including the sharp.

  scales = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]`

I made one array like this.

The character string received by melody = is separated into scale andotherto make an array.

melody = "C D E F |E D C   |E F G A |G F E   |C   C   |C   C   |CCDDEEFF|E D C   "
melody.split(/(\w#?)/)
=> ["", "C", " ", "D", " ", "E", " ", "F", " |", "E", " ", "D", " ", "C", "   |", "E", " ", "F", " ", "G", " ", "A", " |", "G", " ", "F", " ", "E", "   |", "C", "   ", "C", "   |", "C", "   ", "C", "   |", "C", "", "C", "", "D", "", "D", "", "E", "", "E", "", "F", "", "F", "|", "E", " ", "D", " ", "C", "   "]

Each element of the array is found in the block of the map method to find the boolean value of the condition, and each value is added to the new array.

  1. If it is scale, change the specified minute key.
  2. If otherwise, add the element as it is. Will be executed by the following code.
@melody.split(/(\w#?)/).map{
          |m|  /(\w#?)/.match?(m) ?
          scales[(scales.find_index(m) + amount) % scales.length] : m 
         }.join

Dividing the number obtained by adding the ʻindex of the scaleand the increment / decrement of the specified key by thelength of the scales gives the ʻindex of the corresponding scale to which the key was changed. .. Therefore, if you substitute the value of scales [] and specify ʻindex, you can find the scale` with the key change.

Finally, join thisscaleand other again and convert it to a character string, and you're done.

at the end

I think there are some places that have become a little forcible. Please let me know if you have any mistakes or opinions.

Recommended Posts

I tried to solve the Ruby karaoke machine problem (there is an example of the answer)
I tried to solve the Ruby bonus drink 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
[Java] I tried to solve Paiza's B rank problem
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
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 solve AOJ's Binary Search
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