【问题标题】:Search through last 2 integers and compare in a map搜索最后 2 个整数并在地图中进行比较
【发布时间】:2016-11-18 22:06:34
【问题描述】:

我的系统目前具有搜索整数映射列表的功能,每个整数都有键值“sk1”-“sk10”。我需要修改我现在拥有的内容,以便可以搜索列表并比较列表中的最后 2 个数字并返回最高的数字。

目前我可以搜索1并返回当前,我需要搜索所有值并找到“最高增加”

下面是我的数据文件,“mapdata”我会举一个我需要的例子。这存储为 Map[String, List[Int]]。字符串是第一个值,之后是整数列表。

SK1, 9, 7, 2, 0, 7, 3, 7, 9, 1, 2, 8, 1, 9, 6, 5, 3, 2, 2, 7, 2, 8, 5, 4, 5, 1, 6, 5, 2, 4, 1
SK2, 0, 7, 6, 3, 3, 3, 1, 6, 9, 2, 9, 7, 8, 7, 3, 6, 3, 5, 5, 2, 9, 7, 3, 4, 6, 3, 4, 3, 4, 1
SK4, 2, 9, 5, 7, 0, 8, 6, 6, 7, 9, 0, 1, 3, 1, 6, 0, 0, 1, 3, 8, 5, 4, 0, 9, 7, 1, 4, 5, 2, 8
SK5, 2, 6, 8, 0, 3, 5, 5, 2, 5, 9, 4, 5, 3, 5, 7, 8, 8, 2, 5, 9, 3, 8, 6, 7, 8, 7, 4, 1, 2, 3
SK6, 2, 7, 5, 9, 1, 9, 8, 4, 1, 7, 3, 7, 0, 8, 4, 5, 9, 2, 4, 4, 8, 7, 9, 2, 2, 7, 9, 1, 6, 9
SK7, 6, 9, 5, 0, 0, 0, 0, 5, 8, 3, 8, 7, 1, 9, 6, 1, 5, 3, 4, 7, 9, 5, 5, 9, 1, 4, 4, 0, 2, 0
SK8, 2, 8, 8, 3, 1, 1, 0, 8, 5, 9, 0, 3, 1, 6, 8, 7, 9, 6, 7, 7, 0, 9, 5, 2, 5, 0, 2, 1, 8, 6
SK9, 7, 1, 8, 8, 4, 4, 2, 2, 7, 4, 0, 6, 9, 5, 5, 4, 9, 1, 8, 6, 3, 4, 8, 2, 7, 9, 7, 2, 6, 6

将查找并比较每个列表的最后一个数字,因此 SK1 为 -3,SK2 为 -3,SK4 为 6。返回的唯一值应该是键值“SKnumber "及其价值和增长。

因此,如果 SK 4 最高,则结果将是“SK4 - 8, INCREASE 6”

目前,我可以搜索并找到每个尾部的 end int,下面是我的代码,我将如何修改我上面所说的更改?

  val mapdata = readFile("data.txt")

  //5 - Show Current Stock Level (W)
  def handleFive(): Boolean = {
    mnuShowSingleDataStock(currentStockLevel)
    true
  }

// Returns a single result, not a list
  def mnuShowSingleDataStock(stock: (String) => (String,Int)) = {
    print("Stock > ")
    val data = stock(readLine)
    println(s"${data._1}: ${data._2}")
  }

  //Show last element in the list, most current
  def currentStockLevel (stock: String): (String, Int) = {
    (stock, mapdata.get (stock).map(findLast(_)).getOrElse(0))
  }

【问题讨论】:

    标签: scala list


    【解决方案1】:

    不确定您的代码与您请求的内容有何关联,但您可以使用 takeRight 从列表中获取最后 N 个元素 - 在这种情况下,您可以获取最后两个元素并对映射值执行简单映射到计算“增量”,然后使用maxBy 找到具有最大增量的元素:

    val result: (String, (Int, Int)) = mapdata
      .mapValues(_.takeRight(2)) // take only last two ints from each list
      .mapValues { case List(i1, i2) => (i2, i2 - i1) } // compute "increase"
      .maxBy { case (s, (last, increase)) => increase } // maximum by increase value
    
    // result is (Key, (last value, increase)) 
    
    println(s"${result._1} - ${result._2._1}, INCREASE ${result._2._2}")
    // SK4 - 8, INCREASE 6
    

    【讨论】:

    • 提供我自己的代码以表明我不只是要求您完成所有工作,我已经完成了一些工作,只是不确定如何继续处理下一个问题。不过这行得通,干杯
    • 这很好——我现在意识到只有最后三种方法是相关的(对吗?)——如果是这样,你可以删除另外两种,但你添加最后一个确实很好一。
    猜你喜欢
    • 2012-12-02
    • 1970-01-01
    • 2022-12-15
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多