How to define a function in Swift without running it - swift

Starting from the Simple C program found here on stackoverflow, I've done it again in Swift and here's the code:
import Foundation
// variables and constants:
var dice1, dice2: UInt32
var score, scoreToWin, diceSum: Int
dice1 = 0
dice2 = 0
diceSum = 0
// functions:
func rollDice() ->Int {
dice1 = arc4random() % 6 + 1
dice2 = arc4random() % 6 + 1
diceSum = Int(dice1 + dice2)
println("\(diceSum)")
return diceSum
}
// main:
score = rollDice()
println("\(dice1) \(dice2) \(score)")
switch score {
case 7, 11:
println("score=\(score)\nYou WIN")
case 2, 3, 12:
println("score=\(score)\nYou LOOSE")
default:
println("You have to roll a \(score) to WIN")
do {
scoreToWin = score
diceSum = rollDice()
if diceSum == 7 { println("You LOOSE") }
else if diceSum == scoreToWin { println("You WIN") }
} while (diceSum != scoreToWin && diceSum != 7)
}
This is a possible output:
6
3 3 6
You have to roll a 6 to WIN
6
You WIN
Program ended with exit 0
I was not expecting the first line of output, because the first line indicate the function rollDice() was run while been defined.
How can I define a function without actually running it?

score = rollDice() would print the 6 you are seeing due to the println("\(diceSum)") you are doing in the rollDice method.
Declaring a method does not run it. Not in swift, nor in any other language I can think of.

Related

display the even numbers from 1 to 500 using a while loop and the break keyword in swift

My question is as on the title. I'm trying to print even numbers from 1 to 500 suing a while loop and break keyword. Below is my best possible answer I can think of, but this only print number 2. I've been spending hours but I wasn't able to solve it.
var number = 0
while true{
number += 2
print(number)
if number % 2 == 0 && number <= 500 {
break
}
}
You can use Stride
for evenNumber in stride(from: 0, through: 500, by: 2) {
print(evenNumber)
}
To specifically do this with while and break:
var i = 0
while true {
print(i)
i += 2
if i > 500 {
break
}
}
for i in 0...500 {
if i % 2 == 0 {
print(i)
}
}
Use below code
var numbers = 0...500
for number in numbers {
if number % 2 == 0 {
print(number)
}
}
I think it's easier to use build-in stride
let arr = Array(stride(from: 0, to: 502, by: 2))
print(arr)
//
For manually
var counter = 0
var arr = [Int]()
while counter <= 500 {
if counter % 2 == 0 {
print(counter)
arr.append(counter)
}
counter += 1
}
var number = 0
while true {
number += 2
print(number)
// ↓ Your code goes here ↓
if number > 499 {
break
}
}

Identify prime number

For some reason, it always gave me the wrong result. It's always isItPrime = true no matter what number was assigned to the "number" variable.
This is my code:
let number = 6
var i = 1
var isItPrime: Bool?
while i < number {
if number % i == 0 {
isItPrime = false
} else {
isItPrime = true
}
i += 1
}
print(isItPrime)
Can somebody explain to me what's wrong with my code and why the isItPrime bool outputs always true ?
Problem 1
The last iteration of your while loop
while i < number {
if number % i == 0 {
isItPrime = false
} else {
isItPrime = true
}
i += 1
}
does overwrite the result.
So you always end up with the following result
if number % (number-1) == 0 {
isItPrime = false
} else {
isItPrime = true
}
Problem 2
Finally every number can be divided by 1, so you should start i from 2.
So
let number = 6
var i = 2
var isItPrime = true
while i < number {
if number % i == 0 {
isItPrime = false
break
}
}
print(isItPrime)
Refactoring
You can write a similar logic using Functional Programming
let number = 5
let upperLimit = Int(Double(number).squareRoot())
let isPrime = !(2...upperLimit).contains { number % $0 == 0 }
Because isItPrime is overwritten in subsequent iterations, the last number which is checked, which is number - 1 will always set isItPrime to true, because number and number - 1 are coprime.
Instead of saving the value to a boolean, just end the loop when you found out that the number is not a prime:
let number = 6
var isItPrime: Bool = true
for i in 2 ..< number {
if number % i == 0 {
isItPrime = false
break // end the loop, as we know that the number is not a prime.
}
}
print(isItPrime)
When dealing with problems like this, don't be afraid to take out a piece of paper and manually see what is going on in your loop.
Your loop will go from i = 1 to number = 5 (because of the < operator.
With that in mind, we perform each iteration manually.
for i = 1, number = 6
6 mod 1 = 0, isItPrime = false
for i = 2, number = 6
6 mod 2 = 0, isItPrime = false
for i = 3, number = 6
6 mod 3 = 0, isItPrime = false
for i = 4, number = 6
6 mod 4 = 2, isItPrime = true
Last iteration of the loop, for i = 5, number = 6
6 mod 5 = 1, isItPrime = true
There we can see that the problem is that the last iteration will always have a module of 1, therefore resulting in in your else clause getting executed.
It is always returning true because your while loop isn't working the way you want. Currently, it loops until i is 1 less than number. During that final run through the loop, number % i == 0 is false, so your code sets isItPrime to true.
To fix this problem, try this code:
let number = 6
var i = 2
var isItPrime: Bool?
while (i < number || isItPrime == false) {
if number % i == 0 {
isItPrime = false
} else {
isItPrime = true
}
i += 1
}
print(isItPrime)
You may have noticed I set i to 2, because any number modulo (%) 1 is 0
I think it's worth pointing out, however, that:
You should probably make this a method
If you initially set isItPrime to true, you can dispense with the else part of your if-else statement
Hope this helps!
// MARK: - Function
func primeNo(_ num:Int,_ divisor :Int = 2){
if divisor == num{
print("Num is prime")
}else{
if num%divisor != 0{
primeNo(num, divisor + 1)
}else{
print("num is not prime")
}
}
}
// MARK: - Use
primeNo(6)
out Put
num is not prime

Sum of Printed For Loop in Swift

For a project, I'm trying to find the sum of the multiples of both 3 and 5 under 10,000 using Swift. Insert NoobJokes.
Printing the multiples of both 3 and 5 was fairly easy using a ForLoop, but I'm wondering how I can..."sum" all of the items that I printed.
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
print(i)
}
}
(468 individual numbers printed; how can they be summed?)
Just a little walk through about the process. First you will need a variable which can hold the value of your sum, whenever loop will get execute. You can define an optional variable of type Int or initialize it with a default value same as I have done in the first line. Every time the loop will execute, i which is either multiple of 3 or 5 will be added to the totalSum and after last iteration you ll get your result.
var totalSum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0
{
print(i)
totalSum = totalSum + i
}
}
print (totalSum)
In Swift you can do it without a repeat loop:
let numberOfDivisiblesBy3And5 = (0...10000).filter{ $0 % 3 == 0 || $0 % 5 == 0 }.count
Or to get the sum of the items:
let sumOfDivisiblesBy3And5 = (0...10000).filter{ $0 % 3 == 0 || $0 % 5 == 0 }.reduce(0, {$0 + $1})
range : to specify the range of numbers for operation to act on.
here we are using filter method to filter out numbers that are multiple of 3 and 5 and then sum the filtered values.
(reduce(0,+) does the job)
let sum = (3...n).filter({($0 % 3) * ($0 % 5) == 0}).reduce(0,+)
You just need to sum the resulting i like below
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum = sum + i
print(i)
}
}
Now sum contains the Sum of the values
Try this:
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum = sum + i
print(i)
}
}
print(sum)
In the Bottom line, this should to be working.
var sum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0 {
sum += i
print(i)
}
}
print(sum)

