最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to alternate values in an array? - Stack Overflow

programmeradmin1浏览0评论

I am new to JavaScript, and I am struggling with this one question from class. It is probably something easy, but I am pletely stuck at the moment.

Anyway, here is the problem:

I have to create a table of alternating characters of x and o based on a user-specified number of rows and columns. For instance, if the user wanted 3 rows and 3 columns, it would have to look like this:

xox
oxo
xox

I am pletely lost on how you can create an alternating value in an array. This is what I have so far (below), but the logic of this is pletely wrong. If anyone can give me some advice that would be great! I have been looking at this problem for days, but just can’t seem to piece it together.

// a = user input # of columns
// b = user input # of rows

function firstTest(a,b) {
  var firstArray = [];
  var total = [];
  for (i = 0; i < a; i+=1) {        
    firstArray.push("xo");
  }
  for (i=0; i<b; i+=1){
    total.push(firstArray);
  }
  return(total);
}

I am new to JavaScript, and I am struggling with this one question from class. It is probably something easy, but I am pletely stuck at the moment.

Anyway, here is the problem:

I have to create a table of alternating characters of x and o based on a user-specified number of rows and columns. For instance, if the user wanted 3 rows and 3 columns, it would have to look like this:

xox
oxo
xox

I am pletely lost on how you can create an alternating value in an array. This is what I have so far (below), but the logic of this is pletely wrong. If anyone can give me some advice that would be great! I have been looking at this problem for days, but just can’t seem to piece it together.

// a = user input # of columns
// b = user input # of rows

function firstTest(a,b) {
  var firstArray = [];
  var total = [];
  for (i = 0; i < a; i+=1) {        
    firstArray.push("xo");
  }
  for (i=0; i<b; i+=1){
    total.push(firstArray);
  }
  return(total);
}
Share Improve this question edited Aug 25, 2015 at 8:16 Sebastian Simon 19.5k8 gold badges61 silver badges84 bronze badges asked Aug 25, 2015 at 8:10 KevinKevin 471 silver badge4 bronze badges 3
  • andrespagella./getting-even-values-array-without-loops – Barrie Reader Commented Aug 25, 2015 at 8:12
  • stackoverflow./questions/966225/… – Xavjer Commented Aug 25, 2015 at 8:15
  • If you need a checkered pattern then the answers are wrong so far. – aross Commented Aug 25, 2015 at 8:24
Add a ment  | 

9 Answers 9

Reset to default 2

You need only check if the sum of the value of the row and the value of the column is odd or even:

function firstTest(a,b) {
    table = [];
    for ( x = 1 ; x <= a ; x++ ) {
        row = [];
        for ( y = 1 ; y <= b ; y++ ) {
            if (((x+y) % 2) == 0) {
                row.push('x');
            } else {
                row.push('o');
            }
        }
        table.push(row);
    }
    return table;
}

You can alternate values with a boolean variable. For example:

var _switch = false;
// your code here...
if (_switch) firstArray.push("o");
else firstArray.push("x");
// more core here...
_switch = !_switch;

Your code :

// a = user input # of columns
// b = user input # of rows

function firstTest(a,b) {
  var _switch = false;
  var firstArray = [];
  var total = [];
  for (i = 0; i < a; i++) {        
    if (_switch) firstArray.push("x");
    else firstArray.push("o");
    _switch = !_switch;
  }
  for (i=0; i<b; i+=1){
    total.push(firstArray);
  }
  return(total);
}

Solution with Array.apply and Array.prototype.map:

var width = 3,
    height = 3,
    pattern = 'xo',
    array = Array.apply(Array, { length: height }).map(function (_, i) {
        return Array.apply(Array, { length: width }).map(function (__, j) {
            return pattern[(i + j) % 2];
        });
    });

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

The pressed code:

var array = Array.apply(Array, { length: 3}).map(function (_, i) {
        return Array.apply(Array, { length: 3}).map(function (__, j) {
            return 'xo'[(i + j) % 2];
        });
    });

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

