试图找到最大数量的输入(javascript)

Posted

技术标签:

【中文标题】试图找到最大数量的输入(javascript)【英文标题】:Trying to find biggest number of a input (javascript) 【发布时间】:2022-01-16 16:04:41 【问题描述】:

我现在遇到了一个问题:我需要一个函数来查找由参数接收到的数字中的连续数字组成的最高数字。 例如:如果我的输入是 1235789,我的输出应该是 789。如果我的输入是 123689,​​我的输出应该是 123。

function getbiggestNumber(numberInput) 
    const numberString = numberInput.toString(); // turned into string

    const temporaryResult = []; // create the array of possible solutions which i'd go through to find the highest value inside of it

    for (let i = 0; i < numberString.length; i += 1) 
        const temporary = [numberString[i]]; // create a temporary answer that would serve as a base

        for (let x = i + 1; x < numberString.length; x += 1) 
            const subResult = Number(numberString[i]) - Number(numberString[x]); // the result of the current number minus the following number

            if (subResult === -1)  // if they are in a sequence this should be -1
                temporary.push(numberString[x]); // pushing this number to that temporary answer
             // here should be some condition for it to keep running, instead getting into another number of for loop
        
        temporaryResult.push(temporary); //  pushing that temporary answer to the result, so I could keep track of it
    
    console.log(temporaryResult); //  checking the output

问题是这段代码只在数组中提供两位数,这是我发现的唯一方法。 如果有人可以让我了解这一点,我将非常感激。 谢谢!

【问题讨论】:

【参考方案1】:

这看起来有点不必要地令人费解。我只是根据连续数字将字符串分成块,然后调用Math.max

const getBiggestNumber = (numberInput) => 
  const digits = [...String(numberInput)].map(Number);
  const chunks = [];
  let lastDigit;
  let chunk = [];
  for (const digit of digits) 
    if (lastDigit === digit - 1) 
      // Continuation of sequence
      chunk.push(digit);
     else 
      if (chunk.length) chunks.push(chunk);
      // New sequence:
      chunk = [digit];
    
    lastDigit = digit;
  
  chunks.push(chunk);
  return Math.max(
    ...chunks.map(chunk => Number(chunk.join('')))
  );
;
console.log(getBiggestNumber(1235789));

【讨论】:

【参考方案2】:

另一种方法:

const largestStreak = (input) => Math .max (... [...String (input)] .map (Number) .reduce (
  (a, d, i, xs) =>
    d ==  a .at (-1) .at (-1) + 1
      ? [... a .slice (0, -1), [... a .at (-1), d]]
      : [... a, [d]],
  [[]]
) .map (ns => Number (ns .join (''))))

console .log (largestStreak (1235789))
console .log (largestStreak (1235689))

这经历了以下步骤:

input:

1235789

[...String (input)] .map (Number):

[1, 2, 3, 4, 7, 8, 9]

逐步减少累加器:

[[]]
[[], [1]]
[[], [1, 2]]
[[], [1, 2, 3]]
[[], [1, 2, 3], [5]]
[[], [1, 2, 3], [5], [7]]
[[], [1, 2, 3], [5], [7, 8]]
[[], [1, 2, 3], [5], [7, 8, 9]]

.map (ns =&gt; Number (ns .join (''))):

[0, 123, 5, 789]

Math .max (...):

789

【讨论】:

以上是关于试图找到最大数量的输入(javascript)的主要内容,如果未能解决你的问题,请参考以下文章

ValueError:找到样本数量不一致的输入变量:[2839,14195]

没有重复的背包:最大数量的金币

猫鼬中的最小和最大数量验证

java 方法可以包含的修饰符的最大数量是多少?

使用带有扭曲的javascript找到最大总和

试图在几个相关的列中找到不同数量的项目