샘성의 iOS 개발 일지

[Implementation] Grading Students 본문

Algorithm/HackerRank

[Implementation] Grading Students

SamusesApple 2023. 5. 12. 12:53
728x90

문제 설명:

HackerLand University has the following grading policy:

  • Every student receives a grades in the inclusive range from 0 to 100.
  • Any grade less than 40 is a failing grade.

Sam is a professor at the university and likes to round each student's  according to these rules:

  • If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the next multiple of 5.
  • If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade.

Examples

  • grade = 84 round to  (85 - 84 is less than 3)
  • grade = 29 do not round (result is less than 40)
  • grade = 57 do not round (60 - 57 is 3 or higher)

Given the initial value of grade for each of Sam's n students, write code to automate the rounding process.

Function Description

Complete the function gradingStudents in the editor below.

gradingStudents has the following parameter(s):

  • int grades[n]: the grades before rounding

Returns

  • int[n]: the grades after rounding as appropriate

Input Format

The first line contains a single integer, , the number of students.
Each line  of the  subsequent lines contains a single integer, grades[i].

 

 

 

 

내 풀이:

func gradingStudents(grades: [Int]) -> [Int] {
	// 최종 결과를 담을 배열
    var resultArray: [Int] = []
    // 각 배열의 요소를 체크하기
    for i in grades {
    	// 점수가 38보다 높고 5로 나눈 나머지가 2보다 크다면 ( 76 % 5 = 1, 77 % 5 = 2 )
        if i >= 38, i % 5 > 2 {
        	// 결과배열에 원래 점수 + 나머지에 5 뺀 값 더함 (반올림 시키기) 
          resultArray.append(i + (5-(i%5)))  
        } else {
            resultArray.append(i)
        }
    }
    return resultArray
}

 

 

 

 

회고:

  처음에 반올림을 생각해서 Double 형태로 바꾼 후, round 함수를 사용할까 고민했으나 더 복잡해지는 것 같아 위에 풀이처럼 풀게 되었다. 다양한 풀이방식을 활용할 수 있도록 시야를 넓힐 필요성을 더더욱 느꼈다.

728x90

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

[Implementation] Number Line Jumps  (0) 2023.05.12
[Implementation] Apple and Orange  (0) 2023.05.12
[Warm Up] Time Conversion  (0) 2023.05.11
[Warm Up] Birthday Cake Candles  (0) 2023.05.11
[Warm Up] Staircase  (0) 2023.05.11