Skip to content

Instantly share code, notes, and snippets.

@RuizuKun-Dev
Last active April 1, 2023 00:37
Show Gist options
  • Save RuizuKun-Dev/a27568d743d8cd3982c8a26daf0efad9 to your computer and use it in GitHub Desktop.
Save RuizuKun-Dev/a27568d743d8cd3982c8a26daf0efad9 to your computer and use it in GitHub Desktop.
local function generateInput()
local file = io.open("Input.txt", "w")
local nums = {}
for _ = 1, 100 do
table.insert(nums, math.random(1, 100))
end
file:write(table.concat(nums, " "))
file:close()
end
generateInput()
local function generateOutput()
local inFile = io.open("Input.txt", "r")
local input = inFile:read("*all")
inFile:close()
local unsorted = {}
local function getInput()
for num in string.gmatch(input, "%-?%d+") do
table.insert(unsorted, tonumber(num))
end
end
getInput()
local cache = {}
local function countDuplicates()
for _, num in ipairs(unsorted) do
if not cache[num] then
cache[num] = 1
else
cache[num] = cache[num] + 1
end
end
end
countDuplicates()
local sorted = {}
local function sortDuplicates()
local counts = {}
for num, count in pairs(cache) do
if counts[count] then
table.insert(counts[count], num)
else
counts[count] = { num }
end
end
for _, nums in ipairs(counts) do
table.sort(nums)
end
for count, nums in ipairs(counts) do
for _, num in ipairs(nums) do
for _ = 1, count do
table.insert(sorted, num)
end
end
end
end
sortDuplicates()
local outFile = io.open("Output.txt", "w")
outFile:write(table.concat(sorted, " "))
outFile:close()
end
generateOutput()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment