Scala作业

第一题、百元喝酒

作业要求:每瓶啤酒2元,3个空酒瓶或者5个瓶盖可换1瓶啤酒。100元最多可喝多少瓶啤酒?(不允许借啤酒)

思路:利用递归算法,一次性买完,然后递归算出瓶盖和空瓶能换的啤酒数

package com.lagou.homework

/**
 * 作业要求:每瓶啤酒2元,3个空酒瓶或者5个瓶盖可换1瓶啤酒。100元最多可喝多少瓶啤酒?
 * (不允许借啤酒)思路:利用递归算法,先一次性买完,然后递归算出瓶盖和空瓶能换的啤酒数
 */
object HundredBeer {

  def main(args: Array[String]): Unit = {
    var bottle, cap, bcsum: Int = 100 / 2
    bcsum = bottleAndCap(bcsum, bottle, cap)
    println("100元能喝的啤酒数量是:" + bcsum)
  }

  /**
   * 定义一个递归函数,实现瓶子和盖子替换的啤酒数量
   */
  def bottleAndCap(sum: Int, b: Int, c: Int): Int = {
    if (b < 3 && c < 5) {
      return sum
    } else {
      var a1: Int = b / 3
      var a2: Int = b % 3
      var b1: Int = c / 5
      var b2: Int = c % 5
      return bottleAndCap(sum + a1 + b1, a1 + b1 + a2, a1 + b1 + b2)
    }
  }
}

 

运行结果

 

第二题、人机猜拳

    1.1 作业需求

        1. 选取对战角色

        2. 开始对战,用户出拳,与对手进行比较,提示胜负信息

        3. 猜拳结束算分,平局都加一分,获胜加二分,失败不加分

        4 . 循环对战,当输入“n”时,终止对战,并显示对战结果

        5. 游戏结束后显示得分

1.2 作业分析

   分析业务逻辑,抽象出类、类的属性和方法,如下:

    1. 创建用户类User,定义类的属性(name,score)和类的方法(showFist())

    2. 创建计算机类Computer,定义类的属性(name,score)和类的方法(showFist())

    3. 实现计算机随机出拳

    4. 创建游戏类Game,定义类的属性(甲方玩家、乙方玩家、对战次数)

    5. 编写初始化方法、游戏开始方法

 代码详解

package com.lagou.homework

import scala.io.StdIn

object GameDemo {

  //定义变量
  val AIplayer = Map("1" -> "刘备", "2" -> "关羽", "3" -> "张飞")
  val fist = Map("1" -> "石头", "2" -> "剪刀", "3" -> "布")
  var user: User = _
  var computer: Computer = _
  var times = 0

