Class: Array

Inherits:
Object show all
Defined in:
lib/quiz1/t/solutions/Carlos/solitaire.rb,
lib/quiz1/t/solutions/Moses Hohman/util.rb,
lib/quiz1/t/solutions/Florian Gross/solitaire.rb

Direct Known Subclasses

Deck

Instance Method Summary collapse

Instance Method Details

#collect_peel(&p) ⇒ Object

syntactic sugar for Cipher



16
17
18
19
20
# File 'lib/quiz1/t/solutions/Moses Hohman/util.rb', line 16

def collect_peel(&p)
	collected = []
	peel { |a,b| collected << p.call(a,b) }
	collected
end

#generate_keystream(len) ⇒ Object



96
97
98
# File 'lib/quiz1/t/solutions/Carlos/solitaire.rb', line 96

def generate_keystream len
	(1..len).collect {|i| next_key or redo }
end

#move(from_index, to_index) ⇒ Object

Moves the item from a specified index to just before the item with the specified index.



4
5
6
7
8
9
10
# File 'lib/quiz1/t/solutions/Florian Gross/solitaire.rb', line 4

def move(from_index, to_index)
  from_index += self.size if from_index < 0
  to_index += self.size if to_index < 0

  item = self.slice!(from_index)
  self.insert(to_index, item)
end

#next_keyObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/quiz1/t/solutions/Carlos/solitaire.rb', line 64

def next_key
	# step 2: move A joker down 1 card
	pos = index A
	slice! pos
	pos = wrap_down(pos + 1)
	self[pos, 0] = A
	
	# step 3: move B joker down 2 cards
	pos = index B
	slice! pos
	pos = wrap_down(pos + 2)
	self[pos, 0] = B
	
	# step 4: triple cut
	first_joker, second_joker = [index(A), index(B)].sort
	cards_above = slice! 0...first_joker
	second_joker -= cards_above.length
	cards_below = slice! second_joker+1..-1
	push *cards_above
	unshift *cards_below
	
	# step 5: count cut using the value of the bottom card.
	#         reinsert above the last card
	cut = slice! 0, last.value
	self[-1,0] = cut
	
	# step 6: find the letter
	card = self[first.value]
	
	return Joker===card ? nil : card.value
end

#peel(&p) ⇒ Object

“Peels” off a tuple of the elements at each successive index across multiple arrays. Assumes self is an array of these multiple arrays. Stops when any of the arrays is exhausted. I stole this from a ruby mailing list somewhere. I also considered calling this each_tuple



7
8
9
10
11
12
13
# File 'lib/quiz1/t/solutions/Moses Hohman/util.rb', line 7

def peel(&p)
    collect { |a|
        a.length
    }.min.times { |i|
        yield collect { |a| a[i] }
    }
end

#wrap_down(pos) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/quiz1/t/solutions/Carlos/solitaire.rb', line 56

def wrap_down pos
	pos %= length
	if pos == 0
		pos = length
	end
	pos
end