-
Notifications
You must be signed in to change notification settings - Fork 1
/
lattice_paths_pair_index.rb
65 lines (46 loc) · 1.45 KB
/
lattice_paths_pair_index.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true
# This is the question with a special solution, multi approaches
## Approach 1: Using the recursion
# def calculate_paths(row, col)
# return 0 if row.zero? || col.zero?
# return 1 if row == 1 || col == 1
# calculate_paths(row - 1, col) + calculate_paths(row, col - 1)
# end
## Approach 2: Using the dynamic programming
def calculate_paths(row, col)
dp = Array.new(row + 1) { Array.new(col + 1, 0) }
(1..row).each do |i|
(1..col).each do |j|
dp[i][j] = calculate_path(dp, i, j)
end
end
dp[row][col]
end
def calculate_path(dpp, row, col)
return 1 if row == 1 || col == 1
dpp[row - 1][col] + dpp[row][col - 1]
end
def find_pair_index(input_array)
value_to_index = {}
input_array.each_with_index do |row, i|
row.each_with_index do |number, j|
return [value_to_index[number], [i, j]] if value_to_index.key?(number)
value_to_index[number] = [i, j]
end
end
nil
end
# Taking input for the array
puts 'Enter the values for m and n (separated by a space): '
m, n = gets.chomp.split.map(&:to_i)
input_array = []
puts "Enter the array values (#{m} rows x #{n} columns):"
m.times do
input_array << gets.chomp.split.map(&:to_i)
end
# Finding the single pair index
pair_index = find_pair_index(input_array)
# Calculating the number of paths
row = pair_index[1][0] - pair_index[0][0]
col = pair_index[1][1] - pair_index[0][1]
puts "The number of paths is: #{calculate_paths(row + 1, col + 1)}"