Find k number of array elements having the minimum difference amongst themselves - javascript

So basically I have an array of n integers (positive only). I want to have k number of integers from this array into a separate array (k<n) such that the difference between these k numbers is the minimum amongst every other k pairs of integers in an array.
If k is 1, I just need to return the max integer of the array.
I want to implement this in JavaScript. I understand how to run this problem for the values k=1 and k=2. But I don't grasp the general concept of this problem.
For eg:
Array = [6,22,21,63,99,77]
I sorted this array in ascending order. After this I don't understand how to proceed further.

After sorting the array it becomes similar to a sliding window problem.
Run a loop from i=0 to n-k and check the following.
Find the minimum difference between arr[i+k] and arr[i]. The index at which this occurs is your subset of k integers you want.
You can check this link for more details and coding help.

Related

I need help understanding this algorithm solution of Top k frequent element

I am having trouble understanding the last line of this algorithm specifically the inside of the sort method, I don't understand why b[1] is being subtracted by a[1] I tried working through the return statement one step at a time: I know that at Object.entries(storage) I should have an array with 3 arrays inside like so [[1,4],[3,3],[2,1]] I then console logged b[1] to see what it would be and it gave me 4 from the first array and 3 from the second array then I console logged a[1] and the output was 3 from the second array and 2 from the third array so I'm really confused as to why they don't even start from the same index which would be [1]. If I'm not clear or if I'm missing any information let me know and I will try to update my question quickly
The testcase I'm using is nums=[1,1,1,1,3,3,3,2,2] and k=2
the original question in leetcode
var topKFrequent = (nums, k) => {
let storage = {}
for(let num of nums){
storage[num] = (storage[num] ?? 0) + 1
console.log(storage[num],'tset')
}
return Object.entries(storage).sort((a,b) => b[1] -a[1]).map(val=>Number(val[0])).slice(0,k);
}
I'm really confused as to why they don't even start from the same index which would be [1]
The sort method decides "on its own" which two values (two little subarrays in this case -- I will refer to them as "elements") from the input array it will pass as arguments to your callback function. We are not supposed to be concerned by that choice.
Realise that the internal sort algorithm will call your callback function when it wants to know how two elements from the given array compare.
It is normal that this internal sort algorithm will select a and b as two different elements, as it doesn't need to know how the first element compares with itself. It needs to know how two distinct elements compare and for that it will call your callback function. a and b could really be elements at any index in your array, and in subsequent calls of the callback those indices don't have to follow a certain order. It really could be any pair from the array depending on which algorithm the sort method uses. It could in theory even decide to start with the last two elements in your array...
Although we could dive into the source code of the JavaScript engine we are working with (like V8) to determine what a and b would be when the callback is called, it really shouldn't be of our concern. All we are responsible for is to have the callback answer the question how the given a and b compare.
We do this by:
returning 0 when we want a and b to be treated as equal in the sorting order,
returning a negative number when we want a to be ordered before b in the result (we define that a is "less than" b)
returning a positive number when we want a to be ordered after b in the result (we define that a is "greater than" b).
As long as the sorting algorithm doesn't have enough information to complete the sort, it will call the callback to get more info. All the rest of the sorting algorithm is taken care of by the sort method implementation.
Well, given [[1,4],[3,3],[2,1]], it first compares a = [3,3] with b = [1,4]. Your "same index" sounds like you expect it to compare [1,4] with itself? Anyway, b[1] - a[1] = 4-3 = 1 is greater than zero. The sorting algorithm really is ascending, so "greater" means "belongs on the right". So you're telling it that [3,3] belongs to the right of [1,4].
In the second comparison, you're telling it that [2,1] belongs to the right of [3,3].
That's all the sorter needs to know. The only possible order is [[1,4],[3,3],[2,1]].
After that, the map extracts the first number of each pair: [1,3,2]. And then the slice gives you the first k of those, e.g., [1,3] if k=2.
The part after => and before the ) is your compare function. In your case:
b[1] - a[1]
Subtracting your sort values (a,b) makes sort compare numbers instead of strings. The sort order (ascending/descending) depends on comparing b subtracted from a or a from b. Your function assumes there are no Infinity or NaN in the array.

Google Scripts 2D Array sorting by value

I have a 2d array that I am attempting to sort.
The array is typically accessed with this structure: array[r][c].
I want to re-order the values of array, so that each [r] value is sorted by the 4th c value.
Looking online, I've seen a few sorting scripts that seem to work for other structured arrays, but I'm wondering if i'm missing something stupid.
The array is structured so that for each 'r' value in array, there is a list of values, depending on what 'c' value you put in (eg: if you do array[0][2] that will be the first entry's address, and array[0][10] is the first entry's phone number).
I want to be able to sort based off of c values 4 and... 10 (for example). (ideally, I'd sort by multiple columns, such as sort by last name first, then by first name--but i'll settle for one sort for now hahaha )
I'm not certain if any of the default sort functions would work for me, or if i need to write out a manual sort function (which i'm hoping i do not have to do as that would be fairly inefficient).
Thanks for any pointers
You'll need to write your own compare function.
Snippet:
const COLTOSORT = 2;
function compare(row1, row2) {
return row1[COLTOSORT] < row2[COLTOSORT]
? -1
: row1[COLTOSORT] > row2[COLTOSORT]
? 1
: 0;
}
array.sort(compare);
References:
Array#sort

I am not able to understand the code

