I know that similar questions were asked many times. However I didn't find solution which I need and also cannot find out it myself.
My scenario: I have array of bytes. Now I need to convert them into bits and then create array which will contains exact number of bits.
I am able to convert them into bits and create array of specific length, but only with 8 bits in every index.
My code example:
var blocks = byteArr.Select(byte => Convert.ToString(byte, 2).PadLeft(8, '0'))
.Select((byte, i) => new { Value = byte, Index = i })
.GroupBy(x => x.Index / 100)
.Select(grp => grp.Select(x => x.Value).ToArray())
.ToArray();
It returns array. How you see on the screenshot, it creates array of '100 byte arrays' but what I need is array of '100 bits arrays' or better array of strings where every string has 100 bits.
Thanks for reply and help.
Try the following
var blocks = byteArr.SelectMany(myByte => Convert.ToString(myByte , 2).PadLeft(8, '0'))
.Select((bit, i) => new { Bit = bit, Index = i })
.GroupBy(x => x.Index / 100)
.Select(grp => new string(grp.Select(x => x.Bit).ToArray()))
.ToArray();
The SelectMany will break your binary strings into the individual chars, then you'll group them into sets of 100 by the index. Finally you just create the new string of those "char bits".
Related
My task is to find which integers from a collection are divisible to other integers in another collection. I'm trying to solve this using predicates and functions but I'm a bit stuck. Why is this not working?
Func<List<int>, List<int>, List<int>> func = (x, y) => x.Where(n => y.All(m => m % n == 0)).ToList();
I need to return a list of integers
You have swapped n and m in your check, so you are returning all values (n) in x where all values in y are divisible by n. You could give your variables better names to help prevent these errors:
Func<List<int>, List<int>, List<int>> func =
(dividends, divisors) => dividends.Where(
dividend => divisors.All(divisor => dividend % divisor == 0)
).ToList();
I have a list of Object elements
SourceList ResultList (Expected)
Obj_A Obj_F
Obj_B Obj_C
Obj_C Obj_G
Obj_D Obj_B
Obj_E Obj_A
Obj_F Obj_B
Obj_G Obj_E
Shuffle elements in SourceList such that, no element should come at its original index(in SourceList) in ResultList.
For Example, in SourceList C is at index 2, so it must not come at index 2 in ResultList
So far, i have looked into Dearrangement Wiki , but algo gives me possible arrangements and i need just one.
You can use fisher-yates shuffle as a black box, and repeatidly shuffle your array until your result is a dearrangement.
Pseudo code:
while true:
arr = [1,2,...,n]
shuffle(arr)
flag = true
for i from 0 to n:
if arr[i] == i: //not a dearrangement
flag = false
if flag == true: //it's a dearrangement
break
shuffle(arr): //fisher yates
for i from 0 to n:
j = rand(i,n)
swap(arr,i,j)
Properties of this approach:
This is guaranteed to be uniform and ubiased, because every valid rearrangement
gets exactly the same odds to be picked in each iteration.
Since Fisher-Yates generates all permutations, and we invalidate only dearrangement - every dearrangement is attainable.
The probability to get a dearrangement is 1/e1, this means you are going to need (1-1/e)^-1 ~=1.56 shuffles on the average case, which means this algorithm runs in O(n) expected time complexity.
(1) The number of dearrangements is int(n!/e + 1/2), this means the probability for an array to be a dearrangement is (n!/e + 1/2)/n! ~= 1/e, for large values of n.
This works for me:
var SourceList = new List<string>()
{
"Obj_A", "Obj_B", "Obj_C", "Obj_D", "Obj_E", "Obj_F", "Obj_G",
};
var rnd = new Random();
var ResultList =
Enumerable
// create an exceedingly long sequence for retries
.Repeat(0, int.MaxValue)
// select and randomly order all of the indices of `SourceList`
.Select(_ => Enumerable.Range(0, SourceList.Count)
.OrderBy(x => rnd.Next())
.ToArray())
// Discard the indices if they have any matching positions
.Where(x => !x.Where((y, i) => y == i).Any())
// only take one successful set of indices
.Take(1)
// flatten the list of lists to a list
.SelectMany(x => x)
// select the elements from `SourceList` from their index positions
.Select(x => SourceList[x])
// convert to list
.ToList();
The use of .OrderBy(x => rnd.Next()) produces a uniform ordering (no bias) - I have confirmed this in the past.
Do the shuffle, and get all the elements having index un-changed, then rotate positions for all these faulty ones.
This is the code:
var numbers =
lightningsRegions.SelectMany(
s => Regex.Matches(s, #"\[(\d+)[ -]+(\d+)\]")
.Cast<Match>()
.Select(m => m.Groups.Cast<Group>().Skip(1).Select(x => x.Value)
.ToArray())
.Select(x => new { start = int.Parse(x[0]), end = int.Parse(x[1]) })
.SelectMany(x => Enumerable.Range(x.start, x.end - x.start + 1))
)
.ToList();
for (int i = 0; i < list_of_histogramsR.Count ; i++)
{
if (list_of_histogramsR[i] == numbers[i])
{
}
}
I consider the variable numbers as number of indexs. In the end numbers contain 5372 numbers.
So each number from thr 5272 is like an index.
Now i have this List<long[]> list_of_histogramsR wich contain 16595 indexs.
I want to check that if any number from numbers is in list_of_histogramsR as index number then do something.
For example the first number in numbers is 41. So when index number 41 of list_of_histogramsR == to the number 41 in numbers do something. Then the same for the next numbers in the variable numbers.
The problem is that on the IF line im getting error: Error 33 Operator '==' cannot be applied to operands of type 'long[]' and 'int'
Why ?
You can use Contains to check if the list contains a specific number (cast the int to a long):
list_of_histogramsR[i].Contains((long)numbers[i])
I have a List<byte[]>. Each byte array is of size 16bytes. The first 8 bytes is a binary representation of the C# long data type which I use to stop DateTimeTicks. I wonder whether there is a way to sort a bunch of byte arrays in the same order as if I sorted by the long equivalents in ascending order. Obviously its easy if each byte array is deserialized into a long and then sorted but is there a way to get away without deserialization? If not would it be possible to find a logic to convert a DateTimeTick value into a binary representation so that sorting can be performed directly on the binary by, for example by first expressing year in binary form, then month, day, hour, minute, second, millisecond,..? My goal is to skip the deserialization step because I need to send the sorted byte array over a messaging network in binary format and it currently wastes a lot of resources to have to first deserialize for sorting purpose (sorting has to be done before sending the object over the wire), then serialize it again to send it through the messaging system, then deserialize it again.
Any ideas, hints or solutions highly welcome, thank you.
Edit: I currently use the Linq OrderBy function to sort which is fast enough for my purpose and look something along those lines, performance wise. I would like to stick to Linq unless it is not possible to order by byte array, even if I provided an IComparer...
var rnd = new Random();
var data = new List<byte[]>();
//As long as the first 8 bytes are the long, the byte[] can be as long as you want.
for (int i = 0; i < 10; i++)
data.Add(BitConverter.GetBytes((ulong)rnd.Next()));
//Without any 'deserialisation'
if (BitConverter.IsLittleEndian)
data = data.OrderBy(x => x[7]).ThenBy(x => x[6]).ThenBy(x => x[5]).ThenBy(x => x[4]).ThenBy(x => x[3]).ThenBy(x => x[2]).ThenBy(x => x[1]).ThenBy(x => x[0]).ToList();
else //untested, probably wrong
data = data.OrderBy(x => x[0]).ThenBy(x => x[1]).ThenBy(x => x[2]).ThenBy(x => x[3]).ThenBy(x => x[4]).ThenBy(x => x[5]).ThenBy(x => x[6]).ThenBy(x => x[7]).ToList();
//How I'd actually approach it due to simplicity.
//data = data.OrderBy(x => BitConverter.ToUInt64(x, 0)).ToList();
data.ForEach(x => Console.WriteLine(BitConverter.ToUInt64(x, 0)));
Console.ReadLine();
//There are other approaches of course, but at the fundamental level you're
//either going to 'deserialize' the long or test each byte in order.
I am looking for a concise way to generate an array of integers 1 to 100 in c# , ie
int[] values = {1,2,3 ..., 100};
so that I can use the array in a foreach loop:
foreach (var i in values)
{
// do whatever
}
Any ideas?
Using Enumerable.Range:
Enumerable.Range(1, 100).ToArray();
There's probably not much point in me putting this - Oded's 18 votes (including my own +1) pretty much say it all, but just to point out that if you're then going to use the integers in the array, to produce something - let's say an object - then you can roll the whole thing up.
So, let's say you want some strings:
var strings = Enumerable.Range(1,100)
.Select(i => i.ToString()).ToArray();
Gives you an array of strings.
Or perhaps a MyWidget that's produced from a method call, which uses the index for something:
var myWidgets = Enumerable.Range(1,100)
.Select(i => ProduceMyWidget(i)).ToArray();
If the original foreach code block was more than one line of code - then you just use a {} block
var myWidgets = Enumerable.Range(1,100)
.Select(i => {
if(i == 57)
return ProduceSpecial57Widget(i);
else
ProduceByWidget(i);
}).ToArray();
Obviously this last example is a bit silly - but it illustrates often how a traditional foreach can be replaced with a Select plus ToArray() call.