'웹 개발/Algorithm'에 해당되는 글 11건

  1. 2021.03.11 연결된 정점들
  2. 2021.03.11 인접 행렬 길찾기
  3. 2021.03.11 인접 행렬 생성하기

연결된 정점들

웹 개발/Algorithm 2021. 3. 11. 16:27
더보기

문제

방향이 있는 간선들의 목록이 주어질 때, 연결된 정점의 컴포넌트(그룹들)가 몇 개인지 반환하는 함수를 작성하세요.

입력

인자 1: edges

  • 2차원 Array 타입을 요소로 갖는 시작과 도착 정점이 담겨있는 배열들을 담고 있는 목록 (2차원 배열)
  • ex) [[0, 1], [1, 2], [3, 4]]

출력

  • Number 타입을 리턴해야 합니다.
  • 연결된 정점의 컴포넌트의 수를 숫자로 반환합니다.

주의사항

  • 주어진 간선은 무향입니다
    • [1, 2] 는 정점 1에서 정점 2로도 갈 수 있으며, 정점 2에서 정점 1로도 갈 수 있습니다.

입출력 예시

const result = connectedVertices([
	[0, 1],
	[2, 3],
	[4, 5],
]);
console.log(result); // 3

해당 정점들은 아래와 같은 모양을 하고 있습니다.

정점들
const result = connectedVertices([
	[0, 1],
	[2, 3],
	[3, 4],
	[3, 5],
]);
console.log(result); // 2

해당 정점들은 아래와 같은 모양을 하고 있습니다.

정점들
function connectedVertices(edges) {
  let result = []
  for(let edge of edges){
    //result: [[0,1],[2,3]]
    //edge : 3,4
    let li = edge
    let flag = false;
    //toDo
    for(let el of result){
      //el: [2,3]
      if(el.includes(edge[0]) || el.includes(edge[1])){
        flag = true
        if(el.includes(edge[0])){
          el.push(edge[1])
        }
        else{
          el.push(edge[0])
        }
      }
      
    }
    if(flag === false){
      result.push(li)
    }
  }

  let combine = function(arr){
    let result = []    
    for(let i =0; i<arr.length; i++){
      let nextArr = arr[i+1] || []
      let flag= false;
      
      for(let j=0;j<nextArr.length;j++){
        if(arr[i].includes(nextArr[j])){
          flag = true
        }
      }
        
      if(flag){//포함이 되있다.
        result.push(arr[i].concat(nextArr))//서로 포함관계인 두 요소를 합치고
        arr[i + 1] = arr[i+2] //합쳐졌으니 자리를 옮겨준다
        result = combine(result) //포함이 있는지 다시 확인. 있다면 다시 포함.없으면 그대로
      }else{
        result.push(arr[i])
        if(i === arr.length-1 && nextArr.length >= 1){
          result.push(nextArr)
        }
      }
    }
    return result
  }
  let result2 = combine(result)
  let tempArr = result2.slice()
  for(let el of tempArr){
    if(el === undefined){
      result2.pop()
    }
  }
  
  

  return result2.length
}

 

'웹 개발 > Algorithm' 카테고리의 다른 글

금고를 털어라  (0) 2021.03.11
짐 나르기  (0) 2021.03.11
바코드  (0) 2021.03.11
인접 행렬 길찾기  (0) 2021.03.11
인접 행렬 생성하기  (0) 2021.03.11
:

인접 행렬 길찾기

웹 개발/Algorithm 2021. 3. 11. 16:23
더보기

문제

주어진 인접행렬에서 한 정점으로부터 다른 정점으로 이어지는 길이 존재하는지 반환해야 합니다.

입력

인자 1: matrix

  • Array 타입을 요소로 갖는 인접 행렬이 담긴 2차원 배열

인자 2: from

  • Number 타입의 시작 정점

인자 3: to

  • Number 타입의 도착 정점

출력

  • boolean 타입을 리턴해야 합니다.
// function getDirections(matrix, from, to) {
//   // TODO: 여기에 코드를 작성합니다.
//   let passedIndex = []
//   let checkDirection = function(from){
//     let currentArr = matrix[from]
//     let isPassed = false;
//     let result = false;
//     if(currentArr[to] === 1){//직행이 있는지 확인
//       return true
//     }
    
//     for(let i = 0; i< currentArr.length; i++){
//       for(let el of passedIndex){//isPassed 만들기
//         if(el[0] === from && el[1] === i){
//           isPassed = true
//         }
//       }
//       if(currentArr[i] === 1 && isPassed === false){//다른 1인 요소가 있는지 확인      //갔었던 길인지 확인
//         passedIndex.push([from,i])
//         result = checkDirection(i)//그 요소로 들어가서 재귀      
//       }
//       if(result){
//         return result
//       }
//     }
//     return false
//   }
//   return checkDirection(from)

