단순 반복( for, index활용)

응용 반복( 출력 + 반복 )

 

'Algorithm > Boj' 카테고리의 다른 글

조건문  (0) 2022.07.09
출력  (0) 2022.07.07

단순 조건

반복 조건( 조건안에 조건)

'Algorithm > Boj' 카테고리의 다른 글

반복문  (0) 2022.07.11
출력  (0) 2022.07.07

이 글에 백준사이트에서 출제된 출력과 관계된 문제들을 풀고 생각한 과정들을 나열하려고 합니다.

 

백준 사이트에서 출력과 관계된 문제를 풀어봤습니다.

 

하기와 같은 주제로 나눌 수 있습니다.

 

단순출력

반복출력

여러줄 출력

추가 출력

변경 출력

ㄴ입력을 받아서 쪼개고 타입 변환을 하고 고차함수를 사용하여 더하고 출력

ㄴ시뮬레이션 출력

 

 

'Algorithm > Boj' 카테고리의 다른 글

반복문  (0) 2022.07.11
조건문  (0) 2022.07.09

https://leetcode.com/problems/create-target-array-in-the-given-order/

 

Create Target Array in the Given Order - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 풀이를 하자면, nums와 index들이 주어지고

해당 index에 값을 넣어서 배열을 만들어 주면 되는 간단한 문제!!

 

근데, 생각보다 쉽게 풀렸다?

 

왜냐면, result를 초기화하게 되면 인덱스 값이 이미 존재한지 몰랐다....!

 

그래서, result를 0으로 nums의 갯수로 초기화하였는데, 그럴 필요가 없었다. 

이 작업을 하면 0을 없애야하는 추가 작업도 해야하고... 배웠다!

 

생각해보니깐, 이 문제에서만 통한다.

 

테스트 케이스를 보니깐,

갑자기 이상 인덱스가 100으로 가지 않는다.

점점 숫자가 커진다. 오름차순 정렬이기 때문에 비어있는 인덱스가 없기 떄문에 괜찮았던 것이다.

 

 

class Solution {
    func createTargetArray(_ nums: [Int], _ index: [Int]) -> [Int] {
        var result: [Int] = []
        //var result = Array(repeating:0,count:nums.count)
        
        for i in 0..<nums.count{
            result.insert(nums[i],at: index[i])
        }
        
        return result
        
    }
}

다른 고수분들의 풀이도 비슷해서 패스!

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Build an Array with Stack Operations  (0) 2022.07.01
Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30

https://leetcode.com/problems/build-an-array-with-stack-operations/

 

Build an Array With Stack Operations - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제 해설을 하면 이렇다.

target과 n이 주어진다. 

n은 list의 갯수를 결정한다.

 

그래서, target을 보고 비교를 한 다음에 Push 혹은 Pop을 선택한다.

이것을 배열로 저장한다음에 Return한다.

 

내가 간과한 바는 그것이다. Target과 List의 인덱스가 같다는 판단을 하였다.

 

그렇다면!! 어떻게 해야할까?

 

시뮬레이션을 돌려보자!!

 

이중 for문을 활용해 봤는데요.

 

일단, target과 list의 크기가 다름으로써, 조절을 해야하는 문제가 생기네요...

다른 고수님들은 list를 만들지 않고, i를 만들어서

한개씩 풀이하신 것같아요. 

class Solution {
    func buildArray(_ target: [Int], _ n: Int) -> [String] {
        
        var result:[String] = []
        var list:[Int] = []
 
        for i in 1...n{
            list.append(i)
        }
        
        for i in 0..<target.count{
            for j in i..<list.count{
                 
                if target[i] == list[j]{
                    result.append("Push")
                    break
                }else{
                    
                    if i >= target.count{
                        break
                    }else{
                        result.append("Push")
                        result.append("Pop") 
                        continue
                    }
                }
            }
        }
        
        return result

    }
}

 

어렴풋한 생각을 직접 구현으로 하는 것!! 

정말 중요한 것 같아요!!

 

이렇게 i,j를 두어서 직접 제어하는 것도 좋은 방식인것 같아요!!

jayantsogikar님의 풀이

func buildArray(_ target: [Int], _ n: Int) -> [String] {
    var i = 1
    var j = 0
    var res : [String] = []
    while(j < target.count && i <= n){
        if i == target[j]{
            j += 1
            i += 1
            res.append("Push")
        }
        else{
            i += 1
            res.append("Push")
            res.append("Pop")
        }
    }
    return res        
    }

yamironov님의 풀이

class Solution {
    func buildArray(_ target: [Int], _ n: Int) -> [String] {
        let c = target.count
        var i = Int(0), result = [String]()
        for x in 1...n {
            if target[i] == x {
                result.append("Push")
                i += 1
            } else {
                result.append("Push")
                result.append("Pop")
            }
            if i >= c { break }
        }
        return result
    }
}

 

 

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Create Target Array in the Given Order  (0) 2022.07.01
Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30

