Log In  


Not sure where to post this but I'm having issues listing all the permutations of elements in a table in Pico 8 using this code:

output = {}

function permutation(a, n)
	if n == 0 then
		 add(output,a)
	else
		for i = 1, n do
			a[i], a[n] = a[n], a[i]						
			permutation(a, n - 1)
			a[i], a[n] = a[n], a[i]
		end
	end
end
cls()
permutation({"d","z","2"},3,1)

for i=1,#output do
	for j=1,#output[i] do
		print(output[i][j],j*8,i*10)
	end	
end

It just seems to add the table with the the elements in the initial order to the output table, but the output table does end up with the correct number of element tables. that is, trying to find the permutations of a 3 element array yields and output table with length 6.



1

You need to add a copy of a to output, not a itself.


Wow thanks Saffith, I KNEW it was some kind of pass by reference issue.

But my initial attempt to implement a table copy method didn't work and I fell down a rabbit hole of incorrect assumptions about my code....

EDIT for posterities sake here's a working change:

output = {}

function copy_t(tbl)
	local t = {}
	for key, value in pairs(tbl) do
	  t[key] = value
	end
	return t
end

function permutation(a, n)
	if n == 0 then

		 add(output,copy_t(a))
	else
		for i = 1, n do
			a[i], a[n] = a[n], a[i]						
			permutation(a, n - 1)
			a[i], a[n] = a[n], a[i]
		end
	end
end
cls()
permutation({"d","z","2"},3,1)

for i=1,#output do
	for j=1,#output[i] do
		print(output[i][j],j*8,i*10)
	end	
end


[Please log in to post a comment]