使用较少的代码进行脑筋急转弯 [英] Using less code for brain teaser

查看:141
本文介绍了使用较少的代码进行脑筋急转弯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试编码的R问题的小脑筋急转弯。

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

让我们说你桌上有15根蜡烛。根据蜡烛是否已经点亮,您可以在三个不同的回合中点亮给定的蜡烛或将它们放出。因此,如果给定的蜡烛已经点亮,那么你的行动就是把它拿出来。另一方面,如果蜡烛没有点亮,那么你的动作就是点亮它。

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.

最初没有蜡烛点亮。

首先,你会点亮每一秒蜡烛,所以蜡烛数字2到14。

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.

我能用三种不同的if语句手动解决这个问题,但我我想用更少的代码来做。关于我如何做的任何建议?

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?

推荐答案

这似乎有效。

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

谢谢Gregor建议对代码进行一些简化

Thanks, Gregor, for suggesting some simplifications to the code

这篇关于使用较少的代码进行脑筋急转弯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