C# get index of bit - c#

I want to get the index of the first bit that equal to 1, and the index of the last bit that equal to 1.
For example:
data=0x3E
first bit = 1
last bit = 5
How can I do this?

Take a look at BitArray class and its Item property. Then you could create a BitArray and loop it's items to get what you want easily.

I'm sure there are some fun bit-twiddling tricks you can use, but here's a naive solution:
public static void Main()
{
uint data = 0x3E;
uint firstMask = 1;
uint lastMask = 0x80000000;
int? first = null;
int? last = null;
for (int i=0; i < 32; i++) {
if ((firstMask & data) > 0 && first == null)
{
first = i;
}
if ((lastMask & data) != 0 && last == null)
{
last = i;
}
firstMask = firstMask << 1;
lastMask = lastMask >> 1;
}
last = 31-last;
Console.WriteLine(first);
Console.WriteLine(last);
}
See http://dotnetfiddle.net/FmN7QL

Manually build a lookup table:
var firstBit = new int[0x100] { -1, 0, 1, 0 ... };
var lastBit = new int[0x100] { -1, 0, 1, 1 ... };
Then use 'data' to index into those tables.
byte data = 0x3e;
var f = firstBit[data];
var l = lastBit[data];
I'll leave it as an exercise to automate the creation of the tables. :)

Related

Sorting an array of enumeration

