didkoslawow

Untitled

Jan 16th, 2023
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. function diagonalAttack(string) {
  2. const matrix = [];
  3. let leftRightDiag = 0;
  4. let rightLeftDiag = 0;
  5.  
  6. for (let i = 0; i < string.length; i++) {
  7. matrix.push(
  8. string[i].split(' ').map((string) => {
  9. return Number(string);
  10. })
  11. );
  12. }
  13. // Diagonals sum:
  14.  
  15. for (let i = 0; i < matrix.length; i++) {
  16. for (let j = 0; j < matrix.length; j++) {
  17. if (i === j) {
  18. leftRightDiag += matrix[i][j];
  19. }
  20. if (i + j === matrix.length - 1) {
  21. rightLeftDiag += matrix[i][j];
  22. }
  23. }
  24. }
  25. // Checking diagonal sums equality and printing the results:
  26.  
  27. if (leftRightDiag === rightLeftDiag) {
  28. for (let i = 0; i < matrix.length; i++) {
  29. for (let j = 0; j < matrix.length; j++) {
  30. if (i === j || i + j === matrix.length - 1) {
  31. continue;
  32. } else {
  33. matrix[i][j] = rightLeftDiag;
  34. }
  35. }
  36. }
  37. console.log(matrix.map((arr) => arr.join(' ')).join('\n'));
  38. } else {
  39. console.log(matrix.map((arr) => arr.join(' ')).join('\n'));
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment