Select Page

My friends on the Parallax Propeller forum posted the following quiz:

During a 45-minute Facebook job interview you could be requested to write a C++ from scratch that does this:
You have a list of these words
“tsar”, “rat”, “tar”, “star”, “tars”, “cheese”

re-arrange them so the anagrams (words that have the same letters) are grouped together.
output order not important.

Here’s my take (albeit in Lua instead of C++):



t = { "tsar", "rat", "tar", "star", "tars", "cheese", }
function id(s)
local n=0
for i=1,#s do
n = n + s:byte(i,i)
end
return n
end
u = {}
p = {}
for i=1,#t do
p[#p+1] = 0
u[#u+1] = id(t[i])
end
for i=1,#u do
if p[i] == 0 then
p[i] = 1
print("===")
print(t[i])
for j=1,#u do
if p[j] == 0 and u[i] == u[j] then
p[j] = 1
print(t[j])
end
end
end
end

…and the output…



===
tsar
star
tars
===
rat
tar
===
cheese