How to group Arrays with similar values

时间:2022-11-28 11:45:04

I'm looking for a smart way to group any number of arrays with similar values (not necessarily in the same order). The language I'm using is ruby but I guess the problem is pretty language agnostic.

我正在寻找一种智能的方法来将具有相似值的任意数量的数组分组(不一定按相同的顺序)。我使用的语言是红宝石,但我猜这个问题与语言无关。

Given

a = ['foo', 'bar']
b = ['bar', 'foo']
c = ['foo', 'bar', 'baz']
d = ['what', 'ever', 'else']
e = ['foo', 'baz', 'bar']

I'd like to have a function that tells me that

我希望有一个能告诉我的功能

  • a & b are in one group
  • a&b属于一个群体

  • c & e are in one group
  • c&e属于一个小组

  • d is it's own group
  • d是它自己的小组

I can think of a number of not so smart ways of doing this very inefficient, like I could compare each array's values to each others array's values. Or I could check if ((a - b) + (b - a)).length == 0 for all combinations of arrays and group the ones that result in 0. Or I could check if a.sort == b.sort for all combinations of arrays.

我可以想到一些不那么聪明的方法来做这个非常低效的方法,比如我可以将每个数组的值与每个其他数组的值进行比较。或者我可以检查((a - b)+(b - a))。length == 0对于所有数组的组合,并将那些结果分组。或者我可以检查是否a.sort == b.sort适用于所有阵列组合。

I'm sure someone before me has solved this problem way more efficiently. I just can't seem to find how.

我相信在我之前有人能更有效地解决这个问题。我似乎无法找到如何。

1 个解决方案

#1


2  

You can do it with sort without doing it "for all combinations of arrays" but doing it only for all arrays (Schwartzian transform).

您可以通过排序执行此操作,而不是“对于所有阵列组合”,但仅对所有阵列执行(Schwartzian变换)。

arrays = [a, b, c, d, e]
arrays.group_by{|array| array.sort}.values

#1


2  

You can do it with sort without doing it "for all combinations of arrays" but doing it only for all arrays (Schwartzian transform).

您可以通过排序执行此操作,而不是“对于所有阵列组合”,但仅对所有阵列执行(Schwartzian变换)。

arrays = [a, b, c, d, e]
arrays.group_by{|array| array.sort}.values