need help in lua

Hello 

I would like to learn lua and try to realize “kniht’s tour”. Although I know the proglematik and have made the program in several other languages more than once, in lua I do not succeed. Can someone tell me what is wrong here?

thank you in advance.

problemcode:

– kt-02-3.lua

– ******************************************************************

– works fine in: basic256, x11basic, algoid, euphoria, tcl, ring … 

– version whitout grafik /  With Warnsdorff’s rule (extended)

– ******************************************************************

–// possible moves

pm = {{-2,1},{-1,2},{1,2},{2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}}

n    = 8 --//number rows/collons

cbx = n   --// rows

cby = n   --// colls

–// startfeld  ( 2/2 = kritisch!) 

kx  = 2 –

ky  = 2 –

–// startfeld  -  randomizer (for testing)

math.randomseed (os.time ())    – random turn on

–kx =math.random(1, 8)

–ky =math.random(1, 8)

print(“Startfeld kx/ky: “…kx …”/”…ky)

–// make chessboard n*n

–cb = list(cby) for x in cb  x = list(cbx)  next  ??

cb = {}      – cb definition filled with nulls

for i = 1, n do

    cb[i] = {}

    for j = 1, n do

        cb[i][j] = 0

    end

end

function printCB()        – cb printing

for y = 1, n do

  io.write("|")

    for x = 1, n do

      if cb[y][x] <10 then

        io.write(" “…cb[y][x]…”|" )

      else

         io.write( cb[y][x]…"|" )

      end

    end

    print("")

end 

return

end  

#-- between inclusive

–if nx >= 1 and nx <= N and ny >= 1 and ny <= N then  – cb grenzen

function between(x, min, max)

    return (x>=min) and (x<=max)

end 

k = 0 --// jmps-counter 

 while(k < 65) do

  cb[kx][ky] = k+1        – counter set

  pq = {}                 – priority queue (clear)

  

for i = 1, n do

nx = kx + pm[i][1]; ny = ky + pm[i][2]  

if between(nx, 1, cbx) and between(ny, 1, cby) then

      if cb[nx][ny] == 0 then ctr = 1   – zaehler reset

for j = 1, n do   

ex = nx + pm[j][1]; ey = ny + pm[j][2]

if between(ex, 1, cbx) and between(ey, 1, cby) then 

if cb[ey][ex] == 0 then ctr=ctr+1 end

end

end --for j

          table.insert(pq, (ctr*100)+i)     

end – if cb[nx][ny] 

end  – if between…

end – for i  

– Warnsdorff’s algorithmus;   extended

– move to the neighbor that has min number of available neighbors

– randomization:  we could take it - or not

  if #pq > 0 then

    table.sort (pq)      – OK (min first)

    minVal = 8     – max loop nr   

    minD   = 0       – min value     

    math.randomseed (1,10)  – random: 1-10

    math.random(); math.random(); math.random(); --warming up

    for dd = 1, #pq do 

      x = table.remove(pq,1)         – kopf-element loeschen     

      p = math.floor(x / 100)        – p wert extrahieren

      m = x % 10      – m (row) wert extrahieren  

      if p == minVal and math.random() <5 then 

        minVal = p

        minD   = m

      end

      if p < minVal then

          minVal = p

          minD   = m

      end 

    end  --dd

m = minD 

kx = kx + pm[m][1]

ky = ky + pm[m][2]

else 

if k < 63 then

print("Error in Field-No.: "…k)

      break

else

print(" >>>------------------->  Success!")

      break

end

end

k = k+1

end  – while

– ******************  end main pgm   ********************

printCB() 

–[[

sometimes successful too:

| 33|30|37|20|23|16|49|18|

| 36| 1|34|31|38|19|22|15|

| 29|32|39|24|21|50|17|48|

|  2|35|28|59|46|61|14|57|

| 27|44|25|40|51|58|47|62|

|  6| 3|52|45|60|11|56|13|

| 43|26| 5| 8|41|54|63|10|

|  4| 7|42|53|64| 9|12|55|

]]

@neskuk,

Hi.  Welcome to the forums. 

Are you interested in using Corona or just learning Lua?   

If the latter, please be aware, while this sub-forum is for Lua questions it is intended for members of the Corona game and app dev community. 

So, if you’re just learning Lua you may want to find a Lua specific community or a general programming resource.

Whatever the case, there are many Lua resources on the web, but among the best is the PIL: https://www.lua.org/pil/

Also, you can find implementations of many algorithms over at Rosseta Code: https://rosettacode.org/

