CodeGym /행동 /Kotlin SELF /Reports set v0: total, byCategory, top, threshold in a un...

Reports set v0: total, byCategory, top, threshold in a unified style

Kotlin SELF
레벨 26, 레슨 4
사용 가능

1. Data agreement: how reports receive expenses

“Susa reopteul mandeureo”rago malhamyeon, beginnerneun jongjong eoneu keugeun printlneul sangsanghago geugeosi eotteon bangbeob-eurodeun modeun geoseul 계산하고 예쁘게 geuril geotcheoreom saenggakhamnida. Hajiman 실제로 reportneun 영감boda deo 오래 살go: dasi dorabogo, 보완하고, dareun reportdeulgwa 비교합니다. Geuraeseo cheoeum-euro seong-inseureoun gyeoljeong-eun input data-ui form-eul 합의하고, jeo-dodeu i dan-gye course(claesswa OOP eopsi)eseoneun geugeol 안정적으로 유지하는 geosimnida.

Uri-ui siljeonseong inneun console app(“mini-tracker”cheoreom)eseo expense han geoneun daeum gateun pair라고 가정합니다:

  • first: category (String)
  • second: amount (Int) — 가상의 “units”, 핵심: integer

즉, expenses jeonche listneun List<Pair<String, Int>> imnida.

Da-eum-e seo ishl geot-ui example datareul jom bogo gagesseumnida:

fun main() {
    val expenses: List<Pair<String, Int>> = listOf(
        " food " to 120,
        "FOOD" to 80,
        "taxi" to 250,
        "Books" to 90
    )

    println(expenses)
    // [( food , 120), (FOOD, 80), (taxi, 250), (Books, 90)]
}

Ne, categorieseoneun “dirty”hamnida(space, different case). Igeon mistakega anipnida: 현실적입니다. Userneun eonjena datareul 입력해서 program-i 불안해지게 만들 su itseumnida. Urin geugeol ddeo Wirokhae jil geosimnida.

2. Common step: category normalization

Stringeul “as-is”로 groupinghaebon jeogi itdamyeon, 따옴표 속 “magic”eul bwas-eul geosimnida: "Food"wa " food "ga gapjagi dareun categoryga doego, reportga 마치 사람이 세 개의 평행우주에서 식사하는 것처럼 보입니다. Geureohge doejim anke 하려면 normalizationeun modeun report-ui 필수 공통 단계입니다. Geurigo normalizationeun “pretty output”i anigo, 계산 jeone datareul 하나의 내부 형태로 맞추는 geosimnida.

Category normalizationeul wihan jageun 함수를 mandeulgessseumnida: trim() + lowercase(). I 함수는 예측 가능하고, 짧고, eodideun 동일해야 합니다.

fun normalizeCategory(raw: String): String {
    return raw.trim().lowercase()
}

fun main() {
    println(normalizeCategory("  FOOD ")) // food
    println(normalizeCategory("Books"))   // books
}

Ije modeun expensee normalizationeul 적용해 bopsida. Juyoui: original listreul “in place”ro 바꾸지 않고 새 listreul 만듭니다(계산을 깨끗하게 유지하고 surprise를 줄여 줍니다).

fun normalizeExpenses(expenses: List<Pair<String, Int>>): List<Pair<String, Int>> {
    return expenses.map { (cat, amount) ->
        normalizeCategory(cat) to amount
    }
}

fun main() {
    val raw = listOf(" FOOD " to 10, "food" to 5)
    val normalized = normalizeExpenses(raw)

    println(normalized) // [(food, 10), (food, 5)]
}

Apeuro uri-ui daebubun reportsneun ireon malro sijakhal geosimnida: “take expenses → normalize categories → calculate”. Ige baro “unified style”imnida.

3. Report skeleton: calculation separate, rendering separate

Jeil meonjeo “pretty”hage mandeulgo sipseumnida: 계산 jung-e linesreul print하고, emoji do neokgo(but we are in a Kotlin course, not Telegram stickers), 공백으로 정렬하고… geureoda 보니 calculationgwa outputeul 섞어 버려서 format 바꾸neun 게 월요일에 일어나neun 것boda deo himdeureojimnida.

Geuraeseo oneul-ui rule:

  • calculation function-eun numbers/structuresreul return (Int, Map, List<Pair<...>>)
  • render function-eun resultreul String으로 변환(또는 print, 하지만 가급적 string return)
  • main(또는 command handler)ga eonjena, mueoseul 보여 줄지 결정

