Looping in a spiral

前端 未结 30 2787
独厮守ぢ
独厮守ぢ 2020-11-22 15:07

A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fe

30条回答
  •  再見小時候
    2020-11-22 15:38

    Here's a JavaScript (ES6) iterative solution to this problem:

    let spiralMatrix = (x, y, step, count) => {
        let distance = 0;
        let range = 1;
        let direction = 'up';
    
        for ( let i = 0; i < count; i++ ) {
            console.log('x: '+x+', y: '+y);
            distance++;
            switch ( direction ) {
                case 'up':
                    y += step;
                    if ( distance >= range ) {
                        direction = 'right';
                        distance = 0;
                    }
                    break;
                case 'right':
                    x += step;
                    if ( distance >= range ) {
                        direction = 'bottom';
                        distance = 0;
                        range += 1;
                    }
                    break;
                case 'bottom':
                    y -= step;
                    if ( distance >= range ) {
                        direction = 'left';
                        distance = 0;
                    }
                    break;
                case 'left':
                    x -= step;
                    if ( distance >= range ) {
                        direction = 'up';
                        distance = 0;
                        range += 1;
                    }
                    break;
                default:
                    break;
            }
        }
    }
    

    Here's how to use it:

    spiralMatrix(0, 0, 1, 100);

    This will create an outward spiral, starting at coordinates (x = 0, y = 0) with step of 1 and a total number of items equals to 100. The implementation always starts the movement in the following order - up, right, bottom, left.

    Please, note that this implementation creates square matrices.

提交回复
热议问题