Fortran 77-1085文字
subroutine q(u,t)
implicit integer(i-z)
character*33 f,g
dimension t(u)
m=ceiling(log(real(u))/log(2.))
v=2**(m+1)-1
do l=1,m
n=2**(l-1)
k=2**(m-l+2)-3
w=(3+k)*2**(l-1)-k
p=1+(v-w)/2
if(l.ne.1)then
write(f,'(A,I3,A)')'(A',p,',$)'
print f,' '
write(f,'(A5,I3,A3)')'(A3,A',k,',$)'
do j=2**(l-1),2**l-1
if(t(j/2).lt.0.or.t(j).lt.0)then
print f,' ',' '
elseif(mod(j,2).eq.0)then
print f,' /',' '
else
print f,' \ ',' '
endif
enddo
print*
endif
write(f,'(A,I3,A)')'(A',p,',$)'
print f,' '
write(f,'(A5,I3,A3)')'(I3,A',k,',$)'
write(g,'(A2,I3,A3)')'(A',k+3,',$)'
do j=2**(l-1),2**l-1
if(t(j).ge.0)then
print f,t(j),' '
else
print g,' '
endif
enddo
print*
enddo
end
ツリーは、入力配列t
で通常の方法で表されます。ルート1、ルート2、左2、ルート3、右3、ルート4、左4で...
出力は、最大5レベルの深さの従来の端末に収まる必要があります。
ノードの各ペアの間にスラッシュを1つだけ使用します。4つ以上のレベルがあると、上部付近でかなりおかしく見えます。最大3桁のノードを許可しました。
コメントと起動スキャフォールドを含む完全なプログラム:
program tree
parameter (l=8) ! How many nodes to support
dimension i(l)
c Initialize the array to all empty nodes
do j=1,l
i(j)=-1
end do
c Fill in some values
i(1)=3
i(2)=1
i(3)=5
i(5)=2
i(6)=4
i(7)=7
c i(14)=6
c i(15)=8
c Call the printing routine
call q(l,i)
stop
end
c Print an ASCII representation of the tree
c
c u the length of the array containing the tree
c t an integer array representing the tree.
c
c The array contains only non-negative values, and empty nodes are
c represented in the array with -1.
c
c The printed representation uses three characters for every node,
c and places the (back) slash equally between the two node-centers.
subroutine q(u,t)
implicit integer(i-z)
character*33 f,g
dimension t(u)
m=ceiling(log(real(u))/log(2.)) ! maximum depth of the tree
v=2**(m+1)-1 ! width needed for printing the whole tree
! Optimized from 3*2**m + 1*((2**m)-1) at
! the bottom level
do l=1,m
n=2**(l-1) ! number of nodes on this level
k=2**(m-l+2)-3 ! internode spacing
w=(3+k)*2**(l-1)-k ! width needed for printing this row
! Optimized from 3*2**l + k*((2**l)-1) at
! the bottom level
p=1+(v-w)/2 ! padding for this row
c Print the connecting lines associated with the previous level
if(l.ne.1)then ! Write the connecting lines
write(f,'(A,I3,A)')'(A',p,',$)'
print f,' '
write(f,'(A5,I3,A3)')'(A3,A',k,',$)'
do j=2**(l-1),2**l-1
if(t(j/2).lt.0.or.t(j).lt.0)then
print f,' ',' '
elseif(mod(j,2).eq.0)then
print f,' /',' '
else
print f,' \ ',' '
endif
enddo
print*
endif
c Print the nodes on this level
write(f,'(A,I3,A)')'(A',p,',$)'
print f,' '
write(f,'(A5,I3,A3)')'(I3,A',k,',$)'
write(g,'(A2,I3,A3)')'(A',k+3,',$)'
do j=2**(l-1),2**l-1
if(t(j).ge.0)then
print f,t(j),' '
else
print g,' '
endif
enddo
print*
enddo
end
例と同等の入力での出力:
$ ./a.out
3
/ \
1 5
\ / \
2 4 7