This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
クデル's profile picture

Rearranging Tables

Started by クデル, 01 June 2016 - 05:29 AM
クデル #1
Posted 01 June 2016 - 07:29 AM
As the title states, I am having a bit of trouble rearranging tables. I want to arrange a table by key value, as they are all integers I want the first entry to contain the highest integer value. For example:

Sample Input:

{
  h = 1
  e = 1
  l = 3
  o = 2
  " " = 1
  w = 1
  r = 1
  d = 1
}

Desired Output

{
  l = 3
  o = 2
  h = 1
  e = 1
  " " = 1
  w = 1
  r = 1
  d = 1
}
Dragon53535 #2
Posted 01 June 2016 - 08:04 AM
Yeah that's pretty difficult or even impossible. The problem for you is that first of all, there's no duplicates allowed for your setup, plus it's extremely difficult to order a table like you want.

You could store it as a 2 dimensional table with a key for the letter and a key for the value.
Bomb Bloke #3
Posted 01 June 2016 - 09:13 AM
there's no duplicates allowed for your setup

Duplicates simply result in higher integers. For example, "l" has the number three because "l" is repeated three times in "hello world".

But yeah, this can't be done directly, because you can't change the order of non-numeric keys within a table. The pairs function (pretty much the only way to pull an abstract list of keys out of a table) orders keys by their hash representations, and you can't change the hash without changing the key. Hence a different table layout is required, as in order to sort anything you need to use numeric indexes instead.

Eg:

local input = {
	h = 1,
	e = 1,
	l = 3,
	o = 2,
	[" "] = 1,
	w = 1,
	r = 1,
	d = 1
}

local output = {}

-- Create numerically indexed version of the table:
for key, value in pairs(input) do
	output[#output + 1] = {["letter"] = key, ["count"] = value}
end

-- Sort it:
table.sort(output, function(a, b) return a.count > b.count end)

-- Output result:
for i = 1, #output do
	print("Letter = " .. output[i].letter .. ", Count = " .. output[i].count)
end
Edited on 01 June 2016 - 12:53 PM
クデル #4
Posted 01 June 2016 - 11:56 AM
Thanks a bunch, helps a lot. It is also rather interesting how when I even generate the index the order is different every time.