V
V
Vitaly Rtishchev2019-08-08 12:22:02
Algorithms
Vitaly Rtishchev, 2019-08-08 12:22:02

What is the best algorithm for solving the problem?

Write a function that takes an array of strings containing a phone number in the format +7 (XXX) XXX-XX-XX. The function should return pairs of numbers that differ by one digit.
For example,

getPhonePairs([
  '+7 (985) 111-11-11',
  '+7 (985) 111-11-12',
  '+7 (985) 111-11-22',
]);

// ->
[
  ['+7 (985) 111-11-11', '+7 (985) 111-11-12'],
  ['+7 (985) 111-11-12', '+7 (985) 111-11-22'],
];

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GreenBear, 2019-08-08
@vitalyrtishchev

If two numbers are "similar", then they have exactly one different character, which is located in the same position. This means that if a character is removed from a specific position for all numbers, then all "similar" numbers will become identical to each other. This means that they can be collected into a dictionary, where the key is a truncated number, and the value is an array of uncut "similar" numbers.
There are 11 significant characters in the number. We first remove the first character from everyone, we get the first dictionary with similar numbers.
Then we remove the second character from the initial numbers, and we get the second dictionary with "similar numbers" in the second position.
And so we do 11 times, until we get 11 dictionaries.
Further, from each dictionary, it remains to select only those values
It remains only to make pairs of numbers taken from these arrays.
Such an algorithm will not work correctly if initially there are completely identical numbers, but if I understand correctly, initially they are all different.

D
Dmitry Makarov, 2019-08-08
@DmitryITWorksMakarov

Put all numbers into a hash table.
start: We take the first unlabeled number and, starting from it, do a breadth-first search over all neighbors (there are less than or equal to 20).
If a neighbor is found, then write out this pair.
When all neighbors are found for the next number, we mark it.
The next iteration of the search is carried out only for unlabeled neighbors.
We repeat, starting from start, as long as there are unmarked numbers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question