Solving Fizzbuzz Using Rubys Enumerable Module? - ruby

Hey I was given the fizzbuzz task recently and I had answered with the usual,
if ((i%3==0) || (i.to_s.include?('3'))) && ((i%7==0) || (i.to_s.include?('7')))
p 'Fizzbuzz'
elsif (i%3==0) || (i.to_s.include?('3'))
p 'Fizz'
elsif (i%7==0) || (i.to_s.include?('7'))
p 'Buzz'
else
p i
end
and when asked to shorten it I tried using ternary operators:
p (i%3<1 || i.to_s.include?('3')) ? ((i%7<1 || i.to_s.include?('7')) ? "Fizzbuzz" : "Fizz") : ((i%7<1 || i.to_s.include?('7')) ? "Buzz" : i)
but when asked to solve it using the Enumerable methods(select,reject,collect etc) I was well stumped...Any body tried this before??
The select/collect methods were specificaly mentioned so I'm guessing that he had something like this in mind(excuse the crappy code)
(1..100).select { |i| i % 3 == 0 }.collect { "fizz" }
but i'm stuck when trying to do this for the 3 conditions and print out the result(ie iterate through the output array) :\

Probably not much help now, but I've produced a gem (fizzbuzzard) that monkey patches Fixnum such that all multiples of three print as Fizz, all multiples of five etc etc. Interviewers will respect you for using your knowledge of existing libraries rather than pointlessly re-solving solved problems.
Get it from rubgems here and find the source here.
The part I'm proudest of? The test suite. Output reproduced here:
(0h8m|master) [fizzbuzzard] $ rspec
.
Finished in 0 seconds
1 example, FIZZBUZZ failures

def fizzbuzz(i)
[nil,nil,"Fizz",nil, nil,nil,"Buzz"].each_with_index do |fizz_or_buzz, idx|
print fizz_or_buzz if (i.to_i % (1+idx)).zero?
end
end
If the interviewer doesn't laugh, then it's probably not going to be a good fit (for me anyways).
Note that print doesn't add a newline (vs p)
See http://rosettacode.org/wiki/FizzBuzz#Ruby for more common solutions.

This one's a little dense but fun. It abuses arrays and some functional methods slightly to avoid using any if statements.
rules = {
3 => ["fizz"],
7 => ["buzz"]
}
(1..100).map do |n|
[rules.map do |key, value|
value[n % key]
end.compact.join, n.to_s].find do |word|
!word.empty?
end
end.join("\n")

It is not clean to repeat the same conditionals.
p case [
i.%(3).zero? || i.to_s.include?("3"),
i.%(7).zero? || i.to_s.include?("7")
]
when [true, true] then "Fizzbuzz"
when [true, false] then "Fizz"
when [false, true] then "Buzz"
when [false, false] then i
end

This hands you back the results in an array of strings, you can do whatever you want with them at that point.
results = (1..100).to_a.collect do |i|
f = ((i%3).zero? || i.to_s.include?('3'))
b = ((i%7).zero? || i.to_s.include?('7'))
"#{:fizz if f}#{:buzz if b}#{i unless f || b}"
end
p results

Related

Hackerrank New Year Chaos - Ruby - Print as return

I am trying to solve HackerRank's 'New year Chaos' challenge.
The script is supposed to print 'Too chaotic' in a certain case.
Regardless of wether or not my solution is correct, my current problem is that I can't seem to print it as it will then return nil. My solution is not accepted either it I replace it with a puts as it will include quotes.
bribes = 0
chaotic = false
q.each_with_index do |num, index|
if num - 1 - index > 2
chaotic = true
elsif index == 0
else
bribes += q.slice(0, index).count { |x| x > num }
end
end
return chaotic ? print('Too chaotic') : bribes
end
Hacker rank output
thanks!
Interesting problem to tackle. The main difference between print and puts is the included newline with puts. You want to use puts in this case. Here's a good discussion on the topic: https://www.rubyguides.com/2018/10/puts-vs-print/
I'm not sure what was happening with the quotes you mention, so I'd update your solution with puts, and tackle the quotes next.

How to remove 3 or more the same character

