1

In trying to understand the syntax behind while() commands in R, I come to a problem introducing two conditions. There is a post on the topic, but it doesn't seem to work.

The toy code is self-explanatory, and very simple:

> x = sample(c("Y", "M", "_"))
> y = sample(c("O", "U","E", "S", "H"))
> 
> while(paste(x, collapse ="") != "MY_") x = sample(x)
> paste(x, collapse = "")
[1] "MY_"
> 
> while(paste(y, collapse ="") != "HOUSE") y = sample(y)
> paste(y, collapse = "")
[1] "HOUSE"
> 
> while(paste(x, collapse ="") != "MY_" && paste(y, collapse ="") != "HOUSE") x = sample(x); y = sample(y)
> paste(c(x, y), collapse = "")
[1] "MY_OEHSU"

Wrong answer! The expected answer is "MY_HOUSE".

Why isn't && doing the trick?


Thanks to the comments below! If there is a formal answer I will erase this edit to credit where credit is due. Otherwise, and in case it helps other people, this is the correct code:

> x = sample(c("Y", "M", "_"))
> y = sample(c("O", "U","E", "S", "H"))
> 
> while(paste(x, collapse ="") != "MY_") x = sample(x)
> paste(x, collapse = "")
[1] "MY_"
> 
> while(paste(y, collapse ="") != "HOUSE") y = sample(y)
> paste(y, collapse = "")
[1] "HOUSE"
> 
> while(paste(x, collapse ="") != "MY_" || paste(y, collapse ="") != "HOUSE") {x = sample(x); y = sample(y)}
> paste(c(x, y), collapse = "")
[1] "MY_HOUSE"
Community
  • 1
  • 1
Antoni Parellada
  • 4,253
  • 6
  • 49
  • 114

0 Answers0