I am trying to write a for loop, where I have to increment exponentially. I am using stride function but it won't work.
Here's c++ code, I am trying to write a swift version.
for (int m = 1; m <= high - low; m = 2*m){}
can you help me, to write this code in swift version?
A while-loop is probably the simplest solution, but here is an alternative:
for m in sequence(first: 1, next: { 2 * $0 }).prefix(while: { $0 <= high - low }) {
print(m)
}
sequence() (lazily) generates the sequence 1, 2, 4, ..., and prefix(while:) limits that sequence to the given range.
A slight advantage of this approach is that m is only declared inside the loop (so that it cannot be used later accidentally), and that is is a constant so that it cannot be inadvertently modified inside the loop.
There is no for loop in Swift, but you can achieve the same result with basic while loop
var m = 1 // initializer
while m <= high - low { // condition
...
m *= 2 // iterator
}
Based on #MartinR answer, only improvement is readability of the call:
// Helper function declaration
func forgen<T>(
_ initial: T, // What we start with
_ condition: #escaping (T) throws -> Bool, // What to check on each iteration
_ change: #escaping (T) -> T?, // Change after each iteration
_ iteration: (T) throws -> Void // Where actual work happens
) rethrows
{
return try sequence(first: initial, next: change).prefix(while: condition).forEach(iteration)
}
// Usage:
forgen(1, { $0 <= high - low }, { 2 * $0 }) { m in
print(m)
}
// Almost like in C/C++ code
Here is a solution using for:
let n = Int(log(Double(high - low))/log(2.0))
var m = 1
for p in 1...n {
print("m =", m)
...
m = m << 1
}
(Supposing that high - low is greater than 2)
Related
This question already has answers here:
Calculate all permutations of a string in Swift
(10 answers)
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
note: stack overflow incorrectly marked this as duplicate after an answer (there is no built in) was already selected...linked question unrelated
What is the simplest built-in way to calculate num. combinations/permutations in Swift? Official Apple library?
(n C k)
python3.8:
math.comb(n,k)
(n P k)
python3.8:
math.perm(n,k)
Swift does not provide built-in functions for permutation, combination, or even factorial. But these simple formulas are easy to implement.
Here is a trivial factorial function:
func factorial(_ n: Int) -> Int {
return (1...n).reduce(1, { $0 * $1 })
}
But note that this will crash where n >= 21 since 21! is too large to fit in an Int variable.
Here is a naive implementation of "perm":
func perm(n: Int, k: Int) -> Int {
return factorial(n) / factorial(n - k)
}
And for "comb" you can do:
func comb(n: Int, k: Int) -> Int {
return perm(n: n, k: k) / factorial(k)
}
However, there is a simple improvement to be made for "perm". Let's say n = 5 and k = 2. You can write the formula for perm as:
n! = 5! = 5! = 1 * 2 * 3 * 4 * 5
------ ------ -- ----------------- = 4 * 5
(n-k)! = (5-2)! = 3! = 1 * 2 * 3
This boils down to "perm" being equal to (n-k+1) * (n-k+2) * ... n
So let's rewrite the functions to be more efficient:
func mult(_ range: ClosedRange<Int>) -> Int {
return range.reduce(1, { $0 * $1 })
}
func perm(n: Int, k: Int) -> Int {
return mult((n - k + 1)...n)
}
func comb(n : Int, k: Int) -> Int {
return perm(n: n, k: k) / mult(1...k)
}
Note that the "comb" function didn't actually change other than to use mult(1...k) instead of factorial(k) which both give the same result.
These functions still have limits on the sizes of n and k before they will crash due to the limits on the Int data type.
So i have code in xcode playground and got the error error in code
and this is the excercise i do
Return the Factorial
Create a function that takes an integer and returns the factorial of that integer. That is, the integer multiplied by all positive lower integers.
and this is my code
func factorial(_ num: Int) -> Int {
var result :Int = 0
for _ in num...1 {
result = num * (num - 1)
}
return result
}
print(factorial(12)) //error in this line
but in terminal got this output:
The answer is in the error message - the upper bound of the range has to be greater than or equal to the lower.
Therefore you'll need to rewrite the method differently. You also have a fundamental flaw in your code - your maths logic is wrong - result will be overwritten every time, rather than accumulating a total. Adopting a similar approach to the question you can do this:
func factorial(_ num: Int) -> Int {
var result :Int = 1
guard num > 0 else {return result}. //0! is 1 not 0
var num = num
while num > 0 {
result *= num
num -= 1
}
return result
}
There is a more elegant way of performing this using recursion, which avoids the ugly var num=num
func fac2(_ num: Int, total: Int = 1) -> Int {
return num > 0 ? fac2(num-1, total: total * num) : total
}
I understand how lazy variable works but I don't know how to implement properly.
Below is just an example:
func calculation() -> (firstValue: Float, secondValue: Float) {
var a: Float = 2
var b: Float = 2
for i in 1...1000 {
a = a + Float(i)
b = b + Float(i)
print(i)
}
return (a, b)
}
let m = calculation().firstValue
let n = calculation().secondValue
when I run it, the calculation function ran twice (1000 time + 1000 time), first time to get the value to m, and second time to get the value of n.
What I have to do to force the function Calculation to run just only not time and to store the value m and n without repeat the process twice.
The lazy keyword is used on the class/struct/enum member variables.
For your example, you can implement like this:
class Solution {
lazy var tuple: (firstValue: Float, secondValue: Float) = {
var a: Float = 2
var b: Float = 2
for i in 1...1000 {
a = a + Float(i)
b = b + Float(i)
print(i)
}
return (a, b)
}()
}
let s = Solution()
let m = s.tuple.firstValue
let n = s.tuple.firstValue
The tuple variable stores the value returned by the following closure which only runs once.
You can also use a variable to record the return value of the function.
let pair = calculation()
let m = pair.firstValue
let n = pair.secondValue
lazy is the keyword to delay the calculation till the result is first used, so it is not for your case.
You can write something like this:
let values = calculation()
let m: Float = values.firstValue
let n: Float = values.secondValue
Or this:
let (m, n) = calculation()
I see that Swift offers convenient syntax for declaring curried functions. The manual gives partial function application as an example of where curried function will come in handy.
Can someone give me an example where partial function application can be useful? I know this is a general functional programming concept, but an example in Swift would be most appreciated.
Suppose you frequently want to check a number, i, is a multiple of another value. What it might be a multiple of can change, but the rule for how to determine it is always the same: i % n == 0.
You might write a function like this:
func isMultipleOf(#n: Int, #i: Int) -> Bool {
return i % n == 0
}
isMultipleOf(n: 2, i: 3) // false
isMultipleOf(n: 2, i: 4) // true
However, perhaps you find yourself frequently wanting to use this function with other "high-order" functions – that is, functions that take other functions as arguments, such as map and filter:
let r = 1...10
// use isMultipleOf to filter out the even numbers
let evens = filter(r) { isMultipleOf(n: 2, i: $0) }
// evens is now [2,4,6,8,10]
That use of isMultipleOf looks a little clunky and hard to read, so maybe you define a new function, isEven, in terms of isMultipleOf to make it a bit clearer:
let isEven = { isMultipleOf(n: 2, i: $0) }
isEven(2) // true
isEven(3) // false
let evens = filter(r, isEven)
Now, suppose you declare isMultipleOf a little differently, as a curried function:
func isMultipleOf(#n: Int)(#i: Int) -> Bool {
return i % n == 0
}
isMultipleOf is now a function that takes a number, n, and returns a new function that takes a number and checks if it's a multiple of n.
You can now use it to declare isEven like this:
let isEven = isMultipleOf(n: 2)
Or you could use it directly with filter like this:
let evens = filter(r, isMultipleOf(n: 2))
// just like before, evens is [2,4,6,8,10]
I want to solve this
Write a function applyKTimes(f:(Float -> Float),x:Float,k:Int) -> Float
that takes a function f and a float x and applies f to x k times
for example the function f is
func square (number:Float) -> Float
{
return number * number
}
is there a short solution using Swift?
If you don't want to use recursion:
func applyKTimes(f:(Float -> Float), x: Float, k: Int) -> Float {
var result = x
for _ in 0..k {
result = f(result)
}
return result
}
A recursive solution:
func applyKTimes(f:(Float -> Float), x:Float, k:Int) -> Float
{
return k > 0 ? applyKTimes(f, f(x), k - 1) : x
}
I have not checked if Swift guarantees tail call optimization. If it does, than the recursive solution is what you really want. However if it does not you need to unroll it by hand to avoid problems with the stack.
The same, but unrolled by hand:
func applyKTimes(f:(Float -> Float), x:Float, k:Int) -> Float
{
var result = x
for _ in 0..k {
result = f(result)
}
return result
}