For example Knights Tour (you misspelled it):

  • Thanks for the answer.
  • the example in rosetacode ( https://rosettacode.org/wiki/Knight%27s_tour#Lua ), the only one found in lua) is unfortunately recursive. it works acceptable only from start field: 1/1 - not a good example unfortunately.
  • yes, I want to learn lua - lua with corona! 
  • in lua fourth edition is unfortunately nothing usable for my problem with knigtht’s tour.

I’m still not clear what the exact problem is.

How is your code failing?

i’ve no interest in debugging that for you, but i’ll offer this:  one of the more common mistakes converting code from other languages to lua is that numeric array indices are 1-based (not 0-based) by default

while your “for” loops look like they’ve been revised, you must also think about how that change to indexing might affect other calculations, like a modulo or divide on a linear index to extract row/col, or the converse of that, or any other use that implies a 0-basis.

hi roaming gamer

my lua code is strange. it does not work as it should. i have tested it in several other languages and it works perfectly. only in lua not.

I’m pretty irritated. To make sure that I do not fall into the 1-base trap, I rewrote it in ring (1-base) and here it runs perfectly.

it has to hang on some property of lua. I do not know lua yet. I’m learning it now.

look at the code in the iterpreter. then you will see it. I suspect the error in the random part or in the formation of the priority queue. I just do not know how to locate.

hi davebollinger

it does not work as it should. i have tested it in several other languages and it works perfectly. only in lua not.

I’m pretty irritated. To make sure that I do not fall into the 1-base trap, I rewrote it in ring (1-base) and here it runs perfectly.

it has to hang on some property of lua (float / integer / maybe the loops?). I do not know lua yet. I’m learning it now.

I suspect the error in the random part or in the formation of the priority queue.  I just do not know how to locate.

look at the code in the iterpreter. then you will see what i mean. 

Debugging a knights tour code is not trivial. I know what I’m talking about.

:frowning:

the problem is tricky, but the code itself isn’t (or needn’t be)

what’s “hard” is trying to puzzle out someone else’s translation of it for bugs that even the author can’t see.

(fe, i too once wrote a knight’s tour, in lua 3 circa 2000, but it doesn’t look like this one - except perhaps the “pm” table :D)

I don’t see anything wrong with the Lua code itself.  I’d clean that up with better indentation and then re-check your algorithm.

2018 me is hating all those 1-2 character variable names, while remembering 2012 me wouldn’t have even bothered commenting them…

hi dave

no idea what you are talking about.

if you mean that example in rosetta (https://rosettacode.org/wiki/Knight%27s_tour#Lua), the only lua example for kt in lua that you can find on the web, that’s is it not. one could call it unusable. 

hi roaminggamer

look at the code in the interpreter. you will see what I mean. the pgm is totally illogical … unpredictable. the same code in ring or python (for example) works perfectly. but not in lua. Why?

thanks Nick Sherman

but a statement on the matter would be more useful.

I ran the code (with a fixed start and random starts) and no errors popped out.

Yes, the random start version failed, but the were no syntax errors, crashes, or hangs. 

Beyond that, I’m not going to debug the actual algorithm. 

Sorry, but it’s been 20+ years since I had to solve Knight’s Tour in school and this is really not a Corona issue which is where I prefer to put my help time.

Here is the original and a cleaned/modified copy of the code for anyone who has time to help:

https://github.com/roaminggamer/RG_FreeStuff/raw/master/AskEd/2018/11/knightsTour.zip

To run the orignal, do this in main.lua:

require "orig"

To Run the modified do this:

local cleaned = require "cleaned" cleaned.run()

or this to run a specific start:

local cleaned = require "cleaned" cleaned.run( { kx = 2, ky = 3 } )

or this to run them all and not print result:

local cleaned = require "cleaned" for kx = 1, 8 do for ky = 1, 8 do cleaned.run( { kx = kx, ky = ky, quiet = true } ) end end

post the code that works in some other language, then maybe, MAYBE, someone might then take an interest in helping translate it

because that’s likely the only source of your problem, but i doubt anyone will figure it out as is

this translated code apparently has an error, though at least one person (roaminggamer) ran it without error, and you refuse to tell us exactly what the error actually IS (instead you just keep saying “same code runs in other languages” - which can’t be true, this MUST have been translated)

plus there’s lots of “mystery stuff” in there, like passing two values to randomseed, or “math.random()<5” which will always evaluate true, or indexing by 10’s when you only have 8 col/row, plus the few comments present are in german (not my native), obscure variable names, etc – maybe it works, maybe it doesn’t, but it’s just too weird for most of us casual helpers to spend enough time on to figure it out for you.

hi roaminggamer

yes, I write at the beginning of the discussion: the code runs without error. only the results are totally unexpected in comparison with python, basic … or ring. 

So the question remains unexplained: why does not it run properly in lua? (probably randomizer?)

I agree with you - it is not corona problem.

many thanks for cleaned code. I want to study it… and forgive me the indentation mistake. it was (evidently) created by copy & past (I overlooked it).

thanks for the time given.

hi davebollinger

there are a few subscriptions on the web dealing with lua randomizer and his “mysteria”. I tried the samples all without success.

my lua code works without error. it only provides strange results.

to your remark: “same code runs in other languages” - which can not be true.

I can post the RING code here. However, I doubt it will help. you did not even test the lua code yourself. why then this polemic?

the index minValue “10” is intentionally not “8” so that you can not assign it incorrectly (it can also have the value 7 or even 6).

and to german comments: these are my notes … thoughts. I forgot to delete it. apologize.

besides that, German is not my mother tongue. I’ve had to learn a few languages ​​in my (long) life. Now it is German (to be precise - Swiss German).

I agree with you that the discourse here actually develops in a wrong, (polemical) direction (you can already see it not only in these lines). Things are being criticized that have nothing to do with the actual (LUA) problem. even the “indentation” has already been mentioned … or namingstyle of the variables. the effect, even without your accusation (I’m a liar), really disappointing.

I apologize for taking your time. and please also excuse my google english - english is not my “native”.

and here … a little present for you (soon is christmas):

(look at it, it works perfectly. you will find (perhaps) that the program acts more inteligent than any writers here.) :wink:

I hope to have all my notes or comments either translated or deleted and: minValue “10” is now 8! (for you) :wink:

ok… have nice weekend.

[lua]

// kt-02-3.ring warnsdorff extended  (for control of the lua version)

// http://ring-lang.net

// possible moves

pm = [[-2,1],[-1,2],[1,2],[2,1],[-2,-1],[-1,-2],[1,-2],[2,-1]]

n   = 8 //number rows/collons

cbx = n // rows

cby = n // colls

// startfeld  ( 2/2 = critical!) 

kx  = 2 // works fine now

ky  = 2 // works fine now

// make chessboard n*n

cb = list(cby) for x in cb  x = list(cbx)  next

k = 0 // jmps-counter 

while k <= cbx * cby

cb[ky][kx] = k+1

pq = [] // priority Queu (reset)

for i = 1 to n  // row

nx = kx + pm[i][1]; ny = ky + pm[i][2]  

if between(nx, 1, cbx) and between(ny, 1, cby)  

if cb[ny][nx] = 0  ctr = 0  // without impact whether 0 oder 1

for j = 1 to n // col

ex = nx + pm[j][1] ; ey = ny + pm[j][2]

if between(ex, 1, cbx) and between(ey, 1, cby) 

if cb[ey][ex] = 0  ctr++ ok

ok

next 

add(pq,(ctr*100)+i) // format: 302

ok  // if cb[ny][nx]

ok  // if between(nx, 1, cbx) and 

next // for i

#  – Warnsdorff’s algorithmus;   extended

if len(pq) > 0

pq = sort(pq) // min-wert at begin

    minVal = 8 // max loop no

    minD   = 0 // min value (not necessary here)

    for dd = 1 to len(pq)

x= pq[1] // min-value 

p  = floor(x/100) // ctr - counter

m = x % 10 // i    - row (loop-no)

if p = minVal and random(10) <5 // take it… or not.

minVal = p; minD   = m

end

if p < minVal 

minVal = p; minD   = m

end  

Del(pq,1)    // delete item number 

    end  //dd

m = minD 

kx = kx + pm[m][1]

ky = ky + pm[m][2]

else 

if k < 63

see "Error in the field no.: "+k+nl

exit

else

see “Success.” +nl

exit

ok

ok

k++

end // while// end pgm   **************************************

// kontroll-ausgabe:

  for r = 1 to N        // row

    for c = 1 to N // col

see  “|” // 

if cb[c][r] <= (n+1)

see “_” 

//see " " // alt 255 (nok)

see  cb[c][r]

else

        see cb[c][r] // jump-no. from cb

ok

    next //for  

see  “|”

    see nl

  next //for   

func between x, mi, mx // min & max keywords

    between = (x >= mi) AND (x <= mx)

return between

[/lua]

the provided ring code will not run as is:

Line 49 Error (R34) : Variable is required for the assignment operation in file kt.ring&nbsp;

and i’m not about to first debug your ring code just so that i can then debug your lua code derived from it!

>> my lua code works without error. it only provides strange results.

twenty posts later and you STILL haven’t defined what the actual problem is - merely saying “strange results” doesn’t suffice, you have to “help us help you” or why should we even bother?  you get what you pay for with free help.

and who’s the polemical one?  you’ve managed to alienate someone willing to assist, and someone who has actually written a functional knight’s tour in lua.  so i’m done looking at yours, good luck, perhaps others can still help.