1

I stumbled uppon this question .

The problem was to find how many equal ending digits exist between numbers of the two lists. The answer given seems to be quite efficient using trees to implement something similar to a trie. However playing around with it, I found out that it acts a bit differently than what I would expect: When there are more than one "words" of the second list that have "similarity" with one from the first list, that one is returned only once together with the number of the matching digits of only one of the matching words. Wouldn't it be more correct to return an answer for every match?

I tried to think how this could be done, but I cannot come up with anything good(I'm kind of a beginner in prolog...)

Just for convenience I post the code from gusbro's answer:

same_endings(L1, L2, Endings):-
  build_tree(L1, Tree),
  maplist(same_ending(Tree), L2, Endings).

same_ending(Tree, N, N-Len):-
  atom_chars(N, Digs),
  reverse(Digs, RDigs),
  same_ending1(RDigs, Tree, 0, Len).

same_ending1([], _, Len, Len).
same_ending1([Dig|Digs], Tree, Len, Len2):-
  (select(Dig-SubTree, Tree, _) ->
    (succ(Len, Len1), same_ending1(Digs, SubTree, Len1, Len2)) ;
    Len2=Len
  ).

build_tree(L, Tree):-
  foldl(add_tree, L, [], Tree).

add_tree(N, Tree, NTree):-
  atom_chars(N, Digs),
  reverse(Digs, RDigs),
  add_tree1(RDigs, Tree, NTree).

add_tree1([], Tree, Tree).
add_tree1([Dig|Digs], Tree, [Dig-SubTree1|Tree1]):-
  (select(Dig-SubTree, Tree, Tree1) -> true; SubTree-Tree1=[]-Tree),
  add_tree1(Digs, SubTree, SubTree1).

Example :

same_endings([123,223,333],[423,433],Endings).
Endings = [423-2, 433-2].

I would rather expect that a more logical answer would be something like

Endings = [423-2, 423-2, 423-1, 433-1, 433-1, 433-2].
false
  • 10,264
  • 13
  • 101
  • 209
TrieHard
  • 41
  • 2
  • 1
    It seems the code was provided as a starting point. I read, at the bottom of the answer, "You may modify this code a bit to obtain the actual items which have the same endings." How did you do that? What did you try? What are you getting stuck on? What is it that you don't understand in the code in order to proceed? – User9213 Jul 15 '19 at 05:50
  • I tried using the length function of prolog , because the tree as written will look something like this [1-[2-[3,4]]] , so if we find the length of the subtree of 2, we find out how many numbers end with 1,2,3. However I could not apply this for the whole problem. – TrieHard Jul 15 '19 at 17:25

0 Answers0