根据一系列值生成数字序列

问题描述 投票:0回答:1

我想创建一个包含 9 个值的数组作为结果,其中我编写了一个获取最小值和最大值的函数

function generateSequence(min, max, numElements = 9) {
  // Step 1: Calculate the raw step size
  let step = (max - min) / (numElements - 3); // One value below min, and one above max
  
  // Step 2: Dynamically determine the rounding factor based on the step size
  const orderOfMagnitude = Math.pow(10, Math.floor(Math.log10(step))); // Find the magnitude (e.g., 10, 100, 1000)
  
  // Step 3: Round the step to the nearest multiple of the order of magnitude
  const roundedStep = Math.round(step / orderOfMagnitude) * orderOfMagnitude;

  // Step 4: Start from a value a bit lower than the min, ensuring we have one value below min
  const startValue = Math.floor(min / roundedStep) * roundedStep - roundedStep;

  // Step 5: End at a value a bit higher than the max, ensuring we have one value above max
  const endValue = Math.ceil(max / roundedStep) * roundedStep + roundedStep;

  // Step 6: Generate the sequence with the dynamically adjusted start and end
  const sequence = Array.from({ length: numElements }, (_, i) => startValue + i * roundedStep);

  return sequence;
}

const min = 100;
const max = 200;
const result = generateSequence(min, max);
console.log(result);

我只想得到一个高于最大值的值和一个低于最小值的值,如果你看到结果给了我 220 和 240,理想情况下数组应该以 220 结束。但然后我需要 9 个整数,这将减少到 8,所以我想将我的第一个整数转移到更低的值,并基于该序列应该生成,如何做到这一点

javascript arrays
1个回答
0
投票

这对你有用吗?

const generateSequence = (min, max, numElements = 9) =>{
  // Rounded step size based on the range and number of elements
  const step = Math.round((max - min) / (numElements - 2) / 10) * 10; // Rounding to nearest 10 for cleaner values
  // Start value must be exactly one step below min
  const startValue = min - step;
  const sequence = Array.from({ length: numElements }, (_, i) => startValue + i * step);
  // Last value is just above max
  sequence[sequence.length - 1] = max + step;
  return sequence;
}

const min = 100;
const max = 200;
const result = generateSequence(min, max);
console.log(result);

© www.soinside.com 2019 - 2024. All rights reserved.