I am new to javascript. After lots of hours I am not able to understand the code. I would be grateful if someone could help me. Thanks
for(var x = 0; x < id_inters['inters'].length; x++) {
var a,b;
if(id_inters['inters'][x]['First_ID'] == data.main[0].cust) {
a = id_inters['inters'][x]['First_ID'];
b = id_inters['inters'][x]['Second_ID2'];
You can take it with these steps from the for loop:
var x is declared and assigned value of 0.
There will be an Object named id_inters which hold an array named inters which also holds objects in it.
Now inside the loop you declare two variables var a, b;.
Now that n the condition you are checking the value of the iterated object with id_inters['inters'][x]['First_Id'] where x is the index number if each iteration which is incremented from 0 to length of array.
And you are checking each iterated value to the first value of the data['main'][0].cust. Where data is an object which contains an array named data and you are comparing its first object's cust value.
You are given an array A of size N.
A partitioning of the array A is the splitting of A into one or more non-empty contiguous subarrays such that each element of A belongs to exactly one of these subarrays.
Find the number of ways to partition A such that the parity of the sum of elements within the subarrays is alternating. In other words, if Si denotes the sum of the elements in the i-th subarray, then either
S1 is odd, S2 is even, S3 is odd and so on.
or S1 is even, S2 is odd, S3 is even and so on.
For example if A=[1,2,3,3,5]. One way to partition A is [1,2][3,3][5]. Another way to partition A is [1][2][3][3,5]. Note that there exists more ways to partition this array.
Since the answer may be large, output it modulo 998244353.
Input Format
The first line contains a single integer T - the number of test cases. Then the test cases follow.
The first line of each test case contains an integer N - the size of the array A.
The second line of each test case contains N space-separated integers A1,A2,…,AN denoting the array A.
Output Format
For each test case, output the answer modulo 998244353.
Constraints
1≤T≤10000
1≤N≤2⋅105
0≤Ai≤109
Sum of N over all test cases does not exceed 2⋅105
Sample Input 1
3
3
1 2 3
4
4 4 4 4
5
1 2 3 3 5
Sample Output 1
2
1
5
Explanation
Test case 1: The array can be partitioned as follows
[1][2][3]
[1,2,3]
Test case 2: The array can be partitioned as follows
[4,4,4,4]

Looping over undefined array keys

Problem:
I have a DB containing math exercises, split by difficulty levels and date taken.
i want to generate a diagram of the performance over time.
to achieve this, i loop through the query results, and ++ a counter for the level and day the exercise was taken.
example: level 2 exercise was taken at 01.11.2015.
this.levels[2].daysAgo[1].amountTaken++;
with this, i can build a diagram, where day 0 is always today, and the performance over days is shown.
now levels[] has a predefined amount of levels, so there is no problem with that.
but daysAgo[] is very dynamic (it even changes daily with the same data), so if there was only one exercise taken, it would wander on a daily basis (from daysAgo[0] to daysAgo[1] and so on).
the daysAgo[] between that would be empty (because there are no entries).
but for evaluating the diagram, i need them to have an initialized state with amountTaken: 0, and so on.
problem being: i can't know when the oldest exercise was.
Idea 1:
First gather all entries in a kind of proxy object, where i have a var maxDaysAgo that holds the value for the oldest exercise, then initialize an array daysAgo[maxDaysAgo] that gets filled with 0-entries, before inserting the actual entries.
that seems very clumsy and overly complicated
Idea 2:
Just add the entries this.level[level].daysAgo[daysAgo].amountTaken++;, possibly leaving the daysAgo array with a lot of undefined keys.
Then, after all entries are added, i would loop over the daysAgokeys with
for (var i = 1; i < this.maxLevel; i++) { // for every level
for (var j = 0; j < this.levels[i].daysAgo.length; j++) {
but daysAgo.lengthwill not count undefined fields, will it?
So if i have one single entry at [24], length will still be 1 :/
Question:
How can I find out the highest key in an array and loop until there, when there are undefined keys between?
How can i adress all undefined keys up until the highest (and not any more)?
Or: what would be a different, more elegant way to solve this whole problem altogether?
Thanks :)
array.length returns one higher than the highest numerical index, so can be used to loop though even undefined values
as a test:
var a=[]
a[24]=1
console.log(a.length)
outputs 25 for me (in chrome and firefox).

JavaScript Array Length Key Value

Why is this extremely basic JavaScript array giving me a length of 13 when there are only 3 key/value pairs in it. It makes sense that it might think 13 as 0 based index and my last array has a key of 12, but I need to have any array that has a key/value pair that returns me the correct number of pairs. The keys need to be numbers.
http://jsfiddle.net/fmgc8/1/
EDIT: this is how I solved it thanks.
http://jsfiddle.net/fmgc8/4/
it's because the highest number you have is:
array['12'] = 'twelve';
This creates an array length of 13 (since it's 0 based). JavaScript will expand the array to allocate the number of spots it needs to satisfy your specified slots. array[0..9] is there, you just haven't placed anything in them.
There is no diffrence between array['12'] and array[12] (array['12'] is not considered as associative array element). To find associative array length
The length property of arrays returns the biggest non-negative numeric key of the object, plus one. That's just the way it's defined.
If you want to count the key-value pairs, you're going to have to count them yourself (either by keeping track of them as they are added and removed, or by iterating through them).
Or, rearrange your array like this:
var array = [];
array.push(['10','ten']);
array.push(['11','eleven']);
array.push(['12','twelfe']);
alert(array.length);

Categories

Resources