/* nag_rand_init_nonrepeatable (g05kgc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */
/* Pre-processor includes */
#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg05.h>

int main(void)
{
  /* Integer scalar and array declarations */
  Integer exit_status = 0;
  Integer i, lstate, same;
  Integer *state = 0, *x1 = 0, *x2 = 0;
  /* NAG structures */
  NagError fail;
  /* Set the sample size */
  Integer n = 500;
  /* Choose the base generator */
  Nag_BaseRNG genid = Nag_MersenneTwister;
  Integer subid = 0;

  /* Initialize the error structure */
  INIT_FAIL(fail);

  printf("nag_rand_init_nonrepeatable (g05kgc) Example Program Results\n\n");

  /* Get the length of the state array */
  lstate = -1;
  nag_rand_init_nonrepeatable(genid, subid, state, &lstate, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_init_nonrepeatable (g05kgc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Allocate arrays */
  if (!(x1 = NAG_ALLOC(n, Integer)) ||
      !(x2 = NAG_ALLOC(n, Integer)) ||
      !(state = NAG_ALLOC(lstate, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Initialize the generator to a non-repeatable sequence */
  nag_rand_init_nonrepeatable(genid, subid, state, &lstate, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_init_nonrepeatable (g05kgc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Generate a sample of values from a discrete uniform distribution */
  nag_rand_discrete_uniform(n, -100, 100, state, x1, &fail);

  /* Re-initialize the generator to another non-repeatable sequence
     NB: In practice, in order to preserve its statistical properties,
     you should only initialize the RNG generators once */
  nag_rand_init_nonrepeatable(genid, subid, state, &lstate, &fail);

  /* Generate a second sample of values from the same distribution */
  nag_rand_discrete_uniform(n, -100, 100, state, x2, &fail);

  /* Check that the two samples are different */
  same = 1;
  for (i = 0; i < n; i++) {
    if (x1[i] != x2[i]) {
      same = 0;
      break;
    }
  }
  if (same) {
    printf("The two samples are the same\n");
    printf("whilst this is possible, it is unlikely\n");
  } else {
    printf("The two samples differ, as expected\n");
  }

END:
  NAG_FREE(x1);
  NAG_FREE(x2);
  NAG_FREE(state);

  return exit_status;
}