Search code examples
randomfortranrandom-seed

Unique random numbers series in fortran


I have this problem in Fortran where I need to generate a sequence of random numbers (precisely, 729 random numbers between 1 and 1000) and to do I use the intrinsic function random_number().

The problem, of course, is that it returns pseudorandom numbers and it happens to often that I get same values repeated. I'm not an expert in programming with Fortran, but how can I get 729 unique random numbers without repetitions? Can someone help me?


Solution

  • This shows how you can in an inelegant way solve your problem.

    program p
       implicit none
       integer, parameter :: n = 10
       logical :: a(n) = .false.
       integer b(n), cnt
       real x
       cnt = 1
       do
          call random_number(x)
          b(cnt) = n * x + 1
          if (.not. a(b(cnt))) then
             if (b(cnt) > n) cycle
             a(b(cnt)) = .true.
             cnt = cnt + 1
             if (cnt > n) exit
          end if
       end do
       print '(*(1X,I0))', b
    end program p