0

I have an array of arrays. I'm trying to go through each array in my main array and compare the index's against variables. If they are larger than the variables I want to delete that array from the parent array. At the minute when I run the below code when comparing against b, it works the first time and deletes the array but doesn't seem to run again and delete the rest of the arrays where index > b. Any help appreciated.

The following function should print 14 but currently it's printing 16.

a = 4
b = 2
c = 5
n = 5

def count_configurations(a, b, c, n)

  a = (0..a).to_a
  b = (0..b).to_a
  c = (0..c).to_a

  big = [a.max, b.max, c.max].max
  big = (0..big).to_a

  arrays = big.repeated_permutation(3).to_a

  solutions = []

  arrays.each do |array|
    sum = 0
    array.each { |a| sum+=a }

    if sum == n 
      solutions << array
    end
  end

  solutions = solutions.uniq

  solutions.each do |solution|
    if solution[0] > a.max 
      solutions.delete(solution)
    end
  end

  solutions.each do |solution|
    if solution[1] > b.max 
      solutions.delete(solution)
    end
  end

  solutions.each do |solution|
    if solution[2] > c.max 
      solutions.delete(solution)
    end
  end

  puts solutions.count
end
1
  • @texasbruce I'm new.. so I understand it may not be the best code. I'd appreciate if you could add something useful though. Commented Aug 16, 2015 at 17:16

1 Answer 1

2

Assuming solutions contains the proper array, here you go, instead of three each loops:

solutions = solutions.uniq.reject do |solution|
  solution[0] > a.max || solution[1] > b.max || solution[2] > c.max 
end

Details: Enumerable#reject.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your help! Much cleaner as well will look into Enumerables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.