Diagram-euro boneun yeongu:

flowchart LR
    A[raw expenses] --> B[normalize]
    B --> C[calculate totals]
    C --> D[optional: filter threshold]
    D --> E[optional: sort + top-N]
    E --> F[render string]

I lecture-eseoneun 4ga-ui report(total, byCategory, top, threshold)reul, “친척”처럼 느껴지게, eotteon uiyeonhan naga-neun saramcheoreom an 느껴지게 구현하겠습니다.

4. Report total: sum of all expenses

Report totaleun 가장 쉬워 보입니다: “모든 금액을 더해라”. Hajiman 바로 이런 지점에서 beginner typical bugga sijakdoemnida: 외부 카운터, reset 안 함, empty listga “logic”eul 망가뜨림, junggan-e gapjagi println deung. 좋은 소식: Kotlin-eun foldreul 제공하며, 이는 정확히 깔끔한 누적을 위한 것입니다.

전체 합을 계산하는 함수를 만들겠습니다. 각 pair-ui secondreul 더합니다.

fun calcTotal(expenses: List<Pair<String, Int>>): Int {
    return expenses.fold(0) { acc, item ->
        acc + item.second
    }
}

fun main() {
    val expenses = listOf("food" to 10, "taxi" to 20)
    println(calcTotal(expenses)) // 30
}

Wae fold(0)igo reducega anin gayo? foldneun empty list-eseodo 동작합니다: initial valuero 시작하므로 resultga 예측 가능합니다.

Ije total renderreul mandeulgessseumnida. 단순한 string-으로 합시다:

fun renderTotal(total: Int): String {
    return "Total: $total"
}

fun main() {
    println(renderTotal(60)) // Total: 60
}

Geurigo jageun “assembly” example: normalization + total.

fun main() {
    val raw = listOf(" FOOD " to 120, "taxi" to 250)
    val expenses = normalizeExpenses(raw)

    val total = calcTotal(expenses)
    println(renderTotal(total)) // Total: 370
}

5. Report byCategory: sum by categories

“By category” reportneun dataga cheoeum-euro form-eul bakkuneun moment입니다: individual operations listeseo aggregated totals로 이동합니다. Geurigo 이건 정상입니다: report는 “raw events”reul “understandable totals”로 바꾸기 위해 존재합니다. 핵심은 type changereul 두려워하지 말고, 의식적으로 수행하는 것입니다.

Mok표: keyga category, valuega 그 category의 합인 Map<String, Int>reul 얻는 것입니다.

Daeumcheoreom 두 step-euro 명확하게 합시다: groupBy → mapValues + fold.

fun totalsByCategory(expenses: List<Pair<String, Int>>): Map<String, Int> {
    val grouped: Map<String, List<Pair<String, Int>>> =
        expenses.groupBy { it.first }

    return grouped.mapValues { (_, items) ->
        items.fold(0) { acc, item -> acc + item.second }
    }
}

fun main() {
    val expenses = listOf("food" to 10, "food" to 5, "taxi" to 7)
    println(totalsByCategory(expenses)) // {food=15, taxi=7}
}

Yeogiseo jamkkan 멈추고 말로 정리하면: groupByneun map 안에 listdeul-eul 만듭니다. 이해하기엔 편하지만 memory 측면에서 무거울 수 있습니다. Ijeon days-eseoneun groupingBy { ... }.eachCount() mit, “명시적 list 없이” grouping 가능하다는 idea도 봤을 것입니다. Oneul-eun optimizationeul 쫓지 않고 readabilityreul 쫓습니다.

Ije render. 중요한 nuance: Mapeui print orderreul report “contract”ro saenggakhamyeon an 됩니다. Deterministic outputeul 원한다면, 직접 sort해야 합니다. 이는 collection ordering 주제와 직결됩니다: key/value sort는 명시적이어야 하며, geureohji 않으면 orderga “운”에 달립니다.

“Table” 형태 renderreul 만듭니다. Simplicity: category name으로 정렬합니다.

fun renderByCategory(totals: Map<String, Int>): String {
    val rows: List<Pair<String, Int>> = totals.entries
        .map { it.key to it.value }
        .sortedBy { (cat, _) -> cat }

    val sb = StringBuilder()
    for ((cat, sum) in rows) {
        sb.append(cat).append(": ").append(sum).append('\n')
    }
    return sb.toString()
}

