Hello friends! This time I want to share about Least Larger challenges from Codewars. This challenge is very exciting because of training logic and systematic ways of thinking, while providing an idea of how this concept can be useful in the real world. Come on, we discuss together!
So, we are given a number array and a particular index. Our task is to search for the smallest number that is bigger of the elements in the index, then return the index . If there are no numbers that meet, we must return -1.
Example:
Array: [4, 1, 3, 5, 6]
Index: 0 (reference number is 4)
The result is 3, because the smallest number that is larger than 4 is 5, which is in index 3.
Why can 3?
The array starts from 0
So :
4: Index 0
1: Index 1
3: Index 2
5: Index 3
6: Index 4
To complete this challenge, I made a function called Leastlarger. The following is the code:
function leastLarger(a, i) { let smaller = Infinity; // Nilai pembanding awal let result = -1; // Default hasil kalau nggak ada elemen yang memenuhi for (let index = 0; index a[i] && a[index]
How does it work?
initial initialization
- I set the smaller to Infinity as the initial value for comparison.
- Result was set in 1st in case there was no element that meets.
I check every element in the array.
- There are two conditions that must be met:
- If the two conditions are met, I update the smaller and save the element index in the result.
The element is greater than the reference element (A [i]).
- The element is smaller than the previous comparison (smaller).
returns the results
If there are elements that meet, the function of returning the index.
- If there isn't, the results are still -1.
Examples of useConsole.log (Leastlarger ([4, 1, 3, 5, 6], 0)); // Output: 3
console.log(leastLarger([4, 1, 3, 5, 6], 0)); // Output: 3Explanation:
console.log(leastLarger([4, 1, 3, 5, 6], 0)); // Output: 3This code does the same thing, but in a more functional and concise style. Suitable for situations where you want to write a quick solution without too many additional variables.
Ticket ordering system
task scheduling
Inventory management
Oh yes, if friends have other ways to complete this challenge, don't hesitate to share in the comments column, yes! Who knows, we can learn from each other from different approaches. Hopefully this sharing is useful, and happy coding! ?
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3