Hello I have an array of enumerations, and I'm trying sort that array by their enumeration value and get the array index's of the top
private enum Values
{
LOW,
MEDIUM,
HIGH
}
private Values[] Settings = new Values[10];
Settings[0] = LOW;
Settings[1] = HIGH;
Settings[2] = MEDIUM;
Settings[3] = LOW;
Settings[4] = LOW;
Settings[5] = LOW;
Settings[6] = LOW;
Settings[7] = LOW;
Settings[8] = MEDIUM;
Settings[9] = MEDIUM;
Basically now, with what I have above, I need to sort the settings array by enumeration value and get the array indexes of the top (let's say 3) items;
So I'd get back values 1, 2, 8
The platform I'm using does not support LINQ so those handy functions are not available.
I've been trying to wrap my head around this but it would help to have another pair of eyes.
thanks.
Implement a wrapper reference type,
class ValueWrapper : IComparable<ValueWrapper>
{
public Values Value { get; set; }
public int Index { get; set; }
public int CompareTo(ValueWrapper other)
{
return this.Value.CompareTo(other.Value) * -1; // Negating since you want reversed order
}
}
Usage -
ValueWrapper[] WrappedSettings = new ValueWrapper[10];
for(int i = 0; i < WrappedSettings.Length; i++)
{
WrappedSettings[i] = new ValueWrapper { Value = Settings[i], Index = i };
}
Array.Sort(WrappedSettings);
WrappedSettings will be sorted as you specified, preserving the indexes they were in the original array.
how about this:
Values first = Values.Low,second = Values.Low,third = Values.Low;
int firstI = -1,secondI = -1, thirdI = -1;
for(int i = 0;i < Settings.Length;i++)
{
if(Settings[i] > first || firstI == -1)
{
third = second;
thirdI = secondI;
second= first;
secondI= firstI;
first = Settings[i];
firstI = i;
}
else if(Settings[i] > second || secondI == -1)
{
third = second;
thirdI = secondI;
second = Settings[i];
secondI = i;
}
else if(Settings[i] > third || thirdI == -1)
{
third = Settings[i];
thirdI = i;
}
}
So, since you say you work in an environment where Linq is not available, I assume that other things like generics, nullables and so on will not be available either. A very low-tech solution.
Basic idea:
For every possible enum value, from highest to lowest, go through the list. If we find that value, output it and remember how many we have output. If we reach 3, stop the algorithm.
So, we first look for HIGH in the list, then for MEDIUM and so on.
class Program
{
private enum Values
{
LOW,
MEDIUM,
HIGH
}
static void Main(string[] args)
{
// Sample data
Values[] settings = new Values[10];
settings[0] = Values.LOW;
settings[1] = Values.HIGH;
settings[2] = Values.MEDIUM;
settings[3] = Values.LOW;
settings[4] = Values.LOW;
settings[5] = Values.LOW;
settings[6] = Values.LOW;
settings[7] = Values.LOW;
settings[8] = Values.MEDIUM;
settings[9] = Values.MEDIUM;
// Get Values of the enum type
// This list is sorted ascending by value but may contain duplicates
Array enumValues = Enum.GetValues(typeof(Values));
// Number of results found so far
int numberFound = 0;
// The enum value we used during the last outer loop, so
// we skip duplicate enum values
int lastValue = -1;
// For each enum value starting with the highest to the lowest
for (int i= enumValues.Length -1; i >= 0; i--)
{
// Get this enum value
int enumValue = (int)enumValues.GetValue(i);
// Check whether we had the same value in the previous loop
// If yes, skip it.
if(enumValue == lastValue)
{
continue;
}
lastValue = enumValue;
// For each entry in the list where we are searching
for(int j=0; j< settings.Length; j++)
{
// Check to see whether it is the currently searched value
if (enumValue == (int)settings[j])
{
// if yes, then output it.
Console.WriteLine(j);
numberFound++;
// Stop after 3 found entries
if (numberFound == 3)
{
goto finished;
}
}
}
}
finished:
Console.ReadLine();
}
}
Output is as requested 1,2,8
I'm not sure if this is exactly what you want because it doesn't sort the original array, but one way to get the indexes of the top three values is to simply store the indexes of the top values in another array. Then we can loop through the original array, and for each item, see if it's larger than any of the items at the indexes we've stored so far. If it is, then swap it with that item.
For example:
// Start the topIndexes array with all invalid indexes
var topIndexes = new[] {-1, -1, -1};
for (var settingIndex = 0; settingIndex < Settings.Length; settingIndex++)
{
var setting = Settings[settingIndex];
var topIndexLessThanSetting = -1;
// Find the smallest topIndex setting that's less than this setting
for (int topIndex = 0; topIndex < topIndexes.Length; topIndex++)
{
if (topIndexes[topIndex] == -1)
{
topIndexLessThanSetting = topIndex;
break;
}
if (setting <= Settings[topIndexes[topIndex]]) continue;
if (topIndexLessThanSetting == -1 ||
Settings[topIndexes[topIndex]] < Settings[topIndexes[topIndexLessThanSetting]])
{
topIndexLessThanSetting = topIndex;
}
}
topIndexes[topIndexLessThanSetting] = settingIndex;
}
// topIndexes = { 1, 2, 8 }

Want to find Highest Maximum number and Second Highest Maximum Number with their Index value

This code finds the highest number and second highest number but gives the wrong index number, but only in some cases
When array values: {1,3,3,0,3}
When Array Values: {3,3,0,1,2}
If all are unique numbers then it gives an accurate answer with accurate index value; Where do I need to change the code to get accurate index value for above cases?
FirstMaxNumber=arrFindIndex[0];
SecondMaxNumber=arrFindIndex[0];
FirstMaxRatingIndex=0;
SecondMaxRatingIndex=0;
for (int i = 0; i < arrSize; i++)
{
if (FirstMaxNumber <= arrFindIndex[i])
{
SecondMaxNumber = FirstMaxNumber;
FirstMaxNumber = arrFindIndex[i];
FirstMaxRatingIndex = i;
}
else if (SecondMaxNumber <= arrFindIndex[i])
{
SecondMaxNumber = arrFindIndex[i];
SecondMaxRatingIndex = i;
}
}
// print(FirstMaxNumber);
// Print(FirstMaxRatingIndex);
// print(SecondMaxNumber);
// print(SecondMaxRatingIndex);
In the first if statement, the value of the second maximum value is set:
SecondMaxNumber = FirstMaxNumber;
but the index isn't:
SecondMaxRatingIndex = FirstMaxRatingIndex;
FirstMaxRatingIndex = i;
Something like this:
FirstMaxNumber = arrFindIndex[0];
SecondMaxNumber = arrFindIndex[0];
FirstMaxRatingIndex = 0;
SecondMaxRatingIndex = 0;
// Do not use magic values: "arrSize" but actual length: arrFindIndex.Length
for (int i = 1; i < arrFindIndex.Length; i++) {
int v = arrFindIndex[i];
if (v > FirstMaxNumber) {
// so "first" becomes "second"
SecondMaxNumber = FirstMaxNumber;
SecondMaxRatingIndex = FirstMaxRatingIndex;
FirstMaxNumber = v;
FirstMaxRatingIndex = i;
}
else if ((v > SecondMaxNumber) || (i == 1)) {
SecondMaxNumber = v;
SecondMaxRatingIndex = i;
}
}
Why don't you just use LINQ for that?
var arr = new [] {3, 0, 4, 2, 3, 7};
var min = arr.Select((Val, Key) => new { Val, Key }).First(x => x.Val == arr.Min());
var max = arr.Select((Val, Key) => new { Val, Key }).First(x => x.Val == arr.Max());
Console.WriteLine($"Min Key: {min.Key} Val: {min.Val} \nMax Key: {max.Key} Val: {max.Val}");
// Output
// Min Key: 1 Val: 0
// Max Key: 5 Val: 7
If the arrays are short and you don't particularly care how fast it is, the easiest code is something like this:
var indices = Enumerable.Range(0, array.Length).ToArray();
Array.Sort(array, indices, Comparer<int>.Create((a, b) => b - a));
Then indices will contain the indices of all the elements, in descending order, so you just need the first two.
Here's a compilable console app (requires .Net 4.5 or later):
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
static class Program
{
static void Main()
{
test(1, 3, 3, 0, 3); // Prints 1, 2
test(3, 3, 0, 1, 2); // Prints 0, 1
}
static void test(params int[] array)
{
var indices = Enumerable.Range(0, array.Length).ToArray();
Array.Sort(array, indices, Comparer<int>.Create((a,b)=>b-a));
Console.WriteLine($"{indices[0]}, {indices[1]}");
}
}
}

