Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if elements of one array are included in another

Tags:

arrays

ruby

I have the following arrays:

passing_grades = ["A", "B", "C", "D"]
student2434 = ["F", "A", "C", "C", "B"]

and I need to verify that all elements in the student array are included in the passing_grades array. In the scenario above, student2434 would return false. But this student:

student777 = ["C", "A", "C", "C", "B"]

would return true. I tried something like:

if student777.include? passing_grades then return true else return false end

without success. Any help is appreciated.

like image 848
Mark Locklear Avatar asked Mar 04 '14 16:03

Mark Locklear


People also ask

How do you check if an array includes elements of another array?

includes() You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check if all elements in an array are different?

One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.

How do you check if elements of an array are in another array Python?

Use numpy. isin() to find the elements of a array belongs to another array or not. it returns a boolean array matching the shape of other array where elements are to be searched. numpy.


2 Answers

PASSING_GRADES = ["A", "B", "C", "D"]

def passed?(grades)
  (grades - PASSING_GRADES).empty?
end

similar to what CDub had but without bug. more readable in my opinion

like image 79
Iuri G. Avatar answered Sep 23 '22 23:09

Iuri G.


You could have a method that does the difference of the arrays, and if any results are present, they didn't pass:

PASSING_GRADES = ["A", "B", "C", "D"]

def passed?(grades)
  grades.all? {|grade| PASSING_GRADES.include?(grade)}
end

Example:

1.9.3-p484 :117 > student777 = ["C", "A", "C", "C", "B"]
 => ["C", "A", "C", "C", "B"] 
1.9.3-p484 :118 > passed?(student777)
 => true
1.9.3-p484 :118 > passed?(student2434)
 => false
like image 35
CDub Avatar answered Sep 24 '22 23:09

CDub