Get RandomPlusMinus in Swift - ios

I want to get a random number either + or -:
But what's wrong here
func randomPlusMinus(value:Float) -> Float {
return value * (arc4random() % 2 ? 1 : -1)
}
Error: Could not find an overload for '*' that accepts the supplied arguments

Try:
func randomPlusMinus(value:Float) -> Float {
let invert: Bool = arc4random_uniform(2) == 1
return value * (invert ? -1.0 : 1.0)
}
I don't think you can say if 0 or if 1. You should be using a boolean value with if and the ternary operator (cond ? v1 : v2).
Then there's the Swift numerics thing (which is really annoying, they need to add/implement more convertible protocols in the Std library :/ )
PS - I don't have an interpreter handy, but I will double check later

Having an explicit test for the result of the modulo operation works for me:
func randomPlusMinus(value:Float) -> Float {
return 0 == (arc4random() % 2) ? value : -value
}

I'm a little late to answering this, but I feel the simplest solution would be:
func randomPlusMinus(value:Float) -> Float {
return value * (arc4random_uniform(2) * 2 - 1)
}
The arc4random call will (supposedly) return 0 50% of the time and 1 50% of the time. So multiplying by 2 gives 0 or 2, then subtracting 1 gives -1 or 1. So the function returns value * -1 50% of the time and value * 1 the other 50% of the time.

I think this is what you are after if you want to random the +- of original value:
func randomPlusMinus(value:Float) -> Float {
let x = arc4random_uniform(2)
switch x {
case 0 :
return value * -1
default :
return value
}
}

Related

Σ Calculation in iOS SDK

I am working on a financial app where I have to perform a calculation. Finance team provide me below formula for calculation as below image
[![enter image description here][1]][1]
But I am unable to found how to perform below operation in Swift or Objective-C.
n t-1
Σ (1+i)
t=1
Can you please help me providing an idea of the above calculation?
I also read this link but not interested to use the third party.
Swift's reduce function was made for this:
(1...n).reduce(0) { (currentResult, t) -> Decimal in
currentResult + pow(1 + i, t - 1)
}
If we crack it down you have to find summation of (1 + i) ^ (t -1) where t varies from 1 to n.
Equivalent function will be
func evaluteSummation(n: Int, i: Int ) -> Int {
int sum = 0
for t in 1...n {
sum += pow(1 + i, t - 1)
}
return sum
}
You can do code like below.
func calculatePMT(targetValue : Double, interestRate : Double, time: Int) -> Double {
let term = 1.0 + interestRate
var denominator = 0.0
for t in 0..<time {
let p = pow(term, Double(t))
denominator += p
}
return targetValue / denominator
}
let targetValue = 100000.0
let interestRate = 5.0
let time = 4
let pmt = calculatePMT(targetValue: targetValue, interestRate: interestRate, time: time)
print(pmt)

Get result from modulo operation in ios swift [duplicate]

