mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Merge pull request #175 from TheAlgorithms/fizz-buzz-hash-approach
Fizz Buzz: Hash Table approach
This commit is contained in:
commit
4336ec7550
2 changed files with 33 additions and 0 deletions
|
@ -58,6 +58,7 @@
|
|||
* [Arrays Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/arrays_intersection.rb)
|
||||
* [Common Characters](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/common_characters.rb)
|
||||
* [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/find_all_duplicates_in_an_array.rb)
|
||||
* [Fizz Buzz](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/fizz_buzz.rb)
|
||||
* [Good Pairs](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/good_pairs.rb)
|
||||
* [Isomorphic Strings](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/isomorphic_strings.rb)
|
||||
* [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/richest_customer_wealth.rb)
|
||||
|
|
32
data_structures/hash_table/fizz_buzz.rb
Normal file
32
data_structures/hash_table/fizz_buzz.rb
Normal file
|
@ -0,0 +1,32 @@
|
|||
# Write a program that outputs the string representation of numbers
|
||||
# from 1 to n. But for multiples of three it should output “Fizz”
|
||||
# instead of the number and for the multiples of five output “Buzz”.
|
||||
# For numbers which are multiples of both three and five output
|
||||
# “FizzBuzz”.
|
||||
|
||||
#
|
||||
# Approach 1: Hash it!
|
||||
#
|
||||
|
||||
# Complexity Analysis
|
||||
|
||||
# Time Complexity: O(N)
|
||||
# Space Complexity: O(1)
|
||||
|
||||
# @param {Integer} n
|
||||
# @return {String[]}
|
||||
def fizz_buzz(n, fizz_buzz = { 3 => 'Fizz', 5 => 'Buzz' })
|
||||
n.times.map do |i|
|
||||
i += 1
|
||||
num_str = ''
|
||||
|
||||
fizz_buzz.each do |key, value|
|
||||
num_str += value if i % key == 0
|
||||
end
|
||||
|
||||
num_str.empty? ? i.to_s : num_str
|
||||
end
|
||||
end
|
||||
|
||||
n = 15
|
||||
puts(fizz_buzz(n))
|
Loading…
Reference in a new issue