During my lessons of Ruby I came across of this exercise. I'm trying to remove 3 or more the same charactes in a row. Test Cases Input: abbbaaccada Output: ccada Input: bbccdddcb Output: (Empty string)
So far I have solution which doesn't return expected results:
def playground("abbbaaccada")
count = string.length
string.chars.each_with_index.map { |v, i| (v * (count - i)).capitalize }.join('')
end
output gives me
==> AaaaaaaaaaaBbbbbbbbbbBbbbbbbbbBbbbbbbbAaaaaaaAaaaaaCccccCcccAaaDdA
instead of
==> ccada
Could you please advise?
Edit:
Forgot to add that regexp isn't allowed
There are two challenges here:
Match and remove any run of thee or more characters in a row
Recurse to test again in case the previous step created a new run of three
Here's one way to do it:
THREE_OR_MORE = /(.)\1{2,}/
def three_is_too_many(str)
if str.match? THREE_OR_MORE
str = three_is_too_many(str.gsub(THREE_OR_MORE, ''))
end
str
end
The regexp finds any character ('.'), followed by itself ('\1'), two or more times ('{2,}').
Then the routine either a) removes three or more and tests again or b) returns the string.
Here's a potential solution. The following method searches for any subsequence of an array with repeats, and returns the range of the repeated values if there are three or more of them.
def find_3_or_more(ary)
ary.each_index do |i|
j = i + 1
while j < ary.length && ary[i] == ary[j]
j += 1
end
return (i...j) if j - i > 2
end
nil
end
This portion breaks the target string into an array of chars, and repeatedly slices out the characters in ranges identified as repeats until there are none, as indicated by a nil range.
def delete_3_or_more(str)
ary = str.chars
while r = find_3_or_more(ary)
ary.slice!(r)
end
return ary.join
end
It seems to do the job for your test cases.
def recursively_remove_runs_of_3_or_more(str)
arr = str.chars
loop do
a = arr.slice_when { |a,b| a.downcase != b.downcase }.to_a
b = a.reject! { |e| e.size > 2 }
arr = a.flatten
break arr.join if b.nil?
end
end
recursively_remove_runs_of_3_or_more "abbbaaccada"
#=> "ccada"
This uses Enumerable#slice_when (new in MRI v2.2). Note that Array#reject! returns nil when no changes are made.
You could alternatively use Enumerable#chunk_while (new in MRI v2.3). Simply replace:
a = arr.slice_when { |a,b| a.downcase != b.downcase }.to_a
with:
a = arr.chunk_while { |a,b| a.downcase == b.downcase }.to_a
chunk_while and slice_when are yin and yang.
If a regular expression could be used and case where not an issue, you could write:
str = "abbbaaccada"
s = str.dup
loop { break(s) if s.gsub!(/(.)\1{2,}/, '').nil? }
#=> "ccada"
(I wanted to comment, but it doesn't allow me to do that yet.)
Assuming that you are trying to learn, I chose to only give you some tips while avoiding a solution.
There might be shorter ways of doing this using regex or/and some String methods. However, you said you can not use regex.
My tip is, try to solve it only using the sections you have covered so far. It may not necessarily be the most elegant solution, but you can revise it as you progress. As others suggested, recursion might be a good option. But, if you are not familiar with that yet, you can try slicing the string and merging the parts you need. This can be combined with an endless loop to check the new string satisfies your condition: but think about when you need to break out of the loop.
Also, in your code:
v * (count - i)
String#* actually gives you count - i copies of v, concatenated together.

Combining multiple 'elsif' statements

I try to programm snakes in Ruby. In order to get myself more familiar with Ruby. I define the position of every part of the snake through saving its X and Y value in two 1D arrays one for a X value and one for a Y value.
$x = [2,...]
$y = [2,...]
(What I forgot to tell is that the head of the Snake moves through user input while the rest just inherits its position from the part before like this.)
def length(f)
if $length >= f
$y[f] = $y[f-1]
$x[f] = $x[f-1]
end
end
In order to get a field for the Snake to move around I programmed this.
for a in (1..20)
for b in (1..20)
print " X "
end
puts" "
end
Which gives me a 20*20 field.
I then tried to display every part of the snake like on the field like this.(While also drawing a boarder around the field.)
for a in (1..20)
for b in (1..20)
if a == 1 || a == 20
if b == 1 || b == 20
print " + "
else
print " - "
end
elsif b == 1 || b == 20
print " | "
elsif a == $x[0] && b == $y[0]
body
elsif a == $x[1] && b == $y[1]
body
elsif a == $x[2] && b == $y[2]
body
elsif a == $x[3] && b == $y[3]
body
elsif a == $x[4] && b == $y[4]
body
else
print " "
end
end
puts""
end
This works but if the user is really good/ has a lot of spare time I need to make allot of elsif for every one represents a part of the snake if the snake should have as a limit a length of 100 I would need to make 100 elsif statements.(The body is just:
def body
print " # ".green
end
)
I tried fixing it with a for loop like this:
for c in (1..100)
if a == $x[c] && b == $y[c]
body
end
end
and this
loop do
$x.size.times do |index|
if $x[index] == a && $y[index] == b
body
end
end
break
end
But sadly this didn't gave the desired outcome for this interfered with the ifthat draws the boarders of the field.
Is there a way to combine these multiple elsif statements?
Every help would be highly appreciated. ( Sorry for being to vague in the first draft.)
Recommended Refactorings
NB: You included no sample data in your original post, so your mileage with answers will vary.
You have a number of issues, not just one. Besides not being DRY, your code is also not very testable because it's not broken out into discrete operations. There are a number of things you can (and probably should) do:
Break your "body" stuff into discrete methods.
Use Array or Enumerator methods to simplify the data.
Use dynamic methods to loop over your arrays, rather than fixed ranges or for-loops.
Use case/when statements inside your loop to handle multiple conditionals for the same variable.
In short, you need to refactor your code to be more modular, and to leverage the language to iterate over your data objects rather than using one conditional per element as you're currently doing.
Simplify Your Data Set and Handle Procedurally
As an example, consider the following:
def handle_matched_values array
end
def handle_mismatched_values array
end
paired_array = a.zip b
matched_pairs = paired_array.select { |subarray| subarray[0] == subarray[1] }
unmatched_pairs = paired_array.reject { |subarray| subarray[0] == subarray[1] }
matched_pairs.each { |pair| handle_matched_values pair }
matched_pairs.each { |pair| handle_mismatched_values pair }
In this example, you may not even need an if statement. Instead, you could use Array#select or Array#reject to find indices that match whatever criteria you want, and then call the relevant handler for the results. This has the advantage of being very procedural, and makes it quite clear what data set and handler are being paired. It's also quite readable, which is extremely important.
Dynamic Looping and Case Statements
If you truly need to handle your data within a single loop, use a case statement to clean up your conditions. For example:
# Extract methods to handle each case.
def do_something_with data; end
def do_something_else_with data; end
def handle_borders data; end
# Construct your data any way you want.
paired_array = a.zip b
# Loop over your data to evaluate each pair of values.
paired_array.each do |pair|
case pair
when a == b
do_something_with pair
when a == paired_array.first || paired_array.last
handle_borders pair
else
do_something_else_with pair
end
end
There are certainly plenty of other ways to work pairwise with a large data set. The goal is to give you a basic structure for refactoring your code. The rest is up to you!
I would start with something like this:
(1..20).each do |a|
(1..20).each do |b|
if [1, 20].include?(a)
print([1, 20].include?(b) ? ' + ' : ' - ')
elsif (1..100).any? { |i| a == $x[i] && b == $y[i] }
body
else
print(' ')
end
puts('')
end
end
I suppose this would work as a solution even if it is not that advanced?
loop do
$x.size.times do |index|
if $x[index] == a && $y[index] == b
body
end
end
break
end

Perfect numbers array in one expression

I'm trying write a script that will print an array of perfect numbers. The hard part is that I have to do this only in one expression (line).
I searched ruby-doc for some useful methods but I didn't find anything about perfect numbers, so I only managed to do this using two functions:
def is_perf(n)
n == (1...n).select {|i| n % i == 0}.inject(:+)
end
def perfects(range)
(array = (2..range).to_a).each{|p|array.delete_if{|x| is_perf(x)==false }}
end
Can somebody help me squeeze this in just one line ?
For example like this:
(2..1000).select { |p| p == (1...p).select {|i| p % i == 0}.inject(:+) }
=> [6, 28, 496]
Edit: slightly shorter version, as suggested by #steenslag.

Simple way to test if multiple variables have same value, ruby

Is there a simple way of testing that several variables have the same value in ruby?
Something linke this:
if a == b == c == d #does not work
#Do something because a, b, c and d have the same value
end
Of course it is possible to check each variable against a master to see if they are all true, but that is a bit more syntax and is not as clear.
if a == b && a == c && a == d #does work
#we have now tested the same thing, but with more syntax.
end
Another reason why you would need something like this is if you actually do work on each variable before you test.
if array1.sort == array2.sort == array3.sort == array4.sort #does not work
#This is very clear and does not introduce unnecessary variables
end
#VS
tempClutter = array1.sort
if tempClutter == array2.sort && tempClutter == array3.sort && tempClutter == array4.sort #works
#this works, but introduces temporary variables that makes the code more unclear
end
Throw them all into an array and see if there is only one unique item.
if [a,b,c,d].uniq.length == 1
#I solve almost every problem by putting things into arrays
end
As sawa points out in the comments .one? fails if they are all false or nil.
tokland suggested a very nice approach in his comment to a similar question:
module Enumerable
def all_equal?
each_cons(2).all? { |x, y| x == y }
end
end
It's the cleanest way to express this I've seen so far.
How about:
[a,b,c,d] == [b,c,d,a]
Really just:
[a,b,c] == [b,c,d]
will do
a = [1,1,1]
(a & a).size == 1 #=> true
a = [1,1,2]
(a & a).size == 1 #=> false
[b, c, d].all?(&a.method(:==))

Resources