简体   繁体   English

使用 JavaScript 的数字螺旋矩阵...结果有问题

[英]Spiral Matrix Of Numbers with JavaScript... problems with the result

I am trying to create an inverse circular matrix (from the large number to the small number that will be in the middle) of the numbers ... but I am faced with a problem: I cannot display it on the screen.我正在尝试创建数字的逆圆形矩阵(从大数到中间的小数)......但我面临一个问题:我无法在屏幕上显示它。 The user enters the number N and pressing the button the matrix must be formed ...用户输入数字 N 并按下按钮,必须形成矩阵......

But it does not work.... Help me please...但它不起作用......请帮助我...... 在此处输入图片说明

<!DOCTYPE html>
<html>
<head>
<body style="background-color:#bf8b99;" align="center">
<h1>CONSTRUCTOR</h1>
<h2>INPUT NUMBER</h2>

<form>

  <input type="text" name="a" size="15" id="a">

</form><br><br>

<button type="button" onclick="create()">CREATE</button>
<div id="test"></div>

<script>

function create(){
    a=parseFloat(document.getElementById("a").value);
    document.body.style.background = "green";

    var spiral = [a][a];
        var value = 1; 
        var minCol = 0;
        var maxCol = a-1;
        var minRow = 0;
        var maxRow = a-1;

        while (value <= a*a)
        {
            for (int i = minCol; i <= maxCol; i++)
            { spiral[minRow][i] = value;               
                value++;
            }

            for (int i = minRow+1; i <= maxRow; i++) 
            { spiral [i][maxCol] = value;            
                value++; 
            } 

            for (int i = maxCol-1; i >= minCol; i--)
            { spiral[maxRow][i] = value;                      
                value++;
            }

            for (int i = maxRow-1; i >= minRow+1; i--) 
            { spiral[i][minCol] = value;
                value++;
            }      
            minCol++;
            minRow++;          
            maxCol--;           
            maxRow--;
        }

        for (int i = 0; i < spiral.length; i++)
        { 
            for (int j = 0; j < spiral.length; j++)
            {
              document.getElementById('test').innerHTML = spiral[i][j] + "\t";
            }
        }
}
</script>
</body>
</html>

You have several issues in your code:您的代码中有几个问题:

  • var spiral = [a][a] is not doing what you think. var spiral = [a][a]没有按照您的想法行事。 It does not define a 2D array with a width and height of a .它没有定义宽度和高度为a的二维数组。 Instead it creates a 1-dimensional array with one value ( a ) in it.相反,它创建一个一维数组,其中包含一个值 ( a )。 Then it accesses an index of that array only to find it does not have that index a .然后它访问该数组的索引只是发现它没有该索引a And so spiral is assigned undefined .所以spiral被分配了undefined

  • You start filling up row 0, which is already the wrong place: that is not where number 1 will end up in the final result, yet you leave it there.您开始填充第 0 行,这已经是错误的位置:这不是最终结果中第 1 行的位置,但您将其留在那里。

  • At the end you overwrite innerHTML in each iteration.最后,您会在每次迭代中覆盖innerHTML That cannot be what you intended either... It is better to prepare the matrix, and then turn that first into a string, and then finally assign that to the DOM (better with textContent than innerHTML ).这也不是你想要的......最好准备矩阵,然后首先将其转换为字符串,然后最后将其分配给 DOM(使用textContent比使用innerHTML更好)。

  • The \\t character will not render any different than a space when you assign it to the innerHTML of a div without further CSS styling.当您将\\t字符分配给divinnerHTML而没有进一步的 CSS 样式时,它不会呈现与空格有任何不同的效果。 You will get a better result when you use a pre element, which retains white-space (or do it with CSS), and so you can pad each output number with the required number of spaces to align it (use padStart ).当您使用pre元素时,您将获得更好的结果,该元素保留空白(或使用 CSS 进行),因此您可以使用所需数量的空格填充每个输出数字以使其对齐(使用padStart )。

  • The button's text is also misleading.按钮的文字也具有误导性。 You are not dealing with the input as if it is a power of 2: you still raise it to that power with a*a ...你没有把输入当作 2 的幂来处理:你仍然用a*a把它提高到那个幂......

Here is a solution that uses recursion: if the given width is 1 or 2 just return the hard-coded solution (base case).这是一个使用递归的解决方案:如果给定的宽度是 1 或 2,则只返回硬编码的解决方案(基本情况)。 If greater, then solve the problem for a width that is two units less, and then wrap that result with one extra number on all sides.如果更大,则解决宽度少两个单位的问题,然后在所有边上用一个额外的数字包装该结果。 It is not so hard to find the mathematical invariant to do this last step.找到完成这最后一步的数学不变量并不难。

Here is a snippet:这是一个片段:

 function createSpiral(n) { if (n === 1) return [[1]]; if (n === 2) return [[3, 4], [2, 1]]; let spiral = createSpiral(n-2); // add a prefix and a postfix number to those rows: let start = n*(n-1); let end = (n-2)*(n-2) + 1; for (let row of spiral) { row.unshift(start--); row.push(end++); } // add extra row at top and bottom start = n*(n-1)+1; spiral.unshift(spiral[0].map(() => start++)); end = n*(n-2)+2; spiral.push(spiral[0].map(() => end--)); return spiral; } // I/O handling let input = document.querySelector("#width"); let output = document.querySelector("#spiral"); function refresh() { let n = +input.value; // Validate input if (!(n >= 1 && n < 100)) return; // Perform the algorithm let spiral = createSpiral(n); // Format the returned spiral to a nicely formatted string let digits = (n*n+"").length; output.textContent = spiral.map(row => row.map(i => (""+i).padStart(digits)).join(" ")).join("\\n"); } input.addEventListener("input", refresh); refresh();
 <input type="number" id="width" max="99" min="1" value="5"> <pre id="spiral"></pre>

For a spiral, you could take some iteration who are running betwin the sides and by checking the left over padding sizes.对于螺旋,您可以进行一些迭代,它们在两侧运行并检查左侧的填充大小。

 function spiral(length) { var upper = 0, lower = length - 1, left = 0, right = length - 1, i = upper, j = left, result = Array.from({ length }, _ => []), value = length * length; while (true) { if (left++ > right) break; for (; i < lower; i++) result[i][j] = value--; if (lower-- < upper) break; for (; j < right; j++) result[i][j] = value--; if (right-- < left) break; for (; i > upper; i--) result[i][j] = value--; if (upper++ > lower) break; for (; j > left; j--) result[i][j] = value--; } result[i][j] = value--; return result; } var target = document.getElementById('out'), i = 10; while (--i) target.innerHTML += spiral(i).map(a => a.map(v => v.toString().padStart(2)).join(' ')).join('\\n') + '\\n\\n';
 <pre id="out"></pre>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM