Difference between revisions of "W1349 Higher Order Functions"

From Coder Merlin
Line 397: Line 397:
+ B
+ B
+ C
+ C
- D
{
Professor Snape received a new shipment of ingredients and is now sorting them onto three separate shelves. (It's very important that these ingredients not be too close to one another so as not to adversely affect their magical properties.) The first shelf is for ingredients containing blood, the second shelf is for ingredients containing hair, and the third shelf is for ingredients containing eyes. Professor Snape knows that one way to sort these ingredients is as follows:
<syntaxhighlight lang="swift">
    let ingredients = ["asian dragon hair", "beetle eye", "boomslang skin", "chizpurfle fang", "dragon blood",
                      "eel eye", "eye of newt", "frog brain", "griffin claw", "horse hair", "nagini's venom",
                      "re'em blood", "runespoor fang", "salamander blood", "toe of frog", "tongue of dog",
                      "unicorn blood", "unicorn hair"]
    let containsBlood = {(ingredient:String) -> Bool in ingredient.contains("blood")} //
    let containsHair  = {(ingredient:String) -> Bool in ingredient.contains("hair")}  //
    let containsEye  = {(ingredient:String) -> Bool in ingredient.contains("eye")}  //
    var bloodIngredients = ingredients.filter(containsBlood)
    var hairIngredients  = ingredients.filter(containsHair)
    var eyeIngredients  = ingredients.filter(containsEye)
</syntaxhighlight>
Which of the following produce identical results?<br/>
'''A'''
<syntaxhighlight lang="swift">
    var bloodIngredients = ingredients.filter {$0.contains("blood")} //
    var hairIngredients  = ingredients.filter {$0.contains("hair")}  //
    var eyeIngredients  = ingredients.filter {$0.contains("eye")}  //
</syntaxhighlight>
'''B'''
<syntaxhighlight lang="swift">
    var bloodIngredients = ingredients.map {$0.contains("blood")}    //
    var hairIngredients  = ingredients.map {$0.contains("hair")}    //
    var eyeIngredients  = ingredients.map {$0.contains("eye")}      //
</syntaxhighlight>
'''C'''
<syntaxhighlight lang="swift">
    var bloodIngredients = ingredients.reduce {$0.contains("blood")} //
    var hairIngredients  = ingredients.reduce {$0.contains("hair")}  //
    var eyeIngredients  = ingredients.reduce {$0.contains("eye")}  //
</syntaxhighlight>
'''D'''
<syntaxhighlight lang="swift">
    var bloodIngredients = ingredients.filter {$1.contains("blood")} //
    var hairIngredients  = ingredients.filter {$1.contains("hair")}  //
    var eyeIngredients  = ingredients.filter {$1.contains("eye")}  //
</syntaxhighlight>
|type="[]"}
+ A
- B
- C
- D
- D


</quiz>
</quiz>

Revision as of 15:04, 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.

1 Consider the following code:

let x = ["apple", "banana", "carrot", "dill", "eggplant"]
var y = [String]()
for e in x {
     y.append(e)
} //

Which of the following produce identical results?
A

    let x = ["apple", "banana", "carrot", "dill", "eggplant"]
    var y = x.map {$0} //

B

    let x = ["apple", "banana", "carrot", "dill", "eggplant"]
    var y = [String]()
    for i in 0 ..< x.count {
        y.append(x[i])
    } //

C

    let x = ["apple", "banana", "carrot", "dill", "eggplant"]
    var y = [String]()
    for i in stride(from:0, to:x.count, by:1) {
        y.append(x[i])
    } //

D

    let x = ["apple", "banana", "carrot", "dill", "eggplant"]
    var y = [String]()
    for i in stride(from:0, through:x.count-1, by:1) {
        y.append(x[i])
    } //

A
B
C
D

2 Consider the following code:

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    let f = {(accumulator:Double, currentElement:Int) -> Double in
        return accumulator - Double(currentElement)} //
    var y = x.reduce(0.0, f)

Which of the following produce identical results?
A

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    let f = {(accumulator:Double, currentElement:Int) -> Double in
        return accumulator + Double(-currentElement)} //
    var y = x.reduce(0.0, f)

B

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    var y = x.reduce(0.0, {$0 - Double($1)})

C

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    var y = x.reduce(0.0) {$0 - Double($1)} //

D

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    var y = x.reduce(0.0) {Double(-$1) + $0} //

A
B
C
D

3 Consider the following code:

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    for i in stride(from:x.count-1, to:0, by:-2) {
        print(x[i])
    } //

Which of the following produce identical results?
A

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    var isOther = true
    for i in stride(from:x.count-1, to:0, by:-1) {
        if (isOther) {
            print(x[i])
        } //
        isOther = !isOther
    } //

B

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    var index = x.count - 1
    repeat {
        print(x[index])
        index -= 2
    } while (index >= 0)

C

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    var index = x.count - 1
    while index >= 0 {
        print(x[index])
        index -= 2
    } //

D

    let x = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    var index = x.count - 1
    var isOther = true
    while index >= 0 {
        if (isOther) {
            print(x[index])
        } //
        index -= 1
        isOther = !isOther
    } //

A
B
C
D

4 Consider the following code:

    let x = [45, 92, 95, 1014, 25, 83, 17, 19, 35]                                                                                                                                                                
    let y = x.map {$0 * 2}.filter {$0 % 5 == 0}.reduce(0, +)

Which of the following produce identical results?
A

    let x = [45, 92, 95, 1014, 25, 83, 17, 19, 35]
    let f1 = {(n:Int) -> Int  in return n * 2} //
    let f2 = {(n:Int) -> Bool in return n % 5 == 0} //
    let f3 = {(sum:Int, element:Int) -> Int in return sum + element} //
    let y = x.map(f1).filter(f2).reduce(0, f3)

B

    let x = [45, 92, 95, 1014, 25, 83, 17, 19, 35]
    var y = 0
    for e in x {
        let e2 = e * 2
        if e2 % 5 == 0 {
            y += e2
        } //
    } //

C

   let x = [45, 92, 95, 1014, 25, 83, 17, 19, 35]
    var y = 0
    for i in 0 ..< x.count {
        let e = x[i]
        let e2 = e * 2
        if e2 % 5 == 0 {
            y += e2
        } //
    } //

D

    let x = [45, 92, 95, 1014, 25, 83, 17, 19, 35]
    let f1 = {(n:Int) -> Int  in return n * 2} //
    let f2 = {(n:Int) -> Bool in return n % 5 == 0} //
    var y = 0
    for i in stride(from:x.count-1, through:0, by:-1) {
        let e2 = f1(x[i])
        if f2(e2) {
            y += e2
        } //
    } //

A
B
C
D

5 Professor Snape needs to preserve the order of the following ingredients but include only those that begin with the letter "F". He knows that one way of doing this is as follows:

    let ingredients = ["bat spleen", "beetle eye", "dragon blood", "eel eye", "foxglove", "frog brain", "griffin claw"]
    let startsWithF = {(string:String) -> Bool in string.starts(with:"f")} //
    let fIngredients = ingredients.filter(startsWithF)

Which of the following produce identical results?
A

    var fIngredients = [String]()
    for i in 0 ..< ingredients.count {
        if ingredients[i].starts(with:"f") {
            fIngredients.append(ingredients[i])
        } //
    } //

B

    var fIngredients = [String]()
    for i in stride(from:0, to:ingredients.count, by: 1) {
        if ingredients[i].starts(with:"f") {
            fIngredients.append(ingredients[i])
        } //
    } //

C

    var fIngredients = [String]()
    for i in stride(from:0, through:ingredients.count, by: 1) {
        if ingredients[i].starts(with:"f") {
            fIngredients.append(ingredients[i])
        } //
    } //

D

   var fIngredients = [String]()
    for i in stride(from:ingredients.count-1, through:0, by: -1) {
        if ingredients[i].starts(with:"f") {
            fIngredients.append(ingredients[i])
        } //
    } //

A
B
C
D

6 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:

    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")
     } //

