T
T
thsiganenko2015-03-31 20:03:29
JavaScript
thsiganenko, 2015-03-31 20:03:29

What other way can solve the problem of forming a string of a given type (JavaScript solution)?

Good day to members of the Toster community. This is my first question on the project, so don't be too harsh on the wording.
Task:

Form a string containing a matrix with zeros and ones according to the scheme:
0 0 0 1 0 0 0
0 0 1 1 1 0 0
0 1 1 1 1 1 0
1 1 1 1 1 1 1
0 1 1 1 1 1 0
0 0 1 1 1 0 0
0 0 0 1 0 0 0
And display it.

Wrote a JavaScript solution to display the result in the browser console.
(function matrixZeroOwe (line){

   //Определяем середину матрицы, в случае если её размерность будет отличной от 7
   var count = parseInt(line/2);
   
   // Переменная, в которой будет храниться конечный результат
   var strLine = '';

   // Формируем первую половину матрицы, в данном случае первые 4 строки нулей и единиц
   	for(var i = 0; i <= count; i++){
      		strLine += '0'.repeat(count - i) + '1'.repeat(1 + i*2) + '0'.repeat(count - i) + '\n';
   	}

  // Формируем вторую половину матрицы, в данном случае последние 3 строки нулей и единиц
   	for(i -= 2; i >= 0; i--){
      		strLine += '0'.repeat(count - i) + '1'.repeat(1 + i*2) + '0'.repeat(count - i) + '\n';
   	}

   	console.log(strLine);

}
)(7);

The code is working, but it does not leave the feeling that the problem can be solved in a more elegant way, that is, the algorithm for solving the problem can be made simpler and clearer. Of course, you can move the body of the cycles into a separate function, but this does not greatly affect the solution algorithm itself ...
In this connection, I would like to ask the community what options for solving this problem can be found?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey, 2015-03-31
@thsiganenko

Like this: jsfiddle.net/aLhetfa4/1
For the upper left corner, the sum of the indices in the matrix is ​​less than half,
for the upper right the difference of the indices is less than half, and so on..
The final code is this : jsfiddle.net/aLhetfa4/3 reference system, and the code is even simpler: jsfiddle.net/aLhetfa4/4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question