How does modulo of negative numbers work in swift ?
When i did (-1 % 3) it is giving -1 but the remainder is 2. What is the catch in it?
The Swift remainder operator % computes the remainder of
the integer division:
a % b = a - (a/b) * b
where / is the truncating integer division. In your case
(-1) % 3 = (-1) - ((-1)/3) * 3 = (-1) - 0 * 3 = -1
So the remainder has always the same sign as the dividend (unless
the remainder is zero).
This is the same definition as required e.g. in the C99 standard,
see for example
Does either ANSI C or ISO C specify what -5 % 10 should be?. See also
Wikipedia: Modulo operation for an overview
how this is handled in different programming languages.
A "true" modulus function could be defined in Swift like this:
func mod(_ a: Int, _ n: Int) -> Int {
precondition(n > 0, "modulus must be positive")
let r = a % n
return r >= 0 ? r : r + n
}
print(mod(-1, 3)) // 2
From the Language Guide - Basic Operators:
Remainder Operator
The remainder operator (a % b) works out how many multiples of b
will fit inside a and returns the value that is left over (known as
the remainder).
The remainder operator (%) is also known as a modulo operator in
other languages. However, its behavior in Swift for negative numbers
means that it is, strictly speaking, a remainder rather than a modulo
operation.
...
The same method is applied when calculating the remainder for a
negative value of a:
-9 % 4 // equals -1
Inserting -9 and 4 into the equation yields:
-9 = (4 x -2) + -1
giving a remainder value of -1.
In your case, no 3 will fit in 1, and the remainder is 1 (same with -1 -> remainder is -1).
If what you are really after is capturing a number between 0 and b, try using this:
infix operator %%
extension Int {
static func %% (_ left: Int, _ right: Int) -> Int {
if left >= 0 { return left % right }
if left >= -right { return (left+right) }
return ((left % right)+right)%right
}
}
print(-1 %% 3) //prints 2
This will work for all value of a, unlike the the previous answer while will only work if a > -b.
I prefer the %% operator over just overloading %, as it will be very clear that you are not doing a true mod function.
The reason for the if statements, instead of just using the final return line, is for speed, as a mod function requires a division, and divisions are more costly that a conditional.
An answer inspired by cdeerinck, which sacrifices speed for simplicity, is this:
infix operator %%
extension Int {
static func %% (_ left: Int, _ right: Int) -> Int {
let mod = left % right
return mod >= 0 ? mod : mod + right
}
}
I tested it with this little loop in a playground:
for test in [6, 5, 4, 0, -1, -2, -100, -101] {
print(test, "%% 5", test %% 5)
}

why my code is slow when finding Fibonacci sum?

I'm writing answers for project Euler Questions in this repo
but having some performance issues in my solution
Question 2:
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
My Solution is
func solution2()
{
func fibonacci(number: Int) -> (Int)
{
if number <= 1
{
return number
}
else
{
return fibonacci(number - 1) + fibonacci(number - 2)
}
}
var sum = 0
print("calculating...")
for index in 2..<50
{
print (index)
if (fibonacci(index) % 2 == 0)
{
sum += fibonacci(index)
}
}
print(sum)
}
My Question is, why it gets super slow after iteration 42, i want to do it for 4000000 as the question says, any help?
solution 2
func solution2_fast()
{
var phiOne : Double = (1.0 + sqrt(5.0)) / 2.0
var phiTwo : Double = (1.0 - sqrt(5.0)) / 2.0
func findFibonacciNumber (nthNumber : Double) -> Int64
{
let nthNumber : Double = (pow(phiOne, nthNumber) - (pow(phiTwo, nthNumber))) / sqrt(5.0)
return Int64(nthNumber)
}
var sum : Int64 = 0
print("calculating...")
for index in 2..<4000000
{
print (index)
let f = findFibonacciNumber(Double(index))
if (f % 2 == 0)
{
sum += f
}
}
print(sum)
}
The most important thing about PE questions is to think about what it is asking.
This is not asking you to produce all Fibonacci numbers F(n) less than 4000000. It is asking for the sum of all even F(n) less than 4000000.
Think about the sum of all F(n) where F(n) < 10.
1 + 2 + 3 + 5 + 8
I could do this by calculating F(1), then F(2), then F(3), and so on... and then checking they are less than 10 before adding them up.
Or I could store two variables...
F1 = 1
F2 = 2
And a total...
Total = 3
Now I can turn this into a while loop and lose the recursion altogether. In fact, the most complex thing I'm doing is adding two numbers together...
I came up with this...
func sumEvenFibonacci(lessThan limit: Int) -> Int {
// store the first two Fibonacci numbers
var n1 = 1
var n2 = 2
// and a cumulative total
var total = 0
// repeat until you hit the limit
while n2 < limit {
// if the current Fibonacci is even then add to total
if n2 % 2 == 0 {
total += n2
}
// move the stored Fibonacci numbers up by one.
let temp = n2
n2 = n2 + n1
n1 = temp
}
return total
}
It runs in a fraction of a second.
sumEvenFibonacci(lessThan: 4000000)
Finds the correct answer.
In fact this... sumEvenFibonacci(lessThan: 1000000000000000000) runs in about half a second.
The second solution seems to be fast(er) although an Int64 will not be sufficient to store the result. The sum of Fibonacci numbers from 2..91 is 7,527,100,471,027,205,936 but the largest number you can store in an Int64 is 9,223,372,036,854,775,807. For this you need to use some other types like BigInteger
Because you use the recursive, and it cache in the memory.If you iteration 42, it maybe has so many fibonacci function in your memory, and recursive.So it isn't suitable for recursive, and you can store the result in the array, not the reason of the swift.
this is the answer in two different ways
func solution2_recursive()
{
func fibonacci(number: Int) -> (Int)
{
if number <= 1
{
return number
}
else
{
return fibonacci(number - 1) + fibonacci(number - 2)
}
}
var sum = 0
print("calculating...")
for index in 2..<50
{
print (index)
let f = fibonacci(index)
if( f < 4000000)
{
if (f % 2 == 0)
{
sum += f
}
}
else
{
print(sum)
return
}
}
}
solution 2
func solution2()
{
var phiOne : Double = (1.0 + sqrt(5.0)) / 2.0
var phiTwo : Double = (1.0 - sqrt(5.0)) / 2.0
func findFibonacciNumber (nthNumber : Double) -> Int64
{
let nthNumber : Double = (pow(phiOne, nthNumber) - (pow(phiTwo, nthNumber))) / sqrt(5.0)
return Int64(nthNumber)
}
var sum : Int64 = 0
print("calculating...")
for index in 2..<50
{
let f = findFibonacciNumber(Double(index))
if(f < 4000000)
{
if (f % 2 == 0)
{
sum += f
}
}
else
{
print(sum)
return
}
}
}

