【问题标题】:Get index of a 1 in a bitarray?获取位数组中 1 的索引?
【发布时间】:2018-05-08 04:11:12
【问题描述】:

朋友们,谁知道我如何在 Bitarray 中获取 1 的索引并将其推送到数组中。一些功能或其他的东西

我有一个 Uint16 ,在这里我想从这个变量中读取位并获取 1 的索引并将其放入数组或列表中

【问题讨论】:

  • 有负位吗?
  • @PatrickArtner 我的意思是如何在 Bitarray 中获取 1 的索引,也许有一些函数 indexof 或其他东西,我找不到
  • Documentation 在任何特定位置?或者只是任何激活的位?
  • 请提供示例,例如假设你有[0, 0, 0, 1, 0, 1, 1, 0] 位数组,需要的结果是什么?
  • 例如{例如我有一个位数组 [true, false, false, false,true] 或 [1, 0, 0, 0, 0, 1] 如何获取 indexof (true) 或 indexof(1)

标签: c# algorithm bitarray


【解决方案1】:

第 1 步,准备您的 BitArray:

 var bits = new BitArray (new[] { false, true, false, false, true, false, false });

第 2 步,将其更改为您可以理解的形式(列表,1=true,0=false)

 var list = bits.Cast<bool> ().Select (x => x ? 1 : 0).ToList ();

第3步,现在你可以使用你已经知道的IndexOf

 int index = list.IndexOf (1); // index=1, it looks from left ot right

如果您想从右到左搜索表单,请使用列表中的Reverse() 方法。

这不是最佳解决方案,但我认为它对您来说最容易理解。

编辑:

var bits = new BitArray (new[] { false, true, false, false, true, false, false });

var bitsWithIndex = bits.Cast<bool> () // we need to use Cast because BitArray does not provide generic IEnumerable
                        .Select ((bit, index) => new { Bit = bit, Index = index}); // projection, we will save bit indices

// now we will get indices of all true(1) bits [from left to right]
var indices = bitsWithIndex.Where (x => x.Bit == true).Select (x => x.Index).ToArray ();

【讨论】:

  • 但是如果我想在数组中添加这些索引呢?
  • 你帮了我很多)谢谢
  • 但还有一个问题,这是最佳解决方案吗?
  • @RadikHarutyunyan:不,但这已经足够了。你能看到我的答案附近的 ✓ 标志吗?点击它:D
【解决方案2】:

您查询位数组的每个位置并报告索引。您可以使用简单的for 循环并在列表中累积您的真实索引 - 我选择 linq,看起来不错:

using System.Linq;
using System.Collections;

public static IEnumerable<int> GetTrueIndexes(BitArray arr)
{
    if (arr != null)        
        return Enumerable.Range(0,arr.Count).Where( idx => arr.Get(idx));

    return new int[0];
}


public static void Main()
{
    BitArray b = new BitArray(
        "100101010000101"
        .Select(c => c == '0' ? false : true )
        .ToArray());

    var trueIndexes =  GetTrueIndexes(b);       

    System.Console.WriteLine(string.Join(", ",trueIndexes)); 
}

输出:

0、3、5、7、12、14

【讨论】:

    【解决方案3】:

    你有一个 UInt16,你需要读取第 1 位的索引然后:

    List<int> GetIndexes(int number) 
    {
         var result = new List<int>();
         var index = 0;
         while (number > 0) 
         {
             if (number & 1) 
             {
                  result.Add(index);
             } 
             index ++;
             number >= 1;
         }
    
         return result;
    }
    

    【讨论】:

    • 嗯,但如果是布尔值,我怎样才能获得真正的索引?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多