I am not sure if this is what you want to achieve, but i guess you want that the value alternates from cell to cell:

function createAlternatingTable (rows, cols) {
    var table = [];
    var cellCount = 0;
    for (var rowIndex = 0; rowIndex < rows; rowIndex++) {
        var row = [];
        for (var colIndex = 0; colIndex < cols; colIndex++) {
            row.push(cellCount % 2 == 0 ? 'x' : 'o');
            cellCount++;
        }
        table.push(row);
    }
    return table;
}

The trick is the cellCount % 2 == 0. So when the number of cells is even 'x' is inserted, if it is odd, 'o' is inserted.

What you need is a 2 dimensional array where the outer array will have the rows and the inner array will have the columns in each row.

One simple logic we can follow is, we will create the first 2 rows then we can clone them to create rest of them

function firstTest(a, b) {

  var total = [],
    tmp;
  for (var i = 0; i < a; i++) {
    if (i < 2) {
      tmp = [];
      for (var j = 0; j < b; j++) {
        tmp.push((i * b + j) % 2 == 0 ? 'x' : 'o');
      }
    } else {
      tmp = total[i % 2].slice();
    }
    total.push(tmp)
  }
  return total;
}

snippet.log(JSON.stringify(firstTest(1, 1)));
snippet.log(JSON.stringify(firstTest(2, 1)));
snippet.log(JSON.stringify(firstTest(2, 3)));
snippet.log(JSON.stringify(firstTest(3, 2)));
snippet.log(JSON.stringify(firstTest(3, 3)));
<!-- Provides the `snippet` object, see http://meta.stackexchange./a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

try this one

function martix (row,col) {

    var total_sym= row*col;
    var strSym = "";
    for(var i =1;i<=total_sym;i++){ 

        if(i%2){ 
            strSym+='X';
        } else{ 
            strSym+='O';  
        }  
    }

    return strSym;
}


    var strSym   = martix(3,3);
    var arrSym =  strSym.split(''); //["X", "O", "X", "O", "X", "O", "X", "O", "X"]

You can use modulo (%) to alternate the different characters from an array. The modulo option finds the remainder when a dividend is divided by a divisor. ( 14 % 5 = ( 0,8 * 5 ) = 4 ).

This example i wrote will alternate "A","B" and "C" (could be expanded to "what ever"). To make it alternate "X" and "O", just define var altChars = ["X","O"]; instead.

function buildTable(a,b)
{
    var returnTable = [];
    var altChars = ["A","B","C"];
    for (i = 0; i < a; i++)
    {
        returnTable[i] = [];
        for (j = 0; j < b; j++)
        {
           returnTable[i][j] = altChars[ ( ( i * a ) + j + i ) % altChars.length];
        }
    }
return returnTable;
}

console.log(buildTable(4,5));

Made a JSFiddle of the code for demonstation: http://jsfiddle/kdgwbr2q/

Fun challenge.

function xo(a,b) {

  var table = [], i, j;

  for (i = 0; i < a; i++) {
    var row = [];
    for (j = 0; j < b; j++) {
      row.push(((j+i) % 2) ? 'o' : 'x');
    }
    table.push(row);
  }
  return table;
}

xo(3,4) will return:

| x, o, x, o |
| o, x, o, x |
| x, o, x, o |

Play with the Plunker

Wonderful to get things like this working :-)

var getArray = function(rows, columns) {

  var curCell = 0;
  var table = [];

  for (var iRow = 0; iRow < rows; iRow++) {
        var row = [];
        for (var iCol = 0; iCol < columns; iCol++) {
            row.push(curCell % 2 == 0 ? 'x' : 'o');
            curCell++;
        }
        table.push(row);
    }

  for (var i=0; i<table.length; i++) {
    console.log(table[i]);
  }
}
发布评论

评论列表(0)

  1. 暂无评论