Polynomial Division

I am making a program to calculate operations over polynomials and I already finished other operation (+ - *) but stucked with the division, I am getting this error always as it shown in the code
static int[] DividePolnomials(int[] pol1, int[] pol2)
{
int tmp = 0;
int power_tmp = 0;
int[] result_tmp;
int[] result;
if (pol1.Length > pol2.Length)
{
result = new int [pol1.Length];
result_tmp = new int[pol1.Length];
for (int i = 0; pol2.Length<=pol1.Length; i++)
{
if (pol2[pol2.Length-i-1] == 0) // here is the problem it gives that the index is outside the bounds
{
continue;
}
else
{
tmp = pol1[pol1.Length - i - 1] / pol2[pol2.Length - i - 1];
power_tmp = (pol1.Length - i - 1) - (pol2.Length - i - 1);
result[power_tmp] = tmp;
result_tmp = Multiply(result, pol2);
pol1 = SubtractPolnomial(pol1, result_tmp);
}
}
}
else
{
result = new int [pol1.Length];
}
return result;
}
I haven't completed all other scenarios in the code yet due to this error, but I would like to get any help in the case the two polynomials are equals in length
Your i becomes greater than pol2.Length-1, so at this moment you have pol2[-1], pol2[-2] etc. This does not allowed in C#. You can check the next statement:
if ((pol2.Length-i-1 < 0) || (pol2[pol2.Length-i-1] == 0))
{
continue;
}
EDIT: If the first condition is true, the second one will not be evaluated
https://msdn.microsoft.com/en-us/library/6373h346.aspx

Check if List<Int32> values are consecutive

List<Int32> dansConList = new List<Int32>();
dansConList[0] = 1;
dansConList[1] = 2;
dansConList[2] = 3;
List<Int32> dansRandomList = new List<Int32>();
dansRandomList[0] = 1;
dansRandomList[1] = 2;
dansRandomList[2] = 4;
I need a method that, when evaluating the above lists, will return false for dansRandomList and true for dansConList based on the fact dansConList has a consecutive number sequence in it's values, and dansRandomList does not (missing the value 3).
Using LINQ is preferable, if possible.
What I've Tried:
For the sake of achieving the end result, I have used a for loop and compare with 'i' (loop counter) to evaluate the values, but as mentioned above I'd like to use LINQ for this.
One-liner, only iterates until the first non-consecutive element:
bool isConsecutive = !myIntList.Select((i,j) => i-j).Distinct().Skip(1).Any();
Update: a couple examples of how this works:
Input is { 5, 6, 7, 8 }
Select yields { (5-0=)5, (6-1=)5, (7-2=)5, (8-3=)5 }
Distinct yields { 5, (5 not distinct, 5 not distinct, 5 not distinct) }
Skip yields { (5 skipped, nothing left) }
Any returns false
Input is { 1, 2, 6, 7 }
Select yields { (1-0=)1, (2-1=)1, (6-2=)4, (7-3=)4 } *
Distinct yields { 1, (1 not distinct,) 4, (4 not distinct) } *
Skip yields { (1 skipped,) 4 }
Any returns true
* The Select will not yield the second 4 and the Distinct will not check it, as the Any will stop after finding the first 4.
var min = list.Min();
var max = list.Max();
var all = Enumerable.Range(min, max - min + 1);
return list.SequenceEqual(all);
var result = list
.Zip(list.Skip(1), (l, r) => l + 1 == r)
.All(t => t);
You can use this extension method:
public static bool IsConsecutive(this IEnumerable<int> ints )
{
//if (!ints.Any())
// return true; //Is empty consecutive?
// I think I prefer exception for empty list but I guess it depends
int start = ints.First();
return !ints.Where((x, i) => x != i+start).Any();
}
Use it like this:
[Test]
public void ConsecutiveTest()
{
var ints = new List<int> {1, 2, 4};
bool isConsecutive = ints.IsConsecutive();
}
Extension method:
public static bool IsConsecutive(this IEnumerable<int> myList)
{
return myList.SequenceEqual(Enumerable.Range(myList.First(), myList.Last()));
}
Useage:
bool isConsecutive = dansRandomList.IsConsecutive();
Caveat: returns true if empty.
var list = new int[] {-1,0,1,2,3};
var isConsecutive = list.Select((n,index) => n == index+list.ElementAt(0)).All (n => n);
Here is the another one. It supports {1,2,3,4} and {4,3,2,1} both. It tests sequential number differences equals 1 or -1.
Function IsConsecutive(ints As IEnumerable(Of Integer)) As Boolean
If ints.Count > 1 Then
Return Enumerable.Range(0, ints.Count - 1).
All(Function(r) ints(r) + 1 = ints(r + 1) OrElse ints(r) - 1 = ints(r + 1))
End If
Return False
End Function
In order to check whether the series contain consecutive number or not you may use this
Sample
isRepeatable(121878999, 2);
Result = True
since 9 repeats two times , where upto is no of times in series
isRepeatable(37302293, 3)
Result = False
since no number repeat 3 times in series
static bool isRepeatable(int num1 ,int upto)
{
List<int> myNo = new List<int>();
int previous =0;
int series = 0;
bool doesMatch = false;
var intList = num1.ToString().Select(x => Convert.ToInt32(x.ToString())).ToList();
for (int i = 0; i < intList.Count; i++)
{
if (myNo.Count==0)
{
myNo.Add(intList[i]);
previous = intList[i];
series += 1;
}
else
{
if (intList[i]==previous)
{
series += 1;
if (series==upto)
{
doesMatch = true;
break;
}
}
else
{
myNo = new List<int>();
previous = 0;
series = 0;
}
}
}
return doesMatch;
}
// 1 | 2 | 3 | 4 | _
// _ | 1 | 2 | 3 | 4
// | 1 | 1 | 1 | => must be 1 (or 2 for even/odd consecutive integers)
var numbers = new List<int>() { 1, 2, 3, 4, 5 };
const step = 1; // change to 2 for even and odd consecutive integers
var isConsecutive = numbers.Skip(1)
.Zip(numbers.SkipLast(1))
.Select(n => {
var diff = n.First - n.Second;
return (IsValid: diff == step, diff);
})
.Where(diff => diff.IsValid)
.Distinct()
.Count() == 1;
Or we could write that a bit shorter but less readable:
var isConsecutive = numbers.Skip(1)
.Zip(numbers.SkipLast(1), (l, r) => (IsValid: (l-r == step), l-r))
.Where(diff => diff.IsValid)
.Distinct()
.Count() == 1;
Old question, but here's an easy way using some simple algebra.
This only works if your integers start at 1 though.
public bool AreIntegersConsecutive(List<int> integers)
{
var sum = integers.Sum();
var count = integers.Count();
var expectedSum = (count * (count + 1)) / 2;
return expectedSum == sum;
}
It is works for unique list only.
List<Int32> dansConList = new List<Int32>();
dansConList.Add(7);
dansConList.Add(8);
dansConList.Add(9);
bool b = (dansConList.Min() + dansConList.Max())*((decimal)dansConList.Count())/2.0m == dansConList.Sum();
Here is an extension method that uses the Aggregate function.
public static bool IsConsecutive(this List<Int32> value){
return value.OrderByDescending(c => c)
.Select(c => c.ToString())
.Aggregate((current, item) =>
(item.ToInt() - current.ToInt() == -1) ? item : ""
)
.Any();
}
Usage:
var consecutive = new List<Int32>(){1,2,3,4}.IsConsecutive(); //true
var unorderedConsecutive = new List<Int32>(){1,4,3,2}.IsConsecutive(); //true
var notConsecutive = new List<Int32>(){1,5,3,4}.IsConsecutive(); //false
Here is a C version code, I think it's easy to rewrite it in other language based on the logical.
int isConsecutive(int *array, int length) {
int i = 1;
for (; i < length; i++) {
if (array[i] != array[i - 1] + 1)
return 0; //which means false and it's not a consecutive list
}
return 1;
}