https://leetcode.com/problems/available-captures-for-rook/

 

Available Captures for Rook - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제 풀이를 하면,

 

Rock 같은 경우에는 상하좌우 채스판 끝까지 넘어 다닐 수 있다. 

그리고, 중간에 비숍을 만나면, 그만 움직어야하고

하나의 폰을 잡으면 이 방향에서 더이상 잡지 못한다.

 

그래서, 나는 일단 락의 위치를 저장한다음에 

왔다갔다하는 방식으로 풀이하고자 했다.

 

아래는 손코딩한 부분!! 점점 나아질것이다!!

 

class Solution {
    func numRookCaptures(_ board: [[Character]]) -> Int {
    
    var count:Int = 0
    var row:Int = 0
    var col:Int = 0
     // finding origin  
     for i  in 0..<board.count{
         for j in 0..<board[0].count{
             if board[i][j] == "R"{
                 row = i
                 col = j
             }
         }
     }
        
    // to left    
    for i in stride(from:row,to:0,by:-1){
        print("left")
        if board[i][col] == "B"{
            break
        }else if board[i][col] == "p"{
            count += 1
            break
        }
    }
   
   // to right
   for i in stride(from:row,to:board[0].count-1,by:1){
       print("right")
        if board[i][col] == "B"{
            break
        }else if board[i][col] == "p"{
            count += 1
            break
        }  
   }
      
   // to top
   for j in stride(from:col,to:0,by:-1){
       print("up")
        if board[row][j] == "B"{
            break
        }else if board[row][j] == "p"{
            count += 1
            break
        }  
       
   }
  // to bottom
   for j in stride(from:col,to:board.count-1,by:1){
       print("down")
        if board[row][j] == "B"{
            break
        }else if board[row][j] == "p"{
            count += 1
            break
        }       
   } 
        
    return count
}
}




print!


left
left
right
right
right
right
up
up
up
down

 

 

 

위로가는 함수가 제대로 작동하지 않는다....

stride 부분이 잘못되었다.

정확히는 stride부분에서 to: 이 부분을 -1로하여서 끝까지 돌려야하는데, 그러지 못했다.

 

무언가 문제가 어려운면 작은 단위부터 시뮬레이션 돌리는 것도 좋은 방식인 것같다.

   // to top
   for j in stride(from:row,to:0,by:-1){
       print("up")
       print(board[j][col])
        if board[j][col] == "B"{
            print("B")
            break
        }else if board[j][col] == "p"{
            count += 1
            print("ucount")
            break
        }else if board[j][col] == "."{
            print("blink")
            continue
        }  
       
   }
   
   //
   up
   R

수정 후

class Solution {
    func numRookCaptures(_ board: [[Character]]) -> Int {
    
    var count:Int = 0
    var row:Int = 0
    var col:Int = 0
     // finding origin  
     for i  in 0..<board.count{
         for j in 0..<board[0].count{
             if board[i][j] == "R"{
                 row = i
                 col = j
             }
         }
     }
    print(row,col)    
        
    // to left    
    for i in stride(from:col-1,to:-1,by:-1){
        print("left")
        if board[row][i] == "B"{
            break
        }else if board[row][i] == "p"{
            count += 1
            print("lcount")
            break
        }else{
            continue
        }
    }
   
   // to right
   for i in stride(from:col,to:board[0].count,by:1){
       print("right")
        if board[row][i] == "B"{
            break
        }else if board[row][i] == "p"{
            count += 1
            print("rcount")
            break
        }else{
            continue
        }
   }
      
   // to top
   for j in stride(from:row-1,to:-1,by:-1){
       print(row)
       print("up")
       print(board[j][col])
        if board[j][col] == "B"{
            print("B")
            break
        }else if board[j][col] == "p"{
            count += 1
            print("ucount")
            break
        }else if board[j][col] == "."{
            print("blink")
            continue
        }  
       
   }
  // to bottom
   for j in stride(from:row,to:board.count,by:1){
       print("down")
        if board[j][col] == "B"{
            break
        }else if board[j][col] == "p"{
            count += 1
            print("dcount")
            break
        }else{
            continue
        }       
   } 
        
    return count
}
}

당연한게 없듯이, 하나하나 사고하면서 프로그래밍하는 것이 좋다는 생각을 했다.

 

다른 고수분들의 문제풀이를 보아도, 비슷한 것 같아서 넘기겠다!

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Create Target Array in the Given Order  (0) 2022.07.01
Leetcode_Build an Array with Stack Operations  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30

https://leetcode.com/problems/water-bottles/submissions/

 

Water Bottles - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제를 풀이 해볼까요?

