개발/PS

[Swift] 프로그래머스 1단계 모음

유훈 | Yuhun 2022. 6. 6. 05:11
반응형

IDE없이 코딩테스트 연습을 하는데 지금까지 올린것을 제외한 나머지 Lv1을 한번에 정리하려 합니다.

(여유있을때 분리하면서 설명하는걸로!)

목록은 다음과 같습니다.

참고로 모두 제가 짠 코드임으로 더 좋은 방법은 많을 수 있음!

Lv1_2016년.swift
Lv1_3진법 뒤집기.swift
Lv1_x만큼 간격이 있는 n개의 숫자.swift
Lv1_두 정수 사이의 합.swift
Lv1_제일 작은 수 제거하기.swift
Lv1_두 개 뽑아서 더하기.swift
Lv1_소수 찾기.swift
Lv1_시저 암호.swift
Lv1_정수 제곱근 판별.swift
Lv1_평균 구하기swift
Lv1_정수 내림차순으로 배치하기.swift
Lv1_문자열 p와 y의 개수.swift
Lv1_문자열 내 마음대로 정리하기.swift
Lv1_약수의 합.swift
Lv1_하샤드 수.swift
Lv1_이상한 문자 만들기.swift
Lv1_핸드폰 번호 가리기.swift
Lv1_짝수와 홀수.swift
Lv1_콜라츠 추측.swift
Lv1_행렬의 덧셈.swift
Lv1_문자열 다루기 기본.swift
Lv1_자연수 뒤집어 배열로 만들기.swift
Lv1_자릿수 더하기.swift
Lv1_나누어 떨어지는 숫자 배열.swift
Lv1_문자열 내림차순으로 정리하기.swift
Lv1_나머지가 1이 되는 수 찾기.swift
Lv1_직사각형 별 찍기.swift
Lv1_서울에서 김서방 찾기.swift
Lv1_문자열을 정수로 바꾸기.swift
Lv1_최소 직사각형.swift
Lv1_예산.swift
Lv1_수박수박수.swift
Lv1_최대공약수와 최소공배수.swift
Lv1_가운데 글자 가져오기.swift
Lv1_약수의 개수와 덧셈.swift

 

여기서부터 코드 시작!

Lv1_2016년.swift

func solution(_ a:Int, _ b:Int) -> String {
    var dateDic:[Int:Int] = [1:31,2:29,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31]
   var d: [Int:String] = [3:"FRI",2:"SAT",3:"SUN",4:"MON",5:"TUE",6:"WED",0:"THU"]

    var day = 0

    for i in 1..<a {
        day += dateDic[i]!
    }
    day += b

    return d[day%7]!
}


Lv1_3진법 뒤집기.swift

import Foundation

func solution(_ n:Int) -> Int {
    var three: [Int] = []
    var num = n;

    while num > 2  {
        let a = num / 3
        let b = num % 3
        num = a
        three.append(b)
    }

    three.append(num)
    var result: Int = 0
    var lenThree:Int = three.count - 1
    var index:Int = 0;

    while lenThree >= 0 {
        result += three[index]*Int(pow(3.0,Double(lenThree)))
        lenThree -= 1
        index += 1
    }

    return result
}


Lv1_x만큼 간격이 있는 n개의 숫자.swift

func solution(_ x:Int, _ n:Int) -> [Int64] {
    var result:[Int64] = []
    for i in 1...n {
        result.append(Int64(x*i))
    }
    return result
}


Lv1_두 정수 사이의 합.swift

func solution(_ a:Int, _ b:Int) -> Int64 {
    return Int64((a < b ? a...b : b...a).reduce(0,+))
}


Lv1_제일 작은 수 제거하기.swift

func solution(_ arr:[Int]) -> [Int] {
    var arr = arr
    var min:Int = arr[0]
    var checkIndex:Int = 0
    for (index, value) in arr.enumerated() {
        if min > value {min = value; checkIndex = index}
    }
    arr.remove(at: checkIndex)

    return arr.isEmpty ? [-1] : arr
}


Lv1_두 개 뽑아서 더하기.swift

import Foundation

func solution(_ numbers:[Int]) -> [Int] {
    var result: [Int] = []
    var iCount = 0;
    var jCount = 0;

    for i in numbers {
        for j in numbers {
            if jCount == iCount {
                continue
            }
            if !result.contains(i+j){
                result.append(i+j)
            }
          jCount += 1
        }
        iCount += 1
        jCount = 0;
    }

    return result.sorted()
}


