Bronze, Silver & Gold Challenges


#10

This was my solution, similar to yours but doesn’t matter how long array is
var toDoList = [put in as many strings as you like]
Let Count = toDoList.count. // gives how many instances
for i in 1…Count {
toDoList.append(toDoList[Count-i] //appends
toDoList.remove(at: (Count-i)// deletes the value
}
print(toDoList)

It works from the end of the array, appending each value to the end before deleting the original value.


#11

@kees
I had to do some digging but I found these other type properties. I couldn’t say which one Tiberius is using, but I was also wondering why reversed is in the Array documentation and not reverse. At least this gives me a sense of closure.

https://developer.apple.com/documentation/foundation/nsattributedstring.enumerationoptions/1414984-reverse

https://developer.apple.com/documentation/foundation/nsenumerationoptions/1395159-reverse

https://developer.apple.com/documentation/foundation/nsstring.enumerationoptions/1412250-reverse


#12

Here’s my gold solution. This safely unwraps the Optional Index, checking for nil first:

let optIndex = bucketList.index(of: “Fly hot air baloon to Fiji”)
if optIndex != nil {
let index = optIndex!
let newIndex = bucketList.index(index, offsetBy: 2)
print("(bucketList[newIndex])")
}
//Go on a walkabout in australia


#13

debcat, with optionals you’ll want to do your unwrapping with “if let” structures. Also checking if something != nil isn’t very swifty. So it would look something like (also note your spelling as your code would never run ;):

if let optIndex = bucketList.index(of: "Fly hot air balloon to Fiji") {
    let newIndex = bucketList.index(optIndex, offsetBy: 2)
    print("\(bucketList[newIndex])")
}

#14

Ok, thanks. Hard to shake my old C habits! Don’t know what you mean about spelling, this does run. What did I misspell?


#15

Balloon. also for the print, make sure you include the \ (or perhaps the forum just removed it), otherwise your string interpolation won’t work.


#16

Can someone help me? For the silver challenge I don’t get why if you do

var reversedArray = String
for item in toDoList {
reversedArray.insert(item, at: 0)
}
print(reversedArray) // [“Cross off finished items”, “Pay bills”, “Take out the garbage”]

It reverses the order? Doesn’t the loop go through the array and put “Take out garbage” as index 0?


#17

Each item in the toDoList is inserted at index 0 in reversedArray. As a result, the item that was at index 0 and all items that follow it before the insertion move into higher index positions.

reversedArray = []
insert item1, reversedArray = [item1]
insert item2, reversedArray = [item2, item1]
insert item3, reversedArray = [item3, item2, item1]
insert itemN, reversedArray = [itemN, ..., item3, item2, item1]


#18

hey thank you for sharing results! But i did not get this part of code.How this happens? How the insert method works here?

toDoList = ["Takeout garbage",
                "Pay bills",
                "Cross off finished items"]

for item in toDoList {
    toDoList.insert(item, at: 0)
    toDoList.remove(at: 3)
}

#19

I was really baffled by that as well, but it appears that the list of values for item is preset at the beginning of the loop, and is not affected by the changes made to toDoList within the loop. I added a print statement to print out the list contents each pass through the loop and got the following:

[“Take out the garbage”, “Take out the garbage”, “Pay bills”]
[“Pay bills”, “Take out the garbage”, “Take out the garbage”]
[“Cross off finished items”, “Pay bills”, “Take out the garbage”]

So even though “Cross off finished items” is no longer in the list after the first pass through, it winds up getting put back on the last pass.

However, I’d be reluctant to rely on this behavior. My version looks like this:

if toDoList.count > 1
{
    for index in 0...toDoList.count-2
    {
        var item = toDoList.removeLast()
        toDoList.insert(item, at: index)
    }
}

which maintains the list integrity each pass.


#20

// Silver Challenge - without creating a new variable or altering the array’s order

for item in toDoList.reversed() {
   print(item)
}

This preserves the original array, and space isn’t wasted by creating a new variable. This works if you simply want to see the reverse order of the array printed to the screen.


#21

My Bronze challenge idea. Uncomment the “toDoList.removeAll( )” to see different results:

var toDoList = ["Take out garbage", "Pay bills", "Cross off finished items"]

//toDoList.removeAll()

if toDoList.isEmpty {
    print("My to do list is empty.")
} else {
    if toDoList.count == 1 {
        print("I have one thing to do.")
    } else {
        print("I have \(toDoList.count) things to do.")
    }
}

#22

My Gold approach:

var bucketList = ["Climb Mt. Everest"]
var newItems = [
    "Fly hot air balloon to Fiji",
    "Watch the Lord of the Rings trilogy in one day",
    "Go on a walkabout",
    "Scuba dive in the Great Blue Hole",
    "Find a triple rainbow"
]

for item in newItems {
    bucketList.append(item)
}
bucketList.remove(at: 2)
bucketList
print(bucketList.count)
print(bucketList[0...2])
bucketList[2] += " in Australia"

var found: Int?
found = bucketList.index(of: "Fly hot air balloon to Fiji")

if let fijiIndex = found {
    print("The Fiji entry is at Array index position \(fijiIndex).")
    print("The array element that is two positions after the Fiji entry is: \(bucketList[fijiIndex + 2])")
}

#23

I’m a bit confused about your silver challenge using the for-in loop.

The way I interpreted it (obviously wrong):

  • set an empty array containing string values to the variable “reversedArray”
  • for elements in “toDoList” take the empty “reversedArray” and insert items (from toDoList) starting at 0 index and so on
  • reversedArray (the way I see it…again wrong) prints the exact same string as toDoList

Basically, could you explain how the function reversedArray.insert(item, at: 0) actually reverses the list?


#24

Not a problem! I think the part you’re getting confused on is the insert method. Let’s walk through the following example:

let numbers = [1,2,3]

for number in numbers {
    print(number)
}

So when you run that, it will print out 1,2,3. So the reversing magic is happening with the insert method. Consider the following:

let numbers = [1,2,3]
var reversedNumbers = [Int]()

for number in numbers {
    reversedNumbers.insert(number, at: 0)
    print(reversedNumbers)
    
}

When this runs you’ll see:
[1]
[2,1]
[3,2,1]

So when you use reversedNumbers.insert(number, at: 0) it means: "I’m going to insert this number at location 0, and the element that was 0, and everything else will be shifted to the right.

Let me know if that helps, or if you need further clarification!


#25

Thanks a lot I understand now.

Iterating through the for-in loop,

1st time- insert 1 at index 0 into the empty reversedNumbers array
2nd time- insert 2 at index 0 (shifting 1 to the right)
3rd time- insert 3 at index 0 (shifting 2 and 1 to the right)


#26

Here is my solution to the Gold Challenge:

var bucketList = ["Take out garbage", "Fly hot air balloon to Fiji", "Pay bills", "Cross off finished items"]

if let foundIndex = bucketList.index(of: "Fly hot air balloon to Fiji"),
  let twoPositionLaterIndex = bucketList.index(foundIndex, offsetBy: 2, limitedBy: bucketList.endIndex.advanced(by: -1)) {
  print(bucketList[twoPositionLaterIndex])
}

#28

For instance,There are many elements in an array,How do we know where it is in the first place,Letting the program find out for itself is the best way


#29
var bucketList = ["Climb Hill",
              "Watch the lord of the Rings trilogy in one day",
              "Go on a walkabout",
              "Scuba dive in great Blue Hole",
              "find a triple rainbow",
              "fly hot air balloon to Fiji",
              ];

let index = bucketList.index(of :“fly hot air balloon to Fiji”);
print(index!);


#30

Here’s what I came up with…

//Bronze
var toDoList = ["Take out garbage", "Pay Bills", "Cross off finished items"]
var reverseToDoList = [String]()
for i in toDoList {
    reverseToDoList.insert(i, at: 0)
}
print(reverseToDoList)

//Silver
toDoList.reverse()
print(toDoList)

//Gold
let findIndex = bucketList.firstIndex(of: "Fly hot air balloon to Fiji")
print(findIndex!)
let indexPlusTwo = findIndex! + 2
print(bucketList[indexPlusTwo])