How to do this properly in Ruby?
Posted: Tue Oct 29, 2019 2:07 pm
Given an unsorted array of integers (fixnums) with possible duplicates, you want to find the one element from the array, that is closest to a number you compare with, so that the result is equal or higher than the number you compared with.
- The original array needs to stay intact
- If there is no equal or higher number in the original, algorithm should wrap around the array
Simple Example:
array = 0,1,2,3,5,7,9,11
first number to try = 8 => should result in 9
next number to try = 11 => should result in 11
final number to try = 12 => should result in 0
Here's what I came up with (real example, btw., so the numbers in the array are exactly as I would use them)
Is there a better way? Better in terms of "more lightweight", less cpu stress. Not in terms of compacted code that does the same, or code that saves on RAM.
I hope that I thought too complicated, and that there is a better way!
- The original array needs to stay intact
- If there is no equal or higher number in the original, algorithm should wrap around the array
Simple Example:
array = 0,1,2,3,5,7,9,11
first number to try = 8 => should result in 9
next number to try = 11 => should result in 11
final number to try = 12 => should result in 0
Here's what I came up with (real example, btw., so the numbers in the array are exactly as I would use them)
Code: Select all
num = 11
a = [2, 4, 6, 7, 9, 11, 1, 2]
b = a.dup.insert(0,num) #make a shallow copy of a and insert our number
b.sort! #sort the new array
b[(b.index(num) + 1) % b.length] # spit out the number that is next to the one we're looking for, modulo'd by array length
#this results in 11Code: Select all
num = 11
a = [1, 3, 5, 6, 8, 10, 0, 1]
b = a.dup.insert(0,num)
b.sort!
b[(b.index(num) + 1) % b.length]
#this results in 0Is there a better way? Better in terms of "more lightweight", less cpu stress. Not in terms of compacted code that does the same, or code that saves on RAM.
I hope that I thought too complicated, and that there is a better way!