How to implement Tower of Hanoi in AEM Sightly
Asked Answered
P

1

14

I'm trying to implement recursive algorithm solving Tower of Hanoi problem in Sightly. I know this approach may not have many obvious practical applications, I treat it as a puzzle. I end up with something like this:

<sly data-sly-template.step="${@ n, src, aux, dst}" data-sly-unwrap>
  <sly data-sly-test="${n > 0}" data-sly-unwrap>
    <sly data-sly-call="${step @ n = (n-1), src = src, aux = dst, dst = aux}" data-sly-unwrap/>
    ${src} -> ${dst}<br/>
    <sly data-sly-call="${step @ n = (n-1), src = aux, aux = src, dst = dst}" data-sly-unwrap/>
  </sly>
</sly>

<sly data-sly-call="${step @ n = 3, src = 'A', aux = 'B', dst = 'C'}" data-sly-unwrap/>

However, it doesn't compile as the Sightly doesn't support arithmetic operators like -. I don't need to count from 3 to 0, we may do it the opposite way, as the direction doesn't matter here. I just need some kind of counter with following features:

  1. we can increment or decrement it,
  2. we can check if equals to zero or some constant number.

I thought about using string. Empty string would be zero, 'x' would be 1, 'xx' would be 2 and so on. We can check if a string equals to a number (n == 'xxxx'). We can even increment it, using Sightly string formatter:

${'x{0}' @ format = [n]}

However, the above expression can't be used as a parameter in the data-sly-call or in the data-sly-test. We can only display it immediately and no further processing is available.

Do you have any other idea if there is some counter I can use?

Puttergill answered 18/12, 2014 at 10:44 Comment(0)
P
14

Use empty nested arrays: [] is 0, [[]] is 1, [[[]]] is 2, etc. If n is a number then:

  • n[0] decrements it (as we get the inner array),
  • [n] increments it (as we wrap the n with a new array),
  • data-sly-test will accept all n > 0 (at least two opening brackets).

The working code for n=3 would look like this:

<sly data-sly-template.step="${@ n, src, aux, dst}" data-sly-unwrap>
  <sly data-sly-test="${n}" data-sly-unwrap>
    <sly data-sly-call="${step @ n = n[0], src = src, aux = dst, dst = aux}" data-sly-unwrap/>
    ${src} -> ${dst}<br/>
    <sly data-sly-call="${step @ n = n[0], src = aux, aux = src, dst = dst}" data-sly-unwrap/>
  </sly>
</sly>

<sly data-sly-call="${step @ n = [[[[]]]], src = 'A', aux = 'B', dst = 'C'}" data-sly-unwrap/>

The interesting thing here is that such construction of integers is very similar to the set-theoretic definition of natural numbers. It appears that Maths is useful in the web-development after all!

Puttergill answered 18/12, 2014 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.