如何使用新值填充对象列表 [英] How do I populate a list of objects with new values

查看:39
本文介绍了如何使用新值填充对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉:我是菜鸟

我有一个物品类

class item(ind:Int,freq:Int,gap:Int){}

我有一个整数的有序列表

I have an ordered list of ints

val listVar = a.toList

其中 a 是一个数组

我想要一个名为指标的项目列表,其中

I want a list of items called metrics where

ind 是(唯一的)整数freq 是 ind 在列表中出现的次数gap 是 ind 与其之前列表中的数字之间的最小间隙到目前为止,我有:

ind is the (unique) integer freq is the number of times that ind appears in list gap is the minimum gap between ind and the number in the list before it so far I have:

def metrics = for {
  n <- 0 until 255 
  listVar filter (x == n) count > 0 
}
  yield  new item(n, (listVar filter == n).count,0)

这是废话,我知道 - 有什么线索吗?

It's crap and I know it - any clues?

推荐答案

嗯,其中一些很简单:

val freqMap = listVar groupBy identity mapValues (_.size)

这给你 indfreq.要获得 gap,我会使用折叠:

This gives you ind and freq. To get gap I'd use a fold:

val gapMap = listVar.sliding(2).foldLeft(Map[Int, Int]()) { 
  case (map, List(prev, ind)) =>
    map + (ind -> (map.getOrElse(ind, Int.MaxValue) min ind - prev))
}

现在你只需要统一它们:

Now you just need to unify them:

freqMap.keys.map( k => new item(k, freqMap(k), gapMap.getOrElse(k, 0)) )

这篇关于如何使用新值填充对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