Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alternate values in an array?

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);
}
like image 322
Kevin Avatar asked Dec 20 '25 18:12

Kevin


2 Answers

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;
}
like image 140
Carlos M. Meyer Avatar answered Dec 23 '25 08:12

Carlos M. Meyer


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);
}
like image 26
PinkTurtle Avatar answered Dec 23 '25 08:12

PinkTurtle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!