// }
function getDirections(matrix, from, to) {
  let passed = [from];
  let checkDirection = function (matrix, from, to) {
    if (matrix[from][to] === 1) {
      return true;
    }
    for (let i = 0; i < matrix[from].length; i++) {
      if (matrix[from][i] === 1 && !passed.includes(i)) {
        passed.push(i);
        if (checkDirection(matrix, i, to)) {
          return true;
        }
      }
    }
    return false;
  };
  return checkDirection(matrix, from, to);
}
//1. 요소의 값이 1인지 확인
// 1.true from,to 를 갔었던 길인지 확인
//  1.true.true 1.true 단계로 돌아가기
//  1.true.false 
// 
// 0 -> 3
// 0 1 0 1
// 0 0 0 1
// 0 1 0 0
// 1 0 0 0 
더보기

입출력 예시

const result = getDirections(
	[
		[0, 1, 0, 0],
		[0, 0, 1, 0],
		[0, 0, 0, 1],
		[0, 1, 0, 0],
	],
	0,
	2
);
console.log(result); // true
  • 정점 0에서 2로 가는 길이 존재하는지 확인합니다.
  • 0 --> 1 로 가는 간선이 존재하고, 1 --> 2 로 가는 간선이 존재하기 때문에 true를 반환합니다.

'웹 개발 > Algorithm' 카테고리의 다른 글

금고를 털어라  (0) 2021.03.11
짐 나르기  (0) 2021.03.11
바코드  (0) 2021.03.11
연결된 정점들  (0) 2021.03.11
인접 행렬 생성하기  (0) 2021.03.11
:

인접 행렬 생성하기

웹 개발/Algorithm 2021. 3. 11. 16:19
더보기

문제

방향이 있는 간선과 방향이 없는 간선들의 목록들을 받아 2차원 배열의 인접행렬을 반환하는 함수를 작성하세요.

조건

각 간선은 3가지 정보를 담고 있습니다.

  • 0번째: 간선의 시작 정점 (0 이상의 정수)
  • 1번째: 간선의 도착 정점 (0 이상의 정수)
  • 2번째: 방향성 ('undirected' 일시 무향, 'directed' 일시 방향)

입력

인자 1: edges

  • Number 타입의 방향/무향인 간선들의 목록이 담긴 배열

출력

  • Array 타입을 리턴해야 합니다.
  • 2차원 배열의 인접 행렬

주의사항

  • 정점 0에서 정점4로 이어주는 간선이 존재할 경우 정점 1, 2, 3도 존재합니다.
  • 반환하는 인접행렬은 2차원 배열이며, 행(row)는 바깥 배열, 열(column)은 안쪽 배열입니다.
    • let matrix = [[0, 0], [0, 0]]
    • matrix[0] === 0번째 행
    • matrix[0][0] === 0번째 행의 0번째 열
  • 두 정점간의 간선의 유무는 0과 1로 표시합니다.
    • 0: 두 정점간에 간선이 존재하지 않을 경우
    • 1: 두 정점간에 간선이 존재할 경우
  • 아래의 2차원 배열에서 세로축은 시작 정점, 가로축은 도착 정점입니다.

const matrix = [ [0, 0, 0], [0, 0, 0], [0, 0, 0], ];

function createMatrix(edges) {
	// TODO: 여기에 코드를 작성합니다.
  let maxNum = 0
  let numArr= []
  for(let a of edges){//배열의 크기 정하기(가장 큰 숫자 찾기)
    for(let b of a){
      if(typeof b === 'number'){
        numArr.push(b)
      }      
    }
  }
  maxNum = Math.max(...numArr)
  let matrix = []
  for(let i =0; i <= maxNum;i++){//배열 만들기
    matrix.push(new Array(maxNum + 1).fill(0))
  }
  //좌표 찾아서 값 바꾸기
  for(let edge of edges){
    matrix[edge[0]][edge[1]] = 1
    if(edge[2] === 'undirected'){
      matrix[edge[1]][edge[0]] = 1
    }
  }
  return matrix
}
//입출력 예시
let output1 = createMatrix([
	[0, 3, "directed"],
	[0, 2, "directed"],
	[1, 3, "directed"],
	[2, 1, "directed"],
]);

console.log(output1);
/**
 * [
 *  [0, 0, 1, 1],
 *  [0, 0, 0, 1],
 *  [0, 1, 0, 0],
 *  [0, 0, 0, 0]
 * ]
 */

let output2 = createMatrix([
	[0, 2, "directed"],
	[2, 4, "undirected"],
	[1, 3, "undirected"],
	[2, 1, "directed"],
]);

console.log(output2);
/**
 * [
 *  [0, 0, 1, 0, 0],
 *  [0, 0, 0, 1, 0],
 *  [0, 1, 0, 0, 1],
 *  [0, 1, 0, 0, 0],
 *  [0, 0, 1, 0, 0],
 * ]
 */

'웹 개발 > Algorithm' 카테고리의 다른 글

금고를 털어라  (0) 2021.03.11
짐 나르기  (0) 2021.03.11
바코드  (0) 2021.03.11
연결된 정점들  (0) 2021.03.11
인접 행렬 길찾기  (0) 2021.03.11
: