Created
August 1, 2022 12:54
-
-
Save anushshukla/86671762af7853956252cbc279b6b9ee to your computer and use it in GitHub Desktop.
Logistics: finding a package of given weight in a shipment
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
| /* | |
| At logistics we deal with package weights before shipment. | |
| Lets say there are infinite number of packages arranged in increasing order of weights. | |
| You have to find if a package of given weight (W) exist . | |
| If exist return position else return -1; | |
| Infinite : You will never be able to know size of array (Arr.length/size is not possible) | |
| eg. [2,3,6,10, 46 , 49 , 100 , 110 , . , . , . , . , …..] | |
| */ | |
| /* | |
| while | |
| check in batches -> 10 [0..9 index] arr[9] -> value if inputWt = arr[9] return | |
| else if (inputWt < arr[9]) divid and conquer (limit = limit / 2) | |
| else if (inputWt > arr[0+9 -> 19]) | |
| 0 - 10 | |
| 10 - 10 + 10 | |
| 10 - 20 | |
| 20, 20 + 20 | |
| 20 + 40 | |
| 99 | |
| */ | |
| const findPackageByWt(packageWtArr: number[], findPackageWt: number): number { | |
| const isSearchComplete = true; | |
| let limit = 10; | |
| let offset = 0; | |
| while (isSearchComplete) { | |
| const curren2tBatchLastIndex = limit - 1; | |
| const currentBatchLastWt = packageWtArr[currentBatchLastIndex]; | |
| if (currentBatchLastWt === findPackageWt) { | |
| return currentBatchLastIndex; | |
| } | |
| if (packageWtArr.length === 1) { | |
| return -1; | |
| } | |
| if (findPackageWt > currentBatchLastWt) { | |
| offset = limit; | |
| limit += limit; | |
| continue; | |
| } | |
| if (findPackageWt < currentBatchLastWt) { | |
| return findPackageByWt(packageWtArr.splice(offset, limit), findPackageWt); | |
| } | |
| } | |
| } | |
| findPackageByWt([2,3,6,10, 46 , 49 , 100 , 110 , . , . , . , . , …..], 99) // -1 | |
| findPackageByWt([2,3,6,10, 46 , 49 , 100 , 110 , . , . , . , . , …..], 46) // 4 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment