Restrict a number to upper/lower bounds? - ruby-on-rails

Is there a built-in way or a more elegant way of restricting a number num to upper/lower bounds in Ruby or in Rails?
e.g. something like:
def number_bounded (num, lower_bound, upper_bound)
return lower_bound if num < lower_bound
return upper_bound if num > upper_bound
num
end

Here's a clever way to do it:
[lower_bound, num, upper_bound].sort[1]
But that's not very readable. If you only need to do it once, I would just do
num < lower_bound ? lower_bound : (num > upper_bound ? upper_bound : num)
or if you need it multiple times, monkey-patch the Comparable module:
module Comparable
def bound(range)
return range.first if self < range.first
return range.last if self > range.last
self
end
end
so you can use it like
num.bound(lower_bound..upper_bound)
You could also just require ruby facets, which adds a method clip that does just this.

You can use min and max to make the code more concise:
number_bounded = [lower_bound, [upper_bound, num].min].max

class Range
def clip(n)
if cover?(n)
n
elsif n < min
min
else
max
end
end
end

Since you're mentioning Rails, I'll mention how to do this with a validation.
validates_inclusion_of :the_column, :in => 5..10
That won't auto-adjust the number, of course.

Related

Optimizing finding and counting proper divisors in ruby

This code needs to run under 7000ms or it times out and I am trying to learn ruby so I am here to see if anyone has any ideas that could optimize this code. Or if you can just let me know which functions in this code take the most time so I can concentrate on the parts that will do the most good.
The questions to solve is that you have to tell if the number of divisors for any umber is odd or even.
For n=12 the divisors are [1,2,3,4,6,12] – 'even'
For n=4 the divisors are [1,2,4] – 'odd'
Any help is greatly appreciated,
Thanks.
def oddity(n)
div(n) % 2 == 0 ? (return 'even'): (return 'odd')
end
def div(num)
divs = []
(1..num).each{|x| if (num % x == 0) then divs << x end}
return divs.length
end
The key observation here is that you need only the number of divisors, rather than the divisors themselves. Thus, a fairly simple solution is to decompose the number to primes, and check how many combinations can we form.
require 'mathn'
def div(num)
num.prime_division.inject(1){ |prod, n| prod *= n[1] + 1 }
end
prime_division returns a list of pairs, where the first is the prime and the second is its exponent. E.g.:
12.prime_division
=> [[2, 2], [3, 1]]
We simply multiply the exponents, adding 1 to each, to account for the case where this prime wasn't taken.
Since performance is an issue, let's compare the OP's solution with #standelaune's and #dimid's.
require 'prime'
require 'fruity'
n = 100_000
m = 20
tst = m.times.map { rand(n) }
#=> [30505, 26103, 53968, 24108, 78302, 99141, 22816, 67504, 10149, 28406,
# 18294, 92203, 73157, 5444, 24928, 65154, 24850, 64219, 68310, 64951]
def op(num) # Alex
divs = []
(1..num).each { |x| if (num % x == 0) then divs << x end }
divs.length
end
def test_op(tst) # Alex
tst.each { |n| op(n) }
end
def pd(num) # divid
num.prime_division.inject(1){ |prod, n| prod *= n[1] + 1 }
end
def test_pd(tst) #divid
tst.each { |n| nfacs_even?(n) }
end
def div(num) # standelaune
oddity = false
(1..num).each{|x| if (num % x == 0) then oddity = !oddity end}
oddity ? "odd" : "even"
end
def test_div(tst) # standelaune
tst.each { |n| div(n) }
end
compare do
_test_op { test_op tst }
_test_div { test_div tst }
_test_pd { test_pd tst }
end
Running each test 16 times. Test will take about 56 seconds.
_test_pd is faster than _test_div by 480x ± 100.0
_test_div is similar to _test_op
I'm not suprised that divid's method smokes the others, as prime_division uses (an instance of) the default prime generator, Prime::Generator23, That generator is coded in C and is fast relative to other generators in Prime subclasses.
You could solve this by optimising your algorithm.
You don't have to check all numbers below the number you are examining. It is enough to split your number in to it´s prime components. Then it is a simple matter of combinatorics to determine how many possible divisors there are.
One way to get all prime components could be:
PRIME_SET = [2,3,5,7,11,13,17,19]
def factorize(n)
cut_off = Math.sqrt(n)
parts = []
PRIME_SET.each do |p|
return parts if p > cut_off
if n % p == 0
n = n/p
parts << p
redo
end
end
raise 'To large number for current PRIME_SET'
end
Then computing the number of possible can be done in a number of different ways and there are probably ways of doing it without even computing them. But here is a naive implementation.
def count_possible_divisors(factors)
divisors = Set.new
(1..factors.length-1).each do |i|
factors.combination(i).each do |comb|
divisors.add(comb.reduce(1, :*))
end
end
divisors.length + 2 # plus 2 for 1 and n
end
This should result in less work than what you are doing. But for large numbers this is a hard task to achieve.
If you want to stick with your algorithm, here is an optimization.
def div(num)
oddity = false
(1..num).each{|x| if (num % x == 0) then oddity = !oddity end}
oddity ? "odd" : "even"
end

