Top Level Namespace

Instance Method Summary collapse

Instance Method Details

#two_d(array_2d, term) ⇒ Object

The method called by the user. Routes the args and array to one of the other functions.

Parameters:

  • The (Array)

    array to be checked for the terms.

  • There (Object)

    can be a single term, or an array of terms.

Author:



6
7
8
9
10
11
12
# File 'lib/two_d.rb', line 6

def two_d(array_2d, term)
  if term.is_a?(Array)
    two_dm(array_2d, term)
  else
    two_ds(array_2d, term)
  end
end

#two_dm(array_2d, terms) ⇒ Hash

The method called by ‘two_d’ if there was an ARRAY of terms. Simply passes each term in the term array to two_ds and merges the returned hash into the combined hash.

Parameters:

  • The (Array)

    2D array to be checked for the term.

  • The (Array)

    array of terms.

Returns:

  • (Hash)

    A hash of all terms and their indices in => [[index],…] format.



49
50
51
52
53
54
55
# File 'lib/two_d.rb', line 49

def two_dm(array_2d, terms)
  results = Hash.new {}
  terms.each do |term|
    results = results.merge(two_d(array_2d,term))
  end
  return results
end

#two_ds(array_2d, term) ⇒ Hash

The method called by ‘two_d’ if there was a SINGLE term.

Parameters:

  • The (Array)

    2D array to be checked for the term.

  • A (Object)

    single term.

Returns:

  • (Hash)

    A hash with the term as key and an array of indices.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/two_d.rb', line 18

def two_ds(array_2d, term)
  # Find the sub arrays which include the term.
  f_index_array = []
  array_2d.each do |line| 
    result = line.include?(term)
    if result == true
      f_index_array << array_2d.index(line)  
    end
  end

  # Create an array of arrays with the indices in [row, col] order.
  combined_index_array = []
  f_index_array.each do |first|
    counter = 0
    array_2d[first].each do |item|
      result = item == term
      if result == true
        combined_index_array << [first,counter]
      end
    counter += 1
    end
  end
  # Make a hash from the term and the array of indices for that term in the origional 2D array.
  return {term => combined_index_array}
end