function exercise1() {
const array = new Array(10).fill(0).map(() => Math.floor(Math.random() * 100));
console.log("一维数组:", array);
const sum = array.reduce((a, b) => a + b, 0); // 求和
const max = Math.max(...array); // 最大值
const min = Math.min(...array); // 最小值
console.log(`一维数组的和: ${sum}`);
console.log(`一维数组的最大值: ${max}`);
console.log(`一维数组的最小值: ${min}`);
}
function exercise2() {
const array2D = Array(3).fill(0).map(() => Array(3).fill(0).map(() => Math.floor(Math.random() * 100)));
console.log("二维数组:", array2D);
const sum2D = array2D.reduce((a, row) => a + row.reduce((b, val) => b + val, 0), 0);
const max2D = Math.max(...array2D.flat());
const min2D = Math.min(...array2D.flat());
console.log(`二维数组的和: ${sum2D}`);
console.log(`二维数组的最大值: ${max2D}`);
console.log(`二维数组的最小值: ${min2D}`);
}
function randomArray(size, min = 0, max = 100) {
return Array(size).fill(0).map(() => Math.floor(Math.random() * (max - min + 1)) + min);
}
function calculateArrayStats(array) {
const sum = array.reduce((a, b) => a + b, 0);
const max = Math.max(...array);
const min = Math.min(...array);
return { sum, max, min };
}
function exercise3() {
console.log("练习3:改进后的一维数组");
const array1D = randomArray(10);
console.log("一维数组:", array1D);
const stats1D = calculateArrayStats(array1D);
console.log(`一维数组的和: ${stats1D.sum}`);
console.log(`一维数组的最大值: ${stats1D.max}`);
console.log(`一维数组的最小值: ${stats1D.min}`);
console.log("\n练习3:改进后的二维数组");
const array2D = randomArray(3 * 3).reduce((acc, val, index) => {
const row = Math.floor(index / 3);
acc[row] = acc[row] || [];
acc[row][index % 3] = val;
return acc;
}, []);
console.log("二维数组:", array2D);
const flatArray2D = array2D.flat();
const stats2D = calculateArrayStats(flatArray2D);
console.log(`二维数组的和: ${stats2D.sum}`);
console.log(`二维数组的最大值: ${stats2D.max}`);
console.log(`二维数组的最小值: ${stats2D.min}`);
}
exercise1();
exercise2();
exercise3();
一维数组: [23, 45, 67, 12, 89, 34, 56, 78, 90, 11]
一维数组的和: 505
一维数组的最大值: 90
一维数组的最小值: 11
二维数组: [[45, 78, 23], [67, 34, 89], [12, 56, 90]]
二维数组的和: 494
二维数组的最大值: 90
二维数组的最小值: 12
练习3:改进后的一维数组
一维数组: [34, 67, 89, 23, 45, 78, 12, 90, 56, 11]
一维数组的和: 505
一维数组的最大值: 90
一维数组的最小值: 11
练习3:改进后的二维数组
二维数组: [[45, 78, 23], [67, 34, 89], [12, 56, 90]]
二维数组的和: 494
二维数组的最大值: 90
二维数组的最小值: 12