ajayg415 / Javascript-Algorithms

1 stars 0 forks source link

Problem: Arrange the array in a particular pattern #9

Open krishna63 opened 4 years ago

krishna63 commented 4 years ago

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

Input: [-2, 3, 8, 45, 6, 32, 25, 0, 25, 8]
Output: [45, -2, 32, 0, 25, 3, 25, 6, 8]

Sample 2


Input: [10, -8, 76, 3, -6, 4, 12]
Output: [76, -8, 12, -6, 10, 3, 4]

If possible try to add the time complexity for the same.
ajayg415 commented 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;
}
krishna63 commented 4 years ago

@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

Where 'n' is the length of the array

Correct me if i am overlooking something

ajayg415 commented 4 years ago

@krishna63 : yep, I'll think for another logic.

ajayg415 commented 4 years ago

@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;
}
krishna63 commented 4 years ago

@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;
}
ajayg415 commented 4 years ago

@krishna63 , Not working exactly, have a look, also change sortedArray(i) to sortedArray[i]

krishna63 commented 4 years ago

@ajayg415 : Ya i have added the sort function and i see few duplicated get added to it.