top of page
lp.jpeg

Blog

Tags:

DataWeave programming challenge #4: Solve the Tower of Hanoi mathematical puzzle



 

In this post:

 


This challenge is based on the Tower of Hanoi mathematical puzzle - this is a tough one!

Try to solve this challenge on your own to maximize learning. We recommend you refer to the DataWeave documentation only. Try to avoid using Google or asking others so you can learn on your own and become a DataWeave expert!


⚠️ Important: There are 3 different scenarios to test your code is working properly and to ensure there are no hardcoded values. However, only the first scenario is provided in the Playground link below. Please copy+paste the other two scenarios to make sure your solution is working properly.




Input


Consider the following JSON inputs:


SCENARIO 1

{
    "moves": 0,
    "disks": 3,
    "targetTower": "C",
    "towers": {
        "A": [
            1,
            2,
            3
        ],
        "B": [],
        "C": []
    }
}

SCENARIO 2

{
    "moves": 0,
    "disks": 4,
    "targetTower": "C",
    "towers": {
        "A": [
            1,
            2,
            3,
            4
        ],
        "B": [],
        "C": []
    }
}

SCENARIO 3

{
    "moves": 0,
    "disks": 7,
    "targetTower": "Y",
    "towers": {
        "X": [],
        "Y": [],
        "Z": [
            1,
            2,
            3,
            4,
            5,
            6,
            7
        ]
    }
}


Explanation of the problem


Create a DataWeave script to solve the Tower of Hanoi puzzle. The input payload contains the number of moves (starting at 0), the total number of disks in the game, the target tower where all the disks have to be moved, and the 3 towers containing each disk.



(You can use this link to play the game online)


Here are the rules of the game:

  • With each move, you can only move one disk at a time from its current stack to a different stack.

  • You can only place smaller disks on top of bigger disks. For example, you can place disk 1 on top of disk 3 but you can't place disk 5 on top of disk 2.

  • You can only move the disk at the top of any stack.



Expected output


For each of the three scenarios from the input, these are the expected outputs:


SCENARIO 1

{
  "moves": 7,
  "disks": 3,
  "targetTower": "C",
  "towers": {
    "A": [
      
    ],
    "B": [
      
    ],
    "C": [
      1,
      2,
      3
    ]
  }
}

SCENARIO 2

{
  "moves": 15,
  "disks": 4,
  "targetTower": "C",
  "towers": {
    "A": [
      
    ],
    "B": [
      
    ],
    "C": [
      1,
      2,
      3,
      4
    ]
  }
}