fork 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. bag[char] = bag[char] - 1
  11. end
  12.  
  13. local function bag(word)
  14. local b = {}
  15. for char in word:gmatch "." do add(b, char) end
  16. return b
  17. end
  18.  
  19. local state_index = {}
  20.  
  21. function state_index:process(str2)
  22. for c in str2:gmatch "." do
  23. local has_letter = false
  24. for i, bag in ipairs(self.bags) do
  25. if bag[c] and bag[c] >= 1 then
  26. has_letter = true
  27. remove(bag, c)
  28. self.anagrams[i] = self.anagrams[i] .. c
  29. break
  30. end
  31. end
  32. if not has_letter then
  33. self.fail = true
  34. return self
  35. end
  36. end
  37. return self
  38. end
  39.  
  40. function state_index:print()
  41. if self.fail then
  42. print "Failed! Some letters aren't coming from original words"
  43. else
  44. local ans = table.concat(self.anagrams, " ")
  45. local ws = table.concat(self.words, " ")
  46. if ans:len() == ws:len() then
  47. print(ans)
  48. print(ws)
  49. else
  50. print "Failed! The lengths of the strings do not match"
  51. end
  52. end
  53. end
  54.  
  55. local function init(str1)
  56. local state = {
  57. words = {},
  58. bags = {},
  59. anagrams = {},
  60. fail = false
  61. }
  62. setmetatable(state, {__index = state_index})
  63. for word in str1:gmatch("%w+") do
  64. table.insert(state.words, word)
  65. table.insert(state.bags, bag(word))
  66. table.insert(state.anagrams, "")
  67. end
  68. return state
  69. end
  70.  
  71. init(io.read()):process(io.read()):print()
Success #stdin #stdout 0.01s 2544KB
stdin
abab abab abab ab ab ab
abababaabbaabbaabb
stdout
abab abab abab ab ab ab
abab abab abab ab ab ab