Showing posts with label Leap and Scale. Show all posts
Showing posts with label Leap and Scale. Show all posts

### Write a program for sorting array. Quick sort, merge sort, Heap Sort

Ans :

Quick Sorting Integer Array - Explanation

func swap<T: Comparable>(leftValue: inout T, rightValue: inout T) {
(leftValue, rightValue) = (rightValue, leftValue)
}

func partition<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) -> Int {
var q = startIndex
for index in startIndex..<endIndex {
if array[index] < array[endIndex] {
swap(leftValue: &array[q], rightValue: &array[index])
q += 1
}
}
swap(leftValue: &array[q], rightValue: &array[endIndex])
return q
}
func quickSort<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) {
// Base case
if startIndex >= endIndex {
return
}
let placedItemIndex = partition(array: &array, startIndex: startIndex, endIndex: endIndex)
quickSort(array: &array, startIndex: startIndex, endIndex: placedItemIndex-1)
quickSort(array: &array, startIndex: placedItemIndex+1, endIndex: endIndex)
}
func quickSort<T: Comparable>(array: inout [T]) {
quickSort(array: &array, startIndex: 0, endIndex: array.count-1)
}
var numbers = [13, 77, 20, 45, 2, 15, 0, 59, 5, 68, 51, 1, -1, 77]

quickSort(array: &numbers)

Merge Sorting Integer Array - Explanation

func merge<T: Comparable> (array: inout [T], startIndex: Int, middleIndex: Int, endIndex: Int) {
let leftSubarray = Array(array[startIndex...middleIndex])
let rightSubarray = Array(array[middleIndex+1...endIndex])
var index = startIndex
var leftIndex = 0
var rightIndex = 0
while leftIndex < leftSubarray.count && rightIndex < rightSubarray.count {
if leftSubarray[leftIndex] < rightSubarray[rightIndex] {
array[index] = leftSubarray[leftIndex]
leftIndex += 1
}
else {
array[index] = rightSubarray[rightIndex]
rightIndex += 1
}
index += 1
}
while leftIndex < leftSubarray.count {
array[index] = leftSubarray[leftIndex]
index += 1
leftIndex += 1
}
while rightIndex < rightSubarray.count {
array[index] = rightSubarray[rightIndex]
index += 1
rightIndex += 1
}
}

func mergeSort<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) {
// Base case
if startIndex >= endIndex {
return
}
let middleIndex = (startIndex + endIndex) / 2
mergeSort(array: &array, startIndex: startIndex, endIndex: middleIndex)
mergeSort(array: &array, startIndex: middleIndex+1, endIndex: endIndex)
merge(array: &array, startIndex: startIndex, middleIndex: middleIndex, endIndex: endIndex)
}
func mergeSort<T: Comparable>(array: inout [T]) {
mergeSort(array: &array, startIndex: 0, endIndex: array.count-1)
}

var numbers = [13, 77, 20, 45, 2, 15, 0, 59, 5, 68, 51, 1, -1, 77]
mergeSort(array: &numbers)

Heap Sorting Integer Array - Explanation

extension Heap {
public mutating func sort() -> [T] {
for i in stride(from: (nodes.count - 1), through: 1, by: -1) {
nodes.swapAt(0, i)
shiftDown(from: 0, until: i)
}
return nodes
}
}
/*
Sorts an array using a heap.
Heapsort can be performed in-place, but it is not a stable sort.
*/
public func heapsort<T>(_ a: [T], _ sort: @escaping (T, T) -> Bool) -> [T] {
let reverseOrder = { i1, i2 in sort(i2, i1) }
var h = Heap(array: a, sort: reverseOrder)
return h.sort()
}

//Testing
func testSort() {
var h1 = Heap(array: [5, 13, 2, 25, 7, 17, 20, 8, 4], sort: >)
let a1 = h1.sort()
}

// output : [2, 4, 5, 7, 8, 13, 17, 20, 25]

### Have you done battery optimization for gps or api calling?

Ans :

Energy Efficiency in location gathering environment, What can be done.
Stop Location Updates if Accuracy Doesn’t Match Expectations
If your app isn’t receiving updates with the expected level of accuracy, your app should examine the updates it is receiving and determine whether accuracy is improving or staying about the same over time. If accuracy isn’t improving, it’s possible that the desired level of accuracy simply isn’t available at the moment. In this case, stop location updates and try again later so your app doesn’t continuously cause location hardware to draw power.

# Stop Location Services When You Aren’t Using Them

With the exception of navigation apps that offer turn-by-turn directions, most apps don’t need location services to be on all the time. Turn location services on only when they’re needed. Then, leave them on just long enough to get a location fix and turn them off again. Unless the user is in a moving vehicle, the current location shouldn’t change frequently enough to be an issue. You can always start location services again later if you need another update.

# Reduce Accuracy of Standard Location Updates Whenever Possible

Standard location updates let you specify a degree of accuracy ranging from a few meters to a few kilometers by setting the desiredAccuracy property of the location manager object. Requesting higher accuracy than you need causes Core Location to power up additional hardware and waste power for unnecessary precision. Unless your app really needs to know the user’s position within a few meters, don’t set the accuracy level to best (kCLLocationAccuracyBest) or nearest ten meters (kCLLocationAccuracyNearestTenMeters). Also, be aware that Core Location typically provides more accurate data than you have requested. For example, when specifying an accuracy level of three kilometers (kCLLocationAccuracyThreeKilometers), you may receive accuracy within a hundred meters or so.
IMPORTANT
By default, standard location updates on iOS devices run with an accuracy level of best. Change these settings to match your app’s requirements. Otherwise, your app will unnecessarily waste energy.
Auto-Pause and Specify an Activity Type When Receiving Location Updates in the Background
Make sure the location manager object’s pausesLocationUpdatesAutomatically property is set to YES to help conserve power.Set the activityType property to let Core Location know what type of location activity your app is performing at a given time — for example, if your app is performing fitness tracking or automotive navigation

