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

str:find

Started by KingofGamesYami, 09 July 2014 - 06:22 PM
KingofGamesYami #1
Posted 09 July 2014 - 08:22 PM
For some reason, sString:find( word ) is returning a single value instead of two… as it is supposed to according to http://lua-users.org/wiki/StringLibraryTutorial. Is it simply returning the start of the word (from which I can find the rest of it), or is it doing something else?

function zip( sString )
	local len = #sString
	for i = 16, 6, -1 do
		for x = 1, i do
			for word in sString:sub( x ):gmatch( string.rep( ".", i ) ) do
				local s, e = sString:find( word )
				local replace = "<"..s..","..e..">"
				sString = sString:gsub( word, replace )
				sString = sString:sub( 1, x )..word..sString:sub( x + #replace )
				sString = sString:gsub( word:reverse(), "<"..e..","..s..">" )
				sleep( 0 )
			end
		end
	end
	return sString, len - #sString
end
KingofGamesYami #2
Posted 09 July 2014 - 08:48 PM
Also, what is the best way of getting a "tree" for a number? here's an example, since I'm not sure what it's really called:

   16
  2  8
 2  2  4
2  2  2  2
--#and another one
  27
 3  9
3  3  3
Swith #3
Posted 09 July 2014 - 10:24 PM
The "tree" you are talking about is a number's prime factors. Try something like this:


function primeFactors(n)
  i = 2
  while n > 1 do
    if n % i == 0 then
      n = n/i
      print(i)
      i = 2
    else
      i = i + 1
    end
  end
end

primeFactors(84)

would output


2
2
3
7

EDIT: Explanation:

What the function does is starts at the first prime (2) then increases it until it finds the first prime factor, then starts again with the number divided by it. This could easily be done recursively but hopefully this was easier to follow. It would also be fairly easy to amend so that it prints it in a tree form.
Edited on 09 July 2014 - 08:53 PM
KingofGamesYami #4
Posted 09 July 2014 - 11:22 PM
Thanks, that will help me a lot.