|
| 1 | +defmodule LCSubstring do |
| 2 | + def generate_table(word_a, word_b) do |
| 3 | + word_a |
| 4 | + |> Enum.with_index() |
| 5 | + |> Enum.reduce(%{}, fn {_x, index}, acc -> |
| 6 | + nested_map = |
| 7 | + word_b |
| 8 | + |> Enum.with_index() |
| 9 | + |> Enum.reduce(%{}, fn {_x, index}, acc -> |
| 10 | + Map.put(acc, index, 0) |
| 11 | + end) |
| 12 | + |
| 13 | + Map.put(acc, index, nested_map) |
| 14 | + end) |
| 15 | + end |
| 16 | + |
| 17 | + def compute(table, word_a, word_b) do |
| 18 | + for i <- 0..(length(word_a) - 1), reduce: table do |
| 19 | + table -> |
| 20 | + for j <- 0..(length(word_b) - 1), reduce: table do |
| 21 | + table -> |
| 22 | + if Enum.at(word_a, i) == Enum.at(word_b, j) do |
| 23 | + value = (table[i - 1][j - 1] || 0) + 1 |
| 24 | + put_in(table[i][j], value) |
| 25 | + else |
| 26 | + put_in(table[i][j], 0) |
| 27 | + end |
| 28 | + end |
| 29 | + end |
| 30 | + end |
| 31 | +end |
| 32 | + |
| 33 | +word_a = ["b", "l", "u", "e"] |
| 34 | +word_b = ["c", "l", "u", "e", "s"] |
| 35 | + |
| 36 | +result = |
| 37 | + word_a |
| 38 | + |> LCSubstring.generate_table(word_b) |
| 39 | + |> LCSubstring.compute(word_a, word_b) |
| 40 | + |
| 41 | +Enum.each(result, fn {_index, value} -> |
| 42 | + IO.inspect(Map.values(value)) |
| 43 | +end) |
| 44 | + |
| 45 | +# Output |
| 46 | +# [0, 0, 0, 0, 0] |
| 47 | +# [0, 1, 0, 0, 0] |
| 48 | +# [0, 0, 2, 0, 0] |
| 49 | +# [0, 0, 0, 3, 0] |
0 commit comments