fun main() {
    val totals = mapOf("taxi" to 250, "food" to 200)
    print(renderByCategory(totals))
    // food: 200
    // taxi: 250
}

Juyoui: string-eul return합니다. Print할지 file에 쓸지(언젠가) 는 caller code의 결정입니다.

6. threshold: threshold as a separate step

Threshold(threshold)는 report에서 종종 “중요한 줄만 보여 줘”로 등장합니다. 예: “sum >= 100인 categories만 보여 줘”. Trap은 간단합니다: threshold를 잘못된 시점에 적용하면 이상한 결과가 나옵니다. 미래의 자신과 싸우지 않기 위해, threshold를 이미 aggregated data에 적용하는 별도의 순수 단계로 만듭니다.

즉 threshold는 totals filtering이지, individual operations filtering이 아닙니다. Operations를 filter하면 logic이 달라집니다: 작은 구매를 버리게 되는데, category total은 클 수도 있습니다.

Map<String, Int>를 받아, 이후 sorting/render에 편한 pair list를 반환하는 함수를 만들겠습니다:

fun applyThreshold(
    totals: Map<String, Int>,
    threshold: Int
): List<Pair<String, Int>> {
    return totals.entries
        .map { it.key to it.value }
        .filter { (_, sum) -> sum >= threshold }
}

fun main() {
    val totals = mapOf("taxi" to 250, "food" to 90, "books" to 110)
    println(applyThreshold(totals, threshold = 100))
    // [(taxi, 250), (books, 110)]
}

Jigeum-eun “geunyang filter”cheoreom boijiman, 핵심은 architecture입니다: 이 step을 다양한 report에 동일하게 끼워 넣을 수 있고, codega constructor처럼 읽힙니다: “calculate → filter → sort → output”.

7. Report top: top-N categories by sum

Top-N은 대표적인 “presentation” step입니다: 이미 다 계산했고, 이제 무엇을 먼저 보여 줄지 결정합니다. Sortinggwa take(n)은 output에 가까운 곳에서 하는 게 자연스럽습니다: data meaning을 바꾸지 않고, 사용자에게 보여 주는 방식만 바꿉니다.

Aggregated totals를 받는 topCategories 함수를 만들겠습니다. Threshold는 option으로 연결합니다: 먼저 threshold filter, 그다음 descending sort, 그다음 take(n).

fun topCategories(
    totals: Map<String, Int>,
    n: Int,
    threshold: Int
): List<Pair<String, Int>> {
    return totals.entries
        .map { it.key to it.value }
        .filter { (_, sum) -> sum >= threshold }
        .sortedByDescending { (_, sum) -> sum }
        .take(n)
}

fun main() {
    val totals = mapOf("taxi" to 250, "food" to 200, "books" to 90)
    println(topCategories(totals, n = 2, threshold = 100))
    // [(taxi, 250), (food, 200)]
}

Yeogiseo orderga teukhi 중요합니다. 먼저 take(n)을 하고 그다음 threshold를 적용하면 줄을 “잃을” 수 있습니다: filter 전의 첫 N개를 가져온 뒤 일부를 버려, report가 가능한 것보다 적은 줄을 보여 주게 됩니다. Geuraeseo threshold filtering은 take(n)boda 앞에 와야 합니다.

Ije top render. byCategory renderwa 거의 같지만, orderga 이미 정해져 있습니다(sum으로 sort). Geuraeseo render는 현재 순서대로 줄을 출력하기만 하면 됩니다:

fun renderTop(items: List<Pair<String, Int>>): String {
    val sb = StringBuilder()
    for ((cat, sum) in items) {
        sb.append(cat).append(": ").append(sum).append('\n')
    }
    return sb.toString()
}

fun main() {
    val top = listOf("taxi" to 250, "food" to 200)
    print(renderTop(top))
    // taxi: 250
    // food: 200
}

8. Assembling reports v0 into a unified style

Function-i du gae bainoemyeon, brain-i ritualeul gachi yeogimnida. 좋은 스타일은 “pretty”가 아니라 “predictable”입니다: 일주일 후 file을 열어도 바로 어디에 무엇이 있는지 알 수 있습니다. Geuraeseo uriga app에서 codega 살게 될 모습과 비슷한 작은 example로 모두 모아 봅시다(아직은 한 파일에).

Intermediate val name-eul juyouiha세요: pipeline stepdeul-eul 설명합니다.

