Swift 3 generic type function to clamp numeric values into 0 and 1 interval - swift

I want to write a function that clamps a numeric value into the closed 0,1 interval:
func clamp01<T:???>(_ value:T) -> T {
return value < 0 ? 0 : value > 1 ? 1 : value
}
In Swift 3 if I use T:Strideable I get a complaint that 0 and 1 must be typecast (0 as! T resolves the issue, but it's a forced cast).
In Swift 4 I may be able to use T:Numeric but I haven't tried that -- I am looking for a solution in Swift 3.

You could define the function for all Comparable types which
are also ExpressibleByIntegerLiteral, that covers all integer
and floating point types:
func clamp01<T: Comparable & ExpressibleByIntegerLiteral>(_ value: T) -> T {
return value < 0 ? 0 : value > 1 ? 1 : value
}

Related

Nested function unexpected behaviour in Swift?

I was trying the following example for Nested functions but I am getting unexpected behaviour:
func chooseStepFunction(value: Int, backward: Bool) -> (Int) -> Int {
print("Current value: \(value)")
func stepForward(input: Int) -> Int {
print("plus from \(input)");
return input + 1
}
func stepBackward(input: Int) -> Int {
print("minus from \(input)");
return input - 1
}
return backward ? stepBackward : stepForward
}
var currentValue = 4
let moveNearerToZero = chooseStepFunction(value: currentValue, backward: currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != -2 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
I was trying with backward and forward nested function but getting the following result:
Current value: 4
4...
minus from 4
3...
minus from 3
2...
minus from 2
1...
minus from 1
0...
minus from 0
-1...
minus from -1
Like, Every time I am modifying the currentValue and every time I am calling the chooseStepFunction but in console the currentValue inside chooseStepFunction function is executing only once but the currentValue inside while loop is executing evrytime then why the chooseStepFunction is skipping printing the value. In my sense the expected result will be:
Current value: 4
4...
minus from 4
3...
minus from 3
2...
minus from 2
1...
minus from 1
0...
plus from 0
1...
minus from 1
0...
plus from 0
1...
minus from 1
0...
..........
which will be an infinite loop but why it's working fine?
I didn't understand at all?
This line:
let moveNearerToZero = chooseStepFunction(value: currentValue, backward: currentValue > 0)
Is only run once, since it is outside of the loop. So the branch backward ? stepBackward : stepForward is run only once. The code chose stepBackward once, and never again.
let someName = someExpression does not mean "from now on, every time I say someName, evaluate someExpression". It means "evaluate someExpression, and put the result into the constant called someName".
To achieve what you want, you can move the chooseStepFunction call into the loop:
while currentValue != -2 {
print("\(currentValue)... ")
let moveNearerToZero = chooseStepFunction(value: currentValue, backward: currentValue > 0)
currentValue = moveNearerToZero(currentValue)
}

How to normalize Integer variable to positive negative or zero with bit operations

7 -> 1
0 -> 0
-7 -> -1
I've have code:
(x == 0 ? 0 : x / abs(x)) + 1
but is it possible to avoid division and make it faster?
How about
(x == 0 ? 0 : (x < 0 ? -1 : 1))
The idea was to use bit operations to avoid branching code or value conversion.
Haven't found how to do it with bit operations but apple already add this function
https://developer.apple.com/documentation/swift/int/2886673-signum
signum()
Returns -1 if this value is negative and 1 if it’s positive; otherwise, 0.
so simple) raw test shows ~x100 faster implementation

Swift 3 for loop with increment

How do I write the following in Swift3?
for (f = first; f <= last; f += interval)
{
n += 1
}
This is my own attempt
for _ in 0.stride(to: last, by: interval)
{
n += 1
}
Swift 2.2 -> 3.0: Strideable:s stride(...) replaced by global stride(...) functions
In Swift 2.2, we can (as you've tried in your own attempt) make use of the blueprinted (and default-implemented) functions stride(through:by:) and stride(to:by:) from the protocol Strideable
/* Swift 2.2: stride example usage */
let from = 0
let to = 10
let through = 10
let by = 1
for _ in from.stride(through, by: by) { } // from ... through (steps: 'by')
for _ in from.stride(to, by: by) { } // from ..< to (steps: 'by')
Whereas in Swift 3.0, these two functions has been removed from Strideable in favour of the global functions stride(from:through:by:) and stride(from:to:by:); hence the equivalent Swift 3.0 version of the above follows as
/* Swift 3.0: stride example usage */
let from = 0
let to = 10
let through = 10
let by = 1
for _ in stride(from: from, through: through, by: by) { }
for _ in stride(from: from, to: to, by: by) { }
In your example you want to use the closed interval stride alternative stride(from:through:by:), since the invariant in your for loop uses comparison to less or equal to (<=). I.e.
/* example values of your parameters 'first', 'last' and 'interval' */
let first = 0
let last = 10
let interval = 2
var n = 0
for f in stride(from: first, through: last, by: interval) {
print(f)
n += 1
} // 0 2 4 6 8 10
print(n) // 6
Where, naturally, we use your for loop only as an example of the passage from for loop to stride, as you can naturally, for your specific example, just compute n without the need of a loop (n=1+(last-first)/interval).
Swift 3.0: An alternative to stride for more complex iterate increment logic
With the implementation of evolution proposal SE-0094, Swift 3.0 introduced the global sequence functions:
sequence(first:next:),
sequence(state:next:),
which can be an appropriate alternative to stride for cases with a more complex iterate increment relation (which is not the case in this example).
Declaration(s)
func sequence<T>(first: T, next: #escaping (T) -> T?) ->
UnfoldSequence<T, (T?, Bool)>
func sequence<T, State>(state: State,
next: #escaping (inout State) -> T?) ->
UnfoldSequence<T, State>
We'll briefly look at the first of these two functions. The next arguments takes a closure that applies some logic to lazily construct next sequence element given the current one (starting with first). The sequence is terminated when next returns nil, or infinite, if a next never returns nil.
Applied to the simple constant-stride example above, the sequence method is a bit verbose and overkill w.r.t. the fit-for-this-purpose stride solution:
let first = 0
let last = 10
let interval = 2
var n = 0
for f in sequence(first: first,
next: { $0 + interval <= last ? $0 + interval : nil }) {
print(f)
n += 1
} // 0 2 4 6 8 10
print(n) // 6
The sequence functions become very useful for cases with non-constant stride, however, e.g. as in the example covered in the following Q&A:
Express for loops in swift with dynamic range
Just take care to terminate the sequence with an eventual nil return (if not: "infinite" element generation), or, when Swift 3.1 arrives, make use of its lazy generation in combination with the prefix(while:) method for sequences, as described in evolution proposal SE-0045. The latter applied to the running example of this answer makes the sequence approach less verbose, clearly including the termination criteria of the element generation.
/* for Swift 3.1 */
// ... as above
for f in sequence(first: first, next: { $0 + interval })
.prefix(while: { $0 <= last }) {
print(f)
n += 1
} // 0 2 4 6 8 10
print(n) // 6
With Swift 5, you may choose one of the 5 following examples in order to solve your problem.
#1. Using stride(from:to:by:) function
let first = 0
let last = 10
let interval = 2
let sequence = stride(from: first, to: last, by: interval)
for element in sequence {
print(element)
}
/*
prints:
0
2
4
6
8
*/
#2. Using sequence(first:next:) function
let first = 0
let last = 10
let interval = 2
let unfoldSequence = sequence(first: first, next: {
$0 + interval < last ? $0 + interval : nil
})
for element in unfoldSequence {
print(element)
}
/*
prints:
0
2
4
6
8
*/
#3. Using AnySequence init(_:) initializer
let anySequence = AnySequence<Int>({ () -> AnyIterator<Int> in
let first = 0
let last = 10
let interval = 2
var value = first
return AnyIterator<Int> {
defer { value += interval }
return value < last ? value : nil
}
})
for element in anySequence {
print(element)
}
/*
prints:
0
2
4
6
8
*/
#4. Using CountableRange filter(_:) method
let first = 0
let last = 10
let interval = 2
let range = first ..< last
let lazyCollection = range.lazy.filter({ $0 % interval == 0 })
for element in lazyCollection {
print(element)
}
/*
prints:
0
2
4
6
8
*/
#5. Using CountableRange flatMap(_:) method
let first = 0
let last = 10
let interval = 2
let range = first ..< last
let lazyCollection = range.lazy.compactMap({ $0 % interval == 0 ? $0 : nil })
for element in lazyCollection {
print(element)
}
/*
prints:
0
2
4
6
8
*/
Simply, working code for Swift 3.0:
let (first, last, interval) = (0, 100, 1)
var n = 0
for _ in stride(from: first, to: last, by: interval) {
n += 1
}
We can also use while loop as alternative way
while first <= last {
first += interval
}
for _ in 0.stride(to: last, by: interval)
{
n += 1
}

How to calculate the 21! (21 factorial) in swift?

I am making fuction that calculate factorial in swift. like this
func factorial(factorialNumber: UInt64) -> UInt64 {
if factorialNumber == 0 {
return 1
} else {
return factorialNumber * factorial(factorialNumber - 1)
}
}
let x = factorial(20)
this fuction can calculate untill 20.
I think factorial(21) value bigger than UINT64_MAX.
then How to calculate the 21! (21 factorial) in swift?
func factorial(_ n: Int) -> Double {
return (1...n).map(Double.init).reduce(1.0, *)
}
(1...n): We create an array of all the numbers that are involved in the operation (i.e: [1, 2, 3, ...]).
map(Double.init): We change from Int to Double because we can represent bigger numbers with Doubles than with Ints (https://en.wikipedia.org/wiki/Double-precision_floating-point_format). So, we now have the array of all the numbers that are involved in the operation as Doubles (i.e: [1.0, 2.0, 3.0, ...]).
reduce(1.0, *): We start multiplying 1.0 with the first element in the array (1.0*1.0 = 1.0), then the result of that with the next one (1.0*2.0 = 2.0), then the result of that with the next one (2.0*3.0 = 6.0), and so on.
Step 2 is to avoid the overflow issue.
Step 3 is to save us from explicitly defining a variable for keeping track of the partial results.
Unsigned 64 bit integer has a maximum value of 18,446,744,073,709,551,615. While 21! = 51,090,942,171,709,440,000. For this kind of case, you need a Big Integer type. I found a question about Big Integer in Swift. There's a library for Big Integer in that link.
BigInteger equivalent in Swift?
Did you think about using a double perhaps? Or NSDecimalNumber?
Also calling the same function recursively is really bad performance wise.
How about using a loop:
let value = number.intValue - 1
var product = NSDecimalNumber(value: number.intValue)
for i in (1...value).reversed() {
product = product.multiplying(by: NSDecimalNumber(value: i))
}
Here's a function that accepts any type that conforms to the Numeric protocol, which are all builtin number types.
func factorial<N: Numeric>(_ x: N) -> N {
x == 0 ? 1 : x * factorial(x - 1)
}
First we need to declare temp variable of type double so it can hold size of number.
Then we create a function that takes a parameter of type double.
Then we check, if the number equal 0 we can return or do nothing. We have an if condition so we can break the recursion of the function. Finally we return temp, which holds the factorial of given number.
var temp:Double = 1.0
func factorial(x:Double) -> Double{
if(x==0){
//do nothing
}else{
factorial(x: x-1)
temp *= x
}
return temp
}
factorial(x: 21.0)
I make function calculate factorial like this:
func factorialNumber( namber : Int ) -> Int {
var x = 1
for i in 1...namber {
x *= i
}
return x
}
print ( factorialNumber (namber : 5 ))
If you are willing to give up precision you can use a Double to roughly calculate factorials up to 170:
func factorial(_ n: Int) -> Double {
if n == 0 {
return 1
}
var a: Double = 1
for i in 1...n {
a *= Double(i)
}
return a
}
If not, use a big integer library.
func factoruial(_ num:Int) -> Int{
if num == 0 || num == 1{
return 1
}else{
return(num*factoruial(num - 1))
}
}
Using recursion to solve this problem:
func factorial(_ n: UInt) -> UInt {
return n < 2 ? 1 : n*factorial(n - 1)
}
func factorial(a: Int) -> Int {
return a == 1 ? a : a * factorial(a: a - 1)
}
print(factorial(a : 5))
print(factorial(a: 9))

ios how to check if division remainder is integer

any of you knows how can I check if the division remainder is integer or zero?
if ( integer ( 3/2))
You should use the modulo operator like this
// a,b are ints
if ( a % b == 0) {
// remainder 0
} else
{
// b does not divide a evenly
}
It sounds like what you are looking for is the modulo operator %, which will give you the remainder of an operation.
3 % 2 // yields 1
3 % 1 // yields 0
3 % 4 // yields 1
However, if you want to actually perform the division first, you may need something a bit more complex, such as the following:
//Perform the division, then take the remainder modulo 1, which will
//yield any decimal values, which then you can compare to 0 to determine if it is
//an integer
if((a / b) % 1 > 0))
{
//All non-integer values go here
}
else
{
//All integer values go here
}
Walkthrough
(3 / 2) // yields 1.5
1.5 % 1 // yields 0.5
0.5 > 0 // true
swift 3:
if a.truncatingRemainder(dividingBy: b) == 0 {
//All integer values go here
}else{
//All non-integer values go here
}
You can use the below code to know which type of instance it is.
var val = 3/2
var integerType = Mirror(reflecting: val)
if integerType.subjectType == Int.self {
print("Yes, the value is an integer")
}else{
print("No, the value is not an integer")
}
let me know if the above was useful.
Swift 5
if numberOne.isMultiple(of: numberTwo) { ... }
Swift 4 or less
if numberOne % numberTwo == 0 { ... }
Swift 2.0
print(Int(Float(9) % Float(4))) // result 1