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

How do you procedurally generate strings?

Started by ry00000, 23 January 2016 - 04:39 PM
ry00000 #1
Posted 23 January 2016 - 05:39 PM
I want to be able to generate strings like this:
aaaaaaa
aaaaaab
aaaaaac
aaaaaad
aaaaaae
and so on…
How do you do this in Lua?
Creator #2
Posted 23 January 2016 - 05:51 PM
I want to be able to generate strings like this:
aaaaaaa
aaaaaab
aaaaaac
aaaaaad
aaaaaae
and so on…
How do you do this in Lua?

Bruteforcing?


local f = function()
local data = ""
for i=0,255 do -- add as many loops as nneeded
  data = string.char(i)
  for k=0,255 do -- as many loops as needed
    coroutine.yield(data = str:sub(data,1,1)..string.char(k)
  end
end
end

c = coroutine.wrap(f)
--call c as much as needed
ry00000 #3
Posted 23 January 2016 - 06:08 PM
thanks!
Creator #4
Posted 23 January 2016 - 06:10 PM
thanks!

No problem.
SquidDev #5
Posted 23 January 2016 - 07:10 PM
add as many loops as needed

It might be nicer to use a recursive function:


local function f(n, data)
  if n == 0 then
	coroutine.yield(data)
  else
	for i=0,255 do
	  f(n - 1, data .. string.char(i))
	end
  end
end

local function generate(n)
  return coroutine.wrap(function() f(n, "") end)
end

for item in generate(2) do -- Change this for an n long string
	print(item)
end
Edited on 23 January 2016 - 06:10 PM
ry00000 #6
Posted 23 January 2016 - 08:01 PM
Coooooool!!! This'll be immensely useful!!!
Dragon53535 #7
Posted 23 January 2016 - 08:20 PM
Keep in mind, that for each digit to shift once, it takes n^x amount of cycles.


abcd
Lets say this just goes through lowercase letters, for d to change, well only one cycle is needed since it's the one that's always going to change :P/>.
However, for c to change it takes 26^1 amount of cycles to change, or 26. For b to change though it takes 26^2 to change for each letter. and for a it takes 26^3 or 17576 loops for each letter in that slot. If you used uppercase and lowercase, it'd be 52^3 or 140608… It takes a long time to loop through that.