How to determine that one array is a part of another one?

For instance: I have array
var src = new byte[] {1, 2, 3, 4, 5};
var tag = new byte[] {3, 4};
Who know fast method to find index of tag's array?
I need something as following:
int FindIndexOfSeq(byte[] src, byte[] sequence);
a sequence can be in more than one times in src.
Solution: How to find index of sublist in list?
The best you can get is O(m), but that I slightly complex implementation. If you satisfy with a solution that has O(m*n) as worst case you can go with the solution below. If your sequences are ordered and the starting item in the tag array is only present one time in src this will also result in O(m).
class Program
{
static void Main(string[] args)
{
var src = new byte[] { 1, 2, 3, 4, 5 };
var tag = new byte[] { 3, 4 };
var index = FindIndexOfSeq(src, tag);
Console.WriteLine(index);
Console.ReadLine();
}
static int FindIndexOfSeq<T>(T[] src, T[] seq)
{
int index = -1;
for (int i = 0; i < src.Length - seq.Length + 1; i++)
{
bool foundSeq = true;
for (int j = 0; j < seq.Length; j++)
{
foundSeq = foundSeq && src[i + j].Equals(seq[j]);
}
if (foundSeq)
{
index = i;
break;
}
}
return index;
}
}
I assumed the sequence have to be in that order and I have only compiled it in firefox, so not sure if it works :). Also, I made it generic so it handles any type of arrays not just bytes.
UPDATE: The updated code compiles and work... or my simple test worked.
Here's one way to the get the index
for (int i = 0; i < (src.Length - tag.Length); i++ )
{
if (tag.SequenceEqual(src.Skip(i).Take(tag.Length)))
Console.WriteLine("It's at position " + i);
}
Unfortunately it's very slow.
If you just want to know if all of items in tag can be found in src (in any order) then
var src = new byte[] { 1, 2, 3, 4, 5 };
var tag = new byte[] { 4, 3 };
if (src.Intersect(tag).Count() == tag.Length)
Console.WriteLine("tag can be found in src!");
int FindIndexOfSeq<T>(byte[] src, byte[] tag)
{
Int32 tagCount = tag.Count();
// If `tag` is not empty and `src` contains `tag`
if (tagCount > 0 && src.Intersect(tag).Count() == tagCount)
{
// Find index of first element in `tag`
Int32 tagStartIndex = Array.IndexOf(src, tag.First());
// Get the matching slice of `tag` from `src`
var newSrc = src.Skip(tagStartIndex).Take(tag.Count()).ToList();
// Zip them together using their difference
var sum = Enumerable.Zip(tag, newSrc, (i1, i2) => Convert.ToInt32(i2 - i1)).Sum();
// If total of their differences is zero, both sequences match
if (sum == 0)
{
// return starting index of `tag` in `src`
return tagStartIndex;
}
}
// return `Not Found`
return -1;
}
This task is equal to searching substring in string. For this you may use any KMP algorithm for better performance:
http://exclusiveminds.com/2009/12/09/kmp-string-searching-algorithm-in-c/
Solution found.
How to find index of sublist in list?

Categories