如何通过 1 的位置列表解码 0 和 1 的列表? [英] How to decode List of 0s and 1s by List of positions of 1?

查看:43
本文介绍了如何通过 1 的位置列表解码 0 和 1 的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个只包含 0 和 1 的 List[Int].数组中定义的零和一的位置

I want to create an List[Int] containing only 0 and 1. Position of zeros and ones defined in array

val bitMask = List(2,5,6,11,...,621,655)

bitMask - 是结果列表中的位置列表,结果列表的项目为零

bitMask - is list of position ones in result list, over items of resulting list is zeros

结果我想得到

result = List(0,0,1,0,0,1,1,0,...,0,1)

将结果长度计算为bitMask.last + 1

我是用这个代码做到的:

I did it using this code:

result = List.fill(bitMask.last+1)(0).zipWithIndex.map(i => if (bitMask.contains(i._2)) 1 else 0)

可能有更简单、更像 Scala 方式的解决方案?

May have a more simple and more scala-way solution?

推荐答案

BitSet 将提供更高效的查找(实际上,如果您想使用联合、区别等,它会更好):

BitSet will provide more efficient look ups (in fact, it is superior if you want to work with unions, distinctions and so on):

val mask = scala.collection.BitSet(2,5,6,11)
(0 to 100).map(mask)
// Vector(false, false, true, false, false, ...) 

从布尔值到 0/1 的转换应该很简单

Conversion from Boolean to 0/1 should be trivial

这篇关于如何通过 1 的位置列表解码 0 和 1 的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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