如何用0和1填充2D数组,其中第N行的每个第N个元素都是1,其余元素是0

How can I fill a 2D array with 0 and 1, where every Nth element of row N is a 1 and the rest is 0?

本文关键字:元素 何用 余元素 填充 2D 数组      更新时间:2023-10-16

例如,第一行应该全部填充1。在第二行中,每一个第二个元素都应该用1填充,其他元素应该用0填充。在第三行中,每三个元素都应填充1,其他元素应填充0,依此类推

1, 1, 1, 1, 1, ...
1, 0, 1, 0, 1, ...
1, 0, 0, 1, 0, ...
1, 0, 0, 0, 1, ...

像往常一样,有很多方法可以完成任务。例如,您可以使用以下解决方案

#include <iostream>
int main()
{
    const size_t M = 5;
    const size_t N = 10;
    int a[M][N];
    for ( size_t i = 0; i < M; i++ )
    {
        for ( size_t j = 0; j < N; j++ ) a[i][j] = ( j + 1 ) % ( i + 1 ) == 0;
    }
    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }        
    return 0;
}

程序输出为

1 1 1 1 1 1 1 1 1 1 
0 1 0 1 0 1 0 1 0 1 
0 0 1 0 0 1 0 0 1 0 
0 0 0 1 0 0 0 1 0 0 
0 0 0 0 1 0 0 0 0 1 

如果您的编译器不支持基于范围的循环

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }        

然后你可以用它来代替一个普通的循环。例如

    for ( size_t i = 0; i < M; i++ )
    {
        for ( size_t j = 0; j < N; j++ ) std::cout << a[i][j] << ' ';
        std::cout << std::endl;
    }