使用JavaScript中的fill()方法简化二维数组的创建

kcugc4gi  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(144)
const hole = 'O'; // Declare constant for the hole character
const fieldCharacter = '░'; // Declare constant for the field character

// Initialize a field with a given height, width, and percentage of holes
function initiliazeField(height, width, percentage) {
    // Return either the hole or field character based on the percentage
    // If the percentage is not between 0 and 35, log an error message
    const fieldOrHole = (percentage) => {
        return percentage >= 0 && percentage <= 35 ?
            Math.floor(Math.random() * 35) < percentage ?
            hole :
            fieldCharacter :
            console.log('Please enter a number between 0 - 35');
    }

    // Initialize an empty array to hold the rows of the field
    const rows = [];
    // Create rows for the field
    for (let i = 0; i < height; i++) {
        // Initialize an empty array to hold the characters in the row
        const row = [];
        // Populate the row with the appropriate character based on the percentage
        for (let j = 0; j < width; j++) {
            row.push(fieldOrHole(percentage));
        }
        // Add the row to the field
        rows.push(row);
    }
    // Map each element in the rows array to a new array, and log each row to the console
    return rows.map(subArray => subArray.map(element => element)).forEach(row => console.log(row.join(' ')));
};

// Print the initialized field to the console
console.log(initiliazeField(20, 20, 20));

Output:

// Expected a randomly generated two-dimensional array

░ ░ ░ O O ░ O ░ O O
O O O ░ ░ O O ░ ░ O
░ O ░ ░ O ░ O O O O
O O O ░ O ░ ░ O ░ O
░ O O ░ O ░ O ░ ░ O
░ ░ ░ O O ░ O O O ░
O ░ ░ ░ O ░ O ░ ░ ░
O O O ░ ░ ░ O O ░ O
O ░ ░ O ░ ░ ░ ░ O ░
O O ░ ░ ░ ░ O O ░ O

这段代码定义了一个函数initiliazeField(),该函数生成一个二维数组,该数组表示具有给定高度、宽度和孔洞百分比的字段。该字段表示为一个行数组,每行是一个字符数组。字符可以是孔洞('O ')或字段字符('')。
该函数有三个参数:

  • height:字段的高度,表示为字段中的行数。
  • width:字段的宽度,表示为字段中的列数。
  • percentage:字段中孔洞的百分比(必须是0到35之间的数字)该函数首先定义一个嵌套函数fieldOrHole(),该函数根据给定的百分比返回孔洞或字段字符。如果百分比不在0到35之间,则会在控制台中记录一条错误消息。

然后,该函数初始化一个空的行数组以保存字段的行。它通过迭代循环并使用height参数确定行数来为字段创建行。在循环中,它初始化一个空数组行以保存行中的字符。并使用嵌套循环用字符填充行。width参数用于确定行中的列数。每个位置的字符通过调用fieldOrHole()函数来确定。
最后,该函数将rows数组中的每个元素Map到一个新数组,并使用forEach()方法将每行记录到控制台。map()forEach()方法用于迭代rows数组,并将每行记录到控制台。join(' ')方法用于将行中的元素与空格字符连接起来,以便正确格式化输出。

如何使用fill()方法简化initiliazeField()函数?

brccelvz

brccelvz1#

您可能希望使用Array.from

const gen = (height, width, percentage) => Array.from(
  {length: height}, ()=>Array.from(
    {length: width}, ()=>Math.random()*100 < percentage ? '0' : '░'
  )
);

const A = gen(7, 10, 20);
console.log(A.map(a => a.join('')).join("\n"));

我排除了I/O部分,因为将其与生成矩阵的代码分开是有意义的

相关问题