c# convert byte array of ascii values to integer array - c#

I have a byte array of 50 bytes representing 5 integers as ascii characters values. Every integer value is represented as 10 bytes:
byte[] receiveBytes = new byte[] {
20, 20, 20, 20, 20, 20, 20, 20, 20, 49, // 9 spaces then '1'
20, 20, 20, 20, 20, 20, 20, 20, 20, 50, // 9 spaces then '2'
20, 20, 20, 20, 20, 20, 49, 50, 51, 52, // 6 spaces then '1' '2' '3' '4'
20, 20, 20, 20, 20, 20, 53, 56, 48, 49, // 6 spaces then '5' '8' '0' '1'
20, 20, 20, 20, 20, 20, 20, 57, 57, 57}; // 7 spaces then '9' '9' '9'
Please, notice that 20 is an ascii code of space and [48..57] are ascii codes of 0..9 digits.
How can I convert the byte array to an integer array (int[] intvalues == [1, 2, 1234, 5801, 999])?
I have tried first to convert byte array to string and then string to integer like this:
string[] asciival = new string[10];
int[] intvalues = new int[5];
Byte[] receiveBytes = '20202020202020202049 //int value = 1
20202020202020202050 //int value = 2
20202020202049505152 //int value = 1234
20202020202053564849 //int value =5801
20202020202020575757';//int value = 999
asciival[0] = Encoding.ASCII.GetString(receiveBytes, 0, 10);
asciival[1] = Encoding.ASCII.GetString(receiveBytes, 10, 10);
intvalues[0] = int.Parse(asciival[0]);
intvalues[1] = int.Parse(asciival[1]);
But isn't there a simpler way to copy the byte array into the string array?

A for loop can simplify the writing:
byte[] recv = new byte[]{ /* ... */ }
int[] intvalues = new int[recv.Length / 10];
for(int pos = 0; pos < recv.Length; pos += 10)
intvalues[pos / 10] = int.Parse(Encoding.ASCII.GetString(recv, pos, pos + 10));

I suggest using Linq:
Split initial array on 10-items (i.e. 10-byte) chunks
Filter digits ('0'..'9' ) in each chunk
Aggergate digits into a single integer
Implementation:
using System.Linq;
...
Byte[] receiveBytes = new byte[] {
20, 20, 20, 20, 20, 20, 20, 20, 20, 49, // 9 spaces then '1'
20, 20, 20, 20, 20, 20, 20, 20, 20, 50, // 9 spaces then '2'
20, 20, 20, 20, 20, 20, 49, 50, 51, 52, // 6 spaces then '1' '2' '3' '4'
20, 20, 20, 20, 20, 20, 53, 56, 48, 49, // 6 spaces then '5' '8' '0' '1'
20, 20, 20, 20, 20, 20, 20, 57, 57, 57}; // 7 spaces then '9' '9' '9'
int[] intvalues = Enumerable.Range(0, receiveBytes.Length / 10)
.Select(index => receiveBytes
.Skip(index * 10) // Skip + Take: splitting on 10-items chunks
.Take(10)
.Where(b => b >= '0' && b <= '9') // just digits
.Aggregate(0, (s, a) => s * 10 + a - '0'))
.ToArray();
Test
Console.Write(string.Join(", ", intvalues));
Outcome:
1, 2, 1234, 5801, 999
Please, notice, that 10 digits number can well overflow int since maximum int value (int.MaxValue) is 2147483647 only. To represent the initial byte[] as a string you can use Linq once again:
var result = Enumerable
.Range(0, receiveBytes.Length / 10)
.Select(index => receiveBytes
.Skip(index * 10) // Skip + Take: splitting on 10-items chunks
.Take(10)
.Select(b => b.ToString("00"))) // enforce leading "0" if necessary
.Select(items => string.Concat(items));
string text = string.Join(Environment.NewLine, result);
Console.Write(text);
Outcome
20202020202020202049
20202020202020202050
20202020202049505152
20202020202053564849
20202020202020575757

You can try this :-
using System;
using System.Text;
class Example
{
public static void Main()
{
// Define a string.
String original = "ASCII Encoding";
// Instantiate an ASCII encoding object.
ASCIIEncoding ascii = new ASCIIEncoding();
// Create an ASCII byte array.
Byte[] bytes = ascii.GetBytes(original);
// Display encoded bytes.
Console.Write("Encoded bytes (in hex): ");
foreach (var value in bytes)
Console.Write("{0:X2} ", value);
Console.WriteLine(); // Decode the bytes and display the resulting Unicode string.
String decoded = ascii.GetString(bytes);
Console.WriteLine("Decoded string: '{0}'", decoded);
}
}

Related

Reading byte array and converting into float in C#

