👨🏻‍💻iOS 공부/Swift_알고리즘 풀이

[Swift] Swift 값 입력, 비교

728x90
반응형

Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarityoriginality, and difficulty.

The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the triplet b = (b[0], b[1], b[2]).

The task is to find their comparison points by comparing a[0] with b[0]a[1] with b[1], and a[2] with b[2].

  • If a[i] > b[i], then Alice is awarded 1 point.
  • If a[i] < b[i], then Bob is awarded 1 point.
  • If a[i] = b[i], then neither person receives a point.

Comparison points is the total points a person earned.

Given a and b, determine their respective comparison points.

Example

a = [1, 2, 3]
b = [3, 2, 1]

  • For elements *0*, Bob is awarded a point because a[0] .
  • For the equal elements a[1] and b[1], no points are earned.
  • Finally, for elements 2a[2] > b[2] so Alice receives a point.

The return array is [1, 1] with Alice's score first and Bob's second.

Function Description

Complete the function compareTriplets in the editor below.

compareTriplets has the following parameter(s):

  • int a[3]: Alice's challenge rating
  • int b[3]: Bob's challenge rating

Return

  • int[2]: Alice's score is in the first position, and Bob's score is in the second.

Input Format

The first line contains 3 space-separated integers, a[0]a[1], and a[2], the respective values in triplet a.
The second line contains 3 space-separated integers, b[0]b[1], and b[2], the respective values in triplet b.

Constraints

  • 1 ≤ a[i] ≤ 100
  • 1 ≤ b[i] ≤ 100

Sample Input 0

5 6 7
3 6 10

Sample Output 0

1 1

Explanation 0

In this example:

Now, let's compare each individual score:

  • , so Alice receives  point.
  • , so nobody receives a point.
  • , so Bob receives  point.

Alice's comparison score is , and Bob's comparison score is . Thus, we return the array .

Sample Input 1

17 28 30
99 16 8

Sample Output 1

2 1

Explanation 1

Comparing the  elements,  so Bob receives a point.
Comparing the  and  elements,  and  so Alice receives two points.
The return array is .



값을 Arr 형태로 입력 받아서 내부 요소들 간에 비교를 한 후, 점수를 부여하는 과정이다. 


먼저 값을 받기 위해서는 Python에서는 Input()을 사용하였으나, Swift에서는 readLine()을 사용한다. 


readLine()의 경우 Optional 타입으로 값을 반환하기 때문에, 강제 언래핑 혹은 옵셔널 바인딩을 사용하여 값을 꺼내면 된다!


import Foundation 

var aliceArray = readLine()!.components(separatedBy: " ").map{ Int($0)! }
var bobArray = readLine()!.components(separatedBy: " ").map{ Int($0)! }
var alicePoints = 0
var bobPoints = 0

for i in 0...aliceArray.count-1 {
  if aliceArray[i] > bobArray[i] {
    alicePoints += 1
  } else if bobArray[i] > aliceArray[i] {
    bobPoints += 1
  }
}

print("\(alicePoints)" + " " + "\(bobPoints)")



뒤의 components(separtedBy: " ")의 경우는 공백을 기준으로 값을 구분하겠다는 의미이며, 

map의 경우 코드 재사용에 용이하기에 값을 여러번 입력하는 과정에서 효율적으로 사용할 수 있다. 

또한 새로운 컨테이너(배열)을 생성하여 반환하기 때문에 빈 배열을 초기에 생성할 필요도 없다. 이에 append() 연산보다 빠르게 되는 것이다. 


let numbers = [1,2,3,4]


let a = numbers.map { $0 * }

a

// [2,4,6,8]


$0은 배열의 맨 앞 값을 말하며, map을 통해 numbers내의 값을 순회하며 연산을 해주고, 새로운 배열을 뱉어내는 기능을 수행하는 것을 볼 수 있다. 



그리고 값을 비교한 후, 각 변수에 점수를 축적한 후 마지막으로 값을 출력해준다. 




파이썬으로 하면 어떻게 할지 다 떠오르는데.... 아직까지 swift가 많이 어색한 것 같다. 

머리에서 생각한 구조를 구현하기 위해 많이 연습해보고, 여러가지 방법으로 시도해봐야할 필요성을 느끼며 마친다...! 

728x90
반응형