finding median in Ruby [duplicate] - ruby

This question already has answers here:
Find the median of an array
(4 answers)
Closed 9 years ago.
input: A list of numbers from the keyboard.
output: The median of the input numbers
I need the whole code
def median(array)
array.sort!
if (array.length % 2==1 )
return array[array.length/2.0]
else
return (array[array.length/2] + array[(array.length/2)-1])/2.0
end
end
How can I enter list from keyboard and the find the median?

Assuming you want numbers separated by spaced on a single input line (i.e. 1 5 56 6 75), add the following to your script:
input_array = gets.chomp.split(" ")
Then pass input_array to your median method
Update: Note that input_array will be an array of strings, so you'll need to convert values to integers. Here's a good example on doing so.

Related

Sum of first nth term of series [duplicate]

This question already has answers here:
Why is division in Ruby returning an integer instead of decimal value?
(7 answers)
Closed 3 years ago.
I am not understanding why my code isn't looping, for any input I give I get the result of "1.00"
I feel like I am being silly and missing something very obvious.
This series is shown in other places most often as 1/3n+1
But if series_sum(1) = "1.00"
then 3+1 = 4 giving you 1/4 to add to your sum for input of 1 which doesn't make sense
def series_sum(n)
sum = 0
if n == 0
return "0.00"
else
for i in 1..n
sum += 1/(1+(3*(i-1)))
end
end
return "%.2f" % sum.to_s
end
for series_sum(1) should be "1.00"
series_sum(2) should be "1.25"
series_sum(3) should be "1.39"
etc
My code gives "1.00" for any input
Why won't this code run the loop and perform the sum?
When you have expression like z = x/y, in ruby it does specify type for output based on operand provided for division. If x & y both are integer, output calculated is also integer and float value is removed.
So to obtain output as float, you need to have one operand at least as float value which can be found using to_f on variable. Here you need to change only,
- sum += 1/(1+(3*(i-1)))
+ sum += 1.0/(1+(3*(i-1)))

what makes an operator <=> in the block min? [duplicate]

This question already has answers here:
What is the Ruby <=> (spaceship) operator?
(6 answers)
Closed 6 years ago.
Have following example of code:
%w{ Ruby C APL Perl Smalltalk}.min {|a,b| a.size <=> b.size}
return "C"
Can you explain me why "C"? What makes an operator "<=>" ?
The Spaceship operator returns -1 if the left is less than the right, 0 if they are equal, and 1 if the left is greater than the right.
In this case, you're comparing the length of each word in the array and returning the shortest word. If you removed .size from the variable in the block, it would instead return the first word that occurs alphabetically (i.e. 'APL').
What is the Ruby <=> (spaceship) operator?

Empty array when index is end of array [duplicate]

This question already has answers here:
Array slicing in Ruby: explanation for illogical behaviour (taken from Rubykoans.com)
(10 answers)
Closed 7 years ago.
Negative indices count backward from the end of the array (-1 is the
last element). For start and range cases the starting index is just
before an element. Additionally, an empty array is returned when the
starting index for an element range is at the end of the array.
Returns nil if the index (or starting index) are out of range.
Why does
a = [0,1,2,3,4]
a[4] #=> 4
a[4,0] #=> [] - length is 0, so empty array is returned
a[5] #=> nil - makes sense since it is out of range
a[5,0] #=> [] - why is this empty?
a[6,0] #=> nil - but this is nil?
I put in {ix} for the positions instead of commas.
a = [{ix0}0{ix1}1{ix2}2{ix3}3{ix4}4{ix5}]
a[5,0] means go to 5 {ix5} and take 0 elements. That is just an empty array.
{ix6} is not a valid starting positions, thus nil.

Combining rand() numbers

I'm attempting to combine a few random numbers. The numbers are supposed to represent a dice.
For example, I want to roll the dice 5 times and I get the following results:
4 2 1 4 6.
These are all individual numbers but what I want to do is combine it together as 42146.
This might be a very simple question so I apologize for that but I'm still new to Ruby.
I'm generating numbers between [1,6] through this:
number = 1 + rand(6)
1.upto(5).map { rand(1..6) }.join.to_i
1.upto(5) will give you an Enumerator for 5 elements
map { rand(1..6) } will map a random number between 1 and 6 to each of the above elements
join will concatenate all elements of what you got so far
to_i will transform the above result from string to integer
Although all the answers are correct, there is one more option:
dice = 0
5.times do
dice = dice * 10 + rand(1..6)
end
puts dice
Demo: http://ideone.com/WfagFT
This time you treat everything as integers. Everytime (5 rolls) you take the result variable, multiply it by 10 and then add new random number at the end of it. There's no need to use anything else for that.
Of course if you need it, this code can be also written as one-liner and do exactly the same as above:
p #dice if 5.times { #dice = #dice.to_i * 10 + rand(1..6) }
5.times.inject(0){|n, _| n * 10 + 1 + rand(6)}
p Array.new(5){1 + rand(6)}.join # => "53325"

How to find the biggest number in accordance to the rules given (in a way of DP)? [duplicate]

This question already has answers here:
Find largest number with all contiguous triples being unique primes [closed]
(11 answers)
Closed 9 years ago.
Problem: Given a number S in the format of abcdefijak..., every letter refers to a digit. Every 3 digits compose of a 3-digital prime, each different from each other. What is the biggest possible S?
There are lots of method to solve the problem. What's my question is: how to solve it in DP?
I wrote a stupid brute force algorithm:
def isprime(n):
for x in xrange(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
primes3 = filter(isprime, range(100, 1000))
def biggest():
return max([biggie(x, set(primes3)-set([x])) for x in primes3])
def biggie(sofar, primes):
next2 = sofar % 100
found = sofar
for prime in filter(lambda x: 10*next2 <= x < 10*(next2+1), primes):
found = max(found, biggie(10*sofar + (prime % 10), primes - set([prime])))
return found
Which gave me the result of 9419919379773971911373313179. Googled for it, and found this: https://stackoverflow.com/questions/3836008/find-largest-number-with-all-contiguous-triples-being-unique-primes
Closing as duplicate...
Find all 3-digit primes and put them all one after another in descending order. If you have not unseen requirements in your task, that's all.

Resources