search
LoginSignup
55

More than 5 years have passed since last update.

posted at

updated at

RubyやJavaScriptでの配列の差集合・和集合・積集合

ruby の場合、配列の和集合、差集合、積集合は演算子で扱える。

a = [1,2,3,4,4]
b = [3,4,5,6,7]

p  a | b  # 和集合 [1,2,3,4,5,6,7]
p  a - b  # 差集合 [1,2]
p  a & b  # 積集合 [3,4]

JavaScriptだとlodashに、それぞれの関数があったりする。

var _ = require('lodash');

var a = [1,2,3,4,4]
var b = [3,4,5,6,7]

console.log(_.union(a, b));        // 和集合(union) [1,2,3,4,5,6,7]
console.log(_.difference(a, b));   // 差集合(difference set) [1,2]
console.log(_.intersection(a, b)); // 積集合(intersection) [3,4]

英単語をキチンと覚えておくの大事。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
55