algo.tin 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #nop vim: set filetype=tt:;
  2. /*
  3. 本文件属于 PaoTin++ 的一部分。
  4. PaoTin++ © 2020~2023 的所有版权均由担子炮(dzp <danzipao@gmail.com>) 享有并保留一切法律权利
  5. 你可以在遵照 GPLv3 协议的基础之上使用、修改及重新分发本程序。
  6. */
  7. #nop 本文件是 xtintin 的一部分,实现了一些常用算法;
  8. ///=== {
  9. // #@ algo.Diff <字符串1> <字符串2>
  10. // 如果两个字符串参数中,其中一个是另一个插入了一个子串的结果,则本函数可计算并返回该子串。
  11. // };
  12. #func {algo.Diff} {
  13. #local str1 {%1};
  14. #local str2 {%2};
  15. #list str1 {tokenize} {$str1};
  16. #list str2 {tokenize} {$str2};
  17. #local size1 {&str1[]};
  18. #local size2 {&str2[]};
  19. #if { $size1 < $size2 } {
  20. #local tmp {$str1};
  21. #local str1 {$str2};
  22. #local str2 {$tmp};
  23. #local tmp {$size1};
  24. #local size1 {$size2};
  25. #local size2 {$tmp};
  26. };
  27. #local idx {};
  28. #loop {1} {$size2} {idx} {
  29. #local ch1 {$str1[$idx]};
  30. #local ch2 {$str2[$idx]};
  31. #if { "$ch1" != "$ch2" } {
  32. #break;
  33. };
  34. };
  35. #local begin {$idx};
  36. #local end {};
  37. #math end {$size1 - $size2 + $begin - 1};
  38. #local diff {};
  39. #loop {$begin} {$end} {idx} {
  40. #local ch {$str1[$idx]};
  41. #cat diff {$ch};
  42. };
  43. #return {$diff};
  44. };
  45. ///=== {
  46. // #@ algo.ParseVertLayout <竖排文字串>
  47. // 将竖排文字重新排版成横排,方便做匹配。
  48. // 结果是一个列表,其中的每个元素代表一行转换后的文本。
  49. // 为方便计算对齐,其中竖排文字串要求用竖线定出每行的左右边界,且一个汉字必须对应两个空格。
  50. // };
  51. #func {algo.ParseVertLayout} {
  52. #local text {%0};
  53. #replace text {| |} {|};
  54. #replace text {^|} {};
  55. #replace text {|$} {};
  56. #local ch {};
  57. #local lines {};
  58. #local state {left};
  59. #local colNo {1};
  60. #local newline {|};
  61. #parse {$text} {ch} {
  62. #switch {"$state/$ch"} {
  63. #case {"left/ "} {
  64. #local state {right};
  65. };
  66. #case {"right/ "} {
  67. #local state {left};
  68. #local lines[$colNo] {$lines[$colNo] };
  69. #math colNo {$colNo + 1};
  70. };
  71. #case {"%*/$newline"} {
  72. #math colNo {1};
  73. #local state {left};
  74. };
  75. #case {"left/%*"} {
  76. #local lines[$colNo] {$lines[$colNo]$ch};
  77. #math colNo {$colNo + 1};
  78. };
  79. #default {
  80. errLog find BUG;
  81. #return {};
  82. };
  83. };
  84. };
  85. #local output {};
  86. #loop {&lines[]} {1} {colNo} {
  87. #replace {lines[$colNo]} {%+1..s$} {};
  88. #if { {$lines[$colNo]} == {%*%+1..S%*} } {
  89. #list output add {{$lines[$colNo]}};
  90. };
  91. };
  92. #return {$output};
  93. };