I know there are many questions related to it but still they are not solving my problem. Below is my byte array:
As you can see that the byte is of 28 and each 4-byte value represents a single value i.e. I have a client machine which sent me 2.4 and while reading it, it is then converted into bytes.
//serial port settings and opening it
var serialPort = new SerialPort("COM2", 9600, Parity.Even, 8, StopBits.One);
serialPort.Open();
var stream = new SerialStream(serialPort);
stream.ReadTimeout = 2000;
// send request and waiting for response
// the request needs: slaveId, dataAddress, registerCount
var responseBytes = stream.RequestFunc3(slaveId, dataAddress, registerCount);
// extract the content part (the most important in the response)
var data = responseBytes.ToResponseFunc3().Data;
What I want to do?
Convert each 4 byte one by one to hex, save them In a separate variable. Like
hex 1 = byte[0], hex2 = byte[1], hex3 = byte[2], hex4 = byte[3]
..... hex28 = byte[27]
Combine 4-byte hex value and then convert them into float and assign them a variable to hold floating value. Like
v1 = Tofloat(hex1,hex2,hex3,hex4); // assuming ToFloat() is a function.
How can I achieve it?
Since you mentioned that the first value is 2.4 and each float is represented by 4 bytes;
byte[] data = { 64, 25, 153, 154, 66, 157, 20, 123, 66, 221, 174, 20, 65, 204, 0, 0, 65, 163, 51, 51, 66, 95, 51, 51, 69, 10, 232, 0 };
We can group the bytes into 4 byte blocks and reverse them and convert each part to float like:
int offset = 0;
float[] dataFloats =
data.GroupBy(x => offset++ / 4) // group by 4. 0/4 = 0, 1/4 = 0, 2/4 = 0, 3/4 = 0 and 4/4 = 1 etc.
// Need to reverse the bytes to make them evaluate to 2.4
.Select(x => BitConverter.ToSingle(x.ToArray().Reverse().ToArray(), 0))
.ToArray();
Now you have an array of 7 floats:

How to revert array to orginal form after conditional permute

My code:
var unpermuted = new byte[]{137, 208, 135, 4, 191, 255, 132, 99, 85, 54, 58, 137, 208, 37, 151, 30};
var longKey = new byte[] {75, 79, 84, 69, 197, 129, 75, 65, 74, 65, 75, 75, 79, 84, 69, 197, 129, 75, 65, 74, 65};
var permuted = (byte[])unpermuted.Clone();
for(var i = 0; i < permuted.Length;i++)
{
if (i > 1 && (permuted[i] < longKey[i]))
{
var swapCont = permuted[i - 1];
permuted[i - 1] = permuted[i];
permuted[i] = swapCont;
}
}
printArr(unpermuted);
Console.WriteLine();
printArr(permuted);
// How do I reverse permuted array to unpermuted?
Console.WriteLine();
printArr(permuted);
}
public static void printArr(byte[] arr)
{
for(var i = 0; i < arr.Length;i++)
{
Console.Write(arr[i]);
Console.Write(" ");
}
}
I have unpermute array, make deep copy, and after this, if keyValue is higher than value, I swap with previous element.
And the question is:
How to revert permuted array to unpermuted form having only LongKey Array and Permuted array?
It's not possible to "unpermute" the array, given the information that you have.
Imagine that you have the following:
longkey = [1,2,3,9,5]
array = [3,4,9,5,6]
Running your code, the result will be [3,4,5,9,6].
But if the original array is [3,4,5,9,6], the result is the same.
As you can see, there are multiple permutations of the original array that give the same output. And there's not enough information in the result and the longkey array to tell you what the original array was.
In general, if you have a 3-item sequence anywhere in which the following is true, then it's not possible to reliably reverse the operation.
longkey = [b, c, d]
array = [x, y, z]
Where:
b <= x, b <= y
c < x, c > y
d <= z
For example:
longkey = [...,3,9,5,...]
array = [...,9,5,6,...]
The key here is that the 9 can never swap with the thing to its left, and the 6 will never swap with the 5. So the 5 and 9 cannot move except to swap places with each other. If the original order is [9,5,6], the final order will be [5,9,6]. And if the original order is [5,9,6], the result is, again, [5,9,6].

Find all k-size subsets with sum s of an n-size bag of duplicate unsorted positive integers

