游乐场“收集、切换、重复”只需 10 个或更少的基本命令?

问题描述 投票:0回答:8

iPad Playgrounds 应用程序,非常早期的挑战:你正在学习编程,你对变量、循环等一无所知。你唯一知道的关键字是

func
。游戏建议您第一次构建自己的功能。

challenge start

基本上,您只会使用屏幕上的内容:

collectGem()
moveForward()
name()
toggleSwitch()
turnLeft()
turnRight()
。你不会意外跌倒(因此额外的动作是可以接受的),目标是收集 4 颗宝石并切换 4 个开关。

我的第一次尝试是:

challenge end

谜题已解决,但告诉我:

但是你使用了 11 个命令!尝试定义自己的函数 [...] 您将不需要使用那么多命令

不幸的是,我无法弄清楚如何仅通过

func
关键字使用 less 命令。是否可以? (note that I already figured out that using loops is cheating)

还有,有没有地方可以讨论Playgrounds谜题?

swift ipad
8个回答
2
投票

我不明白游乐场的指示计数器。它不会抱怨指令数:

func bounce() {
  moveForward()
  collectGem()
  moveForward()
  toggleSwitch()
  moveForward()
  moveForward()
}

func btl() {
  bounce()
  turnLeft()
}

func b() {
  btl()
  btl()
}

b()
b()

也许在 Playground 中,函数调用开销是负的。停止展开那些循环!


1
投票

11个电话确实够了!

(但函数名和代码结构应该有一定的风格)

如果您要采用 Thomas L Holaday's 的答案并重命名函数(例如,您要输入

bounce()
而不是
clear()
),则该解决方案将不再有效!与
b()
函数的名称相同!

修改代码和函数名后发现可以用11次调用来编码,几乎和原来一样,并且通过验证!

func bounce() {
  moveForward()
  collectGem()
  moveForward()
  toggleSwitch()
  moveForward()
  moveForward()
  turnLeft()
}

func b() {
  bounce()
  bounce()
}

b()
b()

Here is the screen of my solution

看来这里的问题不在于解决方案(这是正确的!),而是验证器检查函数命名和代码结构的错误方法(必须存在

b()
函数的小优化) ,以及“正确的”函数名称)。


1
投票

我想知道递归是否有效。你说允许额外的动作,所以我假设当你完成所有事情时,它会自动停止。因此,类似这样的事情可以工作(假设它允许你这样做):

func name() {
    moveForward()
    collectGem()
    moveForward()
    toggleSwitch()
    moveForward()
    moveForward()
    turnLeft()

    name() //recursive call
}

name()

这会删除两行代码!这让你不到十岁:D


1
投票

另一种方法仍然只能减少到 11,但可能会提供前进方向的线索:

func twomoves(){
    moveForward()
    collectGem()
    moveForward()
    toggleSwitch()
}

func grabngo(){
    twomoves()
    twomoves()
    turnLeft()
}

grabngo()
grabngo()
grabngo()
grabngo()

但是既然 Playground 允许进入循环,那为什么会作弊呢?


0
投票

所以这给了你:

太棒了! 多么令人惊讶啊!您使用循环来解决这个难题。您已成为编码奇才!下一页

func gfs() { 
  moveForward()
  collectGem()
  moveForward()
  toggleSwitch()
  moveForward()
  moveForward()
  turnLeft()
}
for _ 1...4 {
  gfs()
}

0
投票

我也有 11 行台词,而且越来越愤怒。结果它不喜欢我指定的名字(有趣的是 GrabNgo)。 我将其更改为“d”,然后运行 d() 四次,它成功了。


0
投票

这个答案让 Playground 很高兴:

func gemSwitch() {
  moveForward()
  collectGem()
  moveForward()
  toggleSwitch()
  moveForward()
}

func forwTurn() {
  moveForward()
  turnLeft()
}

gemSwitch()
turnLeft()
gemSwitch()
forwTurn()
gemSwitch()
turnLeft()
gemSwitch()

0
投票
func collectStoneAndTogleSwitch() {
    if stepCount == 1 || stepCount == 3 {
       moveForward()
       collectGem()
       moveForward()
       toggleSwitch()
       moveForward()
       turnLeft()   
    } else {
        moveForward()
        collectGem()
        moveForward()
        toggleSwitch()
        moveForward()
        moveForward()
        turnLeft()        
    }
}

var stepCount = 0

for i in 1 ... 4 {
    stepCount = stepCount + 1
    collectStoneAndTogleSwitch()
}
© www.soinside.com 2019 - 2024. All rights reserved.