Photo Storage - FreeCodeCamp #40 Daily Challenge
Photo Storage - Analysis and Explanation
Problem Statement
Given the size of a photo in megabytes (MB) and the capacity of a hard drive in gigabytes (GB), the goal is to determine how many complete photos can be stored on the disk following these rules:
- gigabyte (GB) is equal to megabytes (MB).
- You must return the number of whole photos (no decimals).
Initial Analysis
Understanding the Problem
The logic requires converting the disk capacity from GB to MB and then dividing that total by the size of each photo. Since we are only interested in complete photos, we must round the result down.
Process Visualization
flowchart TD A["Input: photoSize (MB), driveSize (GB)"] --> B["Convert GB to MB: driveSize * 1000"] B --> C["Calculate photos: totalMB / photoSize"] C --> D["Round down (Math.floor)"] D --> E["Result: Number of photos"]
Identified Test Cases
- Basic:
photoSize = 1,driveSize = 1photos. - Exact division:
photoSize = 2,driveSize = 1photos. - With decimals:
photoSize = 3.5,driveSize = 5.5photos. - Edge Case: If the photo size is or negative, we must avoid division by zero.
Solution Development
Chosen Approach
We will use a direct arithmetic formula. It is important to perform the unit conversion first and then apply the JavaScript rounding function to ensure the result is an integer.
Implementation
/**
* Calculates how many complete photos fit on a hard drive.
* @param photoSizeMb Size of each photo in MB.
* @param hardDriveSizeGb Disk capacity in GB.
* @returns Number of whole photos.
*/
function numberOfPhotos(photoSizeMb: number, hardDriveSizeGb: number): number {
if (photoSizeMb <= 0)
return 0
const totalMb = hardDriveSizeGb * 1000
return Math.floor(totalMb / photoSizeMb)
}Complexity Analysis
Time Complexity
. The function performs a constant number of basic arithmetic operations, regardless of the magnitude of the input values.
Space Complexity
. No additional storage is required that depends on the input; only constant local variables are used.
Edge Cases and Considerations
- Division by zero: We validate that
photoSizeMbis greater than zero to avoid execution errors or infinite results. - Unit conversion: The challenge specifies GB = MB. Although is sometimes used in computing, we must stick to the problem requirements.
- Precision: When working with floating-point numbers in JavaScript,
Math.flooris the safest way to obtain the required integer part.
Reflections and Learnings
Applied Concepts
- Unit Conversion: Transforming scales to operate with the same magnitude.
- Controlled Rounding: Using
Math.floorto comply with the “complete photos” constraint.
Possible Improvements
In a real-world environment, validations could be added to ensure inputs are positive numbers and handle potential precision errors in very long decimal numbers, although for this challenge, the direct solution is optimal.