Calculate missing number - ruby

Here's the exercise:
You have been given a list of sequential numbers from 1 to 10,000, but
they are all out of order; furthermore, a single number is missing
from the list. The object of the task is to find out which number is
missing.
The strategy to this problem is to sum the elements in the array, then sum the range 1 to 10,000, and subtract the difference. This is equal to the missing number. The formula for calculating the sum of the range from 1..n being n(n+1)/2.
This is my current approach:
def missing_number(array)
sum = 0
array.each do |element|
sum += element
end
((10000*10001)/2) - sum
end
Where I am getting tripped up is the output when I input an array such as this:
puts missing_number(*1..10000) #=> 0
Why does this happen?
Thanks!

No need to sort the array. An array of length N is supposed to have all but one of the numbers 1..(N+1) so the array length + 1 is the basis for figuring out what the grand_sum would be if all values were there.
def missing_number(array)
grand_sum = (array.length + 1) * (array.length + 2) / 2
grand_sum - array.inject(:+)
end
ADDENDUM
This method takes an array as an argument, not a range. You can't use a range directly because there wouldn't be a missing value. Before calling the method you need some mechanism for generating an array which meets the problem description. Here's one possible solution:
PROBLEM_SIZE = 10_000
# Create an array corresponding to the range
test_array = (1..PROBLEM_SIZE).to_a
# Target a random value for deletion -- rand(N) generates values in
# the range 0..N-1, inclusive, so add 1 to shift the range to 1..N
target_value = rand(PROBLEM_SIZE) + 1
# Delete the value and print so we can check the algorithm
printf "Deleting %d from the array\n", test_array.delete(target_value)
# Randomize the order of remaining values, as per original problem description
test_array.shuffle!
# See what the missing_number() method identifies as the missing number
printf "Algorithm identified %d as the deleted value\n", \
missing_number(test_array)

An alternative approach to solving the problem if it's not performance critical, because of its readability:
def missing_number(array)
(1..10_000).to_a - array
end

Instead of *1..10000, the argument should be (1..10000).to_a.

You shouldn't be using *1..10000, this will just expand to 10,000 arguments. (1..10000).to_a will return zero because there are no elements missing between 1..10000 you need to remove one. Below is some code with a detailed explanation.
def missing_number array
# put elements in order
array.sort!
# get value of last array element
last = array[-1]
# compute the expected total of the numbers
# 1 - last
# (n + 1)(n)/2
expected = (last + 1) * (last / 2)
# actual sum
actual = array.inject{|sum,x| sum + x}
# find missing number by subtracting
(expected - actual)
end
test = (1..10000).to_a
test.delete 45
puts "Missing number is: #{missing_number(test)}"

Related

Ruby prime number sum

