[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

## need help in lua Started by neskuk Nov 14 2018 12:45 PM

23 replies to this topic
need help in lua knights tour warnsdorff extended
[TOPIC CONTROLS]
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

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?

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|
]]

[TOPIC: post.html]
#2

### roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
• Corona Geek

• 7,485 posts
• Corona SDK

@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):

[TOPIC: post.html]
#3

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

•
• 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.
•

[TOPIC: post.html]
#4

### roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
• Corona Geek

• 7,485 posts
• Corona SDK

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

[TOPIC: post.html]
#5

### davebollinger

[GLOBAL: userInfoPane.html]
davebollinger
• Corona Geek

• 1,296 posts
• Enterprise

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.

[TOPIC: post.html]
#6

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

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.

[TOPIC: post.html]
#7

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

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.

[TOPIC: post.html]
#8

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

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

:-(

[TOPIC: post.html]
#9

### davebollinger

[GLOBAL: userInfoPane.html]
davebollinger
• Corona Geek

• 1,296 posts
• Enterprise

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)

• roaminggamer likes this

[TOPIC: post.html]
#10

### roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
• Corona Geek

• 7,485 posts
• Corona SDK

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.

[TOPIC: post.html]
#11

### nick_sherman

[GLOBAL: userInfoPane.html]
nick_sherman
• Corona Geek

• 1,686 posts
• Corona SDK

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

[TOPIC: post.html]
#12

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

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.

[TOPIC: post.html]
#13

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

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?

[TOPIC: post.html]
#14

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

thanks Nick Sherman
but a statement on the matter would be more useful.

[TOPIC: post.html]
#15

### roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
• Corona Geek

• 7,485 posts
• Corona SDK

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.

[TOPIC: post.html]
#16

### roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
• Corona Geek

• 7,485 posts
• Corona SDK

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

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
```

[TOPIC: post.html]
#17

### davebollinger

[GLOBAL: userInfoPane.html]
davebollinger
• Corona Geek

• 1,296 posts
• Enterprise

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.

• Michael Flad, nick_sherman, roaminggamer and 1 other like this

[TOPIC: post.html]
#18

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

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.

[TOPIC: post.html]
#19

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

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.) ;-)
I hope to have all my notes or comments either translated or deleted and: minValue "10" is now 8! (for you) ;-)

ok.. have nice weekend.
```

// 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
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
```

[TOPIC: post.html]
#20

### davebollinger

[GLOBAL: userInfoPane.html]
davebollinger
• Corona Geek

• 1,296 posts
• Enterprise

the provided ring code will not run as is:

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

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.

• nick_sherman likes this

[TOPIC: post.html]
#21

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

1. you're right. have the wrong delimiter ";" used.
2.
3. if p = minVal and random(10) <5 // take it.. or not.
4. minVal = p ";" minD   = m
5. end
6. if p < minVal
7. minVal = p ";" minD   = m
8. end

the correction is here:

minVal = p

minD = m

end

if p < minVal

minVal = p

minD = m

I do not want to get involved with polemik this time.

It only costs time for you and me too.

thank you for looking ring.

it works realy perfect.

[TOPIC: post.html]
#22

### roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
• Corona Geek

• 7,485 posts
• Corona SDK

I agree with Dave here.  You came in with a question not related to game development in any way.  This would normally be an instant, "Can't help!"   This isn't a general help forums.  It is for game developers working with Corona.

However, I'm a sucker for question involving algorithms so I gave it a look.  That said, I hate it when people ask questions and post code that is impossible to read.  I always suggest, 'provide a full project I can download and run'.  I also ask that the OP provide clear and legible code.  It irks me to have to put in more time examining the code that the OP did asking the question.

Again, Dave is right.  Help us to help you and you'll be much better off.  I'm waiting to see a copy of this code in the language you programming language copied it from.  That way we can compare the 'original' to the 'converted Lua' version.

I'd also love to know what 'does not run properly' means.

[TOPIC: post.html]
#23

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

hello roaminggamer

Agreed. I wonder how I was going to react in such situarion in her place. I want to say thank you very much for being patient with me.

I am glad that you are interested in my solution. the algorithm is relatively short (compared to others), clearly understandable and functions really well. we can say perfect because, as we both know, the warnsdorff's rule is not always successful. It often happens that the choice of the best suitable field leads to the dead end.

the part with the random choice distinguishes the solution. we do not always take the first optimal field (in case of equality) but throw a "coin". this makes the knight's path more flexible.

Since I'm still looking for the solution, I need several versions side by side. this is not good with corona (or I do not know how). in the zb-editor I can compare that better. there it does not need the "main" part. therefore no project.

I posted the ring code. for the negligence with the delimiter I'm sorry.

The phrase "not working properly" should mean better: does not deliver the expected results.

Please do not forget that I have to adapt every sentence I write in English more often in the translator. Sometimes things are different than expected.

have nice weekend.

[TOPIC: post.html]
#24

### neskuk

[GLOBAL: userInfoPane.html]
neskuk
• Observer

• 13 posts
• Corona SDK

I can not believe it yet ... but: IT'S ON !
am still testing and clean up.
but it does and it does as good as the RING.
perfect.

have nice weekend.

[topic_controls]

[/topic_controls]