如何在 Javascript 中编写 Pascal 的三角形 - 数组的混淆
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31023844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to program Pascal's Triangle in Javascript - confusion re Arrays
提问by Robin Andrews
I'm having a little trouble with my attempt at this problem. Code Below:
我在尝试解决这个问题时遇到了一些麻烦。代码如下:
function pasc(n){
var result = [[1]];
for (var row = 1; row < n; row++){
for (var col = 1; col <= row; col++){
result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
}
}
return result;
}
pasc(10)
for (var i = 0; i < result.length; i++){
document.write(result[i]+"<br>");
}
It seems the problem hinges on assigning values to an array using an expression like myArray[1][1] = "foo"
似乎问题取决于使用类似的表达式为数组分配值 myArray[1][1] = "foo"
I'm confused about this because I can do this: var myArray = []; myArray[4] = "foo"
which seems to suggest that an element can be created at an arbitrary position in a 1 dimensional array, but not with 2 dimensions.
我对此感到困惑,因为我可以这样做:var myArray = []; myArray[4] = "foo"
这似乎表明可以在一维数组中的任意位置创建元素,但不能在二维数组中创建。
Any help with clearing up my misconceptions appreciated.
任何帮助澄清我的误解表示赞赏。
回答by Akash Kriplani
The Pascal's Triangle can be printed using recursion
可以使用递归打印帕斯卡三角形
Below is the code snippet that works recursively.
下面是递归工作的代码片段。
We have a recursive function pascalRecursive(n, a) that works up till the number of rows are printed. Each row is a element of the 2-D array ('a' in this case)
我们有一个递归函数 pascalRecursive(n, a) 直到打印行数。每行都是二维数组的一个元素(在本例中为“a”)
var numRows = 10,
triangle,
start,
stop;
// N is the no. of rows/tiers
// a is the 2-D array consisting of the row content
function pascalRecursive(n, a) {
if (n < 2) return a;
var prevRow = a[a.length-1];
var curRow = [1];
for (var i = 1; i < prevRow.length; i++) {
curRow[i] = prevRow[i] + prevRow[i-1];
}
curRow.push(1);
a.push(curRow);
return pascalRecursive(n-1, a); // Call the function recursively
}
var triangle = pascalRecursive(numRows, [[1]]);
for(var i = 0; i < triangle.length; i++)
console.log(triangle[i]+"\n");
回答by Logan R. Kearsley
JavaScript doesn't have two-dimensional arrays. What it does have is arrays that happen to contain other arrays. So, yes, you can assign a value to any arbitrary position in an array, and the array will magically make itself big enough, filling in any gaps with 'undefined'... but you can'tassign a value to any position in a sub-array that you haven't explicitly created yet. You have to assign sub-arrays to the positions of the first array before you can assign values to the positions of the sub-arrays.
JavaScript 没有二维数组。它所拥有的是恰好包含其他数组的数组。所以,是的,您可以为数组中的任意位置分配一个值,并且该数组会神奇地使自己足够大,用“未定义”填充任何空白……但是您不能为任何位置分配一个值您尚未明确创建的子数组。您必须先将子数组分配给第一个数组的位置,然后才能为子数组的位置赋值。
Replacing
更换
for (var row = 1; row < n; row++){
for (var col = 1; col <= row; col++){
with
和
for (var row = 1; row < n; row++){
result[row] = [];
for (var col = 1; col <= row; col++){
should do it. Assuming all of your indexing logic is correct, anyway. You've got some problems there, too, since your initial array only contains a single value, so result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
is accessing at least one cell that has never been defined.
应该这样做。无论如何,假设您的所有索引逻辑都是正确的。您在那里也遇到了一些问题,因为您的初始数组只包含一个值,因此result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
访问至少一个从未定义过的单元格也是如此。
回答by Robin Andrews
Thanks Logan R. Kearsley. I have now solved it:
感谢 Logan R. Kearsley。我现在已经解决了:
function pasc(n){
var result = [];
result[0] = [1];
result[1] = [1,1];
for (var row = 2; row < n; row++){
result[row] = [1];
for (var col = 1; col <= row -1; col++){
result[row][col] = result[row-1][col] + result[row-1][col-1];
result[row].push(1);
}
}
return result;
}
for (var i = 0; i < pasc(10).length; i++){
document.write(pasc(10)[i]+"<br>");
console.log(pasc(10)[i]+"<br>");
}
回答by VIJAY P
you can create Pascal's triangle using below code:
您可以使用以下代码创建帕斯卡三角形:
function pascal(n) {
var arr = [];
if (n == 1) {
arr[0] = [];
arr[0][0] = 1;
} else if (n == 2) {
arr[0] = [];
arr[0][0] = 1;
arr[1] = [];
arr[1][0] = 1;
arr[1][1] = 1;
} else if (n > 2) {
arr[0] = [];
arr[1] = [];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (i = 2; i < n; i++) {
arr[i] = [];
arr[i][0] = 1;
for (j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][j] = 1;
}
}
console.log(arr);
for (i = 0; i < arr.length; i++) {
console.log(arr[i].join(' '))
}
}
function pascal(n) {
var arr = [];
if (n == 1) {
arr[0] = [];
arr[0][0] = 1;
} else if (n == 2) {
arr[0] = [];
arr[0][0] = 1;
arr[1] = [];
arr[1][0] = 1;
arr[1][1] = 1;
} else if (n > 2) {
arr[0] = [];
arr[1] = [];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (i = 2; i < n; i++) {
arr[i] = [];
arr[i][0] = 1;
for (j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][j] = 1;
}
}
console.log(arr);
for (i = 0; i < arr.length; i++) {
console.log(arr[i].join(' '))
}
}
pascal(5)
回答by akurudi
This function will calculate Pascal's Triangle for "n" number of rows. It will create an object that holds "n" number of arrays, which are created as needed in the second/inner for loop.
此函数将计算“n”行数的帕斯卡三角形。它将创建一个包含“n”个数组的对象,这些数组是在第二个/内部 for 循环中根据需要创建的。
function getPascalsTriangle(n) {
var arr = {};
for(var row = 0; row < n; row++) {
arr[row] = [];
for(var col = 0; col < row+1; col++) {
if(col === 0 || col === row) {
arr[row][col] = 1;
} else {
arr[row][col] = arr[row-1][col-1] + arr[row-1][col];
}
}
}
return arr;
}
console.log(getPascalsTriangle(5));
回答by Selvam Annamalai
Floyd triangle
弗洛伊德三角
You can try the following code for a Floyd triangle
您可以尝试使用以下代码创建弗洛伊德三角形
var prevNumber=1,i,depth=10;
for(i=0;i<depth;i++){
tempStr = "";j=0;
while(j<= i){
tempStr = tempStr + " " + prevNumber;
j++;
prevNumber++;
}
console.log(tempStr);
}
回答by РАВИ
You can create arbitrary 2d arrays and store it in there and return the correct Pascal. JavaScript does not have a special syntax for creating multidimensional arrays. A common workaround is to create an array of arrays in nested loops.
您可以创建任意二维数组并将其存储在那里并返回正确的 Pascal。JavaScript 没有用于创建多维数组的特殊语法。一个常见的解决方法是在嵌套循环中创建一个数组数组。
Here is my version of the solution
这是我的解决方案版本
function pascal(input) {
var result = [[1], [1,1]];
if (input < 0) {
return [];
}
if (input === 0) {
return result[0];
}
for(var j = result.length-1; j < input; j++) {
var newArray = [];
var firstItem = result[j][0];
var lastItem = result[j][result[j].length -1];
newArray.push(firstItem);
for (var i =1; i <= j; i++) {
console.log(result[j][i-1], result[j][i]);
newArray.push(sum(result[j][i-1], result[j][i]));
}
newArray.push(lastItem);
result.push(newArray);
}
return result[input];
}
function sum(one, two) {
return one + two;
}
回答by Deepak Dhull
Here is the code i created for pascal triangle in javascript
这是我在 javascript 中为帕斯卡三角形创建的代码
'use strict'
let noOfCoinFlipped = 5
let probabiltyOfnoOfHead = 2
var dataStorer = [];
for(let i=0;i<=noOfCoinFlipped;i++){
dataStorer[i]=[];
for(let j=0;j<=i;j++){
if(i==0){
dataStorer[i][j] = 1;
}
else{
let param1 = (j==0)?0:dataStorer[i-1][j-1];
let param2 = dataStorer[i-1][j]?dataStorer[i-1][j]:0;
dataStorer[i][j] = param1+param2;
}
}
}
let totalPoints = dataStorer[noOfCoinFlipped].reduce((s,n)=>{return s+n;})
let successPoints = dataStorer[noOfCoinFlipped][probabiltyOfnoOfHead];
console.log(successPoints*100/totalPoints)
Here is the link as well http://rextester.com/TZX59990
回答by Ahmet Deveci
This is my solve:
这是我的解决方案:
function pascalTri(n){
let arr=[];
let c=0;
for(let i=1;i<=n;i++){
arr.push(1);
let len=arr.length;
if(i>1){
if(i>2){
for(let j=1;j<=(i-2);j++){
let idx=(len-(2*i)+j+2+c);
let val=arr[idx]+arr[idx+1];
arr.push(val);
}
c++;
}
arr.push(1);
}
}
return arr;
}
let pascalArr=pascalTri(7);
console.log(pascalArr);
回答by ankit binjola
here is the pattern for n = 3
这是 n = 3 的模式
#
##
###
here is js code to print this.
这是打印这个的js代码。
function staircase(n) {
for(var i=0 ; i<n ; i++) {
for(var j=n-1 ; j>i ; j--)
process.stdout.write(" ");
for(var k=0 ; k<=i; k++) {
process.stdout.write("#");
}
process.stdout.write("\n");
}
}