for문 사용

function getRandomArray(idxSize, range) {
	/* 랜덤 수를 가진 배열을 반환하는 메서드.
	 * idxSize : 반환받을 배열 사이즈, 
	 * range : 랜덤 수의 범위
	 */
	var indexs = new Array(); // 랜덤 인덱스 배열
	var hasValue = false; //같은 값이 있는지 확인하기 위한 변수
	
	if(idxSize > range) {
		console.error('index size > range');
		return indexs;
	}
	
	while(indexs.length < idxSize) {
		hasValue = false;
		var temp = parseInt(Math.random() * range);
		for(c = 0; c < indexs.length; c++) {
			if(temp == indexs[c]) {
				hasValue = true;
				break;
			}
		}
		if(hasValue == false) {
			indexs.push(temp);
		} 
	}
	return indexs;
}

// 사용방법
var indexs = new Array();
indexs = console.log(getRandomArray(5, 10));
indexs.forEach(function(value) {
	console.log(value);
});


Set 사용

set으로 좀 더 짧은 코드를 작성할 수 있지만 크롬과 오페라, 파이어폭스에서만 지원되며 익스플로러에서는 Set을 지원하지 않는다.

var indexs = new Set();
while(1) {
	indexs.add(parseInt(Math.random() * 10));
	if(indexs.size == 5) {
		console.log(indexs.size);
		break;
	}
}

indexs.forEach(function(value) {
	console.log(value);
});

메서드 배열 만들기

public class Node {
    ...
    public void goNorth() { ... }
    public void goSouth() { ... }
    public void goEast() { ... }
    public void goWest() { ... }

    interface MoveAction {
        void move();
    }

    private MoveAction[] moveActions = new MoveAction[] {
        new MoveAction() { public void move() { goNorth(); } },
        new MoveAction() { public void move() { goSouth(); } },
        new MoveAction() { public void move() { goEast(); } },
        new MoveAction() { public void move() { goWest(); } },
    };

    public void move(int index) {
        moveActions[i].move();
    }
    public void allMove() {
        for (MoveAction m : moveActions)
            m.move();
    }
}

참고


+ Recent posts