How to multiply NSstring by the number? - ios

I can't multiply currentValue variable value.
Code:
#IBAction func PlusMinus()
{
let v = 0
command = nil
let currentValue = v
let v = v*(-1)
displayLabel!.text = m
}
what is wrong ?
You can see screenshot :
http://cl.ly/image/3c2e0V0m021H

You are redefining a constant with the same name 'v'. Also, you're using several instance vars in your code. Copy all relevant code in your question.
#IBAction func PlusMinus()
{
let v = 0
command = nil
let currentValue = v
let v = v*(-1) // you've already defined a constant named 'v'
displayLabel!.text = m
}

let declares a constant. It's like writing 2 = 2 * (-1), makes no sense. Use var for variable values.

Related

why it's printing intialized value after assigning new value to that property?

I am new to swift.Why the value of a is printed zero here?
var a = 0
var b = 0
let closure = { [a] in
print(a,b)
}
a = 10
b = 10
closure()

Find the Missing no from an array the efficient way

I am trying to find an efficient way to solve the find a missing number from an array. I implemented the following way it's O(n). Please write any codes that efficiently solves this, just for learning purpose.
func findMissingNo(arrA: [Int]) -> [Int] {
let firstIndex = arrA.first ?? 0
let lastIndex = arrA.last ?? 0
let rslt = Array(firstIndex...lastIndex)
let missingNoArray = rslt.filter{ !arrA.contains($0)}
return missingNoArray
}
findMissingNo(arrA: [11,12,14,15,16,18]) // Prints [13, 17] by looping 9 times
Quickly written and tested (in terms of times performances against your code, but not in term of possible edges cases/mistakes, for instance, if array is 0...10, it won't work, but I'll let you work on the edges cases, since I focused mainly on the main cases, cases which might be covered during an edit and the end of the question)
Your current code:
func findMissingNo(arrA: [Int]) -> [Int] {
let firstIndex = arrA.first ?? 0
let lastIndex = arrA.last ?? 0
let rslt = Array(firstIndex...lastIndex)
let missingNoArray = rslt.filter{ !arrA.contains($0)}
return missingNoArray
}
let numberArray = [11,12,14,15,18]
let missing1 = findMissingNo(arrA: numberArray)
print("Missing1: \(missing1)")
My attempt:
func findMissingNo2(arrA: [Int]) -> [Int] {
var missingNumbers: [Int] = []
guard arrA.count > 2 else { return missingNumbers }
for i in 0...arrA.count-2 {
var current = arrA[i]
let next = arrA[i+1]
if next != current + 1 {
current += 1
while current != next {
missingNumbers.append(current)
current += 1
}
}
}
return missingNumbers
}
let missing2 = findMissingNo2(arrA: numberArray)
print("Missing1: \(missing2)")
Creating a big batch:
var array = Array(0...1000)
for _ in 0...10 {
if let index = array.indices.randomElement() {
let value = array.remove(at: index)
print("removed: \(value)") //To check just in case that's the good value returned by the methods
}
}
Testing:
let date1 = Date()
for _ in 0...100 {
let missing = findMissingNo(arrA: array)
print(missing)
}
print(Date().timeIntervalSince(date1)) //18.617565035820007
let date2 = Date()
for _ in 0...100 {
let missing = findMissingNo2(arrA: array)
print(missing)
}
print(Date().timeIntervalSince(date2)) //0.09566605091094971
print("---End")
print("")
For the time, I got: 18.857954025268555 vs 0.09159696102142334, a big factor difference (~200 times).
Why is there such a big difference?
Because of
let missingNoArray = rslt.filter{ !arrA.contains($0)}
It means:
for each number in result, check if arrayA contains that number.
->
for each number in result, for each number in arrayA (with a stop condition, so it's not a full iteration, but "almost" in term of complexity) check if there is a match...
Here there is a "double" (which is in fact not double, but n?) iteration that you missed.
I tested first with bigger value (array from "0 to 100000"), but it was taking too much time, with that "low number of values", the difference can already be seen.
Instead, you could use a Set:
let missingNoArray = Array(Set(rslt).subtracting(Set(arrA))).sorted()
It's faster than you method in my tests, (double my solution (0.21 ~ 0.22) in time performances), but still much faster than yours.
I added the sorted(), which may or may not be important in your solution, but will add time consumption since Set aren't ordered.
For the edges cases (ie: [3], [3, 4], [3, 8])
guard arrA.count > 2 else { return missingNumbers }
==>
guard !arrA.isEmpty else { return [] }
guard arrA.count > 2 else {
if arrA[0] + 1 >= arrA[1] {
return []
} else {
return Array((arrA[0] + 1)...arrA[1]).dropLast() //Because last will be arrA[1] which is present)
}
}

Unexpectedly found nil while unwrapping an Optional value (Cannot figure out which part)

I'm new to Swift and I cannot figure out which optional variable that I unwrapped and I assigned nil to it, I tried to debug it on Playground but it won't let me step through the code.
Fatal error: Unexpectedly found nil while unwrapping an Optional value
public class ListNode {
public var val: Int
public var next: ListNode?
public init() { self.val = 0; self.next = nil; }
public init(_ val: Int) { self.val = val; self.next = nil; }
public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
}
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let result = ListNode()
var resultTail = result
var carry: Int = 0
var out: Int = 0
var val1: Int = 0
var val2: Int = 0
var head1: ListNode? = l1
var head2: ListNode? = l2
while (l1 != nil || l2 != nil || carry != 0) {
val1 = head1 != nil ? head1!.val : 0
val2 = head2 != nil ? head2!.val : 0
out = (val1 + val2 + carry) % 10
carry = (val1 + val2 + carry) / 10
resultTail.next = ListNode(out)
resultTail = resultTail.next!
head1 = head1?.next!
head2 = head2?.next!
}
return result.next!
}
}
let node3 = ListNode(3)
let node2 = ListNode(4, node3)
let node1 = ListNode(2, node2)
let node3a = ListNode(5)
let node2a = ListNode(6, node3a)
let node1a = ListNode(4, node2a)
let solution = Solution().addTwoNumbers(node1, node1a)
Best regards,
Farros
If you search for the "unexpectedly found nil" error message you will find several questions and answers that explain what this means and suggest debugging techniques.
While the root cause of this error can be subtle, the trigger for the exception is force unwrapping an optional that is nil or referencing an implicitly unwrapped optional that is nil.
You don't have a lot of code here, so it isn't hard to find where you do one of those things;
You force unwrap in your ternary operator, that is after a check for nil, so that won't crash
You force unwrap resultTail.next and result.next but you have assigned values in those cases, so that won't cause the crash.
The last place is where you force unwrap head1.next and head2.next at the bottom of your while loop. This is a mistake because you know that next will eventually be nil at the end of your list.
Simply removing the ! will eliminate the exception, but introduce a new bug because your while loop condition tests the initial parameters l1 and l2 whose values never change. You risk an infinite loop. I think you meant to reference head1 and head2.
You should try and eliminate all force unwraps and this isn't too hard:
Use the nil coalescing operator instead of the ternary
head1 and head2 are optional, so there is no need to force unwrap next
Your function returns an optional, so we can declare resultTail as an optional and use conditional unwrapping or no unwrapping
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let result = ListNode()
var resultTail: ListNode? = result
var carry = 0
var head1 = l1
var head2 = l2
while (head1 != nil || head2 != nil || carry != 0) {
let val1 = head1?.val ?? 0
let val2 = head2?.val ?? 0
let sum = val1 + val2 + carry
let out = sum % 10
carry = sum / 10
resultTail?.next = ListNode(out)
resultTail = resultTail?.next
head1 = head1?.next
head2 = head2?.next
}
return result.next
}
}
Note that idiomatic Swift you only explicitly type variables where the correct type cannot be inferred automatically by the compiler or you need a different type to that which the compiler will infer.
You can also simplify and clarify your ListNode by using named parameters with defaults in a single init
public class ListNode {
public var val: Int
public var next: ListNode?
public init(val: Int = 0, next: ListNode? = nil) {
self.val = val
self.next = next
}
}
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let result = ListNode()
var resultTail: ListNode? = result
var carry = 0
var head1 = l1
var head2 = l2
while (head1 != nil || head2 != nil || carry != 0) {
let val1 = head1?.val ?? 0
let val2 = head2?.val ?? 0
let sum = val1 + val2 + carry
let out = sum % 10
carry = sum / 10
resultTail?.next = ListNode(val: out)
resultTail = resultTail?.next
head1 = head1?.next
head2 = head2?.next
}
return result.next
}
}
let node3 = ListNode(val:3)
let node2 = ListNode(val: 4, next: node3)
let node1 = ListNode(val: 2, next: node2)
let node3a = ListNode(val:5)
let node2a = ListNode(val: 6, next: node3a)
let node1a = ListNode(val: 4, next: node2a)
let solution = Solution().addTwoNumbers(node1, node1a)

BMI app print result is 0 even with variable being hard coded [duplicate]

This question already has answers here:
Swift: Print decimal precision of division
(3 answers)
Closed 4 years ago.
Firstly Thanks to all upcoming answers .
I am new to swift programming . I am testing out many things lol . I am trying to do a bmi app. I am using print() in order to check all values of my variables.
I am not able to understand why imc value is 0 . Did I miss something ? What's the logic? I tried to hard code it with quotien 90/32400 or x/ySquare same result. I am still getting quotien = 0
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var weightTextField: UITextField!
#IBOutlet weak var heightTextfield: UITextField!
#IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func calculateButton(_ sender: Any) {
imcCalculator()
}
func imcCalculator () {
let myHeight = Int(heightTextfield.text!)
let myWeight = Int(weightTextField.text!)
let x = myWeight!
let y = myHeight!
//let imc = Int(Int(x / pow(y, 2)) * 10000)
let ySquare = y * y
let quotien = 90 / 32400
let imc = (x/ySquare)*10000
if imc > 25 {
resultLabel.text = " Your BMI is \(imc) . You are overweight"
}
else if imc 18 {
resultLabel.text = " Your BMI is \(imc) . You have a normal weight"
}
else {
resultLabel.text = "Your BMI is \(imc) . You are underweight"
}
print(x)
print(y)
print(ySquare)
print(quotien)
print(imc)
}
}
What's happening is called Truncation, or Integer division. The result of integer division differs from language to language. And as stated by the Swift docs:
For integer types, any remainder of the division is discarded
That's why let quotien = 90 / 32400 will give 0 as a result.
I would suggest you use Doubles instead, and your code might look like this:
func imcCalculator () {
guard let myHeight = Double("6"), let myWeight = Double("70") else {
fatalError("Error in the text fields")
}
let x = myWeight
let y = myHeight
//let imc = Int(Int(x / pow(y, 2)) * 10000)
let ySquare: Double = y * y
let quotien: Double = 90.0 / 32400.0
let imc: Double = (myHeight / ySquare) * 10000
let imcString: String = String(format: "Your BMI is %.2d", imc)
if imc > 25 {
resultLabel.text = imcString + " . You are overweight"
}
else if imc < 25 && imc > 18 {
resultLabel.text = imcString + " . You have a normal weight"
}
else {
resultLabel.text = imcString + " . You are underweight"
}
print("x =", x)
print("y =", y)
print("ySquare =", ySquare)
print("quotien =", quotien)
print("imc =", imc)
}
The point is: Arithmetic operations between elements of a certain type, give results of the same type.
Thus, when dividing for example 1 by 2, you should expect the result to be an integer too. And it's a convention to define the integer part of the quotient as the result of the division of the two numbers. 1 divided by 2 (in real number division) gives 0.5, the integer part of that is 0.
On the other hand, 1.0/2.0 is 0.5 since both the Dividend and Divisor are infered to be Doubles. If you don't add the .0 after at least one them, thene fractional part is discarded.
You can try this in a playground:
3/10 //0
3.0/10.0 //0.3
3.0/10 //0.3
3/10.0 //0.3
As noted by #Martin R, the result of integer division differs from the quotient of Euclidean division when the Dividend (numerator) is negative, since truncation always rounds toward zero. Here is what is meant by that:
In integer division: (-3)/10 equals 0
In Euclidean division: The quotient of (-3)/10 is -1

How do you round a UISlider to an int in swift

I was wondering how to round a UISilder value to a int value. Right now it is displaying floats. I am using swift 3 at the moment.
#IBOutlet var slidermove: UISlider!
#IBAction func SliderVal(_ sender: AnyObject) {
print(slidermove)
let x = round(slidermove)
}
round() does not work it will give an error, thanks for anyone that helps
You should round it's value instead of UISlider itself.:
let x = roundf(slider.value) // x is Float
If you need an Int instead of Float, just wrap it with Int initializer:
let x = Int(round(slider.value)) // x is Int
To round a Float to the nearest integer and get the result as
an Int, the (perhaps not so well-known) function lrintf()
can be used. Example:
let x = Float(12.6)
let i = lrintf(x)
print(i) // 13
In your case:
let i = lrintf(slider.value) // `i` is an `Int`

Resources