  /**
   * 开局之前的准备
   */
  def init(): Unit = {
    println("--------欢迎进入游戏世界--------")
    println("****************************")
    println("**********猜拳开始!**********")
    println("****************************
")

    // 用户的角色
    user = new User("游客", 0)

    // 用户选择的对战角色
    println("请选择对战角色:(1.刘备 2.关羽 3.张飞)")
    val key = StdIn.readLine()
    computer = new Computer(AIplayer(key), 0)
  }

  /**
   * 比赛逻辑比对
   */
  def judge(ares: String, bres: String): Unit = {
    if (ares == bres) {
      // 平局
      user.score += 1
      user.fairs += 1
      computer.score += 1
      computer.fairs += 1
    } else if ((ares == "1" && bres == "2") || (ares == "2" && bres == "3") || (ares == "3" && bres == "1")) {
      // 玩家赢
      user.score += 2
      user.wins += 1
      computer.fails += 1
      println("恭喜!你赢啦!")
    } else {
      // 玩家输
      computer.score += 2
      computer.wins += 1
      user.fails += 1
      println("抱歉!你输了!")
    }
  }

  /**
   * 显示对战结果
   */
  def showResults(): Unit = {
    println(s"${computer.name}	VS	${user.name}")
    println(s"对战次数${times}次
")
    println("姓名	得分	胜局	和局	负局")
    println(s"${user.name}	${user.score}	${user.wins}	${user.fairs}	${user.fails}")
    println(s"${computer.name}	${computer.score}	${computer.wins}	${computer.fairs}	${computer.fails}")
  }

  /**
   * 程序入口
   */
  def main(args: Array[String]): Unit = {
    // 初始化对战页面
    init()
    // 开始对战
    println(s"你选择了与${computer.name}对战
要开始么?y/n")
    var next = true
    var s = StdIn.readLine()
    do {
      s match {
        case "y" => {
          println("请出拳!1.石头 2.剪刀 3.布")
          var ares = user.showFist()
          println(s"${computer.name}出拳!")
          var bres = computer.showFist()
          // 判断结果
          judge(ares, bres)
          times += 1
          println("是否开始下一轮?(y/n)")
          s = StdIn.readLine()
        }
        case "n" => {
          // 终止对战并显示结果
          next = false
          println("退出游戏!")
          println("------------------------------")
          showResults()
        }
        case _ => {
          println("是否开始下一轮?(y/n)")
          s = StdIn.readLine()
        }
      }
    }
    while (next)

  }
}

User类

package com.lagou.homework

import scala.util.Random

class Computer(var name: String, var score: Int) {

  var wins = 0
  var fails = 0
  var fairs = 0
  val fist = Map("1" -> "石头", "2" -> "剪刀", "3" -> "布")

  def showFist(): String = {
    val bres = Random.nextInt(3) + 1
    println(s"${name}出拳:${fist(bres.toString)}")
    bres.toString
  }
}

Computer类

package com.lagou.homework

import scala.io.StdIn

class User(var name: String, var score: Int) {

  var wins = 0
  var fails = 0
  var fairs = 0
  val fist = Map("1" -> "石头", "2" -> "剪刀", "3" -> "布")

  //出拳
  def showFist(): String = {
    var ares = StdIn.readLine()
    if (!fist.keySet.contains(ares)) {
      println("输入不符合规范,默认出布!")
      ares = "3"
    }
    println(s"你出拳:${fist(ares)}")
    ares
  }

}

演示结果

 

 

第三题、用户位置时长统计

现有如下数据需要处理:

    字段:用户ID,位置ID,开始时间,停留时长(分钟)

4行样例数据:

  UserA,LocationA,8,60

  UserA,LocationA,9,60

  UserB,LocationB,10,60

  UserB,LocationB,11,80

  样例数据中的数据含义是:用户UserA,在LocationA位置,从8点开始,停留了60钟

 处理要求: 

    1、对同一个用户,在同一个位置,连续的多条记录进行合并

     2、合并原则:开始时间取最早时间,停留时长累计求和

 代码详解

package com.lagou.homework

//定义一个样例类
case class userTime(username: String, location: String, startTime: Int, duration: Int)

object UserLocation extends App {

  // 将数据封装到样例类中,初始化数据到集合
  val userTimeLst: List[userTime] = List(
    userTime("userA", "locationA", 8, 60),
    userTime("userA", "locationA", 9, 60),
    userTime("userB", "locationB", 11, 80),
    userTime("userB", "locationB", 10, 60)
  )

  // 分组,key为姓名加位置,确定唯一,算子为groupBy
  val groupuserTime: Map[String, List[userTime]] = userTimeLst.groupBy(user => user.username + "-" + user.location)
  println("分组")
  groupuserTime.foreach {
    case (k, v) => println(s"key:$k, value:$v")
  }

  // 排序,根据开始时间顺序,算子为mapValues
  val sortuserTime: Map[String, List[userTime]] = groupuserTime.mapValues(_.sortBy(_.startTime))
  println("排序")
  sortuserTime.foreach {
    case (k, v) => println(s"key:$k, value:$v")
  }


  // 统计,算子为mapValues,最终计算出不同组里的连续的开始时间的最终停留时长,原始数据不存在不连续,不考虑不连续
  var firstTime = 0
  val sumuserTime: Map[String, Int] = sortuserTime.mapValues(lst => {
    // 返回开始时间
    firstTime = lst.head.startTime
    // 返回总停留时长
    lst.map(_.duration).sum
  })
  println("最终")
  // 输出最终结果
  sumuserTime.foreach {
    case (k, v) => println(s"key:$k, 开始时间:$firstTime, value:$v")
  }

}

结果验证

原文地址:https://www.cnblogs.com/aloneme/p/15128100.html