{{announcement.body}}
{{announcement.title}}

Day 12 of 30 - Ruby Coding Challenge - Repdigit Number Algorithm in a more Ruby Way

DZone 's Guide to

Day 12 of 30 - Ruby Coding Challenge - Repdigit Number Algorithm in a more Ruby Way

Day 12 of 30 - We're going solve the the Repdigit Algorithm in a more Ruby way, which validates if a digit is repeated in the whole number

· Web Dev Zone ·
Free Resource

Hey!

This is the blog post version of the Youtube video from the 30 Ruby Coding Challenges in 30 Days series


This post will be really short because Ruby, fortunately, provides us a really good way to solve the Repdigit Algorithm

#1 Repdigit Algorithm Version 1

In this solution we’re going to take the following steps:

Step 1

  • given a number, we’ll convert it into a String
Ruby
 




xxxxxxxxxx
1


 
1
number.to_s


Step 2

  • then we can use the method squeeze, which keeps only the unique digits\
Ruby
 




xxxxxxxxxx
1


 
1
number.to_s.squeeze


Step 3

  • now we validate if the remaining length of the array is 1
Ruby
 




xxxxxxxxxx
1


 
1
number.to_s.squeeze.length == 1


The complete code would be:

Ruby
 




xxxxxxxxxx
1


 
1
def is_repdigit(number)
2
    number.to_s.squeeze.length == 1
3
end
4
 
          
5
puts is_repdigit(777) # true
6
puts is_repdigit(774) # false
7
puts is_repdigit(555555) # true
8
puts is_repdigit(456555) # false


Pretty simple, isn’t it? :)

#2 Repdigit Algorithm Version 2

Another way to solve this problem is manipulating chars in Ruby

Step 1

  • getting the chars from the String
Ruby
 




xxxxxxxxxx
1


 
1
number.to_s.chars


Step 2

  • getting the unique chars from the String
Ruby
 




xxxxxxxxxx
1


 
1
number.to_s.chars.uniq


Step 3

  • Validating if the length of the array is 1
Ruby
 




xxxxxxxxxx
1


 
1
number.to_s.chars.uniq.length == 1


The complete code would be:

Ruby
 




xxxxxxxxxx
1


 
1
def is_repdigit(number)
2
  number.to_s.chars.uniq.length == 1
3
end
4
 
          
5
puts is_repdigit(777) # true
6
puts is_repdigit(774) # false
7
puts is_repdigit(555555) # true
8
puts is_repdigit(456555) # false


Amazing! Ruby allows us to solve the problem in a really beautiful and straightforward way ��

That’s it! I hope you liked it and see you in the next challenge : )

Don’t forget to come by and say hi Alex

Twitter Youtube Instagram Linkedin GitHub Courses

Topics:
algorithm analysis, algorithms, coding, data structure, math, programming, programming language, rails, ruby, tutorial for beginners

Published at DZone with permission of Alexandre Gama . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}