Lv1_소수 찾기.swift - 효율성 통과 어려움..(마침 학교에서 자바로 같은 유형을 풀어서 해결!)

import Foundation

func solution(_ n:Int) -> Int {
    var result:[Int] = []

    for i in 2...n {
        var check:Bool = true
        for j in result {
            if i%j == 0 {
                check = false
                break
            }
            if j > Int(sqrt(Double(n))) {
                break
            }
        }
        if check {result.append(i)}
    }

    return result.count
}


Lv1_시저 암호.swift

func solution(_ s:String, _ n:Int) -> String {
    var result:String = ""
    let alpha:[String] = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
	// 나중에 알았지만 let alpha:[Character] = Array("abcdefghijklmnopqrstuvwxyz")가 더 편하다.
    for i in s {
        if i == " " {result += " "; continue}
        if i.isUppercase {
            let index = alpha.firstIndex(of: String(i).lowercased())!
            result += alpha[(index + n) % 26].uppercased()
        }
        else {
            let index = alpha.firstIndex(of: String(i))!
            result += alpha[(index + n) % 26]
        }
    }
    return result
}


Lv1_정수 제곱근 판별.swift

func solution(_ n:Int64) -> Int64 {
    for i in 1...50000000000000/4 {
        if i*i == n {return Int64((i+1)*(i+1))}
        else if i*i > n {return Int64(-1)}
    }
    return 0
}


Lv1_평균 구하기swift

func solution(_ arr:[Int]) -> Double {
    return Double(arr.reduce(0,+)) / Double(arr.count)
}


Lv1_정수 내림차순으로 배치하기.swift

func solution(_ n:Int64) -> Int64 {
    var k:Int = Int(n)
    var result:[Int] = []

    while k != 0 {
        result.append(k % 10)
         k = k/10
    }

    return Int64(result.sorted(by: >).map{String($0)}.joined())!
}


Lv1_문자열 p와 y의 개수.swift

import Foundation

func solution(_ s:String) -> Bool
{
    var count = 0
    for i in s.lowercased() {
        if i == "p" {count+=1}
        else if i == "y" {count-=1}
    }

    return count == 0
}


Lv1_문자열 내 마음대로 정리하기.swift

func solution(_ strings:[String], _ n:Int) -> [String] {
    var result:[String] = []
    var dic:[String:[String]] = [:]

    for str in strings {
        let check:String = String(str[str.index(str.startIndex,offsetBy:n)])
        if let temp = dic[check] {
            dic[check] = (temp + [str]).sorted()
        }
        else {
            dic[check] = [str]
        }
    }

    for key in dic.keys.sorted() {
        guard let t = dic[key] as? [String] else {continue}
        result = result + t
    }

    return result
}


Lv1_약수의 합.swift

func solution(_ n:Int) -> Int {
    return (1...n).filter{ n%$0 == 0 }.reduce(0, {$0+$1})
}


Lv1_하샤드 수.swift

func solution(_ x:Int) -> Bool {
    var value = x
    var check = 0
    while value != 0 {
        check += value % 10
        value = value / 10
    }

    return x%check == 0 ? true : false
}


Lv1_이상한 문자 만들기.swift

func solution(_ s:String) -> String {
    var result:String = ""
    var check = 1

    for i in s {
        if i == " " {
            result += " "
            check = 1
            continue
        }
        (check % 2 == 1) ? (result += String(i).uppercased()) : (result += String(i).lowercased())
        check += 1
    }
    return result
}


Lv1_핸드폰 번호 가리기.swift

func solution(_ phone_number:String) -> String {
    var arr = Array(phone_number)
    for i in 0..<arr.count-4 {
        arr[i] = "*"
    }
    return String(arr)
}


Lv1_짝수와 홀수.swift

func solution(_ num:Int) -> String {
    return (num % 2 == 0) ? "Even" : "Odd"
}


Lv1_콜라츠 추측.swift

func solution(_ num:Int) -> Int {
    var num = num
    var count: Int = 0;
    while count < 500 {
        guard num != 1 else {return count}
        (num%2 == 0) ? (num = num / 2) : (num = num*3 + 1)
        count += 1
    }

    return -1
}


Lv1_행렬의 덧셈.swift

func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    var result: [[Int]] = []
    for i in 0..<arr1.count {
        var temp: [Int] = []
        for j in 0..<arr1[i].count {
            temp.append(arr1[i][j] + arr2[i][j])
        }
        result.append(temp)
    }
    return result
}


Lv1_문자열 다루기 기본.swift

func solution(_ s:String) -> Bool {
    return Int(s) != nil && (s.count == 4 || s.count == 6) ? true : false
}


Lv1_자연수 뒤집어 배열로 만들기.swift

func solution(_ n:Int64) -> [Int] {
    return String(n).map{Int(String($0))!}.reversed()
}


Lv1_자릿수 더하기.swift

import Foundation

func solution(_ n:Int) -> Int{
    let s: String = String(n)
    var result:Int = 0
    for i in s {
        result += Int(String(i))!
    }
    return result
}


Lv1_나누어 떨어지는 숫자 배열.swift

func solution(_ arr:[Int], _ divisor:Int) -> [Int] {

    var arr:[Int] = arr.filter{$0%divisor == 0}.sorted()
    if arr.isEmpty {arr.append(-1)}
    return arr
}


Lv1_문자열 내림차순으로 정리하기.swift

func solution(_ s:String) -> String {
    var lower:[String] = []
    var upper:[String] = []
    for i in s {
        if i.isUppercase {upper.append(String(i))}
        else {lower.append(String(i))}
    }

    return (lower.sorted(by: >) + upper.sorted(by: >)).joined()
}


Lv1_나머지가 1이 되는 수 찾기.swift

import Foundation

func solution(_ n:Int) -> Int {
    for i in 2..<n {
        if n%i == 1 {return i}
    }
    return 0
}


Lv1_직사각형 별 찍기.swift

import Foundation

let n = readLine()!.components(separatedBy: [" "]).map { Int($0)! }
let (a, b) = (n[0], n[1])

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


Lv1_서울에서 김서방 찾기.swift

func solution(_ seoul:[String]) -> String {
    for (i,s) in seoul.enumerated() {
        if s == "Kim" {return "김서방은 \(i)에 있다"}
    }

    return ""
}


Lv1_문자열을 정수로 바꾸기.swift

func solution(_ s:String) -> Int {
    return Int(s)!
}


Lv1_최소 직사각형.swift

import Foundation

func solution(_ sizes:[[Int]]) -> Int {
    var cards = sizes
    var width:[Int] = []
    var height:[Int] = []

    for i in 0..<cards.count {
        cards[i].sort()

        var check:Bool = true
        for j in cards[i] {
            if check {
                width.append(j)
            }
            else{
                height.append(j)
            }
            check = false
        }
    }

    return width.max()!*height.max()!
}


Lv1_예산.swift

import Foundation

func solution(_ d:[Int], _ budget:Int) -> Int {
    var sortedD = d.sorted()
    var bg = budget
    var result = 0
    for i in sortedD {
        if(bg >= i){
            bg -= i
            result += 1
        }
        else {
            break
        }
    }

    return result
}


Lv1_수박수박수.swift

func solution(_ n:Int) -> String {
    return (1...n).map{$0%2 == 0 ? "박" : "수"}.joined()
}


Lv1_최대공약수와 최소공배수.swift

func solution(_ n:Int, _ m:Int) -> [Int] {
    var source:[Int] = []
    var result:[Int] = []
    var a = min(n,m)
    var b = max(m,n)
    var check:Bool = true

    while check {
        check = false
        for i in 1...b {
            if i == 1 {continue}
            if b%i == 0 && a%i == 0 {
                source.append(i)
                b = b / i
                a = a / i
                check = true
                break
            }
        }
    }

    result.append(source.isEmpty ? 1 : source.reduce(1, *))
    result.append(result[0]*a*b)

    return result
}


Lv1_가운데 글자 가져오기.swift

func solution(_ s:String) -> String {

    if s.count % 2 == 0 {
        return String(Array(s)[(s.count/2 - 1)...s.count/2])
    }
    return String(Array(s)[s.count/2])
}


Lv1_약수의 개수와 덧셈.swift

import Foundation

func solution(_ left:Int, _ right:Int) -> Int {
    var sum: Int = 0;
    for i in left...right {
        var count: Int = 0
        for j in 1...i {
            if i%j == 0 {
                count += 1
            }
        }
        if count%2 == 0 {
            sum += i
        } else {
          sum -= i
        }
    }

    return sum
}

 

 

 

반응형