Home > Software engineering >  Get maximum interval between two consecutive numbers
Get maximum interval between two consecutive numbers

Time:10-24

i need to get the maximum interval between two consecutive numbers. Numbers are entered as arguments. Wrote some solution, but don't know how to move on. How can this problem be solved?

const maxInterv = (...args) => {
  let maxInterval = 0;
  let interval = 0;
  for (let i = 0; i < args.length; i  ) {
    interval = args[i   1] - args[i];

  }
};

const result = maxInterv(3, 5, 2, 7, 11, 0, -2); //11

console.log(result)

CodePudding user response:

you can use a simple array.reduce()

const maxInterv = (...args) => 
  args.reduce( (intv,val,i,{[i 1]:nxt}) =>
    !isNaN(nxt) ? Math.max(intv,Math.abs(val-nxt)) : intv
    ,0);
 
const result = maxInterv(3, 5, 2, 7, 11, 0, -2); // 11
                      
document.write( result )  

CodePudding user response:

const maxInterval = (...args) => {
  let max = 0;
  for (let i = 1, interval = 0; i < args.length; i  ) {
    interval = args[i - 1] - args[i];
    if (Math.abs(interval) > max) max = interval;
  }
  return max;
};
const result = maxInterval(3, 5, 2, 7, 11, 0, -2); //11
console.log("the result is", result);

CodePudding user response:

Initialize maxInterval with -Infinity and use Math.max() and Math.abs() function in each interation. Pay attention to range of i.

On the end return maxInterval variable.

CodePudding user response:

const maxInterv = (...args) => {
  // moved interval to the loop, because you don't use that here
  let maxInterval = 0;
  // you are accessing i   1 so you have to iterate to args.length - 1
  for (let i = 0; i < args.length - 1; i  ) {
    // use abs or you will get negative values
    const interval = Math.abs(args[i   1] - args[i]);
    // if current interval is greater than max, set new max
    if (interval > maxInterval) {
      maxInterval = interval
    }
  }
  // remember to return
  return maxInterval
};

const result = maxInterv(3, 5, 2, 7, 11, 0, -2);

console.log(result)

CodePudding user response:

I think this is the shortest one=)

const maxInterv = (arr) => Math.max(...arr.slice(1).map(
(val, key) => Math.abs(val - arr[key])));

const result = maxInterv([3, 5, 2, 7, 11, 0, -2]); // 11
                      
console.log(result);
  • Related