Questions based on higher-order functions — Part III
Question 11: Suppose you have an array of order objects, each containing a product name, quantity, and unit price property. How would you calculate the total revenue generated from orders containing more than 10 units using higher-order functions?
Answer:
struct Order {
let productName: String
let quantity: Int
let unitPrice: Double
}
let orders = [
Order(productName: "Product A", quantity: 5, unitPrice: 10),
Order(productName: "Product B", quantity: 15, unitPrice: 20),
Order(productName: "Product C", quantity: 8, unitPrice: 30),
Order(productName: "Product D", quantity: 12, unitPrice: 25)
]
let revenue = orders.filter { $0.quantity > 10 }.map { $0.quantity * $0.unitPrice }.reduce(0, +)
print("Total revenue from orders with more than 10 units: \(revenue)")
Question 12: Given an array of transactions where each transaction contains a type (debit or credit) and an amount property, how would you find the average debit amount and the average credit amount separately using higher-order functions?
Answer:
enum TransactionType {
case debit
case credit
}
struct Transaction {
let type: TransactionType
let amount: Double
}
let transactions = [
Transaction(type: .debit, amount: 100),
Transaction(type: .credit, amount: 50),
Transaction(type: .debit, amount: 200),
Transaction(type: .credit, amount: 75)
]
let debitTransactions = transactions.filter { $0.type == .debit }
let creditTransactions = transactions.filter { $0.type == .credit }
let averageDebitAmount = debitTransactions.map { $0.amount }.reduce(0, +) / Double(debitTransactions.count)
let averageCreditAmount = creditTransactions.map { $0.amount }.reduce(0, +) / Double(creditTransactions.count)
print("Average debit amount: \(averageDebitAmount)")
print("Average credit amount: \(averageCreditAmount)")
Question 13: Suppose you have an array of orders where each order contains a product name, quantity, and unit price property. How would you find the most expensive product purchased by quantity using higher-order functions?
Answer:
struct Order {
let productName: String
let quantity: Int
let unitPrice: Double
}
let orders = [
Order(productName: "Product A", quantity: 5, unitPrice: 10),
Order(productName: "Product B", quantity: 15, unitPrice: 20),
Order(productName: "Product C", quantity: 8, unitPrice: 30),
Order(productName: "Product D", quantity: 12, unitPrice: 25)
]
if let mostExpensiveOrder = orders.max(by: { $0.unitPrice * Double($0.quantity) < $1.unitPrice * Double($1.quantity) }) {
print("The most expensive product purchased by quantity is \(mostExpensiveOrder.productName)")
} else {
print("No orders found")
}
Question 14: Given an array of tasks where each task contains a name and a duration property, how would you calculate the total duration of all tasks with names starting with “Work” using higher-order functions?
Answer:
struct Task {
let name: String
let duration: Double // in hours
}
let tasks = [
Task(name: "Work Meeting", duration: 1.5),
Task(name: "Work Presentation", duration: 2),
Task(name: "Personal Project", duration: 3),
Task(name: "Work Report", duration: 1)
]
let totalWorkDuration = tasks.filter { $0.name.hasPrefix("Work") }.map { $0.duration }.reduce(0, +)
print("Total duration of work tasks: \(totalWorkDuration) hours")
Question 15: Suppose you have an array of employee objects, each containing a name and a list of projects they have worked on. Each project has a name and a duration property. How would you find the employee who has worked on the longest total duration of projects using higher-order functions?
Answer:
struct Project {
let name: String
let duration: Double // in hours
}
struct Employee {
let name: String
let projects: [Project]
}
let employees = [
Employee(name: "Alice", projects: [Project(name: "Project A", duration: 10), Project(name: "Project B", duration: 15)]),
Employee(name: "Bob", projects: [Project(name: "Project C", duration: 20), Project(name: "Project D", duration: 25)]),
Employee(name: "Charlie", projects: [Project(name: "Project E", duration: 30), Project(name: "Project F", duration: 35)])
]
if let topEmployee = employees.max(by: { employee1, employee2 in
let totalDuration1 = employee1.projects.map { $0.duration }.reduce(0, +)
let totalDuration2 = employee2.projects.map { $0.duration }.reduce(0, +)
return totalDuration1 < totalDuration2
}) {
print("The employee with the longest total duration of projects is \(topEmployee.name)")
} else {
print("No employees found")
}
Question 16: Given an array of students where each student has a name and a list of subjects they are studying, how would you find the student who is studying the most number of subjects using higher-order functions?
Answer:
struct Student {
let name: String
let subjects: [String]
}
let students = [
Student(name: "Alice", subjects: ["Math", "Science", "History"]),
Student(name: "Bob", subjects: ["Math", "English"]),
Student(name: "Charlie", subjects: ["Math", "Science", "English", "Art"])
]
if let topStudent = students.max(by: { $0.subjects.count < $1.subjects.count }) {
print("The student studying the most number of subjects is \(topStudent.name)")
} else {
print("No students found")
}
Question 17: Suppose you have an array of song objects, each containing a title, artist, and duration property. How would you find the total duration of songs by a specific artist using higher-order functions?
Answer:
struct Song {
let title: String
let artist: String
let duration: Double // in minutes
}
let songs = [
Song(title: "Song A", artist: "Artist X", duration: 4.5),
Song(title: "Song B", artist: "Artist Y", duration: 3.2),
Song(title: "Song C", artist: "Artist X", duration: 5.1)
]
let artistToFilter = "Artist X"
let totalDuration = songs.filter { $0.artist == artistToFilter }.map { $0.duration }.reduce(0, +)
print("Total duration of songs by \(artistToFilter): \(totalDuration) minutes")