Open krishna63 opened 4 years ago
@krishna63 can you have a look at below logic.
const getArrayPattern = data => {
let arr = data.slice();
let modArr = [];
removeItem = item => {
arr.splice(arr.indexOf(item), 1)
}
getMinVal = () => {
let val = Math.min.apply(null, arr)
removeItem(val);
return val
}
getMaxVal = () => {
let val = Math.max.apply(null, arr)
removeItem(val);
return val
}
for(let i=0;i<data.length;i++){
modArr.push((i%2)?this.getMinVal():this.getMaxVal())
}
return modArr;
}
@ajayg415 : I see few unnecessary loops to my understanding.
When ever you are trying to get the max
values from the array it might be looping thru all the elements of the array for every call. Instead we can just do the following right
This way the number of times the array loops is
O(n)
O(n/2)
Where 'n' is the length of the array
Correct me if i am overlooking something
@krishna63 : yep, I'll think for another logic.
@krishna63 This is simplified one with only 2 loops.
const getArrayPattern = data => {
let arr = data.slice();
let modArr = [];
arr.sort((a,b)=>(b-a))
for(let i=0;i<data.length;i++){
modArr.push((i%2)?arr.pop():arr.shift())
}
return modArr;
}
@ajayg415 : how about this ?
const getArrayPattern = data => {
const dataLength = data.length;
const halfOfdataLength = Math.ceil(dataLength/2);
const sortedArray = data.sort(function(a,b){return a-b});
const result = [];
if(dataLength <= 1) {
return data;
}
for(let i =0 ; i <= halfOfdataLength; i++) {
let maxValueIndex = dataLength - (i+1);
result.push(sortedArray[maxValueIndex], sortedArray[i]);
}
return result;
}
@krishna63 , Not working exactly, have a look, also change sortedArray(i)
to sortedArray[i]
@ajayg415 : Ya i have added the sort function and i see few duplicated get added to it.
Description: Arrange the array in such away that first highest number followed by first lowest number and second highest number followed by second lowest number among the given array numbers.
Note: If the last highest and last lowest number matches(meaning the same number) then the matched value occurrence has to be only once at the end of the array. This is the reason why you don't see number
8
twice in the output array.Sample 1
Sample 2