Re: Randomly outputting an array
- From: "jon" <jon_d_r@xxxxxxx>
- Date: 14 Jul 2006 12:18:58 -0700
ryanarossi@xxxxxxxxx wrote:
What would be the simplest way to output an array in random order, but
every element in the array MUST be outputted and the elements cannot
repeat?
This describes a random permutation. You might google on that phrase.
Here is a Fortran 95 version. The intrinsic function RANDOM_NUMBER
returns a uniformly distributed pseudorandom real (single precision)
number in the range 0.0 <= r_Num <= 1.0, where "<=" here means "less
than or equal to". The intrinsic INT returns the integer value of its
argument without its fractional part (truncates, does NOT do "nearest
integer"). INT is generic and accepts any numeric input (e.g., converts
between types of integers, from reals and complex numbers of any kinds
to integer. The type specification "REAL (KIND(0D0)" here means double
precision (which simply means twice the precision of the default real
kind). You can rewrite it to work with any type array that you need.
SUBROUTINE permut(X, N)
IMPLICIT NONE
REAL (KIND(0D0)), INTENT(INOUT), DIMENSION(:) :: X
INTEGER, INTENT(IN) :: N
! Produce a random permutation of the numbers
! in the array x(n), overwriting the original array.
REAL (KIND(0.0)) :: r_Num
REAL (KIND(0D0)) :: z
INTEGER :: i, j, k
INTEGER :: Nm1
INTRINSIC :: INT, RANDOM_NUMBER
Nm1 = N - 1
DO i=1,Nm1
j = N - i + 1
CALL RANDOM_NUMBER(r_Num)
k = INT(j*r_Num) + 1
IF (k>j) k = j
IF (k>N) k = j
z = X(j)
X(j) = X(k)
X(k) = z
END DO
END SUBROUTINE permut
.
- References:
- Randomly outputting an array
- From: ryanarossi@xxxxxxxxx
- Randomly outputting an array
- Prev by Date: Re: virus makers and defense systems
- Next by Date: Re: What language for mathematical applications?
- Previous by thread: Re: Randomly outputting an array
- Next by thread: Re: Randomly outputting an array
- Index(es):
Relevant Pages
|