fun main() {
    val rawExpenses = listOf(
        " food " to 120,
        "FOOD" to 80,
        "taxi" to 250,
        "Books" to 90,
        "books " to 30
    )

    val expenses = normalizeExpenses(rawExpenses)

    val total = calcTotal(expenses)
    println(renderTotal(total)) // Total: 570

    val totalsByCat = totalsByCategory(expenses)
    print(renderByCategory(totalsByCat))
    // books: 120
    // food: 200
    // taxi: 250

    val top = topCategories(totalsByCat, n = 2, threshold = 100)
    print(renderTop(top))
    // taxi: 250
    // food: 200
}

Ije neun report setcheoreom boimnida, han “divine println”cheoreom bo이지 않습니다. Ne, ajik 단순합니다. Hajiman 바로 이런 스타일이 복잡해져도 견딥니다: report를 하나 더 추가하면, 같은 scheme에 neatly 들어갑니다.

Report contracts: what we take and what we return

Function-eul manhi sseumyeon, contractsreul 눈에 보이게 두는 게 좋습니다. Ige “억지로 우겨 넣기”를 줄이고, Map을 List를 기대하는 곳에 넘기는 실수를 줄여 줍니다. 아래는 v0 functions table의 compact version입니다.

Function Takes Returns Meaning
normalizeExpenses(...)
List<Pair<String, Int>>
List<Pair<String, Int>>
Categoriesreul 하나의 형태로 맞춘다
calcTotal(...)
List<Pair<String, Int>>
Int
All expenses total
totalsByCategory(...)
List<Pair<String, Int>>
Map<String, Int>
Sums by categories
applyThreshold(...)
Map<String, Int>
,
threshold
List<Pair<String, Int>>
Select categories by threshold
topCategories(...)
Map<String, Int>
,
n
,
threshold
List<Pair<String, Int>>
Top categories by sum
render...(...)
numbers/structures
String
Prepare report text

I tableeun “documentation for documentation”i anigo, reportga deo manhajil ttae 길을 잃지 않기 위한 bangbeob입니다.

9. Common mistakes

Mistake 1: computing top from “raw” operations instead of aggregated totals.
If you take the original expense list and just sort it by amount, you get “largest individual spends”, not “most expensive categories”. Sometimes that is useful, but it is a different report. For category-based top, first do totalsByCategory, then sort totals.

Mistake 2: applying threshold after take(n) and wondering why there are fewer rows than expected.
The logic “take top-2 first, then filter by threshold” can drop a row and leave you with top-1, even though there were other candidates that pass the threshold and could take the place. Threshold is a candidate filter, while take(n) is the final “cutter”, so threshold comes first.

Mistake 3: printing inside calculation functions.
Once you do println inside totalsByCategory or calcTotal, you break reusability. Today you print to console, tomorrow you want one big string, the day after tomorrow you want to save to a file. If calculation returns values and output is separate, you do not corner yourself.

Mistake 4: expecting that Map prints itself in the needed order.
Even if “it happens to work now”, that is not a contract. A report should be deterministic: either sort by key, or by value, or explicitly document the order. In our examples, before output we turn entries into a list of pairs and sort — that makes the result stable and readable.

Mistake 5: forgetting category normalization and getting “FOOD”, “food”, and “ food ” as three different worlds.
Classic: you group by a string, but the string is “dirty”. In reports it hurts especially, because a person looks at the totals and makes decisions. So normalization is a shared step for all reports, and it is better to keep it in one function so rules do not drift apart.

Mistake 6: using reduce where the list can be empty and getting an exception.
reduce requires at least one element; otherwise it has “nothing to start from”. For reports, an empty list is normal (the user has not added anything yet), so for sums and accumulations choose fold with a start value. That makes behavior not only safe but also logical: the sum of an empty set is zero.

1
과제
Kotlin SELF, 레벨 26, 레슨 4
잠금
최종 영수증
최종 영수증
1
과제
Kotlin SELF, 레벨 26, 레슨 4
잠금
fold로 합계 계산
fold로 합계 계산
1
과제
Kotlin SELF, 레벨 26, 레슨 4
잠금
카테고리 요약
카테고리 요약
1
과제
Kotlin SELF, 레벨 26, 레슨 4
잠금
보고서 임계값
보고서 임계값
1
설문조사/퀴즈
Bogo wa pailpaini byeonhwan, 레벨 26, 레슨 4
사용 불가능
Bogo wa pailpaini byeonhwan
Bogo wa pailpaini byeonhwan
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION