Jump to content




Rearranging Tables


  • You cannot reply to this topic
3 replies to this topic

#1 クデル

  • Members
  • 349 posts

Posted 01 June 2016 - 06: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
}


#2 Dragon53535

  • Members
  • 973 posts
  • LocationIn the Matrix

Posted 01 June 2016 - 07: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.

#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 01 June 2016 - 08:13 AM

View PostDragon53535, on 01 June 2016 - 07:04 AM, said:

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 by Bomb Bloke, 01 June 2016 - 01:53 PM.


#4 クデル

  • Members
  • 349 posts

Posted 01 June 2016 - 10: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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users