You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现数组中最大重复数字的求和功能

Solution: Calculate Sum of the Most Frequent Maximum Value in Array

Hey there! Let's adjust your existing code to not just find the maximum value, but also count how many times it appears and calculate the total sum of those maximum elements. I'll fix a couple of small issues in your original code (like string vs number comparisons) while we're at it.

Step-by-Step Modifications:

  • Convert Input to Valid Numbers: Your original code worked with strings, which can lead to incorrect comparisons (e.g., "10" would be considered smaller than "9"). We'll convert each input item to an integer and filter out any invalid entries.
  • Count Maximum Occurrences: Once we have the maximum value, we'll filter the array to get all instances of that value, then count them and compute their sum.
  • Update Output: Show all relevant details—max value, count, and total sum.

Modified Full Code:

function evaluate() {
  // Get input and convert to a valid number array
  const inputStr = prompt("Please enter the array of integers in the form: 1,2,3,1");
  if (!inputStr) {
    document.writeln("Sorry, there is nothing that can be calculated.");
    return;
  }

  const inputArray = inputStr
    .split(',')
    .map(num => parseInt(num.trim(), 10))
    .filter(num => !isNaN(num)); // Remove non-numeric entries

  if (inputArray.length === 0) {
    document.writeln("Invalid input: Please enter valid integers separated by commas.");
    return;
  }

  // Your recursive max function (updated to work with numbers)
  function max(numArray) {
    const nums = numArray.slice();
    if (nums.length === 1) {
      return nums[0];
    }
    if (nums[0] < nums[1]) {
      nums.splice(0, 1);
    } else {
      nums.splice(1, 1);
    }
    return max(nums);
  }

  const maxValue = max(inputArray);
  // Filter all max elements and calculate count + sum
  const maxElements = inputArray.filter(num => num === maxValue);
  const maxCount = maxElements.length;
  const totalSum = maxElements.reduce((sum, num) => sum + num, 0);

  // Output the results
  document.writeln(`The largest number is: ${maxValue}`);
  document.writeln(`It appears ${maxCount} times.`);
  document.writeln(`Total sum of all instances: ${totalSum}`);
  document.writeln(`Starting input string: ${inputStr}`);
}

evaluate();

How It Works:

  • Input Handling: We first check if the user provided any input, then convert each comma-separated item to an integer. Any non-numeric values (like empty strings) are filtered out to avoid errors.
  • Max Value Calculation: Your recursive max function is kept intact, but now it operates on actual numbers instead of strings, so comparisons are accurate.
  • Sum & Count: We use filter to collect all elements equal to the max value, then get the length (count) and use reduce to calculate their total sum.
  • Example Output: For input 5,5,7,9,9,9, you'll see:
    The largest number is: 9
    It appears 3 times.
    Total sum of all instances: 27
    Starting input string: 5,5,7,9,9,9
    

内容的提问来源于stack exchange,提问作者WhoAmI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:20:19