Главная
translate
Войти
Регистрация
Форум
Блоги
Пользователи
Список джемов
Rails проекты
Поиск
Loading...
Login form
Ruby On Rails in UA
/
Code Review, теоретические вопросы
/
Хитрые срезы и сортировки масивов
назад
новый
ответить
2008-06-05 00:05:48
Ответить
Ruslan Voloshin
Адрес:
odessa
Сообщений: 1231
Регистр: 2007-03-13
его блог
40 сообщ.
Хитрые срезы и сортировки масивов
require 'set' s = Set.new((1..10).collect) # => #
# Divide the set into the "true" subset and the "false" subset: that # is, the "less than 5" subset and the "not less than 5" subset. s.divide { |x| x < 5 } # => #
, #
}> # Divide the set into the "0" subset and the "1" subset: that is, the # "even" subset and the "odd" subset. s.divide { |x| x % 2 } # => #
, #
}> s = Set.new([1, 2, 3, 'a', 'b', 'c', -1.0, -2.0, -3.0]) # Divide the set into the "String subset, the "Fixnum" subset, and the # "Float" subset. s.divide { |x| x.class } # => #
, # => #
, # => #
}> #--- s = [1, 2, 3, -1, -2, -4].to_set # Divide the set into sets of numbers with the same absolute value. s.divide { |x,y| x.abs == y.abs } # => #
, # => #
, # => #
, # => #
}> # Divide the set into sets of adjacent numbers s.divide { |x,y| (x-y).abs == 1 } # => #
, # => #
, # => #
}> #--- s.classify { |x| x.class } # => {String=>#
, # => Fixnum=>#
, # => Float=>#
} #--- connections = { 1 => 2, 2 => 3, 3 => 1, 4 => 1 } [1,2,3,4].to_set.divide { |x,y| connections[x] == y } # => #
, #
}> #--- class Array def classify require 'set' h = {} each do |i| x = yield(i) (h[x] ||= self.class.new) << i end h end def divide(&block) Set.new(classify(&block).values) end end [1,1,2,6,6,7,101].divide { |x| x % 2 } # => #
#--- class Array def divide(&block) if block.arity == 2 counts = inject({}) { |h, x| h[x] ||= 0; h[x] += 1; h} to_set.divide(&block).inject([]) do |divided, set| divided << set.inject([]) do |partition, e| counts[e].times { partition << e } partition end end else Set.new(classify(&block).values) end end end [1,1,2,6,6,7,101].divide { |x,y| (x-y).abs == 1 } # => [[101], [1, 1, 2], [6, 6, 7]] #---
------------
Занимаюсь вебом и продвижением сайтов.
divide
,
set
назад
новый
ответить
Ключевые слова:
server name [1]
delete_all [1]
respond_to [1]
actionlinks [1]
freeze rails [1]
ajax rails [1]
Acts As Taggable On Steroids [1]
view [3]
rjust [1]
httpdate [1]
cheat sheets [1]
Ruby on Rails 2.0 [1]
db:session:clear [1]
столбец [1]
complex [1]
MVC [1]
rss ping [1]
production mode [1]
internal [1]
apache mod_rails [1]
Гости: 141 Онлайн:
Іван Будзуляк
,
Oleg
,
О проекте
по всем вопросам обращайтесь на
support
Rubyclub.com.ua
Copyright © 2007 - 2008