Hei,
I’ve been cracking my head on an JS algorithm exercise where I have two arrays: one with genders and one with numbers determining their age. I need to compare both and determine how many are of one gender above a certain age, and how many are of the opposite gender under a certain age. What would be the best way to implement it? The arrays always have the same length.
Example arrays would be:
gender = ["man","woman","man","man","woman"]
age = [30,20,13,63,9]
I’ve used various for
loops in order to determine how many are men and women, as well as over 18 and under.
The for loops were like this:
for(let i = 0; i < age.length; i++) {
if(age[i] >= 18) {
adults ++
} else {
minors ++
}
}
where the initial value of adults
& minors
is 0
I’m considering if I should instead turn them into arrays, and return later the length of the array, since I have to return an amount rather than a list.
5
Answers
You could implement a kind of array zipping with Array.reduce in order to have a more convenient structure to use, and then just filter your objects as you need and get the length of the result:
Just counting
adults
andminors
is not enough. You probably needadultMen
adultWomen
,minorMen
andminorWomen
. And you need to compare for age and gender.Here’s an O(n) solution using object as the data structure:
Try it:
Terser version (
0
for younger,1
for equal,2
for older):…or, if you prefer
-1
/0
/1
:I think we can make this more powerful and more useful by abstracting a bit. We have some lists of values associated with a property name ("gender", "age"). Those lists have the same length. We want to query on the combinations of those lists.
So we can write a generic
combine
that accepts input like{gender: ['man', 'woman', 'man', 'man', 'woman'], age: [30, 20, 13, 63, 9]}
and returns a collection of functions , here justquery
, andcount
, but we might imagine others.Then we pass a predicate function into either of these and get the matching results or their count. So we might write
This is an implementation of that idea:
This is not limited to two properties. If we added
eyes: ['blue', 'brown', 'brown', 'hazel', 'blue']
to our input, then the objects we’re investigating would haveeyes
properties as well.There is one important caveat: the arrays of properties supplied must have the same lengths. That is inherent in the problem statement, of course, but what it really means is that this technique is fairly limited.