Please note that this is required for a C# .NET 2.0 project (Linq not allowed).
I know very similar questions have been asked here and I have already produce some working code (see below) but still would like an advice as to how to make the algorithm faster given k and s conditions.
This is what I've learnt so far:
Dynamic programming is the most efficient way to finding ONE (not all) subsets. Please correct me if I am wrong. And is there a way of repeatedly calling the DP code to produce newer subsets till the bag (set with duplicates) is exhausted?
If not, then is there a way that may speed up the backtracking recursive algorithm I have below which does produce what I need but runs in O(2^n), I think, by taking s and k into account?
Here is my fixed bag of numbers that will NEVER change with n=114 and number range from 3 to 286:
int[] numbers = new int[]
{
7, 286, 200, 176, 120, 165, 206, 75, 129, 109,
123, 111, 43, 52, 99, 128, 111, 110, 98, 135,
112, 78, 118, 64, 77, 227, 93, 88, 69, 60,
34, 30, 73, 54, 45, 83, 182, 88, 75, 85,
54, 53, 89, 59, 37, 35, 38, 29, 18, 45,
60, 49, 62, 55, 78, 96, 29, 22, 24, 13,
14, 11, 11, 18, 12, 12, 30, 52, 52, 44,
28, 28, 20, 56, 40, 31, 50, 40, 46, 42,
29, 19, 36, 25, 22, 17, 19, 26, 30, 20,
15, 21, 11, 8, 8, 19, 5, 8, 8, 11,
11, 8, 3, 9, 5, 4, 7, 3, 6, 3,
5, 4, 5, 6
};
Requirements
Space limit to 2-3GB max but time should be O(n^something) not
(something^n).
The bag must not be sorted and duplicate must not be removed.
The result should be the indices of the numbers in the matching
subset, not the numbers themselves (as we have duplicates).
Dynamic Programming Attempt
Here is the C# dynamic programming version adapted from an answer to a similar question here on stackoverflow.com:
using System;
using System.Collections.Generic;
namespace Utilities
{
public static class Combinations
{
private static Dictionary<int, bool> m_memo = new Dictionary<int, bool>();
private static Dictionary<int, KeyValuePair<int, int>> m_previous = new Dictionary<int, KeyValuePair<int, int>>();
static Combinations()
{
m_memo.Clear();
m_previous.Clear();
m_memo[0] = true;
m_previous[0] = new KeyValuePair<int, int>(-1, 0);
}
public static bool FindSubset(IList<int> set, int sum)
{
//m_memo.Clear();
//m_previous.Clear();
//m_memo[0] = true;
//m_previous[0] = new KeyValuePair<int, int>(-1, 0);
for (int i = 0; i < set.Count; ++i)
{
int num = set[i];
for (int s = sum; s >= num; --s)
{
if (m_memo.ContainsKey(s - num) && m_memo[s - num] == true)
{
m_memo[s] = true;
if (!m_previous.ContainsKey(s))
{
m_previous[s] = new KeyValuePair<int, int>(i, num);
}
}
}
}
return m_memo.ContainsKey(sum) && m_memo[sum];
}
public static IEnumerable<int> GetLastIndex(int sum)
{
while (m_previous[sum].Key != -1)
{
yield return m_previous[sum].Key;
sum -= m_previous[sum].Value;
}
}
public static void SubsetSumMain(string[] args)
{
int[] numbers = new int[]
{
7, 286, 200, 176, 120, 165, 206, 75, 129, 109,
123, 111, 43, 52, 99, 128, 111, 110, 98, 135,
112, 78, 118, 64, 77, 227, 93, 88, 69, 60,
34, 30, 73, 54, 45, 83, 182, 88, 75, 85,
54, 53, 89, 59, 37, 35, 38, 29, 18, 45,
60, 49, 62, 55, 78, 96, 29, 22, 24, 13,
14, 11, 11, 18, 12, 12, 30, 52, 52, 44,
28, 28, 20, 56, 40, 31, 50, 40, 46, 42,
29, 19, 36, 25, 22, 17, 19, 26, 30, 20,
15, 21, 11, 8, 8, 19, 5, 8, 8, 11,
11, 8, 3, 9, 5, 4, 7, 3, 6, 3,
5, 4, 5, 6
};
int sum = 400;
//int size = 4; // don't know to use in dynamic programming
// call dynamic programming
if (Numbers.FindSubset(numbers, sum))
{
foreach (int index in Numbers.GetLastIndex(sum))
{
Console.Write((index + 1) + "." + numbers[index] + "\t");
}
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
}
}
}
Recursive Programming Attempt
and Here is the C# recursive programming version adapted from an answer to a similar question here on stackoverflow.com:
using System;
using System.Collections.Generic;
namespace Utilities
{
public static class Combinations
{
private static int s_count = 0;
public static int CountSubsets(int[] numbers, int index, int current, int sum, int size, List<int> result)
{
if ((numbers.Length <= index) || (current > sum)) return 0;
if (result == null) result = new List<int>();
List<int> temp = new List<int>(result);
if (current + numbers[index] == sum)
{
temp.Add(index);
if ((size == 0) || (temp.Count == size))
{
s_count++;
}
}
else if (current + numbers[index] < sum)
{
temp.Add(index);
CountSubsets(numbers, index + 1, current + numbers[index], sum, size, temp);
}
CountSubsets(numbers, index + 1, current, sum, size, result);
return s_count;
}
private static List<List<int>> m_subsets = new List<List<int>>();
public static List<List<int>> FindSubsets(int[] numbers, int index, int current, int sum, int size, List<int> result)
{
if ((numbers.Length <= index) || (current > sum)) return m_subsets;
if (result == null) result = new List<int>();
List<int> temp = new List<int>(result);
if (current + numbers[index] == sum)
{
temp.Add(index);
if ((size == 0) || (temp.Count == size))
{
m_subsets.Add(temp);
}
}
else if (current + numbers[index] < sum)
{
temp.Add(index);
FindSubsets(numbers, index + 1, current + numbers[index], sum, size, temp);
}
FindSubsets(numbers, index + 1, current, sum, size, result);
return m_subsets;
}
public static void SubsetSumMain(string[] args)
{
int[] numbers = new int[]
{
7, 286, 200, 176, 120, 165, 206, 75, 129, 109,
123, 111, 43, 52, 99, 128, 111, 110, 98, 135,
112, 78, 118, 64, 77, 227, 93, 88, 69, 60,
34, 30, 73, 54, 45, 83, 182, 88, 75, 85,
54, 53, 89, 59, 37, 35, 38, 29, 18, 45,
60, 49, 62, 55, 78, 96, 29, 22, 24, 13,
14, 11, 11, 18, 12, 12, 30, 52, 52, 44,
28, 28, 20, 56, 40, 31, 50, 40, 46, 42,
29, 19, 36, 25, 22, 17, 19, 26, 30, 20,
15, 21, 11, 8, 8, 19, 5, 8, 8, 11,
11, 8, 3, 9, 5, 4, 7, 3, 6, 3,
5, 4, 5, 6
};
int sum = 17;
int size = 2;
// call backtracking recursive programming
Console.WriteLine("CountSubsets");
int count = Numbers.CountSubsets(numbers, 0, 0, sum, size, null);
Console.WriteLine("Count = " + count);
Console.WriteLine();
// call backtracking recursive programming
Console.WriteLine("FindSubsets");
List<List<int>> subsets = Numbers.FindSubsets(numbers, 0, 0, sum, size, null);
for (int i = 0; i < subsets.Count; i++)
{
if (subsets[i] != null)
{
Console.Write((i + 1).ToString() + ":\t");
for (int j = 0; j < subsets[i].Count; j++)
{
int index = subsets[i][j];
Console.Write((index + 1) + "." + numbers[index] + " ");
}
Console.WriteLine();
}
}
Console.WriteLine("Count = " + subsets.Count);
Console.ReadKey();
}
}
}
Please let me know how to restrict the dynamic programming version to subsets of size k and if I can call it repeatedly so it returns different subsets on every call until there are no more matching subsets.
Also I am not sure where to initialize the memo of the DP algorithm. I did it in the static constructor which auto-runs when accessing any method. Is this the correct initialization place or does it need to be moved to inside the FindSunset() method [commented out]?
As for the recursive version, is it backtracking? and how can we speed it up. It works correctly and takes k and s into account but totally inefficient.
Let's make this thread the mother of all C# SubsetSum related questions!
My previous answer works on the principle of cutting off the number of combinations to check. But this can be improved significantly once you sort the array. The principle is similar, but since the solution is entirely different, I've decided to put it in a separate answer.
I was careful to use only .Net Framework 2.0 features. Might add a visual explanation later, but the comments should be enough.
class Puzzle
{
private readonly int[] _tailSums;
public readonly SubsetElement[] Elements;
public readonly int N;
public Puzzle(int[] numbers)
{
// Set N and make Elements array
// (to remember the original index of each element)
this.N = numbers.Length;
this.Elements = new SubsetElement[this.N];
for (var i = 0; i < this.N; i++)
{
this.Elements[i] = new SubsetElement(numbers[i], i);
}
// Sort Elements descendingly by their Number value
Array.Sort(this.Elements, (a, b) => b.Number.CompareTo(a.Number));
// Save tail-sums to allow immediate access by index
// Allow immedate calculation by index = N, to sum 0
this._tailSums = new int[this.N + 1];
var sum = 0;
for (var i = this.N - 1; i >= 0; i--)
{
this._tailSums[i] = sum += this.Elements[i].Number;
}
}
public void Solve(int s, Action<SubsetElement[]> callback)
{
for (var k = 1; k <= this.N; k++)
this.Solve(k, s, callback);
}
public void Solve(int k, int s, Action<SubsetElement[]> callback)
{
this.ScanSubsets(0, k, s, new List<SubsetElement>(), callback);
}
private void ScanSubsets(int startIndex, int k, int s,
List<SubsetElement> subset, Action<SubsetElement[]> cb)
{
// No more numbers to add, and current subset is guranteed to be valid
if (k == 0)
{
// Callback with current subset
cb(subset.ToArray());
return;
}
// Sum the smallest k elements
var minSubsetStartIndex = this.N - k;
var minSum = this._tailSums[minSubssetStartIndex];
// Smallest possible sum is greater than wanted sum,
// so a valid subset cannot be found
if (minSum > s)
{
return;
}
// Find largest number that satisfies the condition
// that a valid subset can be found
minSum -= this.Elements[minSubsetStartIndex].Number;
// But remember the last index that satisfies the condition
var minSubsetEndIndex = minSubsetStartIndex;
while (minSubsetStartIndex > startIndex &&
minSum + this.Elements[minSubsetStartIndex - 1].Number <= s)
{
minSubsetStartIndex--;
}
// Find the first number in the sorted sequence that is
// the largest number we just found (in case of duplicates)
while (minSubsetStartIndex > startIndex &&
Elements[minSubsetStartIndex] == Elements[minSubsetStartIndex - 1])
{
minSubsetStartIndex--;
}
// [minSubsetStartIndex .. maxSubsetEndIndex] is the
// full range we must check in recursion
for (var subsetStartIndex = minSubsetStartIndex;
subsetStartIndex <= minSubsetEndIndex;
subsetStartIndex++)
{
// Find the largest possible sum, which is the sum of the
// k first elements, starting at current subsetStartIndex
var maxSum = this._tailSums[subsetStartIndex] -
this._tailSums[subsetStartIndex + k];
// The largest possible sum is less than the wanted sum,
// so a valid subset cannot be found
if (maxSum < s)
{
return;
}
// Add current number to the subset
var x = this.Elements[subsetStartIndex];
subset.Add(x);
// Recurse through the sub-problem to the right
this.ScanSubsets(subsetStartIndex + 1, k - 1, s - x.Number, subset, cb);
// Remove current number and continue loop
subset.RemoveAt(subset.Count - 1);
}
}
public sealed class SubsetElement
{
public readonly int Number;
public readonly int Index;
public SubsetElement(int number, int index)
{
this.Number = number;
this.Index = index;
}
public override string ToString()
{
return string.Format("{0}({1})", this.Number, this.Index);
}
}
}
Usage and performance testing:
private static void Main()
{
var sw = Stopwatch.StartNew();
var puzzle = new Puzzle(new[]
{
7, 286, 200, 176, 120, 165, 206, 75, 129, 109,
123, 111, 43, 52, 99, 128, 111, 110, 98, 135,
112, 78, 118, 64, 77, 227, 93, 88, 69, 60,
34, 30, 73, 54, 45, 83, 182, 88, 75, 85,
54, 53, 89, 59, 37, 35, 38, 29, 18, 45,
60, 49, 62, 55, 78, 96, 29, 22, 24, 13,
14, 11, 11, 18, 12, 12, 30, 52, 52, 44,
28, 28, 20, 56, 40, 31, 50, 40, 46, 42,
29, 19, 36, 25, 22, 17, 19, 26, 30, 20,
15, 21, 11, 8, 8, 19, 5, 8, 8, 11,
11, 8, 3, 9, 5, 4, 7, 3, 6, 3,
5, 4, 5, 6
});
puzzle.Solve(2, 17, PuzzleOnSubsetFound);
sw.Stop();
Console.WriteLine("Subsets found: " + _subsetsCount);
Console.WriteLine(sw.Elapsed);
}
private static int _subsetsCount;
private static void PuzzleOnSubsetFound(Puzzle.SubsetElement[] subset)
{
_subsetsCount++;
return; // Skip prints when speed-testing
foreach (var el in subset)
{
Console.Write(el.ToString());
Console.Write(" ");
}
Console.WriteLine();
}
Output:
Each line is a found subset, numbers in () are the original index of the number used in the subset
14(60) 3(107)
14(60) 3(109)
14(60) 3(102)
13(59) 4(105)
13(59) 4(111)
12(64) 5(96)
12(64) 5(104)
12(64) 5(112)
12(64) 5(110)
12(65) 5(96)
12(65) 5(104)
12(65) 5(112)
12(65) 5(110)
11(100) 6(108)
11(100) 6(113)
11(61) 6(108)
11(61) 6(113)
11(92) 6(108)
11(92) 6(113)
11(62) 6(108)
11(62) 6(113)
11(99) 6(108)
11(99) 6(113)
9(103) 8(93)
9(103) 8(94)
9(103) 8(97)
9(103) 8(98)
9(103) 8(101)
Subsets found: 28
00:00:00.0017020 (measured when no printing is performed)
The higher k is, the more cutoffs can be made. This is when you'll see the major performance difference. Your current code (the recursive version) also performs significantly slower when s is goes higher.
With k=5, s=60
Your current code: found 45070 subsets in 2.8602923 seconds
My code: found 45070 subsets in 0.0116727 seconds
That is 99.6% speed improvement
There are multiple solutions, but nobody showed how to use dynamic programming to find the answer.
The key is to use dynamic programming to build up a data structure from which all solutions can later be found.
In addition to the requested function, I collected information about how many solutions there are, and wrote FindSolution(node, position) to return the solution at position position starting with node without calculating the rest. If you want all of them, using that function would be inefficient. But, for example, with this function it is doable to calculate the billionth way to express 10000 as a sum of 20 primes. That would not be feasible with the other approaches given.
using System;
using System.Collections.Generic;
public class SubsetSum
{
public class SolutionNode<T>
{
// The index we found the value at
public int Index {get; set;}
// The value we add for this solution
public T Value {get; set;}
// How many solutions we have found.
public int Count {get; set;}
// The rest of this solution.
public SolutionNode<T> Tail {get; set;}
// The next solution.
public SolutionNode<T> Next {get; set;}
}
// This uses dynamic programming to create a summary of all solutions.
public static SolutionNode<int> FindSolution(int[] numbers, int target, int subsetSize)
{
// By how many are in our list, by what they sum to, what SolutionNode<int> has our answer?
List<Dictionary<int, SolutionNode<int>>> solutionOf = new List<Dictionary<int, SolutionNode<int>>>();
// Initialize empty solutions.
for (int i = 0; i <= subsetSize; i++)
{
solutionOf.Add(new Dictionary<int, SolutionNode<int>>());
}
// We discover from the last number in the list forward.
// So discovering from the last index forward makes them ordered.
for (int i = numbers.Length - 1; -1 < i; i--)
{
int number = numbers[i];
// Descending here so we don't touch solutionOf[j-1] until after we have solutionOf[j] updated.
for (int j = subsetSize; 0 < j; j--)
{
// All previously found sums with j entries
Dictionary<int, SolutionNode<int>> after = solutionOf[j];
// All previously found sums with j-1 entries
Dictionary<int, SolutionNode<int>> before = solutionOf[j-1];
foreach (KeyValuePair<int, SolutionNode<int>> pair in before)
{
SolutionNode<int> newSolution = new SolutionNode<int>();
int newSum = pair.Key + number;
newSolution.Index = i;
newSolution.Value = number;
newSolution.Count = pair.Value.Count;
newSolution.Tail = pair.Value;
if (after.ContainsKey(newSum))
{
newSolution.Next = after[newSum];
newSolution.Count = pair.Value.Count + after[newSum].Count;
}
after[newSum] = newSolution;
}
// And special case empty set.
if (1 == j)
{
SolutionNode<int> newSolution = new SolutionNode<int>();
newSolution.Index = i;
newSolution.Value = number;
newSolution.Count = 1;
if (after.ContainsKey(number))
{
newSolution.Next = after[number];
newSolution.Count = after[number].Count;
}
after[number] = newSolution;
}
}
}
// Return what we found.
try
{
return solutionOf[subsetSize][target];
}
catch
{
throw new Exception("No solutions found");
}
}
// The function we were asked for.
public static IEnumerable<List<int>> ListSolutions (SolutionNode<int> node)
{
List<int> solution = new List<int>();
List<SolutionNode<int>> solutionPath = new List<SolutionNode<int>>();
// Initialize with starting information.
solution.Add(0); // This will be removed when we get node
solutionPath.Add(node); // This will be our start.
while (0 < solutionPath.Count)
{
// Erase the tail of our previous solution
solution.RemoveAt(solution.Count - 1);
// Pick up our next.
SolutionNode<int> current = solutionPath[solutionPath.Count - 1];
solutionPath.RemoveAt(solutionPath.Count - 1);
while (current != null)
{
solution.Add(current.Index);
solutionPath.Add(current.Next);
if (current.Tail == null)
{
yield return solution;
}
current = current.Tail;
}
}
}
// And for fun, a function that dynamic programming makes easy - return any one of them!
public static List<int> FindSolution(SolutionNode<int> node, int position)
{
// Switch to counting from the end.
position = node.Count - position - 1;
List<int> solution = new List<int>();
while (node != null)
{
while (node.Next != null && position < node.Next.Count)
{
node = node.Next;
}
solution.Add(node.Index);
node = node.Tail;
}
return solution;
}
public static void Main(string[] args)
{
SolutionNode<int> solution = FindSolution(
new[]{
7, 286, 200, 176, 120, 165, 206, 75, 129, 109,
123, 111, 43, 52, 99, 128, 111, 110, 98, 135,
112, 78, 118, 64, 77, 227, 93, 88, 69, 60,
34, 30, 73, 54, 45, 83, 182, 88, 75, 85,
54, 53, 89, 59, 37, 35, 38, 29, 18, 45,
60, 49, 62, 55, 78, 96, 29, 22, 24, 13,
14, 11, 11, 18, 12, 12, 30, 52, 52, 44,
28, 28, 20, 56, 40, 31, 50, 40, 46, 42,
29, 19, 36, 25, 22, 17, 19, 26, 30, 20,
15, 21, 11, 8, 8, 19, 5, 8, 8, 11,
11, 8, 3, 9, 5, 4, 7, 3, 6, 3,
5, 4, 5, 6}
, 400, 4);
IEnumerable<List<int>> listing = ListSolutions(solution);
foreach (List<int> sum in listing)
{
Console.WriteLine ("solution {0}", string.Join(", ", sum.ToArray()));
}
}
}
Incidentally this is my first time trying to write C#. It was...painfully verbose.
Simply search for all combinations of size K, and check each if it satisfies the condition.
The fastest algorithm for k combinations, suiting your case, would be:
for (var i1 = 0; i1 <= n; i1++)
{
for (var i2 = i1 + 1; i2 <= n; i2++)
{
for (var i3 = i2 + 1; i3 <= n; i3++)
{
...
for (var ik = iOneBeforeK + 1; ik <= n; ik++)
{
if (arr[i1] + arr[i2] + ... + arr[ik] == sum)
{
// this is a valid subset
}
}
}
}
}
But you are talking about numbers and summing them up, meaning you could make cutoffs with a smarter algorithm.
Since all numbers are positive, you know that if a single number is big enough, you cannot add to it any more positive numbers and have it sum up to s. Given s=6 and k=4, the highest number to include in the search is s-k+1=3. 3+1+1+1 is k numbers, 1 being your lowest possible number, sums up to 6. Any number above 3 couldn't have 3 other positives added to it, and have the sum <= 6.
But wait, your minimum possible value isn't 1, it is 3. That's even better. So assume k=10, n=60, min=3. The "highest number scenario" is x+min(k-1)=n -> x=60-3*9=33. So the highest number to even consider would be 33.
This cuts the amount of relevant numbers in the array to consider, hence it cuts the amount of combinations to look for.
But it gets even better. Assume k=10, n=60, min=3. The first number in the array happens to be 20, so it is relevant and should be checked. Lets find the relevant subsets that include that 20:
A new "puzzle" appears! k=10-1, n=60-20, min=3. You can now cutoff many numbers from the subpuzzle, and again and again which each step further in.
This can be improved even further by calculating the average of the k-1 lowest numbers in the subpuzzle and use that as min.
It is possible to improve this even further by precalculating the k lowest numbers average in subpuzzle [0..n], and k-1 lowest numbers average in subpuzzle [1..n], and k-2 lowest numbers average in subpuzzle [2..n] and so on, and use them instead of recalculating same stuff again and again within each subpuzzle assessment.
Try to use code below. Sorry, i had not time to optimise code. You can compare all methods that you have, and and make conclusion which is faster, don't forgot to share results.
C# (you can try to rid from List may be it will give you performance improvement:
public static IEnumerable<List<int>> findSubsetsWithLengthKAndSumS2(Tuple<int, int> ks, List<int> set, List<int> subSet, List<int> subSetIndex)
{
if (ks.Item1 == 0 && ks.Item2 == 0)
{
var res = new List<List<int>>();
res.Add(subSetIndex);
return res;
}
else if (ks.Item1 > 0 && ks.Item2 > 0)
{
var res = set.Select((x, i) =>
{
var newSubset = subSet.Select(y => y).ToList();
newSubset.Add(x);
var newSubsetIndex = subSetIndex.Select(y => y).ToList();
newSubsetIndex.Add(i);
var newSet = set.Skip(i).ToList();
return findSubsetsWithLengthKAndSumS2(Tuple.Create(ks.Item1 - 1, ks.Item2 - x), newSet, newSubset, newSubsetIndex).ToList();
}
).SelectMany(x => x).ToList();
return res;
}
else
return new List<List<int>>();
}
...
var res = findSubsetsWithLengthKAndSumS2(Tuple.Create(2, 293), numbers.ToList(), new List<int>(), new List<int>());
F# (I added it Just for fun =), it is not optimized too, i beleive the slowest place in code is 'skip' ):
let skip (list:List<int>) index =
list |> List.mapi (fun i x -> if i > index then Some(x) else None) |> List.filter (fun x -> x.IsSome) |> List.map (fun x -> x.Value)
let rec findSubsetsWithLengthKAndSumS (ks:int*int) (set:list<int>) (subSet:list<int>) =
[
match ks with
|0,0 -> yield subSet
| x,y when x > 0 && y > 0 -> yield! set |> List.mapi (fun i x-> findSubsetsWithLengthKAndSumS ((fst ks)-1,(snd ks)-x) (skip set i ) (x::subSet)) |> Seq.concat
| _,_-> yield []
]
...
let res = Subsets.findSubsetsWithLengthKAndSumS (2,293) numbers [] |> List.filter (fun x-> x.Length >0)
I beleive this Iterative version would be faster than others in many times. It uses .net 2.0:
public delegate IEnumerable< IEnumerable< int > > findSubset();
public delegate bool findSubsetsIterativeFilter( int[] sourceSet, int[] indiciesToSum, int expected );
public static bool Summ( int[] sourceSet, int[] indicies, int expected )
{
var sum = 0;
for( int i = 0; i < indicies.Length; i++ )
sum += sourceSet[ indicies[ i ] ];
return sum == expected;
}
public static IEnumerable< IEnumerable< int > > findSubsetsIterative( int k, int[] sourceSet, findSubsetsIterativeFilter specialCondition, int expected )
{
var a = new int[ k ];
for( int i = 0; i < k; i++ )
a[ i ] = i;
var p = k - 1;
while( p >= 0 )
{
if( specialCondition( sourceSet, a, expected ) )
yield return ( int[] )a.Clone();
p = ( a[ k - 1 ] == sourceSet.Length - 1 ) ? p - 1 : k - 1;
if( p >= 0 )
for( int i = k - 1; i >= p; i-- )
a[ i ] = a[ p ] + i - p + 1;
}
}
...
findSubsetsIterative( 2, a, Summ, 293 );
I had measured my code and Yorye's and here is what i get. My code is faster in 4-10x. Did you used 'findSubsetsIterative' from my answer in your experiments?
findSubsetsIterative( 4, GenerateSOurceData(1), Summ, 400 ) Elapsed:
00:00:00.0012113 puzzle.Solve(4, 400, PuzzleOnSubsetFound) Elapsed:
00:00:00.0046170
findSubsetsIterative( 5, GenerateSOurceData(1), Summ, 60 ) Elapsed:
00:00:00.0012960 puzzle.Solve(5, 60, PuzzleOnSubsetFound) Elapsed:
00:00:00.0108568
Here i increased incoming array in 5x (just copied array 5 times into new big array):
findSubsetsIterative( 5, GenerateSOurceData(5), Summ, 60 )
Elapsed: 00:00:00.0013067
puzzle.Solve(5, 60, PuzzleOnSubsetFound)
Elapsed: 00:00:21.3520840
it can be solved by a similar solution as the knapsack problem
dp[i][j][k]=number of k-size subsets with sum equal to j using first "i" elements
dp[i][j][k]=dp[i-1][j][k] + dp[i-1][j-a[i]][k-1]
is the update of the dp (using the ith element or not using it)
for(int i=0;i<=n;i++) dp[i][0][0]=1;
for(int i=1;i<=n;i++){
for(int j=0;j<=w;j++){
for(int k=1;k<=i;k++){
dp[i][j][k]=dp[i-1][j][k] ;
if(j>=a[i-1]){
dp[i][j][k]+=dp[i-1][j-a[i-1]][k-1];
}
}
}
}

Select first k elements in C# LINQ such that the sum of elements is less than S [duplicate]

This question already has answers here:
Linq: How to query items from a collection until the sum reaches a certain value
(2 answers)
Closed 9 years ago.
I have an array of numbers and a variable S. I want to select first k elements out of them using LINQ in C# such that the sum of k elements is less than S.
For example:
int[] Numbers = { 1, 4, 53, 23, 15, 12, 15, 25, 45, 13, 16, 76, 43, 82, 24 };
int S = 100;
The result would be an array: {1, 4, 53, 23, 15}
Take a look at TakeWhile:
int[] Numbers = { 1, 4, 53, 23, 15, 12, 15, 25, 45, 13, 16, 76, 43, 82, 24 };
int total = 0;
var result = Numbers.TakeWhile(i =>
{
total += i;
return total < s
});

Graphing (even with consecutive values)

I have this code:
var temp = allsuminterestarray.OrderBy(i => int.Parse(i)).GroupBy(i => i);
int[] forvaluescount = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50};
int j = 0;
foreach (var val in temp)
{
Console.WriteLine(val.Key + " " + val.Count());
while ((forvaluescount[j] < Convert.ToInt32(val.Key)) && (forvaluescount[j] != Convert.ToInt32(val.Key)))
{
probabilities.Series["Series1"].Points.AddXY(forvaluescount[j], 0/trials);
j++;
}
j++;
probabilities.Series["Series1"].Points.AddXY(val.Key, val.Count()/trials);
}
NOTE: temp has pair values. For example:
(11, 1),
(14, 1),
(18, 1),
(19, 3),
(20, 1),
(21, 3),
(22, 1),
(24, 3),
(27, 1),
(29, 2),
(30, 1),
(31, 2) as X and Y values for a chart in C#.
Basically what happens here is that say i have a value of 11 for val.Key. The code should work such that it will assign to a CHART values of 1-10 as X and 0 as Y. Then 11 as X with its corresponding Y value.
The loop will continue such that there will be no missing values in between the values of temp.
I believe there's nothing wrong with the code as it output consecutive values.
The problem here is that even if i do the plotting of X and Y in order i get a graph like this:
I was expecting a similar image to this (this was generated only with the values of temp:
However there should be no missing plots of (X,0).
Please help and thank you!

Categories