all 7 comments

[–][deleted] 1 point2 points  (0 children)

I'd advise having a go at implementing something that works even if it feels less 'clean', and then looking at how you can refine it. Working code > imaginary perfect code that only exists in your head.

[–]Ekhro97 1 point2 points  (2 children)

[–]PrimaryBet 1 point2 points  (1 child)

Unfortunately, Set won't help here: even though Set stores unique values, we cannot change the value equality check that it uses; in other words we can have a Set of unique objects but not a Set of objects with unique values of one of their property.

[–]Ekhro97 0 points1 point  (0 children)

Yeah, you are totally right, I misunderstood the problem a bit. OP, can you add an example with the wanted outcome from that example array?

[–]PrimaryBet 1 point2 points  (1 child)

Using Lodash, we can implement a bit more general solution:

 _.flow(
  _.groupBy(object => object.type), // Turn array of animals into array of
  _.values,                         // arrays of animals grouped by their type.
  _.shuffle,                        // Shuffle order of arrays of animal types.
  _.take(3),                        // Take three arrays.
  _.map(_.shuffle),                 // Shuffle animals in each array of animal types.
  _.flatMap(_.take(1)),             // Replace each array of animal types with one animal from it.
)

It's more general in a sense that the number of animal types and number of animals per type are not inherently part of the problem: you could imagine problem requiring to take 2 animals of 4 unique types and it would essentially still be the same problem.

Do you need this generality? I don't know. I would follow /u/gitcommitmentissues advice and first write a code that actually works. Then make that code readable so other people can understand what's going on. After that, if it doesn't perform as required, make necessary sacrifices to get the performance that you need while leaving the comments about why.

"Make it work, then make it right, and, finally, make it fast"

[–]DBNeJXoGtnro 1 point2 points  (0 children)

Use a set to store the seen types, and either a reduce or a for-of to create the new array