일단, 쉽게 생각하면 이러한 문제입니다.

 

꽉찬 병이 있고 다 마십니다. 그러면 비어있는 병이 있을 테죠?

 

근데, 어떤 착하신분이 비어있는 병을 가져오면 새로운것으로 주신다고 합니다!!

 

그래서, 생각해보면 크게 우리는 꽉찬 병, 비어있는 병 중심에 사고를 해야합니다!

 

그렇다면, 문제대로 손코딩을 해보았는데요.

 

아래와 같은 흐름으로 진행됩니다.

 

15 -> 0  -> 3 -> 0 -> 1 -> 0 : 꽉찬 병

0 -> 15 -> 3 -> 6 -> 2 -> 3 : 빈 병

 

이것을 생각하시면서, 코드를 구현하면 됩니다.

 

일단, 저는 배열 사용이 편하기 때문에 result 배열을 사용해서 마지막에 reduce()를 할 것입니다.

 

그러면, 일단 result에 apped n을 해줍니다.

그리고, n은 비어있는 병이 될테니, empty라는 값에 누적해줍니다.

 

여기서 누적을 해줘야하는 이유는 병을 리필 받고 이전에 있는 비어있는 병이랑 합쳐야하기 때문이죠!

 

그다음에 n은 empty/numE 으로 empty는 empty%numE으로 정의를 해주면 마무리 됩니다.

 

class Solution {
    func numWaterBottles(_ numBottles: Int, _ numExchange: Int) -> Int {
        
        var numB = numBottles
        var numE = numExchange
        
        var empty = 0
        var result:[Int] = []
        
        while numB>0{
            
            result.append(numB)
            empty += numB
            numB = empty/numE
            empty = empty%numE
        }
        return result.reduce(0,+)
    }
}

 

다른 고수님의 풀이를 봐볼까요? 어떻게 기상천외하게 작성하셨는지 궁금합니다 ㅎㅎ

 

이 분은 저처럼 Empty라는 값을 따로 정의하지 않았습니다.

 

그리고, numBottles>=numExchange를 조건으로 while하셨군요.

 

그리고  balance 를 numB%numE에 나머지를 대입하시고 

 

res에서 활용하시는 방향으로 가셨네요!!

 

재미있게 하셨네요, 깔끔하게!

class Solution {
    func numWaterBottles(_ numBottles: Int, _ numExchange: Int) -> Int {
        var bottles = numBottles
        var numBottles = numBottles
        while(numBottles>=numExchange){
            let balance = numBottles%numExchange
            let res=(numBottles-balance)/numExchange
            numBottles=balance+res
            bottles+=res
        }
        return bottles
    }
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Build an Array with Stack Operations  (0) 2022.07.01
Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30
Leecode_Flipping an Image  (0) 2022.06.30

https://leetcode.com/problems/distribute-candies-to-people/

 

Distribute Candies to People - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제 풀이를 시작해 볼께요!!

 

캔디가 있고 사람이 있습니다.

 

캔디가 7개가 있고 사람이 4명이 있다고 했을때,

 

첫번째 사람은 1개, 두번째 사람은 2개, 세번째 사람은 3개 네번 째 사람은 1개를 받게 됩니다.

 

여기서, 네번째 사람은 왜 1 개를 받냐면, 캔디가 7개 밖이 없기 떄문입니다.

 

그렇다면, 여기서 얻을 수 있는 힌트는 

 

캔디의 갯수로 while을 수행하고 캔디의 갯수가 0이 되면 마무리 되는 로직을 생각할 수 있습니다.

 

구체적으로, 총 두가지 경우에수가 생기겠죠?

중간에 Candy가 없어지는 경우 Candy가 있는 경우를 if로 분기로 나누면 될것같아요.

 

처음으로는, Candy가 있는 경우를 생각해보아요!

 

A B C D

1 2 3 ~ 

이렇게 1개 씩 추가하면서 캔디를 줄 수 있을까요??

주는 캔디를 n 이라고 하고 한 사람에게 주는 캔디를 n + 1라고 

하면 될까요?

 처음에 n = 0 으로 설정하구요!

오케이 그러면 

allocation[n % num_people]  += n + 1 

이라고 생각하면 될까요?

 

그런다음, 캔디를 줬으니깐 갯수에서 빼야겠죠?

canndies -= (n + 1)

 

그리고 n += 1 을 하면 점점 증가하겠죠!!

 

오케이 이제 전반적인 아이디어는 정리가 되었는데,

 

이제는 진행 중간에 캔디가 다 없어질때에요!!

 

candies = 7

A B C D

1 2 3

이것을

 

candies - (n + 1) < 0 

