I’m new to Ruby and I can’t think of how to do this! I would like each
element in an array to compare itself with all its proceeding elements.
For example:
In an array of 10 elements,
a[0] will be compared to a[1] … a[9]
a[1] will be compared to a[2] … a[9]
…
a[9] will not be compared, as there is nothing larger than it.
For those who don’t understand, I think the Java/C++ equivalent would
be:
I notice that you don’t DO anything with the comparison. What’s the
point? If you’re trying to verify that the array is sorted, you can
do this with a LOT fewer operations…
I’m new to Ruby and I can’t think of how to do this! I would like each
element in an array to compare itself with all its proceeding elements.
Why?
I’m making a scheduler for my college courses! First, it picks out the
courses I need to take (based on what is being offered that semester)
and stores it in an array. Then it checks the array, comparing the
elements to all the others, and picks out classes are no more than 30
minutes apart from each other. (That’s why I’ve got to compare all of
the elements.)
An example output looks like this so far:
MONDAY/WEDNESDAY: VALID COURSE COMBINATIONS
ITEC 3860 => “Software Development I” with [Dr. XYZ] (12:0-13:45)
ITEC 3200 => “Intro to Databases” with [Dr. ABC] (14:0-15:15)
*** OR ***
ITEC 4820 => “Info Technology Project II” with [Dr. Lil’teapot]
(12:0-13:45)
ITEC 3200 => “Intro to Databases” with [Mr. Nodoctorate] (14:0-15:15)
It’s been a fun project to help familiarize me with Ruby!
First, it picks out the courses I need to take (based on what is being
offered that semester) and stores it in an array. Then it checks the
array, comparing the elements to all the others
Then you might be interested in Array#combination:
classes = [‘devel’, ‘databases’, ‘IT’]
classes.combination(2).each do |a, b|
puts “comparing #{a} with #{b}”
end
comparing devel with databases
comparing devel with IT
comparing databases with IT
#method 2
a.each_with_index do |e1,i|
a[(i+1)…a.length].each do |e2|
# Compare e1 and e2
end
end
a[(i+1)…a.length].each
^ That blew my mind Jose!
It’s a bit inefficient as it will create n intermediate Arrays. Also,
the range should be (i+1) … a.length (i.e. excluding a.length).
Here’s a variant which does not create all the intermediate sub arrays:
a.each_with_index do |e, i|
for j in i+1 … a.length
puts “compare #{e} to #{a[j]}”
end
end
Here are more solutions with less math (no “i+1”):
a.each_with_index do |e, i|
for j in 0 … i
puts “compare #{e} to #{a[j]}”
end
end
a.each_with_index do |e, i|
i.times do |j|
puts “compare #{e} to #{a[j]}”
end
end