How to find all numbers divisible by another number in swift?

How do I find all the numbers divisible by another number in swift that have a remainder of 0? This is a Fizzbuzz related question.
Lets say that...
let number = 150
And I want to do something like...
print("Fizz") // for all the numbers where the remainder of number % 3 == 0.
So if number was 15, it would print "Fizz" 5 times.
This will work
let number = 150
for num in 1...number {
if num % 3 == 0 {
print("Fizz :\(num)")
}
}
you can just loop through the number and check with your desired divisible number if the remainder is 0 then print fizz
let number = 15
for i in 0..<number {
if i % 3 == 0 {
print("\(i) Fizz")
}
}
It will print Fizz 5 times with the i value, that which number is Fizz.
Simply try this code: (You can simply replace num with any Int number and divider that is also an Int value which is used to divide all numbers till num. )
override func viewDidLoad() {
let num:Int = 15
let divider:Int = 3
var counter:Int = divider
while counter <= num {
print("Fizz")
counter += divider
}
}
func fizzbuzz(number: Int) -> String {
if number % 3 == 0 && number % 5 == 0 {
return "Fizz Buzz"
} else if number % 3 == 0 {
return "Fizz"
} else if number % 5 == 0 {
return "Buzz"
} else {
return String(number)
}
}
https://www.hackingwithswift.com/guide/ios-classic/1/3/challenge

Refactor for-loop statement to swift 3.0

I have following line in my code:
for (i = 0, j = count - 1; i < count; j = i++)
Can anyone help to remove the two compiler warnings, that i++ will be removed in Swift 3.0 and C-style for statement is depreciated?
You could use this:
var j = count-1
for i in 0..<count {
defer { j = i } // This will keep the cycle "logic" all together, similarly to "j = i++"
// Cycle body
}
EDIT
As #t0rst noted, be careful using defer, since it will be executed no matter how its enclosing scope is exited, so it isn't a 100% replacement.
So while the standard for ( forInit ; forTest ; forNext ) { … } will not execute forNext in case of a break statement inside the cycle, a return or an exception, the defer will.
Read here for more
Alternatively, lets go crazy to avoid having to declare j as external to the loop scope!
Snippet 1
let count = 10
for (i, j) in [count-1..<count, 0..<count-1].flatten().enumerate() {
print(i, j)
}
/* 0 9
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8 */
Snippet 2
for (i, j) in (-1..<count-1).map({ $0 < 0 ? count-1 : $0 }).enumerate() {
print(i, j)
}
Trying to win the prize for the craziest solution in this thread
Snippet 1
extension Int {
func j(count:Int) -> Int {
return (self + count - 1) % count
}
}
for i in 0..<count {
print(i, i.j(count))
}
Snippet 2
let count = 10
let iList = 0..<count
let jList = iList.map { ($0 + count - 1) % count }
zip(iList, jList).forEach { (i, j) in
print(i, j)
}
You could use a helper function to abstract away the wrapping of j as:
func go(count: Int, block: (Int, Int) -> ()) {
if count < 1 { return }
block(0, count - 1)
for i in 1 ..< count {
block(i, i - 1)
}
}