Algorithm for sum of integers [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Finding all possible combinations of numbers to reach a given sum
I have to create method which from array of numbers selects numbers, which sum will be exact as required one or if such doesn't exist select the minimal greater one.
What would be the algorithm of this function?
public int[] selectExactSum(int[] X, int SUM) {
}
example:
numbers are: {5, 2, 8, 4, 6} and required sum is 12.
The result would be: {2, 4, 6}
If required sum is 13, the result would be:{2, 8, 4} - so, the sum would be in this case 14 - the first minimal greater one.
If Required sum is 15, the possible results would be: {5, 2, 8} or {5, 4, 6}. In this case return the one of your choice - probably the first one you get.
What would be the algorithm for custom numbers and sum?
Thanks,
Simon

This is a generalized case of the problem called subset sum. It's an NP-complete problem, thus the best known algorithm is pseudo-polynomial.
If you understand the above linked algorithm, you can deduct the modification necessary to solve your problem.

How about recursively?
public static int[] SelectExactSum(int[] x, int sum) {
int[]
rest = x.Skip(1).ToArray(),
with = x.Length == 1 ? x : x.Take(1).Concat(SelectExactSum(rest, sum - x[0])).ToArray(),
without = x.Length == 1 ? new int[0] : SelectExactSum(rest, sum);
int withSum = with.Sum(), withoutSum = without.Sum();
return
withSum >= sum ? (withoutSum >= sum ? (withSum < withoutSum ? with : without) : with) :
withoutSum >= sum ? without : new int[0];
}
Note: Calling SelectExactSum(new int[] {5,2,8,4,6}, 13) doesn't return {2,8,4} as stated in the question, but {5,8} as that actually sums up to 13.

Took me about 15 minutes to made it, you can see it running here:
http://jesuso.net/projects/selectExactSum/index.php?numbers=5%2C2%2C8%2C4%2C6&reqSum=15
And here's the code:
http://jesuso.net/projects/selectExactSum/selectExactSum.txt
I made it as simple as possible, but its made on PHP, let me know if you need some help translating it to c#.

Related

Confusing value's used in find Missing number between 1 - X

Hi guys im learning c# currently and Im trying to run threw some interview questions to try and understand them and learn in the process.
I found a question, How do you find the missing number in a given integer array of 1 to 100?
I think I get the General Idea of having to get the sum, Then the Sum of the Sequence then Minus X - Y;
But im confused about the code example below, Why is he using * (arr.Length + 2) When the Equation is n*(n+1)/2 I know its correct but shouldnt this be (arr.Length + 1) * (arr.Length) / 2 According tot he formula
Im terribly confused.
//array to find the missing number between 1 and 10
// Simplicity, We will take number 1 to 10 i where Number 5 is missing in the sequence.
int[] arr = { 1, 2, 3, 4, 6, 7, 8, 9, 10 };
int missingNumber,Totalsum;
// Accoreding to series rule, calculating sum of total numbers upto 10
//sum of first n natutal numbers=n*(n+1)/2
Totalsum = (arr.Length + 1) * (arr.Length + 2) / 2;
// Missing number is calculating.
foreach (int item in arr)
{
Totalsum = Totalsum - item;
}
missingNumber = Totalsum;
Console.WriteLine("missing number : {0}",missingNumber);
Not a Assignment. Just someone trying to learn programming by them selves looking up random questions to learn practically
Where i got the question
https://simpleprogrammer.com/programming-interview-questions/
The Explanation I found
https://www.interviewsansar.com/find-missing-number-between-1-to-n-in-array-in-c/
The comment gives the answer to your question:
// Accoreding to series rule, calculating sum of total numbers upto 10
//sum of first n natutal numbers=n*(n+1)/2
It's just that it's a number sequence that "should have 10 numbers but actually only has 9"
The formula needs n to be 10, but the array has a length of 9. 9+1 is n, 9+2 is n+1

C# formula to determine index

I have a maths issue within my program. I think the problem is simple but I'm not sure what terms to use, hence my own searches returned nothing useful.
I receive some values in a method, the only thing I know (in terms of logic) is the numbers will be something which can be duplicated.
In other words, the numbers I could receive are predictable and would be one of the following
1
2
4
16
256
65536
etc
I need to know at what index they appear at. In othewords, 1 is always at index 0, 2 at index 1, 4 at index 3, 16 is at index 4 etc.
I know I could write a big switch statement but I was hoping a formula would be tidier. Do you know if one exists or any clues as the names of the math forumula's I'm using.
The numbers you listed are powers of two. The inverse function of raising a number to a power is the logarithm, so that's what you use to go backwards from (using your terminology here) a number to an index.
var num = 256;
var ind = Math.Log(num, 2);
Above, ind is the base-2 logarithm of num. This code will work for any base; just substitute that base for 2. If you are only going to be working with powers of 2 then you can use a special-case solution that is faster based on the bitwise representation of your input; see What's the quickest way to compute log2 of an integer in C#?
Try
Math.Log(num, base)
where base is 2
MSDN: http://msdn.microsoft.com/en-us/library/hd50b6h5.aspx
Logarithm will return to You power of base from you number.
But it's in case if your number really are power of 2,
otherwise you have to understand exactly what you have, what you need
It also look like numbers was powered to 2 twice, so that try this:
private static int getIndexOfSeries(UInt64 aNum)
{
if (aNum == 1)
return 0;
else if (aNum == 2)
return 1;
else
{
int lNum = (int)Math.Log(aNum, 2);
return 1+(int)Math.Log(lNum, 2);
}
}
Result for UInt64[] Arr = new UInt64[] { 1, 2, 4, 16, 256, 65536, 4294967296 } is:
Num[0] = 1
Num[1] = 2
Num[2] = 4
Num[3] = 16
Num[4] = 256
Num[5] = 65536
Num[6] = 4294967296 //65536*65536
where [i] - index
You should calculate the base 2 logarithm of the number
Hint: For the results:
0 2
1 4
2 16
3 256
4 65536
5 4294967296
etc.
The formula is, for a give integer x:
Math.Pow(2, Math.Pow(2, x));
that is
2 to the power (2 to the power (x) )
Once the formula is known, one could solve it for x (I won't go through that since you already got an answer).

Distance between two numbers in looping sequence [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Assuming you have a sequence like this: 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, etc. Basically a sequence consisting of N numbers, repeating over and over.
What is the simplest algorithm for finding the distance/difference between two numbers in this sequence? For example the distance from 5 to 7 is +2 and the distance from 0 to 6 is -2. For a more high level view what I have a looping/repeating sequence number, and I need to find out how much "before" or "after" a number is of another on the closest path (fewest number between them).
Assuming X>Y:
dist(X, Y) = min { X-Y, N-(X-Y-1) }
Examples for N = 7:
dist(7, 5) = min {7-5, 7-(7-5-1)} = min {2, 6} = 2
dist(6, 0) = min {6-0, 7-(6-0-1)} = min {6, 2} = 2
dist(5, 1) = min {5-1, 7-(5-1-1)} = min {4, 4} = 4
The last example points a small flaw in your distance definition: Is dist(5, 1) = 4 or dist(5, 1) = -4 ? I've changed your definition a little bit to avoid negative distances (so my algorithm calculates the absolute value of the distance). If you want to keep your definition then make the distance negative if and only if the first argument of the min is greater than the second.
This is quite simple and work with consecutive and non consecutive numbers, maybe make it an extension method :
[TestFixture]
public class NumbersFixture
{
[Test]
public void FindDistance()
{
var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2 };
var num1 = 6;
var num2 = 0;
var from = numbers.IndexOf(num1);
var indexFound = numbers.FindIndex(from, f => f == num2);
var distance = from - indexFound;
var result = string.Format("{0}", distance);
Console.WriteLine(result);
}
}

Custom order by, is it possible?

I have the following collection:
-3, -2, -1, 0, 1, 2, 3
How can I in a single order by statement sort them in the following form:
The negative numbers are sorted first by their (absolute value) then the positive numbers.
-1, -2, -3, 0, 1, 2, 3
Combination sorting, first by the sign, then by the absolute value:
list.OrderBy(x => Math.Sign(x)).ThenBy(x => Math.Abs(x));
or:
from x in list
orderby Math.Sign(x), Math.Abs(x)
select x;
This is conceptually similar to the SQL statement:
SELECT x
FROM list
ORDER BY SIGN(x), ABS(x)
In LINQ-to-Objects, the sort is performed only once, not twice.
WARNING: Math.Abs(x) will fail if x == int.MinValue. If this marginal case is important, then you have to handle it separately.
var numbers = new[] { -3, -2, -1, 0, 1, 2, 3 };
var customSorted = numbers.OrderBy(n => n < 0 ? int.MinValue - n : n);
The idea here is to compare non-negative numbers by the value they have. And compare negative numbers with the value int.MinValue - n which is -2147483648 - n and because n is negative, the higher negative number we, the lower negative result the outcome will be.
It doesn't work when the list itself contains the number int.MinValue because this evaluates to 0 which would be equal to 0 itself. As Richard propose it could be made with longĀ“s if you need the full range but the performance will be slightly impaired by this.
Try something like (VB.Net example)
Orderby(Function(x) iif(x<0, Math.Abs(x), x*1000))
...if the values are <1000
You could express it in LINQ, but if I were reading the code two years later, I'd prefer to see something like:
list.OrderBy(i=>i, new NegativeThenPositiveByAscendingAbsoluteValueComparer());
You will need to implement IComparer.

How do I order an array of floating point numbers using a criteria other than size, using LINQ?

For example, I have an array of floating point numbers:
float[] numbers = new float[] { 1, 34, 65, 23, 56, 8, 5, 3, 234 };
If I use:
Array.Sort(numbers);
Then the array is sorted by the size of the number.
I want to sort the numbers by another criteria, so element A should go before element B if f(A) < f(B), rather than the usual of A < B.
So, for example, If I want to sort them according to there value modulo 5. The array would become:
5, 65, 1, 56, 3, 8, 23, 34, 234
I think it can be done through LINQ, but I'm not sure how.
I want to sort the numbers by another criteria, so element A should go before element B if f(A) < f(B)
numbers.OrderBy(f);
You can use the Comparison<T> overload of Array.Sort:
Array.Sort(numbers, (a,b) => (a % 5).CompareTo(b % 5));
Comparison<T> is just a delegate, so you can use lambdas / anonymous methods. It's not LINQ, but I think it's what you meant.
Using LINQ:
var result = from n in numbers orderby n % 5, n select n;
var sortedNumbers = result.ToArray();
Alternately:
var result = numbers.OrderBy(n => n % 5).ThenBy(n => n);
Ordering by mod 5, then by the number yields the results in the order you specified.
Have a look at IComparer ;-) and let an List sort the elements for you with your custom comparer.
More Brute even! I suggest you to make an Array of f(x) and then sort on that!

Categories

Resources