Hello, friends! This time I want to share about the Least Larger challenge from CodeWars. This challenge is really exciting because it trains logic and systematic thinking, as well as giving an idea of how this concept can be useful in the real world. Come on, let's discuss it together!
So, we are given an array of numbers and a certain index. Our task is to find the smallest number that is greater than the element at that index, then return the index. If there are no matching numbers, 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 greater than 4 is 5, which is at index 3.
why can it be 3?
The array starts from 0
so:
4 : index 0
1 : index 1
3 : index 2
5 : index 3
6 : index 4
To solve this challenge, I created a function called leastLarger. Here's 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.length; index++) { if (a[index] > a[i] && a[index] < smaller) { smaller = a[index]; // Update nilai terkecil yang lebih besar result = index; // Simpan indeks elemen } } return result; // Kembalikan hasil }
Initialization
Array Iteration
Returning Results
console.log(leastLarger([4, 1, 3, 5, 6], 0)); // Output: 3
Explanation:
For those of you who like a more "JavaScript-only" approach, we can write this solution in one line of code using built-in methods like filter, Math.min, and findIndex:
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.length; index++) { if (a[index] > a[i] && a[index] < smaller) { smaller = a[index]; // Update nilai terkecil yang lebih besar result = index; // Simpan indeks elemen } } return result; // Kembalikan hasil }
This code does the same thing, but in a more functional and concise style. Great for situations where you want to write a quick solution without too many additional variables.
A function like this is actually quite relevant in various real situations. Some examples:
Ticket Booking System
Task Scheduling
Inventory Management
This challenge looks simple, but when I tried it, I realized that neat logic is very important. What I like about this challenge is how relevant this concept is to apply in the real world.
Oh yes, if friends have other ways to complete this challenge, don't hesitate to share them in the comments column, OK! Who knows, we might learn from each other's different approaches. Hopefully this sharing is useful, and happy coding! ?
The above is the detailed content of Sharing CodeWars Challenge Solutions: Least Larger, from Basic to Aris. For more information, please follow other related articles on the PHP Chinese website!