# Restrict Location Updates to Specific Regions or Locations

Some apps don’t need to receive continuously location updates, and just need to know when the user is within a certain distance of a location. For example, a grocery app may display new coupons whenever the user nears the store. There are several Core Location APIs that can keep your app informed.
NOTE
The monitoring techniques described below provide entry and exit notifications only. To determine the user’s actual location when a notification is received, you must call the requestLocation: or startUpdatingLocation: method of the location manager object. These monitoring techniques also require an authorization status of kCLAuthorizationStatusAuthorizedAlways.
Activity Types
• CLActivityTypeOther
The location manager is being used for an unknown activity.
The location manager is being used specifically during vehicular navigation to track location changes to the automobile. This activity might cause location updates to be paused only when the vehicle does not move for an extended period of time.
• CLActivityTypeFitness
The location manager is being used to track any pedestrian-related activity. This activity might cause location updates to be paused only when the user does not move a significant distance over a period of time.
The location manager is being used to track movements for other types of vehicular navigation that are not automobile related. For example, you would use this to track navigation by boat, train, or plane. Do not use this type for pedestrian navigation tracking. This activity might cause location updates to be paused only when the vehicle does not move a significant distance over a period of time.
Visit Monitoring
Visit monitoring allows an app to receive entry and exit notifications for specific locations the user visits frequently or for long periods of time such as home, work, or a favorite coffee shop.
To begin monitoring for visits, assign a delegate to the location manager object and call itsstartMonitoringVisits method. Note that calling this method enables all visit updates in your app, not just ones for the current delegate. When enabled, visit events are delivered to the locationManager:didVisit:method of the delegate. If your app isn’t running when a visit event is delivered, your app is relaunched automatically. When visit location updates are no longer required, call stopMonitoringVisits

# Register for Significant-Change Location Updates Only as a Last Resort

If GPS-level accuracy isn’t critical for your app, you don’t need continuous tracking, and region or visit monitoring isn’t more appropriate for your app, you can use the significant-change location service instead of the standard one.
IMPORTANT
Region and visit monitoring are sufficient for most use cases and should always be considered before significant-change location updates. In the event significant-change location updates are needed, keep in mind the following, which can actually result in higher energy use if not employed effectively:
• > Significant-change location updates wake the system and your app once every 15 minutes, at minimum, even if no location changes have occurred.
• > Significant-change location updates run continuously, around the clock, until you stop them.
To start significant-change location updates, call the startMonitoringSignificantLocationChanges method of the location manager object. When you’re done, call stopMonitoringSignificantLocationChanges .

### Write a program for get only numeric from "a,b,1,2,c,4,d,3"

Ans :

let string = "I have to buy 3 apples, 7 bananas, 10eggs"
let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
if let number = Int(item) {
print("number: \(number)")
}

}

Output :

3
7
10

### Write a program to swap between two numbers without third variable

Ans :

For Int :

var x = 5
var y = 7

x = x + y
y = x - y
x = x - y

print(x)
print(y)

For Other Types :

var a = "a"
var b = "b"
(b, a) = (a, b)

### What is error and exception? Difference between exception and error

Ans :

Exception and Error is of course different. Following explanation in given for considering Objective-C.

Exception : Exceptions cause applications to crash if left unhandled. They generally occur when trying to perform an operation on an object incorrectly, such as using an out-of-bounds index to access an array item, or passing nil to a method that doesn’t accept it. In other words, they are caused by developer mistakes. Unhandled exceptions in your published apps must be avoided at all costs.

They are warnings to developers that a serious coding issue has occurred and needs to be fixed. They are expected to occur during development of you application, and provide information that will help you solve the issue before shipping your app.

In Objective-C, NSException is there to handle unwanted exception. This class contains 3 key points of information :

Name : Name identifies the type of exception that has occurred. The name property is used as the high level categorization.

Reason : Reason is a short explanation of why the exception has been thrown. For example “+[Class Selector] unrecognized selector sent to class 0x10866fb88”.

Userinfo : UserInfo is an NSDictionary of additional information that can help to debug the problem.

Error Errors don’t get thrown, and they don’t cause the application to crash. They are created to hold information about a failure

Errors in iOS are represented by the NSError class which provides these 3 properties:

domain is a high level grouping of errors.

code is used to distinguish different types of errors within a domain.

Exceptions are caused by programming faults, and must be fixed or handled. Errors are expected to happen from time to time and should be dealt with accordingly.

### What is accuracy of GPS location?

Ans :

CLLocationAccuracy class provides accuracy constant.

`kCLLocationAccuracyKilometer:`
Accurate to the nearest kilometer.

`kCLLocationAccuracyBestForNavigation:`
The highest possible accuracy that uses additional sensor data to facilitate navigation apps.
`kCLLocationAccuracyBest:`
The best level of accuracy available.
`kCLLocationAccuracyNearestTenMeters:`
Accurate to within ten meters of the desired target.
`kCLLocationAccuracyHundredMeters:`
Accurate to within one hundred meters.
`kCLLocationAccuracyThreeKilometers:`
Accurate to the nearest three kilometres.

### Difference between network location and gps location.

Ans :

Network location usually refers to cellular location, or wifi location. They are less accurate then GPS (Global Positioning System - satellite based) location. When the app cannot obtain GPS location (probably because the target device is inside a building), the less accurate network location is obtained and uploaded to the map page.