xref: /freebsd/contrib/bmake/unit-tests/hanoi-include.mk (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
1# $NetBSD: hanoi-include.mk,v 1.1 2020/10/03 17:30:54 rillig Exp $
2#
3# Implements the Towers of Hanoi puzzle, thereby demonstrating a bunch of
4# useful programming techniques:
5#
6# * default assignment using the ?= assignment operator
7# * including the same file recursively
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 -f hanoi-include.mk
15# endless loop:
16#	make -f hanoi-include.mk N=3
17
18N?=	5			# Move this number of disks ...
19FROM?=	A			# ... from this stack ...
20VIA?=	B			# ... via this stack ...
21TO?=	C			# ... to this stack.
22
23.if $N == 1
24.  for from to in ${FROM} ${TO}
25all::
26	@echo "Move the upper disk from stack ${from} to stack ${to}."
27.  endfor
28.else
29_:=	${N::!=expr $N - 1} ${TMP::=${VIA}} ${VIA::=${TO}} ${TO::=${TMP}}
30.  include "${.PARSEDIR}/${.PARSEFILE}"
31_:=	${N::!=expr $N + 1} ${TMP::=${VIA}} ${VIA::=${TO}} ${TO::=${TMP}}
32
33.  for from to in ${FROM} ${TO}
34all::
35	@echo "Move the upper disk from stack ${from} to stack ${to}."
36.  endfor
37
38_:=	${N::!=expr $N - 1} ${TMP::=${VIA}} ${VIA::=${FROM}} ${FROM::=${TMP}}
39.  include "${.PARSEDIR}/${.PARSEFILE}"
40_:=	${N::!=expr $N + 1} ${TMP::=${VIA}} ${VIA::=${FROM}} ${FROM::=${TMP}}
41.endif
42