local function add(bag, char)
if bag[char] then
bag[char] = bag[char] + 1
else
bag[char] = 1
end
end
local function remove(bag, char)
bag[char] = bag[char] - 1
end
local function bag(word)
local b = {}
for char in word:gmatch "." do add(b, char) end
return b
end
local state_index = {}
function state_index:process(str2)
for c in str2:gmatch "." do
local has_letter = false
for i, bag in ipairs(self.bags) do
if bag[c] and bag[c] >= 1 then
has_letter = true
remove(bag, c)
self.anagrams[i] = self.anagrams[i] .. c
break
end
end
if not has_letter then
self.fail = true
return self
end
end
return self
end
function state_index:print()
if self.fail then
print "Failed! Some letters aren't coming from original words"
else
local ans = table.concat(self.anagrams, " ")
local ws = table.concat(self.words, " ")
if ans:len() == ws:len() then
print(ans)
print(ws)
else
print "Failed! The lengths of the strings do not match"
end
end
end
local function init(str1)
local state = {
words = {},
bags = {},
anagrams = {},
fail = false
}
setmetatable(state, {__index = state_index})
for word in str1:gmatch("%w+") do
table.insert(state.words, word)
table.insert(state.bags, bag(word))
table.insert(state.anagrams, "")
end
return state
end
init(io.read()):process(io.read()):print()
bG9jYWwgZnVuY3Rpb24gYWRkKGJhZywgY2hhcikKICBpZiBiYWdbY2hhcl0gdGhlbgogICAgYmFnW2NoYXJdID0gYmFnW2NoYXJdICsgMQogIGVsc2UKICAgIGJhZ1tjaGFyXSA9IDEKICBlbmQKZW5kCgpsb2NhbCBmdW5jdGlvbiByZW1vdmUoYmFnLCBjaGFyKQogIGJhZ1tjaGFyXSA9IGJhZ1tjaGFyXSAtIDEKZW5kCgpsb2NhbCBmdW5jdGlvbiBiYWcod29yZCkKICBsb2NhbCBiID0ge30KICBmb3IgY2hhciBpbiB3b3JkOmdtYXRjaCAiLiIgZG8gYWRkKGIsIGNoYXIpIGVuZAogIHJldHVybiBiCmVuZAoKbG9jYWwgc3RhdGVfaW5kZXggPSB7fQoKZnVuY3Rpb24gc3RhdGVfaW5kZXg6cHJvY2VzcyhzdHIyKQogIGZvciBjIGluIHN0cjI6Z21hdGNoICIuIiBkbwogICAgbG9jYWwgaG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