Swift string formula into a real calculation - ios

I have several formulas stored in a Plist such as A * B. I'm trying to figure out how I could take this formula currently stored as a string in a Plist and use it as an actual calculation formula. I tried going the route of making the formula to \(A) * \(B) and then setting A and B before trying to use the formula but it did not work. Any suggestions?
example
let A = 5
let B = 2
println (formula)
actually printed out "\(A) * \(B)"

Xcode 8.3.1 • Swift 3.1
extension String {
var expression: NSExpression {
return NSExpression(format: self)
}
}
let a = 5
let b = 2
let intDictionary = ["a": a,"b": b]
var formula = "a * b"
if let timesResult = formula.expression.expressionValue(with: intDictionary, context: nil) as? Int {
print(timesResult) // 10
}
formula = "(a + b) / 2"
if let intAvgResult = formula.expression.expressionValue(with: intDictionary, context: nil) as? Int {
print(intAvgResult) // 3
}
let x = 5.0
let y = 2.0
let z = 3.0
let doubleDictionary = ["x": x, "y": y, "z": z]
formula = "(x + y + z) / 3"
if let doubleAvgResult = formula.expression.expressionValue(with: doubleDictionary, context: nil) as? Double {
print(doubleAvgResult)
}

Use NSExpression.
NSExpression *expression = [NSExpression expressionWithFormat:#"4 + 5 - 2**3"];
id value = [expression expressionValueWithObject:nil context:nil]; // => 1
Expression creation is formatted, so you can input your params as part of the equation.
More info here.

#Leo for Swift 3 (as opposed to obj-c) in Xcode 8 it would look like this:
let mathExpression = NSExpression(format: "4 + 5 - 2**3")
let mathValue = mathExpression.expressionValue(with: nil, context: nil) as? Int

Related

Adam Optimizer is apparently not converging

I am trying to write a neural network in rust + arrayfire, and while gradient descent works, ADAM does not.
fn back_propagate(
&mut self,
signals: &Vec<Array<f32>>,
labels: &Array<u8>,
learning_rate_alpha: f64,
batch_size: i32,
) {
let mut output = signals.last().unwrap();
let mut error = output - labels;
for layer_index in (0..self.num_layers - 1).rev() {
let signal = Self::add_bias(&signals[layer_index]);
let deriv = self.layer_activations[layer_index].apply_deriv(output);
let delta = &(deriv * error).T();
let matmul = matmul(&delta, &signal, MatProp::NONE, MatProp::NONE);
let gradient_t = (matmul / batch_size).T();
match self.optimizer {
Optimizer::GradientDescent => {
let weight_update = learning_rate_alpha * gradient_t;
self.weights[layer_index] -= weight_update;
}
Optimizer::Adam => {
let exponents = constant(2f32, gradient_t.dims());
self.first_moment_vectors[layer_index] = (&self.beta1[layer_index]
* &self.first_moment_vectors[layer_index])
+ (&self.one_minus_beta1[layer_index] * &gradient_t);
self.second_moment_vectors[layer_index] = (&self.beta2[layer_index]
* &self.second_moment_vectors[layer_index])
+ (&self.one_minus_beta2[layer_index]
* arrayfire::pow(&gradient_t, &exponents, true));
let corrected_first_moment_vector = &self.first_moment_vectors[layer_index]
/ &self.one_minus_beta1[layer_index];
let corrected_second_moment_vector = &self.second_moment_vectors[layer_index]
/ &self.one_minus_beta2[layer_index];
let denominator = sqrt(&corrected_second_moment_vector) + 1e-8;
let weight_update =
learning_rate_alpha * (corrected_first_moment_vector / denominator);
self.weights[layer_index] -= weight_update;
}
}
output = &signals[layer_index];
let err = matmulTT(
&delta,
&self.weights[layer_index],
MatProp::NONE,
MatProp::NONE,
);
error = index(&err, &[seq!(), seq!(1, output.dims()[1] as i32, 1)]);
}
}
I've stored beta1, beta2, 1-beta1, 1-beta2 in constant arrays for every layer just to avoid having to recompute them. It appears to have made no difference.
GradientDescent converges with a learning rate alpha=2.0, however with Adam, if i use alpha>~0.02, the network appears to get locked in. Funnily enough, if I remove all the hidden layers, it does work. Which tells me something, but I'm not sure what it is.
I figured it out, for anyone else, my alpha=0.01 is still too high, once I reduced it to 0.001, it converged very quickly

SwiftUI IOS Dynamic CorePlot Data

How do I implement dynamic data to my CorePlot? I'd like my graph to look like this:
How should I implement my JSON API and to decode the values to set it as X-axis?
JSON API: https://dcmicrogridiep.000webhostapp.com/datamainjson.php
This is my sample code for the CorePlot graph which uses hard coded values.
import Foundation
import SwiftUI
import CorePlot
class CalculatePlotData: ObservableObject {
var plotDataModel: PlotDataClass? = nil
func plotYEqualsX()
{
//set the Plot Parameters
plotDataModel!.changingPlotParameters.yMax = 10.0
plotDataModel!.changingPlotParameters.yMin = -5.0
plotDataModel!.changingPlotParameters.xMax = 10.0
plotDataModel!.changingPlotParameters.xMin = -5.0
plotDataModel!.changingPlotParameters.xLabel = "x"
plotDataModel!.changingPlotParameters.yLabel = "y"
plotDataModel!.changingPlotParameters.lineColor = .red()
plotDataModel!.changingPlotParameters.title = " y = x"
plotDataModel!.zeroData()
var plotData :[plotDataType] = []
for i in 0 ..< 120 {
//create x values here
let x = -2.0 + Double(i) * 0.2
//create y values here
let y = x * 8
let dataPoint: plotDataType = [.X: x, .Y: y]
plotData.append(contentsOf: [dataPoint])
}
plotDataModel!.appendData(dataPoint: plotData)
}
func ploteToTheMinusX()
{
//set the Plot Parameters
plotDataModel!.changingPlotParameters.yMax = 10
plotDataModel!.changingPlotParameters.yMin = -3.0
plotDataModel!.changingPlotParameters.xMax = 10.0
plotDataModel!.changingPlotParameters.xMin = -3.0
plotDataModel!.changingPlotParameters.xLabel = "x"
plotDataModel!.changingPlotParameters.yLabel = "y = exp(-x)"
plotDataModel!.changingPlotParameters.lineColor = .blue()
plotDataModel!.changingPlotParameters.title = "exp(-x)"
plotDataModel!.zeroData()
var plotData :[plotDataType] = []
for i in 0 ..< 60 {
//create x values here
let x = -8.0 + Double(i) * 5
//create y values here
let y = exp(-x)
let dataPoint: plotDataType = [.X: x, .Y: y]
plotData.append(contentsOf: [dataPoint])
}
plotDataModel!.appendData(dataPoint: plotData)
return
}
}
If you don't need the actual date values elsewhere in the app, you can just send the numbers in the "times" field provided by the API to the plot directly. You'll set the plot ranges based on those values and define a label formatter with the correct reference date to properly display the date values. Look at the DatePlot example app for a simple Swift example.

how to take binary string input from user in swift

I want to take input from user in binary, What I want is something like:
10101
11110
Then I need to perform bitwise OR on this. I know how to take input and how to perform bitwise OR, only I want to know is how to convert because what I am currently using is not giving right result. What I tried is as below:
let aBits: Int16 = Int16(a)! //a is String "10101"
let bBits: Int16 = Int16(b)! //b is String "11110"
let combinedbits = aBits | bBits
Edit: I don't need decimal to binary conversion with radix, as my string already have only 0 and 1
String can have upto 500 characters like:
10011011111010110111001011001001101110111110110001001111001111101111010110110111‌​00111001100011111010
this is beyond Int limit, how to handle that in Swift?
Edit2 : As per vacawama 's answer, below code works great:
let maxAB = max(a.count, b.count)
let paddedA = String(repeating: "0", count: maxAB - a.count) + a
let paddedB = String(repeating: "0", count: maxAB - b.count) + b
let Str = String(zip(paddedA, paddedB).map({ $0 == ("0", "0") ? "0" : "1" }))
I can have array of upto 500 string and each string can have upto 500 characters. Then I have to get all possible pair and perform bitwise OR and count maximum number of 1's. Any idea to make above solution more efficient? Thank you
Since you need arbitrarily long binary numbers, do everything with strings.
This function first pads the two inputs to the same length, and then uses zip to pair the digits and map to compute the OR for each pair of characters. The resulting array of characters is converted back into a String with String().
func binaryOR(_ a: String, _ b: String) -> String {
let maxAB = max(a.count, b.count)
let paddedA = String(repeating: "0", count: maxAB - a.count) + a
let paddedB = String(repeating: "0", count: maxAB - b.count) + b
return String(zip(paddedA, paddedB).map({ $0 == ("0", "0") ? "0" : "1" }))
}
print(binaryOR("11", "1100")) // "1111"
print(binaryOR("1000", "0001")) // "1001"
I can have array of upto 500 string and each string can have upto 500
characters. Then I have to get all possible pair and perform bitwise
OR and count maximum number of 1's. Any idea to make above solution
more efficient?
You will have to do 500 * 499 / 2 (which is 124,750 comparisons). It is important to avoid unnecessary and/or repeated work.
I would recommend:
Do an initial pass to loop though your strings to find out the length of the largest one. Then pad all of your strings to this length. I would keep track of the original length of each string in a tiny stuct:
struct BinaryNumber {
var string: String // padded string
var length: Int // original length before padding
}
Modify the binaryOR function to take BinaryNumbers and return Int, the count of "1"s in the OR.
func binaryORcountOnes(_ a: BinaryNumber, _ b: BinaryNumber) -> Int {
let maxAB = max(a.length, b.length)
return zip(a.string.suffix(maxAB), b.string.suffix(maxAB)).reduce(0) { total, pair in return total + (pair == ("0", "0") ? 0 : 1) }
}
Note: The use of suffix helps the efficiency by only checking the digits that matter. If the original strings had length 2 and 3, then only the last 3 digits will be OR-ed even if they're padded to length 500.
Loop and compare all pairs of BinaryNumbers to find largest count of ones:
var numbers: [BinaryNumber] // This array was created in step 1
maxOnes = 0
for i in 0 ..< (numbers.count - 1) {
for j in (i + 1) ..< numbers.count {
let ones = binaryORcountOnes(numbers[i], numbers[j])
if ones > maxOnes {
maxOnes = ones
}
}
}
print("maxOnes = \(maxOnes)")
Additional idea for speedup
OR can't create more ones than were in the original two numbers, and the number of ones can't exceed the maximum length of either of the original two numbers. So, if you count the ones in each number when you are padding them and store that in your struct in a var ones: Int property, you can use that to see if you should even bother calling binaryORcountOnes:
maxOnes = 0
for i in 0 ..< (numbers.count - 1) {
for j in (i + 1) ..< numbers.count {
if maxOnes < min(numbers[i].ones + numbers[j].ones, numbers[i].length, numbers[j].length) {
let ones = binaryORcountOnes(numbers[i], numbers[j])
if ones > maxOnes {
maxOnes = ones
}
}
}
}
By the way, the length of the original string should really just be the minimum length that includes the highest order 1. So if the original string was "00101", then the length should be 3 because that is all you need to store "101".
let number = Int(a, radix: 2)
Radix helps using binary instead of decimical value
You can use radix for converting your string. Once converted, you can do a bitwise OR and then check the nonzeroBitCount to count the number of 1's
let a = Int("10101", radix: 2)!
let b = Int("11110", radix: 2)!
let bitwiseOR = a | b
let nonZero = bitwiseOR.nonzeroBitCount
As I already commented above "10101" is actually a String not a Binary so "10101" | "11110" will not calculate what you actually needed.
So what you need to do is convert both value in decimal then use bitwiseOR and convert the result back to in Binary String (in which format you have the data "11111" not 11111)
let a1 = Int("10101", radix: 2)!
let b1 = Int("11110", radix: 2)!
var result = 21 | 30
print(result)
Output: 31
Now convert it back to binary string
let binaryString = String(result, radix: 2)
print(binaryString)
Output: 11111
--: EDIT :--
I'm going to answer a basic example of how to calculate bitwiseOR as the question is specific for not use inbuilt function as string is very large to be converted into an Int.
Algorithm: 1|0 = 1, 1|1 = 1, 0|0 = 0, 0|1 = 1
So, What we do is to fetch all the characters from String one by one the will perform the | operation and append it to another String.
var str1 = "100101" // 37
var str2 = "10111" // 23
/// Result should be "110111" -> "55"
// #1. Make both string equal
let length1 = str1.characters.count
let length2 = str2.characters.count
if length1 != length2 {
let maxLength = max(length1, length2)
for index in 0..<maxLength {
if str1.characters.count < maxLength {
str1 = "0" + str1
}
if str2.characters.count < maxLength {
str2 = "0" + str2
}
}
}
// #2. Get the index and compare one by one in bitwise OR
// a) 1 - 0 = 1,
// b) 0 - 1 = 1,
// c) 1 - 1 = 1,
// d) 0 - 0 = 0
let length = max(str1.characters.count, str2.characters.count)
var newStr = ""
for index in 0..<length {
let charOf1 = Int(String(str1[str1.index(str1.startIndex, offsetBy: index)]))!
let charOf2 = Int(String(str2[str2.index(str2.startIndex, offsetBy: index)]))!
let orResult = charOf1 | charOf2
newStr.append("\(orResult)")
}
print(newStr)
Output: 110111 // 55
I would like to refer Understanding Bitwise Operators for more detail.
func addBinary(_ a: String, _ b: String) {
var result = ""
let arrA = Array(a)
let arrB = Array(b)
var lengthA = arrA.count - 1
var lengthB = arrB.count - 1
var sum = 0
while lengthA >= 0 || lengthB >= 0 || sum == 1 {
sum += (lengthA >= 0) ? Int(String(arrA[lengthA]))! : 0
sum += (lengthB >= 0) ? Int(String(arrB[lengthB]))! : 0
result = String((sum % 2)) + result
sum /= 2
lengthA -= 1
lengthB -= 1
}
print(result) }
addBinary("11", "1")

Why does the xcode say "Expression was too complex to be solved in reasonable time..." for my Swift code?

I am writing an app, and I have a block of code that reads like this:
let DestViewController: ftrViewController = segue.destinationViewController as! ftrViewController
let weightInt: Int? = Int(weightInKilos.text!)
let dehydrationInt: Int? = Int(percentOfDehydration.text!)
let lossesInt: Int? = Int(ongoingLosses.text!)
let factorFloat: Float? = Float(Factor.text!)
let lrs24Int = (30 * weightInt! + 70) * factorFloat! + weightInt! * dehydrationInt! * 10 + lossesInt!
However, Xcode says that Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions.
My equation looks right to me, and I do not believe that my equation is too complex, because I had the same error when the problem was simply that I wasn't declaring the integers correctly (the deal with the ?s and the !s).
Does anybody see a problem in my code that is leading to this error, or is the expression truly too hard for the computer to solve in reasonable time? Thanks!
PS- I think the problem might be the float, because before I added the float, it was working fine.
Rewritten Code
let weightInt: Float? = Float(weightInKilos.text!)
let dehydrationInt: Float? = Float(percentOfDehydration.text!)
let lossesInt: Float? = Float(ongoingLosses.text!)
let factorFloat: Float? = Float(Factor.text!)
let step1 = (30 * weightInt! + 70) * factorFloat! + weigh
let lrs24Int = step1 * dehydrationInt! * 10 + lossesInt!
It was not Only Float problem. I used float to avoid type conversions as all are float. The Main Problem was the Complexity of expression.

Adding time Strings in swift

I have an array of timeStrings of the following format:
x Hr(s) xx min.
I need to add these up to give a total. I'm wondering what is the best way to do this?
My thoughts were to find the index of "Hr(s)". Then if i substring between index 0 and the index of "Hr(s)", I have my hrs var and then add 6 to index of "Hr(s)" and find the index of "min" - 1, to give me the min var.
Then I need to take into account if seconds is greater than 60. So if I divide my seconds var by 60 and the answer is great than 1, I add that answer to my hrs var?
Can anyone see any flaws in this logic?
Sample implementation:
JSON response:
{"status":"OK","hrs":[{"scheduleDate":"2015-11-09","userName":"John Doe","company":"Company X","hrsWorked":"0 Hr(s) 42 min"},{"scheduleDate":"2015-11-10","userName":"Jane Doe","company":"Company Y","hrsWorked":"0 Hr(s) 47 min"},{"scheduleDate":"2015-11-10","userName":"Bob loblaw","company":"Company X","hrsWorked":"0 Hr(s) 37 min"},{"scheduleDate":"2015-11-10","userName":"Joe Soap","company":"Company Y","hrsWorked":"0 Hr(s) 50 min"},{"scheduleDate":"2015-11-10","userName":"Test","company":"Company Y","hrsWorked":"0 Hr(s) 40 min"}],"queryStatus":"OK","message":null,"count":5}
var hrsVar = 0
var minsVar = 0
loop through hrsArray{
hrsMinStr = hrsWorkedInJson
if let endHrsIndex = hrsMinStr.lowercaseString.characters.indexOf("Hr(s)") {
print("Index: \(index)")
let hrsStr = Int(hrsMinStr.substringWithRange(Range<String.Index>(start: 0, end: endHrsIndex)))
hrsVar += hrsStr
let minStr = Int(hrsMinStr.substringWithRange(Range<String.Index>(start: endHrsIndex + 1, end: hrsMinStr.length - 3)))
minsVar += minStr
}
}
if minsVar/60 > 1 {
hrsVar = hrsVar + minsVar/60
minsVar = minsVar%60
}
Update
It seems as though I cannot pass in "Hr(s)" and instead only a single character "h". Because of this, I was trying to use the advancedBy(x) method to get the right endIndex. But I'm getting the error:
Cannot invoke initializer for type 'Range<Index>' with an argument list of type '(start: Int, end: String.CharacterView.Index)'
Updated code:
if let endHrsIndex = hrsMinStr.lowercaseString.characters.indexOf("h") {
print("Index: \(endHrsIndex)")
let hrsStr = Int(hrsMinStr.substringWithRange(Range<String.Index>(start: 0, end: endHrsIndex)))
hrsVar += hrsStr
let minStr = Int(hrsMinStr.substringWithRange(Range<String.Index>(start: endHrsIndex.advancedBy(5), end: hrsMinStr.length.characters.count.advancedBy(-3))))
minsVar += minStr
}
I'm really looking for the most efficient approach as possible, so please advise if there is a better way/if you see issues with this approach
import Foundation
let str = "0 Hr(s) 42 min"
let time = str
.stringByReplacingOccurrencesOfString("Hr(s)", withString:":")
.stringByReplacingOccurrencesOfString("min", withString: "")
.stringByReplacingOccurrencesOfString(" ", withString: "")
let t = time.characters.split(Character(":"))
let h = Int(String(t[0])) // 0
let m = Int(String(t[1])) // 1
and sum
import Foundation
var time: [(hours:Int,minutes:Int,seconds:Int)] = []
for i in 0...5 {
let h = Int(arc4random_uniform(24))
let m = Int(arc4random_uniform(60))
let s = Int(arc4random_uniform(60))
time.append((h,m,s))
}
let t = time.reduce(0) { (sum, time: (hours: Int, minutes: Int, seconds: Int)) -> Int in
sum + time.seconds + time.minutes * 60 + time.hours * 60 * 60
}
let seconds = t % 60
let minutes = ((t - seconds) / 60) % 60
let hours = ((t - seconds) / 3660)
time.forEach {
print(String(format: " %6d:%02d:%02d", arguments: [$0.hours,$0.minutes, $0.seconds]))
}
print("-------------------")
print(String(format: "Sum: %6d:%02d:%02d", arguments: [hours,minutes,seconds]))
/*
12:25:04
2:43:36
14:09:35
11:59:43
10:39:19
23:32:14
-------------------
Sum: 74:29:31
*/
You should most likely try using the scanners in your case.
let string = "12 Hr(s) 37 min"
let scanner = NSScanner(string: string)
var min: Int = 0
var hour : Int = 0
scanner.scanInteger(&hour)
scanner.scanString("Hr(s) ", intoString: nil)
scanner.scanInteger(&min)
Or even easier if you create this part in Objective-C:
int min, hour;
sscanf("12 Hr(s) 37 min", "%d Hr(s) %d min", &hour, &min);

Resources