본문 바로가기
개발

코틀린 1.repeat() 2.count() 3.함수 안될 때

by kks950115 2023. 11. 24.
728x90

.repeat()

/**
 * Executes the given function [action] specified number of [times].
 *
 * A zero-based index of current iteration is passed as a parameter to [action].
 *
 * @sample samples.misc.ControlFlow.repeat
 */
@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
    contract { callsInPlace(action) }

    for (index in 0 until times) {
        action(index)
    }
}





사용 예시
// greets three times
repeat(3) {
    println("Hello")
}

// greets with an index
repeat(3) { index ->
    println("Hello with index $index")
}

repeat(0) {
    error("We should not get here!")
}

repeat는 for문을 인라인 함수로 작동시키는 것이다. 

내부를 보면 알겠지만 0부터 until로 넣은 숫자까지 돌리는 것이다.

{}안에 내용을 간결하게  n번 반복하게  할 수도 있지만.....

 

 

 

 

내가 이 함수에 대해 찾아본 이유는 코테 연습문제를 풀다가 막혀서이다.

숫자 짝궁
class Solution {
    fun solution(X: String, Y: String): String {
        var answer: String = ""
        
        for(num in 0 .. 9)  {
            answer+=(num.toString()).repeat(
                
                minOf(
                    X.count{it.toString() == num.toString()},
                    Y.count{it.toString() == num.toString()}
                )
            )
        }
        //println("처리전 ${answer}")
        answer=answer.split("").sortedDescending().joinToString("")
        
        //println("처리 ${answer}")
        if(answer.length==0){
            answer="-1"
        }
        if(answer.toList().distinct() == listOf('0')){
            answer="0"
        }
        // if(answer.toLong() == 0L){
        //     answer="0"
        // }
        return answer
    }
}

 

저 코드는 내가 짠게 아니고 다른 사람이 짠걸 내 방식대로 응용한거다.  성능 보장 X 일단 통과하긴 했다.

원래 내가 짠건 이중 포문으로 하나하나 다 비교하면서 실행해서인지 시간초과가 떴고... 머리를 싸매고 고민했지만 결국 해결하지 못했다.  다른 사람의 코드를 그대로 배끼는 건 아닌 거 같아서 내가 이해할 수 있게 바꾸었다.

위에 repeat가 쓰인 곳을 보면 앞에 string으로 변환한 변수에다가 쓴 걸 볼 수 있다.

숫자는 안되고 문자만 된다. 라고 알고 있었는데....로그에는  CharSequence라는 것에만 된다고 써있다.  그런데 난 숫자를 toString()으로 string으로 변환하여 썼는데....

원래 0을 구분할 때 int로 바꿀려고 했는데 숫자가 길어지면 범위가 초가되는 바람에 런타임 에러가 뜬다.

결국 리스트로 만들고 중복을 제거해서 0과 비교하는 방식으로 한 것 같다....(내가 짠 게 아님)

 

찾은 결과

CharSequence는 클래스가 아니라 인터페이스이다.

인터페이스는 추상클래스와 비슷하다. 쉽게 설명하면 미리 이름과 용도를 적어놓은 설계도를 만들고 구현은 다른데서 하지만 설계도에 맞게 만드는 것이다.

구현할 때는 string이나 stringbuilder 등을 사용할 수 있는데 보통 string을 많이 쓴다고 한다. 즉 인터페이스이기 때문에 string도 업캐스팅(string -> CharSequence 으로 변환)하여 호환이 된다는 것이다. 그래서 내가 toString()으로 바꿨음에도 작동한 것이다.

 

 

 

 

 

 

 

kotlin-stdlib / kotlin.text / count    .count()

/**
 * Returns the number of characters matching the given [predicate].
 */
public inline fun CharSequence.count(predicate: (Char) -> Boolean): Int {
    var count = 0
    for (element in this) if (predicate(element)) ++count
    return count
}

 

요거를 썼다.

count는 콜렉션에도 있고 시퀸스에도 있지만 내가 쓴건 코틀린.텍스트에 있는 것이다.

 

쓰는 법은 간단하다.

 

val myInt = 12312312542343212
myInt.toString().count { it == '2' } // 6

val myString = "ajvbieofsodfsddasoidjqlwnvsc"
myString.count { it == 'd' } // 4

 

주의할 점은 비교할 때  숫자는 안되고 문자열만 된다.

 

 

오늘 있었던 작은 해프닝...

fun String.replaceFirst(
    oldChar: Char,
    newChar: Char,
    ignoreCase: Boolean = false
): String




fun String.replaceFirst(
    oldValue: String,
    newValue: String,
    ignoreCase: Boolean = false
): String

 

코테 연습문제에서 코드를 짜는데  replace가 안됐다. 

분명 str= str.replace(바뀔 거, "")인데 오류가 뜨는 것이다.

알고보니 위에 써져있는 거처럼 첫번째 인자에 따라서 달라지는 것이였다. 

즉 (string , string) 인줄 알았는데 (char, char)로 적용되어서 오류가 생겼던 것이다......

하;...... 혹여나 나와 같은 사람들이 없기를 바라는 마음으로 글을 적는다. 

728x90
반응형

댓글