Last active
December 18, 2015 20:59
-
-
Save vanhalt/5844145 to your computer and use it in GitHub Desktop.
Basic exercises with Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[*1..100].each do |number| | |
text = "" | |
text << "fizz " if number % 3 == 0 | |
text << "buzz " if number % 5 == 0 | |
unless text.empty? | |
puts text | |
else | |
puts number | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class IndexSort | |
def self.sort(ary, ascend=true) | |
ary_ = [] | |
ary.each do |num| | |
ary_[num] = num | |
end | |
ary_ = ary_.select { |value| !value.nil? } | |
ascend ? ary_ : ary_.reverse | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LinkedList | |
ITEM = Struct.new :prev, :next, :content | |
def initialize(content) | |
@hsh = {} | |
@hsh[0] = ITEM.new(nil, nil, content) | |
@hsh[0].content = content | |
end | |
def add(element) | |
if element.instance_of? LinkedList | |
element.contents.each do |value| | |
add_content value | |
end | |
else | |
add_content element | |
end | |
end | |
def delete(index) | |
item = @hsh[index] | |
@hsh[item.prev].next = item.next | |
@hsh[item.next].prev = item.prev | |
item.prev = nil | |
item.next = nil | |
end | |
def contents | |
@hsh.values.collect(&:content) | |
end | |
def deleted?(item) | |
item.prev.nil? && item.next.nil? | |
end | |
def last | |
@hsh.each_pair.select { |index, item | !deleted?(item) && item.next.nil? }.first.last.content | |
end | |
def first | |
@hsh.each_pair.select { |index, item | !deleted?(item) && item.prev.nil? }.first.last.content | |
end | |
private | |
def add_content(content) | |
index = @hsh.length | |
@hsh[index-1].next = index if index > 1 | |
@hsh[index] = ITEM.new(index-1, nil, content) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment