[Javascript] 백준 Code test

Darcy Daeseok YU ·2025년 1월 13일

백준 문제 샘플 데이터 가져오기

const inputs = require('fs').readFileSync(0,'utf8).toString().trim();

// 0 
  1
const inputs = require('fs').readFileSync(0,'utf8).toString().trim().split("\n").map(Number);
 [1, 2] 


//  0 0 
    1 1

const inputs = require('fs').readFileSync(0,'utf8).toString().trim().split("\n").map(el => el.trim().split(" ").map(Number)

[ [0, 0], [1, 1] ]

Reverse the middle range of an array.

const arr = [1,2,3,4,5];
let from = 1  ,to = 3;

let start = from - 1; 
let end = to - 1; 

 const subArray = arr.slice(start, end + 1).reverse();
  arr.splice(start, subArray.length, ...subArray);



while(start < end){
	const temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    
    // or 

	[arr[start], arr[end]]  = [arr[end], arr[start]] 

	
	start++;
	end--';
} 

숫자 위치 리버스 :: 123 => 321

function reverseNum(num){
	let reversed = 0;
	while( num > 0 ) {
		reversed = reversed * 10 + num % 10;
		num = Math.floor(num / 10); 

	}

	return reversed;

}


function reverseNumRecursive(num, reversed = 0){

    if(num === 0) return reversed; 

    return reverseNumRecursive(Math.floor(num/10), reversed * 10 + (num % 10));

}

다이아몬드 별

const n = 5; // Number of rows for the upper half

// Upper half of the diamond
for (let i = 0; i < n; i++) {
    console.log(" ".repeat(n - i - 1) + "*".repeat(2 * i + 1));
}

// Lower half of the diamond
for (let i = n - 2; i >= 0; i--) {
    console.log(" ".repeat(n - i - 1) + "*".repeat(2 * i + 1));
}

중복된 문자 구하기

const word = require("fs").readFileSync(0, 'utf8').toString().trim().toLowerCase();
const cnts = {};
let maxCnt = 0; 

for (const char of word) {
    cnts[char] = (cnts[char] || 0) + 1;
    maxCnt = Math.max(maxCnt, cnts[char]);
}

let maxChar = ""; 
let tied = 0; 
for (const key in cnts) {
    if (cnts[key] === maxCnt) {
        tied++;
        maxChar = key;
    }
    if (tied > 1) break;  
}

console.log(tied > 1 ? '?' : maxChar.toUpperCase());

이차원 배열에서 최대값 찾기 + 위치 정보 구하기

let N = 0;
let M = 0;
const arr = [];
input.forEach((aarr) => {
    M = aarr.length;
    arr.push(...aarr);
});
console.log("arr====", arr) 
const maxVal = Math.max(...arr);
const index = arr.indexOf(maxVal);
console.log(maxVal)
console.log(Math.floor(index/M) +1 , index%M +1);

// 가로 : Math.floor(index / M) : 
// 세로 : index % M; 

일반 수학
1193/분수찾기

1 2 6 7 15
3 5 8 14
4 9 13
10 12
11

참고


const target = +require('fs').readFileSync(0, 'utf8').toString().trim();

let accNumTo = 1; 
let accNumFrom = 1; 
let layer = 1 ; 

while( accNumTo < target ){
    accNumFrom = accNumTo+1;
    accNumTo += layer + 1; 
    layer++; 


}

const numerator = target - accNumFrom + 1 ; 
const denominator = accNumTo - target + 1;

let isTopToBottom = layer % 2 === 0 ; 
isTopToBottom ? `${numerator}/${denominator}` : `${denominator}/${numerator}`; 

정렬: Bubble & Quick Sort

Bubble Sort


const totalQnty = input[0];
const arr = input.slice(1);

for(let i = 0; i < totalQnty; i++){
    
    for(let j = i + 1 ; j < totalQnty ; j++){
            if(arr[i] > arr[j]){
                    const temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
             } 
    }
}


console.log(arr.join("\n"));

Quick Sort (Array.sort)


const totalQnty = input[0];
const array = input.slice(1);


function quickSort(arr){
    if(arr.length <= 1) return arr; 
    const pivot = arr[0];
    const leftSmallerThanPivot = arr.slice(1).filter(num => num <= pivot);
    const rightBiggerThanPivot = arr.slice(1).filter(num => num > pivot);
     
    return [...quickSort(leftSmallerThanPivot), pivot, ...quickSort(rightBiggerThanPivot)];
}; 
const sortedArr = quickSort(array);

console.log(sortedArr.join("\n"));

Median value 중간값 대표값 from scratch
arr.sort 쓰면 편함.

const input = require("fs").readFileSync(0, 'utf8').toString().trim().split("\n").map(Number);

const quickSort = (arr) =>{
    if(arr.length <= 1) return arr; 
    const pivot = arr[0];
    const left = arr.slice(1).filter(number =>{ return number <= pivot});
    const right = arr.slice(1).filter(number => number > pivot);
    return [...quickSort(left), pivot, ...quickSort(right)];
} 

const result = quickSort(input);
let total = result.reduce((acc, num) => { return acc + num} , 0);  

console.log(total / result.length);
console.log(result[Math.floor(result.length / 2)]);
profile
React, React-Native https://darcyu83.netlify.app/

0개의 댓글