3

I am new to JavaScript, and I am struggling with this one question from class. It is probably something easy, but I am completely 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 completely 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 completely 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);
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Kevin
  • 47
  • 1
  • 4

9 Answers9

2

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);
}
PinkTurtle
  • 6,942
  • 3
  • 25
  • 44
  • Interesting...I knew there was something with a boolean value I could of used. I guess I just didn't know how to use it. Still learning! but learned something new. Thanks – Kevin Aug 25 '15 at 18:26
  • Np. Feel free to upvote my answer if it did help you =). – PinkTurtle Aug 25 '15 at 19:27
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;
}
Carlos M. Meyer
  • 436
  • 3
  • 9
  • This is the only answer always yielding a checkered pattern. – aross Aug 25 '15 at 08:28
  • Thanks for all your help! I believe all the answers I see below are very similar. I see that knowing the modulo operator, you can check if something is even or odd. Also I think I just confused myself how the arrays would be positioned with pushing two different user inputs. – Kevin Aug 25 '15 at 18:36
1

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 compressed 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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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.

DavidVollmers
  • 677
  • 5
  • 17
0

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.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

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.net/kdgwbr2q/

Magnus
  • 1,422
  • 11
  • 22
0

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"]
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
0

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 |

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
0

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]);
  }
}
ArBro
  • 731
  • 5
  • 18