Check if an integer is divisible by another integer (Swift)

I need to check if an integer is divisible by another integer exactly.
If not I would like to round it up to the closest multiple of the number.
Example:
var numberOne = 3
var numberTwo = 5
numberTwo is not a multiple of numberOne therefore I would like it to round numberTwo up to 6.
How would I do this?
Thank you
1) If you want to check or an integer is divided by another integer:
Swift 5
if numberOne.isMultiple(of: numberTwo) { ... }
Swift 4 or less
if numberOne % numberTwo == 0 { ... }
2) Function to round to the closest multiple value:
func roundToClosestMultipleNumber(_ numberOne: Int, _ numberTwo: Int) -> Int {
var result: Int = numberOne
if numberOne % numberTwo != 0 {
if numberOne < numberTwo {
result = numberTwo
} else {
result = (numberOne / numberTwo + 1) * numberTwo
}
}
return result
}
You can use the modulo operator %:
numberTwo % numberOne == 0
The modulo finds the remainder of an integer division between 2 numbers, so for example:
20 / 3 = 6
20 % 3 = 20 - 6 * 3 = 2
The result of 20/3 is 6.666667 - the dividend (20) minus the integer part of that division multiplied by the divisor (3 * 6) is the modulo (20 - 6 * 3) , equal to 2 in this case.
If the modulo is zero, then the dividend is a multiple of the divisor
More info about the modulo at this wikipedia page.
Swift 5
isMultiple(of:)
Returns true if this value is a multiple of the given
value, and false otherwise.
func isMultiple(of other: Int) -> Bool
let rowNumber = 4
if rowNumber.isMultiple(of: 2) {
print("Even")
} else {
print("Odd")
}
You can use truncatingRemainder. E.g.,
if number.truncatingRemainder(dividingBy: 10) == 0 {
print("number is divisible by 10")
}

Randomly generate "-1" or "1" - Shortest Method

I need to randomly generate either a "-1" or a "1" to determine the sign of a number randomly... What's the shortest method? I am currently using this but it seems pretty long:
sign = (round((arc4random() % 2)))-((round((arc4random() % 2))) == 0);
What about arc4random_uniform(2) ? -1 : 1?
or arc4random_uniform(2)*2 - 1
short int randomNumber () {
return arc4random() % 2 ? 1 : -1;
}

Resources