I have four numbers that can possible be the same, but or most likely different. Basically I want this function to chose no number of they are equal, but if they aren’t, pick the lowest one, and if there are two that are the same, to just pick one of them and go with that.
Like for example I have 3434, 3396, 3414, and 3374. Well I want the function to return to me say 0 if they’re all the same, 1 for the first one and so on. So in this situation I would need to be returned 4.
But if the numbers were 321, 576, 812, and 321 it would return to me 1.
I’ve been at this for a couple of days now and I just can’t seem to find any way of doing what I need to do. Anyone know something that could make this work magically? Thanks!
EDIT
My approach had me doing something along the lines of creating an array sorting it and trying to use the last result, but when I sort the array, the keys get messed up so I don’t know which value it belonged to
var choices = new Array();
choices[1] = parseInt(value1);
choices[2] = ...
choices = choices.sort();
//and then I ran into the problem that my keys being not starting
//with 0, it added an element which I was able to remove by doing this
choices = choices.splice(0,4);
And then I’m stuck for there
Here’s a start on the journey to answering your question. As others have pointed out, this code does not handle all the cases you mention; this is deliberate.
Hand-rolled way;
O(n)and one pass:Far more concise; also
O(n)but two passes through the array:N.B
Array.indexOfrequires a shim in older versions of IE.This exercise, as they say, is left to the reader.