Re: Randomly outputting an array




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

.



Relevant Pages

  • Re: Classes and subclasses
    ... The array of reals, I call rArray, is defined as ... type recData = packed record ...
    (alt.comp.lang.borland-delphi)
  • Re: newbie: array input
    ... Element in INTEGERarray constructor at is REAL ... Ian probably focused too narrowly on the error ... reals instead of converting the one real to an integer. ... There are times when a compact form for something is also the clearest ...
    (comp.lang.fortran)
  • Re: Optimizing a calculation over a series - clarifications
    ... 6-byte reals, but as I mentioned this is not trivial - using Delphi ... Are you using the CPU for type real? ... Clock: longint absolute $40:$6c; ... Consider having an array of that size, initialised to zero, for the ...
    (comp.lang.pascal.borland)
  • user-defined array type
    ... I'd like to define my own 'type' that is just a shorthand for making an ... array of reals of a certain dimension. ...
    (comp.lang.fortran)
  • Re: random generator for a given period
    ... On 2009-02-15 01:35:28 -0400, Andrei Alexandrescu ... array such that the same index is never visited more than once. ... The Wikipedia article on "random permutation" should get you started. ... The usual theory covers prime or prime power modulus only as these ...
    (sci.stat.math)