How to Find the Middle Character(s) in Ruby?

I'm trying to write a method in Ruby that:
if the string length is even numbers it will return the middle two characters and,
if the string length is odd it will return only the middle character
i put together this code, but it is not working:
def the_middle(s)
if s.length % 2 == 0
return s.index(string.length/2-1) && s.index(string.length/2)
else
return s.index(string.length/2).round
end
end
I think the problem is in the syntax, not the logic, and I was hoping someone could identify where the syntax error might be.
I really appreciate your help!
Actually you have both syntax errors and logic (semantic) errors in that code.
First of all it seems you have misunderstood how the index method on string works. It does not return the character at the given index but the index of a given substring or regex as can be seen in the documentation:
Returns the index of the first occurrence of the given substring or pattern (regexp) in str.
You're also using the wrong operator to concatenate the two middle characters when the string length is even. && is the logical and operator. It's usually used for conditions and not assigments - for example in an if statement if s.length.even? && s.length > 2. The operator you want to use is + which concatenates strings.
Finally, you're using string.length but string is not defined anywhere. What you mean is probably s.length (the input parameter).
The correct solution would be more like the following:
def the_middle(s)
if s.length.even?
return s[s.length/2-1] + s[s.length/2]
else
return s[s.length/2]
end
end
I have taken the liberty to replace s.length % 2 == 0 with s.length.even? as it's more intention revealing and really the ruby way of finding out whether an integer is even or odd.
You can solve this without a conditional using String#[].
Using a range with a negative end:
def the_middle(s)
i = (s.length - 1) / 2
s[i..-i.succ]
end
Or start and length:
def the_middle(s)
a, b = (s.length - 1).divmod(2)
s[a, b + 1]
end
Both return the same results:
the_middle("a") #=> "a"
the_middle("aba") #=> "b"
the_middle("abcba") #=> "c"
the_middle("abcdcda") #=> "d"
# ^
the_middle("abba") #=> "bb"
the_middle("abccba") #=> "cc"
the_middle("abcddcda") #=> "dd"
# ^^
Try this:
def get_middle(s)
x = (s.length/2)
s.length.even? ? s[x-1..x] : s[x]
end
Since olerass already answered your doubt about the syntax, i will suggest you a less verbose solution for the question in the title:
def the_middle(s)
return s[s.length/2] if s.length.odd?
s[s.length/2-1] + s[s.length/2]
end
Same answer the syntax is just consolidated.
Format (logic result) ? ( if true this is the result) : (if false this is the result)
def get_middle(s)
num = s.length
num.even? ? ( s[num/2-1] + s[num/2]) : (s[num/2])
end

call function until (with call limit)

