Module: TwistyPuzzles::Utils::ArrayHelper

Included in:
AbstractMove, ColorScheme, CubeConstants, CubePrintHelper, CubeState, Part, Part, PartCycle, StickerCycleFactory
Defined in:
lib/twisty_puzzles/utils/array_helper.rb

Overview

A few array related helper methods.

Instance Method Summary collapse

Instance Method Details

#apply_permutation(array, permutation) ⇒ Object

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
# File 'lib/twisty_puzzles/utils/array_helper.rb', line 7

def apply_permutation(array, permutation)
  raise ArgumentError unless array.length == permutation.length
  raise ArgumentError unless permutation.uniq.length == permutation.length

  permutation.map do |i|
    raise ArgumentError unless i.is_a?(Integer) && i >= 0 && i < array.length

    array[i]
  end
end

#check_types(array, type) ⇒ Object



80
81
82
# File 'lib/twisty_puzzles/utils/array_helper.rb', line 80

def check_types(array, type)
  array.each { |e| raise TypeError unless e.is_a?(type) }
end

#find_only(array, &block) ⇒ Object



96
97
98
# File 'lib/twisty_puzzles/utils/array_helper.rb', line 96

def find_only(array, &block)
  only(array.select(&block))
end

#only(array) ⇒ Object

Returns the only element of an array and raises if the array has not exactly one element.

Raises:

  • (ArgumentError)


85
86
87
88
89
90
91
92
93
94
# File 'lib/twisty_puzzles/utils/array_helper.rb', line 85

def only(array)
  raise ArgumentError, "Can't take the only element of an empty array." if array.empty?

  unless array.length == 1
    raise ArgumentError,
          "Can't take the only element of an array with #{array.length} elements."
  end

  array[0]
end

#replace_once(array, old_element, new_element) ⇒ Object

Raises:

  • (ArgumentError)


100
101
102
103
104
105
106
# File 'lib/twisty_puzzles/utils/array_helper.rb', line 100

def replace_once(array, old_element, new_element)
  raise ArgumentError unless array.count { |e| e == old_element } == 1

  new_array = array.dup
  new_array[new_array.index(old_element)] = new_element
  new_array
end

#rotate_out_nils(array) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/twisty_puzzles/utils/array_helper.rb', line 68

def rotate_out_nils(array)
  first_part = []
  second_part = []
  # Valid input goes either start -> first_part -> nil_middle -> second_part
  # or start -> first_nil_part -> middle -> second_nil_part
  state = :start
  array.each do |element|
    state = next_state(state, array, element, first_part, second_part)
  end
  second_part + first_part
end

#turned_equals?(left, right) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
# File 'lib/twisty_puzzles/utils/array_helper.rb', line 18

def turned_equals?(left, right)
  return false if left.length != right.length

  (0...left.length).any? do |r|
    return true if left.rotate(r) == right
  end
  false
end