Advertisement
WeltEnSTurm

Untitled

Aug 20th, 2016
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.36 KB | None | 0 0
  1.  
  2. int[][] next(string haystack, string needle){
  3.     if(!needle.length)
  4.         return [[]];
  5.     int[][] matches = [];
  6.     foreach(hi, h; haystack){
  7.         if(needle[0].toLower == h.toLower){
  8.             foreach(m; haystack.next(needle[1..$])){
  9.                 if(m.all!(a => a > hi))
  10.                     matches ~= ([hi.to!int] ~ m);
  11.             }
  12.         }
  13.     }
  14.     return matches;
  15. }
  16.  
  17.  
  18. int[] compareFuzzy(string haystack, string needle){
  19.     writeln(haystack);
  20.     auto matches = haystack.next(needle);
  21.     foreach(m; matches){
  22.         foreach(i; 0..haystack.length){
  23.             if(m.canFind(i))
  24.                 write("*");
  25.             else
  26.                 write(" ");
  27.         }
  28.         writeln;
  29.     }
  30.     int best = -1;
  31.     int bestScore;
  32.     foreach(i, m; matches){
  33.         if(m.length < needle.length)
  34.             continue;
  35.         auto s = m.score;
  36.         if(s > bestScore){
  37.             bestScore = s;
  38.             best = i.to!int;
  39.         }
  40.     }
  41.     if(best < 0)
  42.         return [0];
  43.     return [bestScore] ~ matches[best];
  44. }
  45.  
  46.  
  47. int score(int[] match){
  48.     int s = 0;
  49.     int previous = -1;
  50.     foreach(m; match){
  51.         if(previous == -1){
  52.             previous = m;
  53.             continue;
  54.         }
  55.         if(m == previous+1){
  56.             s += 1000;
  57.         }
  58.         previous = m;
  59.     }
  60.     return s;
  61. }
  62.  
  63. unittest {
  64.     assert("122".compareFuzzy("123")[0] <= 0);
  65.     assert("3345".compareFuzzy("345")[0] > 0);
  66.     assert(
  67.         "3345".compareFuzzy("345")[0] ==
  68.         "2345".compareFuzzy("345")[0]
  69.     );
  70.     assert(
  71.         "3245".compareFuzzy("345")[0] <
  72.         "2345".compareFuzzy("345")[0]
  73.     );
  74.     assert("ls".compareFuzzy("ls")[0] > 0);
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement