fork(1) download
  1. local function add(bag, char)
  2. if bag[char] then
  3. bag[char] = bag[char] + 1
  4. else
  5. bag[char] = 1
  6. end
  7. end
  8.  
  9. local function remove(bag, char)
  10. if bag[char] and bag[char] >= 1 then
  11. bag[char] = bag[char] - 1
  12. end
  13. end
  14.  
  15. local function bag(word)
  16. local b = {}
  17. for char in word:gmatch "." do add(b, char) end
  18. return b
  19. end
  20.  
  21. local state_index = {}
  22.  
  23. function state_index:process(str2)
  24. for c in str2:gmatch "." do
  25. for i, bag in ipairs(self.bags) do
  26. if bag[c] and bag[c] >= 1 then
  27. remove(bag, c)
  28. self.anagrams[i] = self.anagrams[i] .. c
  29. break
  30. end
  31. end
  32. end
  33. return self
  34. end
  35.  
  36. function state_index:print()
  37. print(table.concat(self.anagrams, " "))
  38. print(table.concat(self.words, " "))
  39. end
  40.  
  41. local function init(str1)
  42. local state = {
  43. words = {},
  44. bags = {},
  45. anagrams = {},
  46. }
  47. setmetatable(state, {__index = state_index})
  48. for word in str1:gmatch("%w+") do
  49. table.insert(state.words, word)
  50. table.insert(state.bags, bag(word))
  51. table.insert(state.anagrams, "")
  52. end
  53. return state
  54. end
  55.  
  56. init(io.read()):process(io.read()):print()
Success #stdin #stdout 0.02s 2500KB
stdin
abab ab ab ab ab ab ab ab ab ab ab ab
abababababababababababaabb
stdout
abab ab ab ab ab ab ab ab ab ab ab ab
abab ab ab ab ab ab ab ab ab ab ab ab