2

This is a little brain teaser of a R problem I trying to code.

Lets say you have 15 candles on a table. In three different rounds you will either light the given candles, or put them out, based on whether the candle is already lit or not. So if the given candle is already lit, then your action will be to put it out. On the other hand, if the candle is not lit, then your action will be to light it up.

Initially none of the candles are lit.

Firstly, you will light up every second candle, so candle number 2 till 14.

Secondly, you will light up/put out every third candle.

Lastly, you will light up/put out every fifth candle.

In the end I would like to know which candles are lit up.

I have created a data frame with the two variables. The number of candles, and a binary variable, stating whether the candle is lit or not.

I am able to solve this manually with three different if-statements, but I would like to do it with less code. Any suggestions on how I might do it?

  • Can you post your code? – Caio Sym Nov 08 '17 at 19:20
  • Why not share your if statements solution and your variable initialization to make this more [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). That way it doesn't take as much time to start from scratch. Are all candles green? – MrFlick Nov 08 '17 at 19:21

2 Answers2

5

This seems to work.

candles <- vector(mode="logical", length=15)

for(i in c(2,3,5)){
  candles[1:15 %% i == 0] <- !candles[1:15 %% i == 0]
}

which(candles)
## 2  3  4  5  8  9 14

Thanks, Gregor, for suggesting some simplifications to the code

Alex P
  • 1,574
  • 13
  • 28
4

Although @Alex has come up with a solution, another way (I think) would be to repeatedly take the symmetric differences of the sets:

sym_diff <- function(x, y) union(setdiff(x, y), setdiff(y, x))

set1 <- seq(2, 14, 2)
set2 <- seq(3, 15, 3)
set3 <- c(5, 10, 15)

sort(sym_diff(sym_diff(set1, set2), set3))

[1]  2  3  4  5  8  9 14

We could also make use of the %>% (pipe) operator from the magrittr package to make the code a bit cleaner and easier to understand:

library(magrittr) # load %>%
# use the %>% for cleaner code
set1 %>%
  sym_diff(set2) %>%
  sym_diff(set3) %>%
  sort()
[1]  2  3  4  5  8  9 14
bouncyball
  • 10,631
  • 19
  • 31