티스토리 뷰

728x90
SMALL

배열에서 2개더한게 weight인 배열 index 찾기(hash table 사용)

function findSumBetter(arr, weight) {
    var hashtable = {};

    for (var i = 0, arrLength = arr.length; i < arrLength; i++) {
        var currentElement = arr[i],
            difference = weight - currentElement;

        // check the right one already exists
        if (hashtable[currentElement] != undefined) {
            return [i, hashtable[currentElement]];
        } else {
            // store index
            hashtable[difference] = i;
        }
    }
    return -1;
}
findSumBetter([1, 2, 3, 4,5], 9); // [ 4, 3 ]

나선형으로 출력(달팽이)

var M = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]];
function spiralPrint(M) {
    var topRow = 0,
        leftCol = 0,
        btmRow = M.length - 1,
        rightCol = M[0].length - 1;

    while (topRow < btmRow && leftCol < rightCol) {
        for (var col = 0; col <= rightCol; col++) {
            console.log(M[topRow][col]);
        }
        topRow++;
        for (var row = topRow; row <= btmRow; row++) {
            console.log(M[row][rightCol]);
        }
        rightCol--;
        if (topRow <= btmRow) {
            for (var col = rightCol; col > leftCol; col--) {
                console.log(M[btmRow][col]);
            }
            btmRow--;
        }
        if (leftCol <= rightCol) {
            for (var row = btmRow; row > topRow; row--) {
                console.log(M[row][leftCol]);
            }
            leftCol++;
        }
    }
}
spiralPrint(M);

틱택토 게임(3목)

function checkRow ( rowArr, letter ) {
    for ( var i=0; i < 3; i++) {
        if (rowArr[i]!=letter) {
            return false;
        }
    }
    return true;
}

function checkColumn ( gameBoardMatrix, columnIndex, letter ) {
    for ( var i=0; i < 3; i++) {
        if (gameBoardMatrix[i][columnIndex]!=letter) {
            return false;
        }
    }
    return true;
}

function ticTacToeWinner ( gameBoardMatrix, letter) {

    // Check rows
    var rowWin = checkRow(gameBoardMatrix[0], letter)
        || checkRow(gameBoardMatrix[1], letter)
        || checkRow(gameBoardMatrix[2], letter);

    var colWin = checkColumn(gameBoardMatrix, 0, letter)
        || checkColumn(gameBoardMatrix, 1, letter)
        || checkColumn(gameBoardMatrix, 2, letter);

    var diagonalWinLeftToRight = (gameBoardMatrix[0][0]==letter && gameBoardMatrix[1][1]==letter && gameBoardMatrix[2][2]==letter);
    var diagonalWinRightToLeft = (gameBoardMatrix[0][2]==letter && gameBoardMatrix[1][1]==letter && gameBoardMatrix[2][0]==letter);

    return rowWin || colWin || diagonalWinLeftToRight || diagonalWinRightToLeft;
}

var board = [['O','-','X'],['-','O','-'],['-','X','O']];
ticTacToeWinner(board, 'X'); // false
ticTacToeWinner(board, 'O'); // true

 

728x90
LIST

' > 자바스크립트로 하는 자료 구조와 알고리즘' 카테고리의 다른 글

해시 테이블  (0) 2020.12.19
검색과 정렬  (0) 2020.12.18
집합  (0) 2020.12.17
재귀  (0) 2020.12.17
메모리 누수  (0) 2020.12.17
댓글
공지사항