Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let size = gets().split(' ').map(Number);
- fieldY = size[0];
- fieldX = size[1];
- let matrix = [];
- let coins = 0
- let position = [0,0] //coordinates
- for (let i = 1 ; i <= fieldY; i++){
- matrix.push(gets().split(' ').map(Number));
- }
- // тука се намира нулевата позиция
- loop:
- for(let i = 0 ; i <= fieldX-1; i++){
- for (let j = 0; j <= fieldY-1; j++){
- if(matrix[i][j] === 0 ){
- position[0] = i
- position[1] = j
- break loop;
- }
- }
- }
- //тази функция определя максималната посока според правилото
- // "he chooses a cell (always the largest) from the order left, right, up, down"
- let maxLRUD = (dir) =>{
- let max = dir.slice();
- max = max.sort((a,b) => a-b)
- let maximum = max[3]
- if(dir[0] >= maximum){
- return 'left';
- } else if(dir[1] >= maximum){
- return 'right';
- } else if(dir[2] >= maximum){
- return 'up'
- } else if(dir[3] >= maximum){
- return 'down'
- }
- }
- //тука се определа посоката според монетите и накрая се извиква горната функция
- let maxCoinsDirection = (position) =>{
- let left = 0;
- let right = 0 ;
- let up = 0 ;
- let down = 0;
- if (position[0]>0){
- up = matrix[position[0]-1][position[1]]
- }
- if (position[0]<fieldY-1){
- down = matrix[position[0]+1][position[1]]
- }
- if (position[1]<fieldX-1){
- right = matrix[position[0]][position[1]+1]
- }
- if (position[1]>0){
- left = matrix[position[0]][position[1]-1]
- }
- let dir = [left, right, up, down]
- return maxLRUD(dir)
- }
- // тази функция определя дали е свършила играта
- let endCheck = (position) => {
- let endLeft, endDown, endRight, endUp = false
- if( position[1] === 0 ){
- endLeft = true;
- } else if (matrix[position[0]][position[1]-1] === 0){
- endLeft = true;
- }
- if(position[1] === fieldX-1){
- endRight =true
- } else if (matrix[position[0]][position[1]+1] === 0 ){
- endRight = true;
- }
- if(position[0] === 0){
- endUp =true
- } else if (matrix[position[0]-1][position[1]] === 0 ){
- endUp = true;
- }
- if(position[0] === fieldY-1){
- endDown =true
- } else if( matrix[position[0]+1][position[1]] === 0 ){
- endDown = true;
- }
- if(endLeft && endRight && endUp && endDown){
- return true
- } else {
- return false
- }
- }
- let direction = ''
- //тука се събират монетите
- while(true){
- if(endCheck(position)){
- break;
- }
- direction = maxCoinsDirection(position)
- if(direction === 'left'){
- matrix[position[0]][position[1]-1] --;
- position[1]--;
- } else if (direction === 'right'){
- matrix[position[0]][position[1]+1] --;
- position[1]++;
- } else if (direction === 'up') {
- matrix[position[0]-1][position[1]] --;
- position[0] --;
- } else if (direction === 'down') {
- matrix[position[0]+1][position[1]] --;
- position[0]++;
- }
- coins++
- }
- console.log(coins);
Advertisement
Add Comment
Please, Sign In to add comment