Which of the following produce identical results?
A

    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")
    } //

B

    var ingredientsFollowingEye = [String]()
    for i in stride(from:1, to:ingredients.count, by: 1) {
        if ingredients[i-1].contains("eye") {
            ingredientsFollowingEye.append(ingredients[i])
        } //
    } //

C

 var ingredientsFollowingEye = [String]()
    for i in 1 ..< ingredients.count {
        if ingredients[i-1].contains("eye") {
            ingredientsFollowingEye.append(ingredients[i])
        } //
    } //

D

    var ingredientsFollowingEye = [String]()
    for i in 1 ... ingredients.count {
        let ingredient = ingredients[i]
        if ingredients[i-1].contains("eye") {
            ingredientsFollowingEye.append(ingredient)
        } //
    } //

A
B
C
D

7 Bubotuber pus is the liquid found in the swellings of the magical Bubotuber plant. It is very valuable for its acne-ridding qualities. It is a thick, yellowish-green liquid and smells strongly of petrol. Combining two drops of Bubotuber pus increases the efficacy of all other ingredients by 159%. Professor Snape has an array of efficacies of several ingredients and he knows that he can calculate the new efficacies as follows:

    let efficacies = [124.3, 157.9, 2.4, 15.9, 108.8, 16.5, 74.3]
    let adjuster = {(originalEfficacy:Double) -> Double in return originalEfficacy * 1.59} //
    var adjustedEfficacies = efficacies.map(adjuster)

Which of the following produce identical results?
A

    var adjustedEfficacies = efficacies.map {$0 * 1.59} //

B

    var adjustedEfficacies = efficacies.map {$1 * 1.59} //

C

    var adjustedEfficacies = [Double]()
    for efficacy in efficacies {
        adjustedEfficacies.append(efficacy * 1.59)
    } //

D

    var adjustedEfficacies = [Double]()
    for i in 0 ..< efficacies.count {
        adjustedEfficacies.append(Double(i) * 1.59)
    } //

A
B
C
D

8 As is well known:

  • 17 sickles = 1 galleon
  • 29 knuts = 1 sickle

Professor Snape has a list of prices for potion ingredients in knuts and wants to convert these prices to fractional galleons and then determine the total price for all ingredients. He knows that one way to do this is:

    let pricesInKnuts = [498.0, 398.0, 943.0, 1094.0, 1523.0, 327.0, 105.0]
    let knutsPerSickle = 29.0
    let sicklesPerGalleon = 17.0
    var totalPriceInGalleons = 0.0
    for priceInKnuts in pricesInKnuts {
        let priceInSickles = priceInKnuts / knutsPerSickle
        let priceInGalleons = priceInSickles / sicklesPerGalleon
        totalPriceInGalleons += priceInGalleons
    } //

Which of the following produce identical results?
A

    var totalPriceInGalleons = 0.0
    for priceInKnuts in pricesInKnuts {
        totalPriceInGalleons += priceInKnuts / knutsPerSickle / sicklesPerGalleon
    } //

B

    var pricesInSickles = [Double]()
    for priceInKnuts in pricesInKnuts {
        pricesInSickles.append(priceInKnuts / knutsPerSickle)
    } //
    var pricesInGalleons = [Double]()
    for priceInSickles in pricesInSickles {
        pricesInGalleons.append(priceInSickles / sicklesPerGalleon)
    } //
    var totalPriceInGalleons = 0.0
    for priceInGalleons in pricesInGalleons {
        totalPriceInGalleons += priceInGalleons
    } //

C

    var totalPriceInGalleons = pricesInKnuts.map {$0 / knutsPerSickle}.map {$0 / sicklesPerGalleon}.reduce(0.0, +)

D

    var totalPriceInGalleons = pricesInKnuts.filter {$0 > knutsPerSickle}.filter {$0 > sicklesPerGalleon}.reduce(0.0, +)

A
B
C
D

9 Professor Snape received a new shipment of ingredients and is now sorting them onto three separate shelves. (It's very important that these ingredients not be too close to one another so as not to adversely affect their magical properties.) The first shelf is for ingredients containing blood, the second shelf is for ingredients containing hair, and the third shelf is for ingredients containing eyes. Professor Snape knows that one way to sort these ingredients is as follows:

    let ingredients = ["asian dragon hair", "beetle eye", "boomslang skin", "chizpurfle fang", "dragon blood",
                       "eel eye", "eye of newt", "frog brain", "griffin claw", "horse hair", "nagini's venom",
                       "re'em blood", "runespoor fang", "salamander blood", "toe of frog", "tongue of dog",
                       "unicorn blood", "unicorn hair"]

    let containsBlood = {(ingredient:String) -> Bool in ingredient.contains("blood")} //
    let containsHair  = {(ingredient:String) -> Bool in ingredient.contains("hair")}  //
    let containsEye   = {(ingredient:String) -> Bool in ingredient.contains("eye")}   //

    var bloodIngredients = ingredients.filter(containsBlood)
    var hairIngredients  = ingredients.filter(containsHair)
    var eyeIngredients   = ingredients.filter(containsEye)

Which of the following produce identical results?
A

    var bloodIngredients = ingredients.filter {$0.contains("blood")} //
    var hairIngredients  = ingredients.filter {$0.contains("hair")}  //
    var eyeIngredients   = ingredients.filter {$0.contains("eye")}   //

B

    var bloodIngredients = ingredients.map {$0.contains("blood")}    //
    var hairIngredients  = ingredients.map {$0.contains("hair")}     //
    var eyeIngredients   = ingredients.map {$0.contains("eye")}      //

C

     var bloodIngredients = ingredients.reduce {$0.contains("blood")} //
     var hairIngredients  = ingredients.reduce {$0.contains("hair")}  //
     var eyeIngredients   = ingredients.reduce {$0.contains("eye")}   //

D

     var bloodIngredients = ingredients.filter {$1.contains("blood")} //
     var hairIngredients  = ingredients.filter {$1.contains("hair")}  //
     var eyeIngredients   = ingredients.filter {$1.contains("eye")}   //

A
B
C
D