2

I try to return the Y array from the second loop. I expect it to be (n - [k + 2]) length but I get output of n length array

a1q1 <- function (n , j , k , m, X0) {
  X <- numeric(length=n)
  Xn <- X0
  for (i in 1:n) {
    Xn <- (103515245*Xn + 12345) %% 2^32
    X[i] <- Xn
  }
  Y <- numeric(length=n - k - 1)
  for (i in k + 2:n) {
    Y[i - k - 1] <- (X[i - j] + X[i - k]) %% m
  }
  return (Y)
}

Z <- a1q1(100, 5, 90, 11, 0)
Z
# [1]  6  5  8  3  1 10  1  1  9  6  2  2  5  7 NA NA NA NA NA NA NA NA NA NA NA NA
# [27] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
# [53] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
# [79] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
user20650
  • 24,654
  • 5
  • 56
  • 91

2 Answers2

2

This often catches me too. You need to put parentheses around k+2, in the second for loop.. Try this minor adjustment below:

  for (i in (k+2):n) {
    Y[i-k-1] <- (X[i-j] + X[i-k]) %% m
  }
langtang
  • 22,248
  • 1
  • 12
  • 27
1

@langtang has shown what you need to do.

The problem is operator precedence:

> 1+2:3
[1] 3 4

Here we are saying "add 1 to the sequence 2:3"

> (1+2):3
[1] 3

And here we are saying "create a sequence from 1+2 to 3".

Even when you don't need to use parentheses it is often a good idea to do so. Judicious use makes the code easier to read. So for example if the intention was to actually use 1+2:3 it would be better to write 1+(2:3). In this way it quite obvious what is going on:

(1+2):3

vs

1+(2:3)
Robert Long
  • 5,722
  • 5
  • 29
  • 50