[Javascript]차집합, 교집합, 합집합을 구하는 예제입니다.
<script>
/**************************************************************
- 차집합, 교집합, 합집합을 구하는 예제입니다.
- 성능은 전혀 고려되지 않았습니다.
- 더 좋은 방법이 있으면 저에게도 알려주십시오~
http://shed.egloos.com
bluedskim@gmail.com
**************************************************************/
function 교집합_혹은_차집합_구하기(차집합이면_false_교집합이면_true) {
// textarea의 값을 배열로 변환
var 임시토크나이저 = new StringTokenizer(document.all['집합A'].value, "\n");
var 집합A = 임시토크나이저.getTokens();
// textarea의 값을 배열로 변환
임시토크나이저 = new StringTokenizer(document.all['집합B'].value, "\n");
var 집합B = 임시토크나이저.getTokens();
// 결과창을 비움
document.all['연산결과'].value = '';
// 집합A의 모든 요소에 대해 집합B의 요소와 비교
for(i = 0 ; i < 집합A.length ; i++ ) {
공통요소면_true = false;
// full scan 검색
for(j = 0 ; j < 집합B.length; j++) {
if(집합B[j] == 집합A[i]) {
공통요소면_true = true;
break;
}
}
debug('집합의_요소=' + 집합A[i] + ' 공통요소면_true=' + 공통요소면_true);
if(공통요소면_true == 차집합이면_false_교집합이면_true) document.all['연산결과'].value += 집합A[i] + "\n";
}
}
function 합집합_구하기() {
//집합A - 집합B 을 구한다.
교집합_혹은_차집합_구하기(false);
// 위의 결과에 집합B를 통째로 합친다
document.all['연산결과'].value += document.all['집합B'].value;
}
[집합A]
[집합B]
[결과]
[디버그:더블클릭하여 삭제]
<script> /* 여기서 부터는 로직과 직접 관련 없음 */ /* 여기서 부터는 로직과 직접 관련 없음 */ /** * 디버그용 함수 */ function debug(str) { document.all['debugConsole'].value += '[' + (new Date()).toLocaleString() + '] ' + str + '\n'; } /* Client side JavaScript object for tokenization of a string. Best used for something as simple as a comma separated record of values. Edited 27/09/2004 11:26AM Added a trim function and fixed a few "this" references that were not there and should have been. Edited 14/02/2005 9:33PM Thanks to Cliff Hale for this! getTokens() is dropping the last token in the string if the last token is only 1 char in length (e.g., "1,2,3" would result in it returning "1,2") To remedy this, I made the following change: .... // Go through material, token at a time. while (this.material.length - start >= 1) Also changed the while in getTokens to skip over repeating instances of the separator. */ /* Constructor. Split up a material string based upong the separator. Param - material, the String to be split up. Param - separator, the String to look for within material. Should be something like "," or ".", not a regular expression. */ function StringTokenizer (material, separator) { // Attributes. this.material = material; this.separator = separator; // Operations. this.getTokens = getTokens; this.nextToken = nextToken; this.countTokens = countTokens; this.hasMoreTokens = hasMoreTokens; this.tokensReturned = tokensReturned; // Initialisation code. this.tokens = this.getTokens(); this.tokensReturned = 0; } // end constructor /* Go through material, putting each token into a new array. Return - the array with all the tokens in it. */ function getTokens() { // Create array of tokens. var tokens = new Array(); var nextToken; // If no separators found, single token is the material string itself. if (this.material.indexOf (this.separator) < 0) { tokens [0] = this.material; return tokens; } // end if // Establish initial start and end positions of the first token. start = 0; end = this.material.indexOf (this.separator, start); // Counter for how many tokens were found. var counter = 0; // Go through material, token at a time. var trimmed; while (this.material.length - start >= 1) { nextToken = this.material.substring (start, end); start = end + 1; if (this.material.indexOf (this.separator, start + 1) < 0) { end = this.material.length; } // end if else { end = this.material.indexOf (this.separator, start + 1); } // end else trimmed = trim (nextToken); // Remove any extra separators at start. while (trimmed.substring(0, this.separator.length) == this.separator) { trimmed = trimmed.substring (this.separator.length); } trimmed = trim(trimmed); if (trimmed == "") { continue; } tokens [counter] = trimmed; counter ++; } // end if // Return the initialised array. return tokens; } // end getTokens function /* Return a count of the number of tokens in the material. Return - int number of tokens in material. */ function countTokens() { return this.tokens.length; } // end countTokens function /* Get next token in material. Return - next token in material. */ function nextToken() { if (this.tokensReturned >= this.tokens.length) { return null; } // end if else { var returnToken = this.tokens [this.tokensReturned]; this.tokensReturned ++; return returnToken; } // end else } // end nextToken function /* Tests if there are more tokens available from this tokenizer's string. If this method returns true, then a subsequent call to nextToken will successfully return a token. Return true if more tokens, false otherwise. */ function hasMoreTokens() { if (this.tokensReturned < this.tokens.length) { return true; } // end if else { return false; } // end else } // end hasMoreTokens function function tokensReturned() { return this.tokensReturned; } // end tokensReturned function function trim (strToTrim) { return(strToTrim.replace(/^\s+|\s+$/g, '')); } // end trim function
[집합B]
[결과]
[디버그:더블클릭하여 삭제]
<script> /* 여기서 부터는 로직과 직접 관련 없음 */ /* 여기서 부터는 로직과 직접 관련 없음 */ /** * 디버그용 함수 */ function debug(str) { document.all['debugConsole'].value += '[' + (new Date()).toLocaleString() + '] ' + str + '\n'; } /* Client side JavaScript object for tokenization of a string. Best used for something as simple as a comma separated record of values. Edited 27/09/2004 11:26AM Added a trim function and fixed a few "this" references that were not there and should have been. Edited 14/02/2005 9:33PM Thanks to Cliff Hale for this! getTokens() is dropping the last token in the string if the last token is only 1 char in length (e.g., "1,2,3" would result in it returning "1,2") To remedy this, I made the following change: .... // Go through material, token at a time. while (this.material.length - start >= 1) Also changed the while in getTokens to skip over repeating instances of the separator. */ /* Constructor. Split up a material string based upong the separator. Param - material, the String to be split up. Param - separator, the String to look for within material. Should be something like "," or ".", not a regular expression. */ function StringTokenizer (material, separator) { // Attributes. this.material = material; this.separator = separator; // Operations. this.getTokens = getTokens; this.nextToken = nextToken; this.countTokens = countTokens; this.hasMoreTokens = hasMoreTokens; this.tokensReturned = tokensReturned; // Initialisation code. this.tokens = this.getTokens(); this.tokensReturned = 0; } // end constructor /* Go through material, putting each token into a new array. Return - the array with all the tokens in it. */ function getTokens() { // Create array of tokens. var tokens = new Array(); var nextToken; // If no separators found, single token is the material string itself. if (this.material.indexOf (this.separator) < 0) { tokens [0] = this.material; return tokens; } // end if // Establish initial start and end positions of the first token. start = 0; end = this.material.indexOf (this.separator, start); // Counter for how many tokens were found. var counter = 0; // Go through material, token at a time. var trimmed; while (this.material.length - start >= 1) { nextToken = this.material.substring (start, end); start = end + 1; if (this.material.indexOf (this.separator, start + 1) < 0) { end = this.material.length; } // end if else { end = this.material.indexOf (this.separator, start + 1); } // end else trimmed = trim (nextToken); // Remove any extra separators at start. while (trimmed.substring(0, this.separator.length) == this.separator) { trimmed = trimmed.substring (this.separator.length); } trimmed = trim(trimmed); if (trimmed == "") { continue; } tokens [counter] = trimmed; counter ++; } // end if // Return the initialised array. return tokens; } // end getTokens function /* Return a count of the number of tokens in the material. Return - int number of tokens in material. */ function countTokens() { return this.tokens.length; } // end countTokens function /* Get next token in material. Return - next token in material. */ function nextToken() { if (this.tokensReturned >= this.tokens.length) { return null; } // end if else { var returnToken = this.tokens [this.tokensReturned]; this.tokensReturned ++; return returnToken; } // end else } // end nextToken function /* Tests if there are more tokens available from this tokenizer's string. If this method returns true, then a subsequent call to nextToken will successfully return a token. Return true if more tokens, false otherwise. */ function hasMoreTokens() { if (this.tokensReturned < this.tokens.length) { return true; } // end if else { return false; } // end else } // end hasMoreTokens function function tokensReturned() { return this.tokensReturned; } // end tokensReturned function function trim (strToTrim) { return(strToTrim.replace(/^\s+|\s+$/g, '')); } // end trim function