邻接矩阵生成器

huangapple 未分类评论43阅读模式
英文:

Adjacency matrix generator

问题

目标是创建一个邻接矩阵生成器元素的唯一值是0或1必须对称即元素在[i][j] == [j][i]的 Java 代码

我有一些代码但结果是一个nx5矩阵如果我设定 n = 13得到的矩阵是一个13x5矩阵)。它是对称的元素的值介于0-1之间所以这不是问题另一个问题是我不太清楚如何使用非double类型的数组这更多是一个美观问题 + 理想情况下对角线应填充为 -而不是零就像现在一样

Random random = new Random();
double[][] array = new double[n][n];

for (int i = 0; i < array.length; i++)
{
    for (int j = 0; j <= i; j++)
    {
        int x = random.nextInt(2);
        array[i][j] = x;

        if (i != j)
        {
            array[j][i] = x;
        }
    }
}

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        if (i == j || (i + j + 1) == n)
        {
            array[i][j] = 0;
        }
    }
}

for (double[] a : array)
{
    System.out.println(Arrays.toString(a));
}
英文:

My goal is to create an adjacency matrix generator (the only value elements can have is 0 or 1; it has to be symmetric, meaning element in [i][j] == element [j][i]) in Java.

I have some code, but the result is an nx5 matrix (if I establish n = 13, the resulting matrix is a 13x5 matrix). It is symmetric and the values of elements is bounded between 0-1, so that is not an issue. Another problem is I don't really know how to have an array without doubles, which is more of an aesthetical problem + ideally, the diagonal would be filled with "-" instead of zeroes, as it is now.

    Random random = new Random();
    double[][] array = new double[n][n];

    for (int i = 0; i &lt; array.length; i++)
    {
        for (int j = 0; j &lt;= i; j++)
        {
            int x = random.nextInt(2);
            array[i][j] = x;

            if (i != j)
            {
                array[j][i] = x;
            }
        }
    }

    for (int i = 0; i &lt; n; i++)
    {
        for (int j = 0; j &lt; n; j++)
        {

            if (i == j || (i + j + 1) == n)
            {
                array[i][j] = 0;
            }
        }
    }

    for (double[] a : array)
    {
        System.out.println(Arrays.toString(a));
    }
}

huangapple
  • 本文由 发表于 2020年7月24日 02:12:56
  • 转载请务必保留本文链接:https://java.coder-hub.com/63060595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定