EDU Course Challenges 1
So I don't feel quite ready to resume Angela's course! No, I've had a look through the other Udemy courses I've purchased and have decided to test out the challenges from the EDU one. I just enjoyed the last few so much that I want to get stuck in and apply what I know before I go back to Angela's. OK here we go!
Start time - 20:39
Challenges for types etc.
Start time - 20:39
Challenges for types etc.
1. Type this code in a playground:
var num = 5
num.advancedBy(3)
What is the result? We talked about advancedBy in connection with String indices. What does this result tell you about these indices? Do the .successor() and .predecessor() methods also work with Ints? Does the .predecessor() work when num is 0?
I've never actually come across advancedBy before. It will be interesting to see if the latest Xcode even recognises it! So I assume the answer will be 8!
num.advanced(by: 3)
Indeed, the syntax has chosen since this EDU course. No bother, I fixed it easily and the answer was 8! For the next bit, I presume that the successor and predecessor methods and and take away 1 respectively. Presumably the latter will take 0 to -1...
Apparently not! Neither of these methods exist any more, or they never did.
2. Will the following code work? Why or why not? If not, how would you fix it?
var quantity = 17
let price = 4.95
let cost = quantity * price
The easy answer is no. I will need to convert the quantity to a double. Easy.
var quantity = 17
let price = 4.95
let cost = Double(quantity) * price
Done!
3. What is the difference between var and let?
Easy again. Var is variable; let is constant. Var is mutable, let is immutable.
4. Given the following declarations:
let name = "frog"
let action = "hop"
show two ways to print the string “I am a frog, and I hop.” using the name and action constants.
These would be concatenation and string interpolation...
print("I am a " + name + ", and I " + action + ".")
print("I am a \(name), and I \(action).")
Yes! Worked like a charm...
5. let frogName : String?
If frogName is later assigned the string “Benny” and printed using this code:
print("Hi, my name is \(frogName)")
what will be printed? Is this result desirable? If not, how should it be fixed?
Unfortunately what will be printed is 'optional' with frogName so we have to force unwrap it...
let frogName : String?
frogName = "Benny"
print("Hi, my name is \(frogName!)")
Not good doing this though but we KNEW that there was a definitely a value in frogName...
6. Given the String “ABCDE”, what is the most efficient way to extract the character “C”?
Hmm interesting. I would use a for in loop possibly...
var string = "ABCDE"
string.contains("C")
Not a loop but I've got a bool here. Will check the solution after!
7. Suppose, in your implementation of “FrogTracker 9000,” you want to track a frog's name, current lily pad, age, and weight in grams in a single variable type. Write a type definition that allows this
var frogTracker9000 = (name: "Steve", lilyPad: "Second on the left", age: 12, weightInGrame: 712)
No problem - a tuple used. Of course, I would never do this in practice and use a class instead! :)
Checking solutions....So the only one I didn't; get does not work with the given syntax oh well!
Next lot of challenges...
Challenges for arrays, loops etc.
1. Given the following array declaration:
let array = [1, 2, 3, 4, 5]
write a for, for-in, while, and repeat loop that prints each value of the array multiplied by 2. You will need to define another variable to use in the while and repeat loops. Why?
let array = [1, 2, 3, 4, 5]
write a for, for-in, while, and repeat loop that prints each value of the array multiplied by 2. You will need to define another variable to use in the while and repeat loops. Why?
let array = [1, 2, 3, 4, 5]
for x in array {
print(x * 2)
}
Now that is fine but I cannot figure out how to use while loops with arrays! Let me check online...
*Xcode being very....slow....time...being....wasted.........!
*Xcode working again (15 minutes lost at least!)
var index = 1
while index <= array.count {
print (index * 2)
index += 1
}
index = 0
repeat {
index += 1
print(index * 2)
} while index < array.count
Got them! Needed some help online initially but I got it. I needed to have the value of index (could have called it anything). Then I needed the count method...all good in the end!
2. Given your current understanding of arrays, how might we declare a two-dimensional array of Ints? (That is, an array of arrays of type Int? Give an example in code, and use it. Hint: each dimension of an array requires another set of square brackets. Try various combinations in a playground. Don't give up, you'll figure it out!
What on Earth?! I will try....
var intArray = [1, [1, 2, 3, 4, 5], 2, 3, 4, 5] as [Any]
Xcode offered this fix. Not sure if that's write.
for number in intArray {
print(number)
}
We'll see....
*Skipping the colour challenge - no idea!
3. Write a declaration for a variable named “errorCodes” that is a dictionary with Int keys and String values.
Should be easy...Done!
var errorCodes = [1: "Error1", 2: "Error2", 3: "Error3"]
4. Add the following error codes to your errorCodes dictionary:
1 : file not found
2 : divide by zero
3 : a horrible error has occurred
4 : entirely too many frogs
Simulate error 3 by printing the value for the key 3. Remember that the values of a dictionary are returned as optionals: I want the actual string here, not an optional.
let errorMessage = errorCodes[3]
print(errorMessage!)
Again, I've used forced unwrapping which is supposed toe avoided! I could do it a more long winded way....
if let message = errorCodes[3] {
print(message)
} else {
print("No error message found!")
}
This optional binding is much safer! I'm finally using optional stuff!
5. For each error code, print the actual code and the code number. For example, for error code 2, you might print “'divide by zero' has error code 2”. Use a loop to print all four error codes. Given that errorCodes is a collection type, what kind of loop should you use?
Right so a for in loop it is....
for (number, message) in errorCodes {
print("\(message) has error code \(number)")
}
Easy!
6. Write a for-in loop that prints “n is even” where n is an even number in a range given. The result of n % 2 is zero if the number is even. Only print even numbers. If the number is odd, don't print anything at all.
for n in 1...10 {
if n % 2 == 0 {
print(n)
}
}
Yes! Nailed it!
6. Write a loop that iterates over the range -4..<5. If the current number is 0, print “number is 0,” otherwise print “number is not 0.” Use a guard statement to trap the condition of number being 0.
for x in -4..<5 {
if x == 0 {
print("Number is 0")
} else {
print("Number is not 0")
}
}
I tried but couldn't get the guard statement to work - I thought that was for optionals anyway! Anyway, mine does work at least!
6. Write a switch statement in a for-in loop on the range 0...100. If the current number is in the range 0...30, print “low in the range.” If it's in the range 31...70, print “middle of the range,” and if it's above 70, print “high in the range.” There are many ways to do this: in your implementation, either use a range or a where clause in the case statements.
Last one! This should be fine!
Done!
for number in 0...100 {
switch number {
case 0...30:
print("Low in the range")
case 31...70:
print("Middle in the range")
case 71...100:
print("High in the range")
default:
print("Invalid number")
}
}
There we go! Now checking answers....
OK a few things....First of all, the while and repeat loops can be this simple:
var i = 0
// while loop
while i < 5 {
print(array[i] * 2)
i+=1
}
// repeat loop
i = 0
repeat {
print(array[i] * 2)
i+=1
} while i < 5
However, I really like my .count use, as if the array updated, the code is foolproof!
For the int in an int for the array (madness it sounds!) here's how that looks:
var multiply : [[Int]]
//give each element a value
multiply = [
[0, 0, 0, 0, 0],
[0, 1, 2, 3, 4],
[0, 2, 4, 6, 8],
[0, 3, 6, 9, 12],
[0, 4, 8, 12, 16]
]
//get products from the table
multiply[2][2]
multiply[4][2]
multiply[3][4]
I've never done this before so good to see something new! Interesting!
And this is the use of guard:
for n in -4 ..< 5 {
guard n != 0 else {
print("number is 0")
continue
}
print("number is not 0")
}
The syntax here shows that if n is not equal to nil, the else statement being the opposite for not the case. The use of continue I'm not too sure about.
For the switch statement, I did it with ranges - totally logical. Here's how it is with the where clauses - something I've never really used in practice before:
or n in 0...100 {
switch n {
case n where n <= 30:
print("low in the range")
case n where n > 30 && n <= 70:
print("middle of the range")
default:
print("high in the range")
}
}
So this is more wordy but it does mean I can cover things out of the range. That figures!
Finish time 22:19 (75 minutes approximately with all the delays!)
So, overall I did well with these challenges. Some were harder than others. But to go in, not seeing the lectures at all is great practice. Lots of useful things picked up here. For the next three challenges (Sections 4, 5 and 6), I think I will go through the key information - skim through where necessary before doing the challenges. I'm delaying going back to Angela's course, but I am finding it really useful to do more of this practical stuff. More tomorrow!
Comments
Post a Comment