I am trying to take the sum of the n first prime numbers. I found a way of showing the first 100, but I don't know how to get rid of 1 and how to make a sum with the numbers. I was thinking about storing them into an array, but I can not figure it out.
num = 1
last = 100
while (num <= last)
condition = true
x = 2
while (x <= num / 2)
if (num % x == 0)
condition = false
break
end
x = x + 1
end
primes = [] # Here
if condition
puts num.to_s
primes << num.to_s # Here
end
num = num + 1
end
puts primes.inject(:+) # Here
Based on what I understood from what you guys are saying I added these lines (the ones commented # Here). It still does not print the sum of them. What I meant with getting rid of 1 is that I know that 1 is not considered a prime number, and I do not get how to make it without 1. Thank you very much guys for your time and answers, and please understand that I am just starting to study this.
If you want to add a list of numbers together you can use the following:
list_of_prime_numbers.inject(0) {|total,prime| total + prime}
This will take the list of numbers, and add them one by one to an accumulator (total) that was injected into the loop (.inject(0)), add it to the current number (prime) and then return the total which then becomes the value of total in the next iteration.
I'm not quite sure what you mean by:
I don't know how to get rid of 1
but if you mean to not use the first number (which is 1 in a list of primes starting from 0)
then you could do:
list_of_prime_numbers[1...list_of_prime_numbers.length].
inject(0) {|total,prime| total + prime}
Which would only get all the numbers except the first up to but not including the length of the array
and as for getting the number into the array you could push it into the array like so:
list_of_prime_numbers << prime_number
You can make use of Prime Enumerable in ruby
require 'prime'
((1..100).select { |number| Prime.prime?(number) }).inject(:+)
OR
Prime.each(100).inject(:+)
Hope this helps.

Sort Integer Array Ruby

Have the function PermutationStep (num) take the num parameter being passed and return the next number greater than num using the same digits. For example: if num is 123 return 132, if it's 12453 return 12534. If a number has no greater permutations, return -1 (ie. 999)
Here's my code. I'd like to sort an array of large integers in numerical order. Using the regular sort method doesn't give the right order for some numbers. Is there a sort_by structure that I can replace 'sort' with in my code below?
def PermutationStep(num)
num = num.to_s.split('').map {|i| i.to_i}
permutations = num.permutation.to_a.sort #<= I want to sort by numerical value here
permutations.each_with_index do |n, idx|
if n == num
if n == permutations[-1]
return -1
else
return permutations[idx+1].join.to_i
end
end
end
end
For example, 11121. When I run the code it gives me 11121.I want the next highest permutation, which should be 12111.
Also, when I try { |a,b| b <=> a }, I also get errors.
You can pass a block to sort.
num.permutation.to_a.sort { |x, y| x.to_i <=> y.to_i }
This SO thread may be of some assistance: How does Array#sort work when a block is passed?
num.permutation.to_a is an array of arrays, not an array of integers, which causes the result not what you expected.
Actually you don't need to sort since you only need the minimum integer that is bigger than the input.
def PermutationStep(num)
nums = num.to_s.split('')
permutations = nums.permutation.map{|a| a.join.to_i}
permutations.keep_if{|n| n > num}.min || -1
end
puts PermutationStep(11121) # 11211
puts PermutationStep(999) # -1
Call to_i before your sort the permutations. Once that is done, sort the array an pick the first element greater than your number:
def PermutationStep(num)
numbers = num.to_s.split('')
permutations = numbers.permutation.map { |p| p.join.to_i }.sort
permutations.detect { |p| p > num } || -1
end
You don't need to consider permutations of digits to obtain the next higher number.
Consider the number 126531.
Going from right to left, we look for the first decrease in the digits. That would be 2 < 6. Clearly we cannot obtain a higher number by permuting only the digits after the 2, but we can obtain a higher number merely by swapping 2 and 6. This will not be the next higher number, however.
We therefore look for the smallest digit to the right of 2 that is greater than 2, which would be 3. Clearly, the next higher number will begin 13 and will have the remaining digits ordered smallest to largest. Therefore, the next higher number will be 131256.
You can easily see that the next higher number for 123 is 132, and for 12453 is 12534.
The proof that procedure is correct is easily established by induction, first showing that it is correct for numbers with two digits, then assuming it is correct for numbers with n>=2 digits, showing it is correct for numbers with n+1 digits.
It can be easily implemented in code:
def next_highest(n)
a = n.to_s.reverse.split('').map(&:to_i)
last = -Float::INFINITY
x,ndx = a.each_with_index.find { |d,i| res = d<last; last=d; res }
return nil unless x
swap_val = a[ndx]
swap_ndx = (0...ndx).select { |i| a[i] > swap_val }.min_by{ |i| a[i] }
a[ndx], a[swap_ndx] = a[swap_ndx], swap_val
a[0...ndx] = a[0...ndx].sort.reverse
a.join.reverse
end
next_highest(126531) #=> "131256"
next_highest(109876543210) #=> "110023456789"

Finding median for even length array in ruby

I cannot figure out why I cannot get the even length portion correct.
def median(array)
array.sort!
if array.length % 2 == 0 #if amount of array members is even
(array[(array.length/2) + 1] + array[array.length/2]) / 2.to_f #return average of the 2 middle array members
else #if amount of array members is odd
array[array.length/2.ceil] #return middle number
end
end
My attempt is for example, an array whose length is 6, and whose 3rd and 4th index value are 7 and 9.
array[6/3+1] + array [6/3]
(array[4] + array[3]) /2
9 + 7 / 2
I am receiving this error
Error!
median returns the correct median of an even-length array
expected: 5.5 got: 6.0 (compared using ==)
I have seen a shorter solution, but am most curious if I can make sense of the logic path I am trying to follow, thanks for playing along!
Solution I have seen:
def median(array)
sorted = array.sort
len = sorted.length
return (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0
end
Arrays are zero-indexed. So if the length was 4, you need to be taking average of indices 1 and 2. Your current attempt would take average of indices 3 and 2 for a length of 4. So you just need to change one small thing (plus into minus):
(array[(array.length/2) - 1] + array[array.length/2]) / 2.to_f
For an even numbered Fixnum n, this is always true: ( n - 1 ) / 2 == ( n / 2 ) - 1, which means you have figured out a similar approach to the one you found. This is not too surprising, there are a limited number of ways to calculate medians efficiently.
Here is my solution to your whole problem. you need use to -1 that's the reason "arr[(arr.length/2)-1]". Also you can use 2.0 instead of 2.to_f.
#Write a method that finds the median of a given array of integers. If the array has an odd number of integers,
# return the middle item from the sorted array. If the array has an even number of integers,
# return the average of the middle two items from the sorted array.
def find_median(arr)
arr.sort!
if arr.length.even?
return (arr[arr.length/2] + arr[(arr.length/2)-1])/2.0
else #else odd
return arr[arr.length/2.0]
end
end
puts find_median([2,3,4,9,7,8])

Random number generator issues in Ruby

My intention here is just to fill up an array with numbers in order from 1, to a random number between 1 and 1000. However, after repeatedly running this code (about 50 times), the highest number I have gotten is 120, and only twice has it been over 100. The majority of my arrays were anywhere between 0 and 60. This behavior appears off to me. Am I doing something wrong?
my_array = []
i = 0
while i <= rand(1000)
my_array << i
i += 1
end
puts my_array.count
puts my_array
Your function is broken, because you're checking versus the random number. Do this:
(0..1000).collect{ rand(1000) }
This will return an array of one thousand random numbers.
Or, closer to your code:
my_array = []
i = 0
while i <= 1000
my_array << rand(1000)
i += 1
end
As per comment, what you want is:
(1..rand(1000))
(1..rand(1000)).to_a
The first results in a range, which is "easier to carry around", the second results in the populated array.
(Edit) Note:
(1..10) is inclusive - (1..10).to_a == [1,2,3,4,5,6,7,8,9,10]
(1...10) is partially exclusive - (1...10).to_a == [1,2,3,4,5,6,7,8,9] - it does not include the end of the array, but still includes the beginning.
It sounds like you want:
(1...rand(1000)).to_a
Additionally, I have amended my code to reflect what I was trying to accomplish initially. My problem was that every time I looped through my code I generated a new random number. Because of this, as 'i' incremented toward 1000 it became more and more likely that a random number would be generated that was lower than 'i'. My fix, while not as elegant as the solution above that I accepted, was to store the random number in a variable, BEFORE attempting to use it in a loop. Thanks again. Here is the amended code:
my_array = []
i = 0
g = rand(1000)
while i <= g
my_array << i
i += 1
end
puts my_array.count
puts my_array

The 'upto' method in Ruby

I'm learning Ruby, and there has been a bit of talk about the upto method in the book from which I am learning. I'm confused. What exactly does it do?
Example:
grades = [88,99,73,56,87,64]
sum = 0
0.upto(grades.length - 1) do |loop_index|
sum += grades[loop_index]
end
average = sum/grades.length
puts average
Let's try an explanation:
You define an array
grades = [88,99,73,56,87,64]
and prepare a variable to store the sum:
sum = 0
grades.length is 6 (there are 6 elements in the array), (grades.length - 1) is 5.
with 0.upto(5) you loop from 0 to 5, loop_index will be 0, then 1...
The first element of the array is grades[0] (the index in the array starts with 0).
That's why you have to subtract 1 from the number of elements.
0.upto(grades.length - 1) do |loop_index|
Add the loop_index's value to sum.
sum += grades[loop_index]
end
Now you looped on each element and have the sum of all elements of the array.
You can calculate the average:
average = sum/grades.length
Now you write the result to stdout:
puts average
This was a non-ruby-like syntax. Ruby-like you would do it like this:
grades = [88,99,73,56,87,64]
sum = 0
grades.each do |value|
sum += value
end
average = sum/grades.length
puts average
Addendum based on Marc-Andrés comment:
You may use also inject to avoid to define the initial sum:
grades = [88,99,73,56,87,64]
sum = grades.inject do |sum, value|
sum + value
end
average = sum / grades.length
puts average
Or even shorter:
grades = [88,99,73,56,87,64]
average = grades.inject(:+) / grades.length
puts average
From http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_integer.html#upto:
upto int.upto( anInteger ) {| i | block }
Iterates block, passing in integer values from int up to and
including anInteger.
5.upto(10) { |i| print i, " " }
produces:
5 6 7 8 9 10
Upto executes the block given once for each number from the original number "upto" the argument passed. For example:
1.upto(10) {|x| puts x}
will print out the numbers 1 through 10.
It is just another way to do a loop/iterator in Ruby. It says do this action n times based on i being the first number the the number in parens as the limit.
My example would have been this:
1.upto(5) { |i| puts "Countup: #{i}" }
So what you're actually doing here is saying, I want to count up from 1 to the number 5, that's specifically what this part is saying:
1.upto(5)
The latter part of code (a block) is just outputting the iteration of going through the count from 1 up to 5. This is the output you might expect to see:
Countup: 1
Countup: 2
Countup: 3
Countup: 4
Countup: 5
Note: This can be written is another way if you're using multilines:
1.upto(5) do |i|
puts "Countup: #{i}"
end
Hope this helps.
An alternative that looks more like Ruby to me is
require 'descriptive_statistics'
grades=[88,99,73,56,87,64]
sum = grades.sum
average = grades.mean
sd = grades.standard_deviation
Of course it depends what you're doing.

Resources