Swift
Swift
We define a function named maxProduct that takes an array of integers nums as input
We first check if the input array nums is empty. If it is, we return 0, as there's no valid
We initialize three variables: var_out, var_a, and var_i to the first element of the nums
array.
We then iterate through the nums array starting from the second element (index 1).
Inside the loop, we check if the current element nums[i] is less than 0. If it is, we swap
the values of var_a and var_i. This step is used to handle negative numbers in the
array.
We calculate the maximum product ending at the current element nums[i] and update
var_a with the maximum of the current element and the product of var_a and nums[i].
This step ensures that var_a stores the maximum product ending at the current position.
Similarly, we calculate the minimum product ending at the current element nums[i] and
update var_i with the minimum of the current element and the product of var_i and
nums[i]. This step ensures that var_i stores the minimum product ending at the current
position.
We update var_out with the maximum of var_out and var_a. This step ensures that
var_out stores the maximum product among all possible products ending at different
After the loop is complete, we return the final value of var_out, which represents the
We define an input array input and call the maxProduct function with this input array.
Finally, we print the result, which is the maximum product of the subarray.
Question 1a
import UIKit
if nums.isEmpty {
return 0
for i in 1..<nums.count {
if nums[i] < 0 {
swap(&var_a, &var_i)
return var_out
Part b
import UIKit
if nums.isEmpty {
return 0
for i in 1..<nums.count {
minEndingHere)
minEndingHere)
return maxProduct
Question 1b
minEndingHere to track the maximum product overall, the maximum product ending at
the current index, and the minimum product ending at the current index, respectively.
It iterates through the input array nums starting from the second element (index 1).
For each element at index i, it calculates the new maxEndingHere and minEndingHere
and maxEndingHere.
The loop continues until it processes all elements in the input array.
Finally, the function returns the maxProduct, which represents the maximum product of
a subarray.
import UIKit
if nums.isEmpty {
return 0
for i in 1..<nums.count {
minEndingHere)
minEndingHere)
return maxProduct
// Example 2
// Calculate and print the maximum product of a subarray for the second example
(2*3*4*5)
Question 2
Code
import UIKit
struct Client {
}
// Create an empty array to store client information
} else {
let newClient = Client(userID: userID, name: name, age: age, balance: balance)
clientDatabase.append(newClient)
clientDatabase[index].name = newName
}
clientDatabase[index].age = newAge
clientDatabase[index].balance = newBalance
} else {
return client
} else {
return nil
}
// Function to display all clients in the database
func displayAllClients() {
print("Client Database:")
(client.balance)")
// Example usage
displayAllClients()
Explanation
An example usage is demonstrated with two clients added, one client's information
Question 2a
userID:
should be represented using the UInt32 (unsigned 32-bit integer) data type. Using an
name:
Explanation: The client's name is a text-based field and should be represented using the
String data type. This allows for the storage of variable-length strings, accommodating
full names.
age:
Explanation: The client's age is represented as an integer value. The Int data type is
suitable for storing whole numbers, including positive and negative values. Since age
should always be a non-negative integer, you might consider using UInt (unsigned
integer) to enforce that constraint, but Int is commonly used for age.
balance:
number to accommodate decimal values. You can use the Double data type for
balance. However, for financial calculations where precision is crucial, consider using
the Decimal data type, which provides high precision for decimal arithmetic. Using
Question 2b
To store client data and efficiently perform functions such as checking and updating the
balance with a given userID, you can consider different data structures in Swift. The
Dictionary:
Use Case: If you need fast access to client information based on their userID.
Recommendation: Create a dictionary where userID serves as the key, and the client
data (e.g., name, age, balance) is stored as the associated value. This allows for quick
To check the balance with a given userID, you can use clientData[userID]?.balance.
To update the balance for a given userID, you can use clientData[userID]?.balance =
newBalance.
Use Case: If you need to maintain an ordered list of clients and perform operations that
or tuple containing userID, name, age, and balance. This allows you to maintain a client
struct Client {
To update the balance for a given userID, you can iterate through the clients array,
Use Case: If you need to manage a large number of clients and require data
Recommendation: Use a database system like Core Data or SQLite. These systems
allow you to create client entities with attributes for userID, name, age, and balance.
You can perform efficient queries and updates based on various criteria, including
userID.
You would define a database schema that includes a client table with columns for each
client attribute.
Swift APIs.
Question 2c
import Foundation
struct Client {
// Create an array to store client data (you can initialize it with your test data)
clients[senderIndex].balance -= amount
clients[receiverIndex].balance += amount
// Transaction successful
return true
} else {
return false
(client.balance)")
} else {
displayBalance(userID: senderID)
displayBalance(userID: receiverID)
} else {
explanation
checks the sender's balance, deducts the amount from the sender, and adds it to the
The displayBalance function displays the final balance of a client based on their userID.
of $500. The result is printed, along with the final balances of both sender and receiver.
Question 3b
When a user opens the app for the first time, they are presented with a registration form
where they can create an account by providing details like name, age, and choosing a
Upon successful registration, the user's profile is created, and they can log in using their
credentials.
2. Home Screen:
After logging in, users are taken to the home screen, which serves as the app's main
dashboard.
The home screen displays the user's current location on a map, allows them to start and
3. Activity Tracking:
When the user clicks the "Start Activity" button, the app begins tracking their location
The app calculates the distance traveled, updates the user's activity statistics, and
4. Activity Statistics:
The app displays real-time activity statistics, including distance traveled and points
5. Points System:
Points are earned based on the user's activity. The app tracks the user's progress and
6. Gift Store:
Users can access the gift store from the home screen or a dedicated view controller.
The gift store displays available gifts, their point values, and allows users to redeem
If the money transfer feature is implemented, users can initiate transfers to other users
The app validates the transfer and updates both users' point balances.
8. User Profile:
Users can access their profile information, including name, age, and point balance,
9. User Logout:
Users can log out of their accounts, and their session is terminated.
10. Persistence:
- User profiles, points, and activity history are stored persistently, so users can access
- If a backend server is used, the app communicates with the server for user
To achieve these features, different UIViews and UIControls are used in various view
controllers. Here's a brief overview of how some of the features are designed:
- MapView: The MapView is used to display the user's current location. It utilizes the
MapKit framework to show the map and annotate the user's position.
- Buttons (Start, Stop, Redeem): UIButtons are used to trigger actions such as
- Text Fields: UITextFields are used for user input during registration and, if applicable,
- UITableView: UITableViews can be used to display lists of gifts in the gift store and
user profiles.
- Core Location: Core Location framework is used to access the device's GPS for
- User Defaults: UserDefaults can be used for storing small amounts of user data
persistently.
communicate with a backend server for features like registration, login, and data
synchronization.
- CoreData (Optional): CoreData framework can be used for local data storage and