xref: /freebsd/contrib/bmake/unit-tests/hanoi-include.mk (revision c7a063741720ef81d4caa4613242579d12f1d605)
1# $NetBSD: hanoi-include.mk,v 1.3 2022/05/08 07:27:50 rillig Exp $
2#
3# Implements the Towers of Hanoi puzzle, demonstrating a bunch of more or less
4# useful programming techniques:
5#
6#	* default assignment using the ?= assignment operator
7#	* including the same file recursively (rather unusual)
8#	* extracting the current value of a variable using the .for loop
9#	* using shell commands for calculations since make is a text processor
10#	* using the :: dependency operator for adding commands to a target
11#	* on-the-fly variable assignment expressions using the ::= modifier
12#
13# usage:
14#	env N=3 make -r -f hanoi-include.mk
15#
16# endless loop, since command line variables cannot be overridden:
17#	make -r -f hanoi-include.mk N=3
18
19N?=	5			# Move this number of disks ...
20FROM?=	A			# ... from this stack ...
21VIA?=	B			# ... via this stack ...
22TO?=	C			# ... to this stack.
23
24.if $N == 1
25.  for from to in ${FROM} ${TO}
26all::
27	@echo "Move the upper disk from stack ${from} to stack ${to}."
28.  endfor
29.else
30_:=	${N::!=expr $N - 1} ${TMP::=${VIA}} ${VIA::=${TO}} ${TO::=${TMP}}
31.  include "${.PARSEDIR}/${.PARSEFILE}"
32_:=	${N::!=expr $N + 1} ${TMP::=${VIA}} ${VIA::=${TO}} ${TO::=${TMP}}
33
34.  for from to in ${FROM} ${TO}
35all::
36	@echo "Move the upper disk from stack ${from} to stack ${to}."
37.  endfor
38
39_:=	${N::!=expr $N - 1} ${TMP::=${VIA}} ${VIA::=${FROM}} ${FROM::=${TMP}}
40.  include "${.PARSEDIR}/${.PARSEFILE}"
41_:=	${N::!=expr $N + 1} ${TMP::=${VIA}} ${VIA::=${FROM}} ${FROM::=${TMP}}
42.endif
43