Ruby/Array/As Set

Материал из Wiki.crossplatform.ru

Версия от 18:00, 13 сентября 2010; ViGOur (Обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

Computing Set Operations on Arrays: Difference

p [1,2,3] - [1,4,5]            # => [2, 3]



Computing Set Operations on Arrays: Intersection

p [1,2,3] & [1,4,5]            # => [1]



Computing Set Operations on Arrays: Union

p [1,2,3] | [1,4,5]            # => [1, 2, 3, 4, 5]



Difference (-) creates a new array, removing elements that appear in both arrays

tue = [ "shop", "eat", "sleep" ]
wed = [ "shop", "eat", "read", "sleep" ]
wed - tue # => ["read"]



Exclude a list of natrual number

def natural_numbers_except(exclude)
  exclude_map = {}
  exclude.each { |x| exclude_map[x] = true }
  x = 1
  while true
    yield x unless exclude_map[x]
    x = x.succ
  end
end
natural_numbers_except([2,3,6,7]) do |x|
 break if x > 10
 puts x
end
# 1
# 4
# 5
# 8
# 9
# 10



Minus from one array

u = [:red, :orange, :yellow, :green, :blue, :indigo, :violet]
a = [:red, :blue]
u - a                   # => [:orange, :yellow, :green, :indigo, :violet]



Ruby can do several set operations on arrays

# Intersection      &
# Difference        -
# Union             |
# Intersection (&) creates a new array, merging the common elements of two arrays but removing uncommon elements and duplicates.
tue = [ "shop", "eat", "sleep" ]
wed = [ "shop", "eat", "read", "sleep" ]
tue & wed # => ["shop", "eat", "sleep"]



Set operation based on array

require "set"
a = [1,2,3]
b = [3,4,5]
a.to_set ^ b.to_set          # => #<Set: {5, 1, 2, 4}>
(a | b) - (a & b)            # => [1, 2, 4, 5]



Set operation on array constant

[3,3] & [3,3]               # => [3]
[3,3] | [3,3]               # => [3]
[1,2,3,3] - [1]             # => [2, 3, 3]
[1,2,3,3] - [3]             # => [1, 2]
[1,2,3,3] - [2,2,3]         # => [1]



TypeError: cannot convert Set into Array

array = [1,2,3]
set = [3,4,5].to_set
set & array                 # => #<Set: {3}>
array & set



Union (|) joins two arrays together, removing duplicates:

tue = [ "shop", "eat", "sleep" ]
wed = [ "shop", "eat", "read", "sleep" ]
tue | wed # => ["shop", "eat", "read", "sleep"]