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
maxfunction is kept intact, but now it operates on actual numbers instead of strings, so comparisons are accurate. - Sum & Count: We use
filterto collect all elements equal to the max value, then get the length (count) and usereduceto 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
相关产品推荐
相关产品推荐

