Difference between revisions of "W1349 Higher Order Functions"
From Coder Merlin
Line 248: | Line 248: | ||
+ B | + B | ||
- C | - C | ||
- D | |||
{ | |||
Professor Snape found an interesting pattern. Ingredients which are listed after another ingredient containing the word "eye" have special visibility properties. He knows that one way of finding these ingredients is as follows: | |||
<syntaxhighlight lang="swift"> | |||
let ingredients = ["bat spleen", "beetle eye", "dragon blood", "eel eye", "foxglove", "frog brain", "griffin claw"] | |||
var previousWasEye = false | |||
var ingredientsFollowingEye = [String]() | |||
for ingredient in ingredients { | |||
if previousWasEye { | |||
ingredientsFollowingEye.append(ingredient) | |||
} // | |||
previousWasEye = ingredient.contains("eye") | |||
} // | |||
</syntaxhighlight> | |||
Which of the following produce identical results?<br/> | |||
'''A''' | |||
<syntaxhighlight lang="swift"> | |||
var previousWasEye = false | |||
var ingredientsFollowingEye = [String]() | |||
for i in stride(from:0, to:ingredients.count, by: 1) { | |||
let ingredient = ingredients[i] | |||
if previousWasEye { | |||
ingredientsFollowingEye.append(ingredient) | |||
} // | |||
previousWasEye = ingredient.contains("eye") | |||
} // | |||
</syntaxhighlight> | |||
'''B''' | |||
<syntaxhighlight lang="swift"> | |||
var ingredientsFollowingEye = [String]() | |||
for i in stride(from:1, to:ingredients.count, by: 1) { | |||
if ingredients[i-1].contains("eye") { | |||
ingredientsFollowingEye.append(ingredients[i]) | |||
} // | |||
} // | |||
</syntaxhighlight> | |||
'''C''' | |||
<syntaxhighlight lang="swift"> | |||
var ingredientsFollowingEye = [String]() | |||
for i in 1 ..< ingredients.count { | |||
if ingredients[i-1].contains("eye") { | |||
ingredientsFollowingEye.append(ingredients[i]) | |||
} // | |||
} // | |||
</syntaxhighlight> | |||
'''D''' | |||
<syntaxhighlight lang="swift"> | |||
var ingredientsFollowingEye = [String]() | |||
for i in 1 ... ingredients.count { | |||
let ingredient = ingredients[i] | |||
if ingredients[i-1].contains("eye") { | |||
ingredientsFollowingEye.append(ingredient) | |||
} // | |||
} // | |||
</syntaxhighlight> | |||
|type="[]"} | |||
+ A | |||
+ B | |||
+ C | |||
- D | - D | ||
</quiz> | </quiz> |
Revision as of 14:48, 24 March 2019
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Exercises[edit]
Professor Snape needs your help to organize ingredients for a wide variety of potions. You'll need to verify blocks of code to ensure that they're doing exactly what Professor Snape needs. Be careful! Any mistakes can be hazardous to his health. In some cases, more than one answer will be correct.