Java Reference
In-Depth Information
public static void
mysteriousRecursive(
int
[] tab,
int
k)
{
if
(k == tab . length
−
1)
display(tab) ;
for
(
int
j=k; j
<
t a b . l e n g t h ;
j ++)
{
swap3( tab , k , j ) ;
mysteriousRecursive(tab , k + 1) ;
swap3( tab , k ,
j ) ;
}
}
public static void
init(
int
[] tab)
{
for
(
int
i=0; i
<
tab . length ; i++)
tab[i]=i+1;
}
public static void
main( String [ ]
args )
{
int
n = Integer . parseInt(args [0]) ;
int
[] t =
new i n t
[n];
init(t);
swap2( t [ 0 ] , t [ n
−
1]) ;
mysterious(t , 0) ;
//
mysteriousRecursive(t, 0);
}
}
Once this code compiled, what is the result displayed in the console
output by invoking
java MysteriousProgram 4
? Describe explicitly the
program execution steps and its outcome for the general case (for any
given
n
>
0
)
SOLUTION:
For
n
= 4, the program displays the following output:
1234
2134
3214
4231
Function
init
fills array
t
that is given by reference with values
rangingfrom1to
n
. Function
swap2
performs a permutation on the
copied values
of two array cells, and thus does not modify the original
array cells since it works with copies. The array contents order is
therefore preserved. In the
mysterious
function, the value of
k
does
not change and denote a cell array. Here, we use function
swap3
that
allows one to exchange the contents of two array cells. At the first loop
round, we exchange an array cell with itself. Then, we successively
exchange the contents of the cell with the contents of the following
Search WWH ::
Custom Search