首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Kotlin:如何利用Kotlin数据结构在面试中编写有效的解决方案

Kotlin:如何利用Kotlin数据结构在面试中编写有效的解决方案
EN

Stack Overflow用户
提问于 2022-01-18 21:53:44
回答 1查看 54关注 0票数 1

我在一次面试中问到了这个问题,在最后一节我和科特林乐队的谈话中失败了。我正在尝试重新创建fun taskCompleted() --我想看看如何实现它,仅仅是为了玩它。所以这就是我所得到的

代码语言:javascript
复制
data class Article(val title: String, val content: String, val duration: Int, val date: Int)

data class StreakInfo(val goalsMet: Int, val breakDown: List<Boolean>)

interface ReadingGoalService{
    fun getDailyReadingGoal(): Int
}

interface TaskService{

    fun allTasks(): List<Article>
}

class MockInterview{

   
    fun taskCompleted(){}

    //temporary
    private fun today(): Int{

        return 1
    }
}

fun getAllSteaks(streakInfo: StreakInfo){
    //don't implement
}

我的要求是在哪里做fun taskCompleted(),我应该做以下几件事

代码语言:javascript
复制
        //TODO 1 current day is today
        //TODO 2 take all the articles that were read on the current day
        //TODO 3 sum readingDurations of articles for current Day
        //TODO 4 check if sum of readingDurations is >= than reading goal
        // TODO 5 if sum of readingDuration is >= goal repeat 2..3.. and 4. for currentDay-1
        //TODO 6 if sum of readingDuration is < goal - stop

知道我怎么能在科特林做到这一点吗?我计划将此作为一个学习过程。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-18 22:09:06

正如我所提到的,我强烈建议您看看Kotlin Koans,因为他们向您介绍了许多我认为肯定会教您如何执行几乎所有那些TODO的例子!(他们有解决办法!)

在这次采访中,您是否知道如何使用Kotlin标准库中的聚合和映射函数,并检查是否可以通过使用适当数量的参数来重用大量代码。

以下是我如何处理这个问题:

代码语言:javascript
复制
fun today() = 1 // TODO 1: Current day is today

fun tasksDoneByDay(taskService: TaskService, day: Int = today()): List<Article> {
    // TODO2: Here I have all tasks that were done at "today()"
    return taskService.allTasks().filter { task -> task.date == day }
}

// TODO 3
fun durationsForDay(taskService: TaskService, day: Int = today()) = tasksDoneByDay(taskService, day).sumBy { it.duration }


// TODO 4
fun durationsForDayMeetGoal(taskService: TaskService, goal: Int, day: Int = today()) = durationsForDay(taskService, day) >= goal

// TODO 5 if sum of readingDuration is >= goal repeat 2..3.. and 4. for currentDay-1

fun todo5(taskService: TaskService, goal: Int) {
  val today = today()
  return when(val durationsForTodayMeetGoal = durationsForDayMeetGoal(taskService, goal, today)) {
    false -> durationsForDayMeetGoal(taskService, goal, today - 1)
    true -> durationsForTodayMeetGoal
  }
}

// TODO 6 I don't understand...

essentially the same as todo five but when it's false dont do anything?
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70762855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档