Hey, we're on the same day! I'll share my code here just to reduce clutter and I seriously know no one who cares about this.
I did two of these because I was really struggling with returns and errors and ended up doing extra research on them. I felt like I needed and still need practice.
I did this first using a command called guard that we hadn't learned yet, but it really made more sense to me. And I didn't know how to do the square root of numbers so I had to look up and research sqrt theory and found the easy one about subtracting consecutive numbers, and figured I could try to do that. I hadn't read any of the hints yet so I guess I was building something to take any number and then limited it to 10k per instructions.
enum RootError: Error {
case outOfBounds
case noRoot
case negative
}
func squareRoot(number: Int) throws -> Int {
guard number < 10000 else {
throw RootError.outOfBounds
}
guard number >= 0 else {
throw RootError.negative
}
var root = 0
var remainder = number
while remainder >= root {
root += 1
remainder -= 2 * root - 1
if remainder == 0 {
return root
}
}
throw RootError.noRoot
}
do {
let result = try squareRoot(number: 100)
print(result)
} catch RootError.noRoot {
print("number is not a perfect square")
} catch RootError.outOfBounds {
print("number is too big for my tiny brain")
} catch RootError.negative {
print("can't take the root of a negative")
}
catch {
print("other error")
//I wanted to put an error in for putting in some sort of character that wasn't an INT but I didn't know how and I was really feeling like a cheater who wasn't practicing the right things at this point.
}
Anyways, I kind of felt like that was cheating given all the extra research I did and looked at the hints to give me more direction based on what we learned, and I came up with this.
//establish enum of errors
enum PotentialError: Error {
case tooBig
}
//lets use a set and calculate all the various numbers times themselves between 1&10k. Use a set b/c its faster and I don't care about order.
var squares = Set<Int>()
func findAllSquares (number: Int) throws {
if number > 10000 || number < 1 {
throw PotentialError.tooBig
}
}
//calculate all the squares
//using if loop here for creating the set
for i in 1...100 {
let multiple = i * i
squares.insert(multiple)
if multiple == number {
print("the square root of \(number) is \(i)")
return
}
}
}
func getRoot() {
do {
try findAllSquares(number: 25)
} catch PotentialError.tooBig {
print("the number is too big or too small for my tiny brain")
} catch {
print("random error")
}
}
getRoot()
Anyways. I'm super happy with this one b/c I feel like it was more true to the assignment based on the material. I spent a day on this problem, which is probably way too long, but I am not yet a programmer and this really is the very beginning of my journey. I love the challenge and the way of thinking involved. I kind of wanted to try a different one but I need to move on.
Thanks for looking at my code.