 1 - (6) < 0{

 allocation[n % num_people] += candies

 candies = 0

}

으로 마무리하면 됩니다.

 

이제, 위의 내용을 논리적으로 맞추기만 하면 됩니다!!

class Solution {
    func distributeCandies(_ candies: Int, _ num_people: Int) -> [Int] {
        var candies = candies
        var allocation: [Int] = Array(repeating: 0, count: num_people)
        var n = 0
        while candies > 0 {
            if candies - (n + 1) < 0 {
                allocation[n % num_people] += candies
                candies = 0
            } else {
                allocation[n % num_people] += n + 1
                candies -= (n + 1)
            }
            n += 1
        }
        return allocation
    }
    
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Transpose Matrix  (0) 2022.06.30
Leecode_Flipping an Image  (0) 2022.06.30
Leetcode_Baseball Game  (0) 2022.06.30

https://leetcode.com/problems/transpose-matrix/

 

Transpose Matrix - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

 

풀이를 해보자구, 어디에서 막히는 지!!

 

일단, 문제 파악 자체는 오래 걸리지 않았어!! 

 

어떻게 구성을 할까를 고민을 많이 해봤어!!

 

일단, 간단히 설명하면,

 

2  4  -1

-10 5 11 

18 -7 6

 

이 것이 주어지면, y = -x 방향으로 전환을 해주면 되거든!!

 

2  -10 18

4  5  -7

-1 11 6 

이렇게 말이죠!! 

 

그러면, 이제 구성을 어떻게 할까 생각을 해봤어요!!

 

Slice하는 방식

인덱스로 해결하는 방법

 

나는 인덱스로 해결하고자하였다.

근데, 어디서 막혔나면, 1,4,7를 추가 하였다.... 근데 이것을 어떻게 하면 효율적으로 할지 아이디어가 떠오르지 않기에 고수님들의 코드를 보았따.

class Solution {
    func transpose(_ matrix: [[Int]]) -> [[Int]] {
        
        var flatArr = matrix.flatMap{$0}
        var result: [[Int]] = []
        
        for i in 0..<flatArr.count{
            if i.isMultiple(of:matrix.count){
               result.append([flatArr[i]])
            }
          
        }
        print(result)
        
        return []   
    }
}

상기에서 하기와 같이 수정했어!

class Solution {
    func transpose(_ matrix: [[Int]]) -> [[Int]] {
        
        var row = matrix.count
        var col = matrix[0].count
        var result: [[Int]] = []
        
        for i in 0..<col{
          var resultRow:[Int] = []
            for j in 0..<row{
                resultRow.append(matrix[j][i])
            }
           result.append(resultRow) 
        }
        
        return result

    }
}

 

 

snehakasetty님의 해결방안인데, 내가 머리속으로 어렴풋이 그렸던 코드가 이것이다.

 

A라는 행렬을 새로 만든 행렬에 삽입하자 라는 생각이 포인트!!!

나는 swapt 할 생각만 했었다.

c[j][i] = A[i][j] !! 이부분이 핵심적인 내용!!

func transpose(_ A: [[Int]]) -> [[Int]] {
    
    if(A.count == 0){
        return A
    }
    
    var c = Array(repeating: Array(repeating: 0, count: A.count), count: A[0].count)

    for i in 0 ..< A.count {
        for j in 0 ..< A[0].count {
            c[j][i] = A[i][j]
        }
    }
    return c
}

 

 

아래분의 해설도 볼만 하다.

전달 받은 행렬의 행과 렬의 갯수를 rowCount, colCount라고 정의를 내려 주었고 

 

collum{

row 

}

 

이런식으로 진행했네!!

 

이것이랑 같이 보면 좋을 것 같아서 첨부함.

var col = 7
var row = 3


for i in 0..<row{
    for j in 0..<col{
        print("*",terminator:"")
    }
    print("")
}

print("----------------------------")

for i in 0..<col{
    for j in 0..<row{
        print("*",terminator:"")
    }
    print("")
}
*******
*******
*******
----------------------------
***
***
***
***
***
***
***

 

for문을 잘보면 col이랑 row의 위치를 변경해서 넣어버렸네 좋은 선택인듯!!

그리고 resultRow라는 것도 함수내에 사용되고 초기화해야하니깐, 함수 내에 정의내린것도 좋다!!!

class Solution {
    func transpose(_ matrix: [[Int]]) -> [[Int]] {
        var result = [[Int]]()

        let rowCount = matrix.count
        let colCount = matrix[0].count

        for colId in 0..<colCount {
            var resultRow = [Int]()
            for rowId in 0..<rowCount {
                resultRow.append(matrix[rowId][colId])
            }
            result.append(resultRow)
        }

        return result
    }
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leecode_Flipping an Image  (0) 2022.06.30
Leetcode_Baseball Game  (0) 2022.06.30
Leetcode_Robot-return-to-origin  (0) 2022.06.30

+ Recent posts