Hello, I have this solution to towers of hanoi problem. However my output is very strange:
import sequtils
type
Towers* = ref object
source*, destination*, auxiliary*: seq[int]
proc newTowers*(args: varargs[int]): Towers =
result = Towers(source: newSeq[int](args.len()),
destination: newSeq[int](), auxiliary: newSeq[int]()
)
for index, item in args:
result.source[index] = item
proc len*(t: Towers): int =
return t.source.len()
proc display*(t: Towers) =
echo("Source\t", t.source,
"\nAuxiliary\t", t.auxiliary,
"\nDestination\t", t.destination
)
proc moveItem(src, dst: var seq[int]) {.inline.} =
dst.add src[0]
src.delete(0,0)
proc transfer(i: int; src, dst, aux: var seq[int]) {.inline.} =
if i > 0:
transfer(i - 1, src, aux, dst)
moveItem(src, dst)
transfer(i - 1, aux, dst, src)
proc fix*(t: var Towers) =
transfer(t.source.len(), t.source, t.destination, t.auxiliary)
var t = newTowers(1, 3, 6, 89, 99, 122)
t.display()
t.fix()
t.display()
Result:
[user0@user0-pc app]$ nimble build
Verifying dependencies for [email protected]
Building app/app using c backend
[user0@user0-pc app]$ ./app
Source @[1, 3, 6, 89, 99, 122]
Auxiliary @[]
Destination @[]
Source @[]
Auxiliary @[]
Destination @[1, 6, 89, 99, 3, 122]
-- Successful runtime.
As you can see, the expected "destination" should be @[1, 3, 6, 89, 99, 122]. Why is 3 so far to the right?
In your moveItem you have the wrong logic.
Elements should be both taken and put on the top of the pile. If you're taking from the index 0 (of src), you should put it also on the index 0 (of dst), not at the last index.
The correct moveItem is either:
proc moveItem(src, dst: var seq[int]) =
dst.insert(src[0], 0)
src.delete(0)
or:
proc moveItem(src, dst: var seq[int]) =
dst.add src[src.high]
src.delete(src.high)