I have a function that generates random output (string).
I need to call that function until I get 3 different outputs (strings).
What is the most elegant way to generate array with 3 unique strings by calling the function, with the limit how many times the function can be called if the output is not generated in specified number of attempts?
Here's what I currently have:
output = []
limit_calls = 5
limit_calls.times do |i|
str = generate_output_function
output.push str
break if output.uniq.size > 2
end
Can this be beautified / shortened to 1 line? I'm pretty sure in ruby.. :)
Thanks
Using a set makes it (a bit) easier:
require 'set'
output = Set.new
limit_calls = 5
call_count = 0
while output.size < 3 and call_count < limit_calls
output << generate_output_function
call_count += 1
end
output
or with an array
output = []
limit_calls = 5
while output.size < limit_calls and output.uniq.size < 3
output << generate_output_function
end
output.uniq
UPDATE with the call limit. Seems like the Array version wins! Thanks Iain!
Will also ponder a version using inject.
UPDATE 2 - with inject:
5.times.inject([]) { |a, el| a.uniq.size < 3 ? a << generate_output_function : a }
there is your oneliner. I am not sure I prefer it cause it is a bit hard to follow.....
Froderik's answer missed out the call_limit requirement. What about a function like...
def unique_string_array(call_limit)
output = []
calls = 0
until (output.size == 3 || calls == call_limit) do
(output << generate_output_function).uniq! && calls+=1
end
output
end
It isn't a one-liner but it is readable... with this implementation, you may end up with arrays less than size 3. The most important thing is that you have a test that asserts the behaviour you want! (in order to test this thoroughly you'll have to stub out the call to generate_output_function)

What is the meaning of '<==>' in Ruby? [duplicate]

This question already has answers here:
What is the Ruby <=> (spaceship) operator?
(6 answers)
Closed 9 years ago.
What is the meaning of '<==>' in Ruby?
Example: The code comes from the following class that compares numbers in the format x.x.x,
def <==>(other)
# Some code here
end
The following code comes from this class that orders numbers like x.x.x,
class Version
attr_reader :fst, :snd, :trd
def initialize(version="")
v = version.split(".")
#fst = v[0].to_i
#snd = v[1].to_i
#trd = v[2].to_i
end
def <=>(other)
return #fst <=> other.fst if ((#fst <=> other.fst) != 0)
return #snd <=> other.snd if ((#snd <=> other.snd) != 0)
return #trd <=> other.trd if ((#trd <=> other.trd) != 0)
end
def self.sort
self.sort!{|a,b| a <=> b}
end
def to_s
#sorted = #fst.to_s + "." + #snd.to_s + "." + #trd.to_s
#Puts out "#{#sorted}".
end
end
That is the spaceship operator. However, it is actually <=> (not <==>).
Although that is not its official name, I'm sure, it's the most commonly used name for that operator. It is a comparison operator where
If other is less than self, return 1,
If other is equal to self, return 0
If other is greater than self, return -1
It is a powerful operator in that by just implementing this you can do sorting of your own type and participate in a lot of other niceties, like the Enumerable mixin.
Why don't you just try it out? By just typing in the code you posted, it is trivial to see for yourself that it doesn't mean anything, since <==> is not a valid method name in Ruby. The code you posted will just raise a SyntaxError.

LocalJumpError (Ruby on Rails)

I have searched/Googled around but I'm struggling with the following problem.
I am building a Rails 2.3.2 application and one of the requirements is to calculate the median of an array of results. I am using code for calculating the median from the Ruby Cookbook but keep running in to a problem with receiving an error 'LocalJumpError - no block given' when I attempt to find the median of an array where there are an odd number of members.
The example code in my view is as follows:
<%= survey_response.median([6,4,5,4,4,2]) %>
Then in survey_response.rb model the methods are as follows:
def mean(array)
array.inject(array.inject(0) { |sum, x| sum += x } / array.size.to_f)
end
def median(array,already_sorted=false)
return nil if array.empty?
array = array.sort unless already_sorted
m_pos = array.size / 2
return array.size % 2 == 1 ? array[m_pos] : mean(array[m_pos-1..m_pos])
end
The error is caused when the median method refers back to the mean method to get the media of an odd total of items in the array. I just can't figure out why I get that error or indeed how to fix it - so I'd hugely appreciate any help/guidance/laughing anybody could offer me!
Thanks
Simon
Lis looks like it's due to you using a fractional index into the array. Try replacing:
m_pos = array.size / 2
with:
m_pos = (array.size / 2).ceil
Also, try changing your mean function to this:
def mean(array)
array.inject(0) { |sum, x| sum += x } / array.size.to_f
end
That mean method looks horribly botched. Try this:
def mean(array)
a.inject(0) { |sum,x| sum += x } / a.size.to_f
end
Better code:
def mean(array)
array.inject { |sum, n| sum + n } / array.length.to_f
end
def median(array)
return nil if array.empty?
array.sort!
middle = array.length / 2
(array.length % 2 == 1) ? array[middle] : mean([array[middle-1], array[middle]])
end
puts median([5,11,12,4,8,21]) # => 9.5

Resources