local t = { 3,2,5,1,4 , 6 , 5 , 8, 2} local function compare( a, b ) return a \< b -- Note "\<" as the operator end table.sort( t, compare ) print( table.concat( t, ", " ) ) --\> 1, 2, 2, 3, 4 , 5 , 5 , 6 , 8
Repeat (2) and (5)
How to sort numbers without repeating?
There’s a few ways to do this, but off the top of my head, after your code to sort the array, you can increment through the sorted list and add unique values to a new array.
I didn’t test this code, but something like this.
local newT = {} local lastValAdded = t[1] - 1 -- seed so you have a value that is not in the array for i = 1, #t do if t[i] ~= lastVal then newT[#newT + 1] = t[i] lastValAdded = t[i] end end
local n = 1 for i = 1, #t do if t[n] == t[n + 1] then table.remove(t, n) n = n - 1 end n = n + 1 end
This example is complete:
local t = { 3,2,5,1,4 , 6 , 5 , 8, 2} local function compare( a, b ) return a \< b -- Note "\<" as the operator end table.sort( t, compare ) local n = 1 for i = 1, #t do if t[n] == t[n + 1] then table.remove(t, n) n = n - 1 end n = n + 1 end print( table.concat( t, ", " ) ) --\> 1, 2, 3, 4, 5, 6, 8
another approach might be to invert your table, then invert it back, eliminating duplicates prior to sorting. for example:
-- GIVEN: local t = { 3,2,5,1,4 , 6 , 5 , 8, 2} -- ADDED: local u = {} for k,v in pairs(t) do u[v]=k end t = {} for k,v in pairs(u) do t[#t+1]=k end -- GIVEN: local function compare( a, b ) return a \< b -- Note "\<" as the operator end table.sort( t, compare ) print( table.concat( t, ", " ) )
There’s a few ways to do this, but off the top of my head, after your code to sort the array, you can increment through the sorted list and add unique values to a new array.
I didn’t test this code, but something like this.
local newT = {} local lastValAdded = t[1] - 1 -- seed so you have a value that is not in the array for i = 1, #t do if t[i] ~= lastVal then newT[#newT + 1] = t[i] lastValAdded = t[i] end end
local n = 1 for i = 1, #t do if t[n] == t[n + 1] then table.remove(t, n) n = n - 1 end n = n + 1 end
This example is complete:
local t = { 3,2,5,1,4 , 6 , 5 , 8, 2} local function compare( a, b ) return a \< b -- Note "\<" as the operator end table.sort( t, compare ) local n = 1 for i = 1, #t do if t[n] == t[n + 1] then table.remove(t, n) n = n - 1 end n = n + 1 end print( table.concat( t, ", " ) ) --\> 1, 2, 3, 4, 5, 6, 8
another approach might be to invert your table, then invert it back, eliminating duplicates prior to sorting. for example:
-- GIVEN: local t = { 3,2,5,1,4 , 6 , 5 , 8, 2} -- ADDED: local u = {} for k,v in pairs(t) do u[v]=k end t = {} for k,v in pairs(u) do t[#t+1]=k end -- GIVEN: local function compare( a, b ) return a \< b -- Note "\<" as the operator end table.sort( t, compare ) print( table.concat( t, ", " ) )