Created
April 18, 2021 17:01
-
-
Save isaac-weisberg/649a25349f09bfa6601692df4c7c07e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ApartmentPlacement: Equatable { | |
let entrance: Int | |
let floor: Int | |
let location: Int | |
} | |
func calculateApartmentPlacement(for apartmentNumber: Int, totalEntrances: Int, totalFloors: Int) -> ApartmentPlacement? { | |
let apartmentIndex = apartmentNumber - 1 | |
guard totalEntrances > 0, totalFloors > 0 else { | |
return nil | |
} | |
let totalLocations = 4 | |
let totalApartmentsPerEntrance = totalFloors * totalLocations | |
let totalApartments = totalEntrances * totalApartmentsPerEntrance | |
guard (0..<totalApartments).contains(apartmentIndex) else { | |
return nil | |
} | |
let seekedEntranceIndex = apartmentIndex / totalApartmentsPerEntrance | |
let seekedFloorIndex = apartmentIndex % totalApartmentsPerEntrance / totalLocations | |
let seekedLocationIndex = apartmentIndex % totalLocations | |
let seekedEntranceNumber = seekedEntranceIndex + 1 | |
let seekedFloorNumber = seekedFloorIndex + 1 | |
let seekedLocationNumber = seekedLocationIndex + 1 | |
return ApartmentPlacement( | |
entrance: seekedEntranceNumber, | |
floor: seekedFloorNumber, | |
location: seekedLocationNumber | |
) | |
} | |
// The following is just tests | |
let values: [(ApartmentPlacement?, ApartmentPlacement?)] = [ | |
(calculateApartmentPlacement(for: 1, totalEntrances: 1, totalFloors: 1), ApartmentPlacement(entrance: 1, floor: 1, location: 1)), | |
(calculateApartmentPlacement(for: 2, totalEntrances: 1, totalFloors: 1), ApartmentPlacement(entrance: 1, floor: 1, location: 2)), | |
(calculateApartmentPlacement(for: 3, totalEntrances: 1, totalFloors: 1), ApartmentPlacement(entrance: 1, floor: 1, location: 3)), | |
(calculateApartmentPlacement(for: 4, totalEntrances: 1, totalFloors: 1), ApartmentPlacement(entrance: 1, floor: 1, location: 4)), | |
(calculateApartmentPlacement(for: 5, totalEntrances: 1, totalFloors: 1), nil), | |
(calculateApartmentPlacement(for: 5, totalEntrances: 2, totalFloors: 1), ApartmentPlacement(entrance: 2, floor: 1, location: 1)), | |
(calculateApartmentPlacement(for: 37, totalEntrances: 5, totalFloors: 3), ApartmentPlacement(entrance: 4, floor: 1, location: 1)), | |
(calculateApartmentPlacement(for: 359, totalEntrances: 75, totalFloors: 12), ApartmentPlacement(entrance: 8, floor: 6, location: 3)), | |
] | |
let testValues = values.map { lhs, rhs in | |
lhs == rhs | |
} | |
values.forEach { vals in | |
print(vals) | |
} | |
let allTestsWorkedOut = testValues.allSatisfy { $0 } | |
print("All tests passed: \(allTestsWorkedOut)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment