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);
}
}
Related
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
I need to find the minimum from a given range without running O(n).
The array might be a some diagonal line or a hyperbole. here are three sample arrays:
var arrDiag1 = new double[10] { 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5 };
var arrDiag2 = new double[10] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
var arrHyperbole = new double[10] { 9, 8, 7, 6, 5, 4, 3, 4, 5, 6 };
I tried building some sort of calculation from the line in the desert exercise but it came out no good.
Anyone has a better idea?
Thanks for the help
update
With dasblinkenlight help I managed to get to this method:
private double BinarySearchMin(double[] arr, int left, int leftMiddle, int rightMiddle, int right)
{
if (left == right)
return arr[left];
if (arr[leftMiddle] < arr[rightMiddle])
{
right = rightMiddle;
leftMiddle = ((right - left) / 3);
rightMiddle = ((right - left) / 3 * 2);
return BinarySearchMin(arr, left, leftMiddle, rightMiddle, right);
}
if (arr[leftMiddle] > arr[rightMiddle])
{
left = leftMiddle;
leftMiddle = ((right - left) / 3) + left;
rightMiddle = ((right - left) / 3 * 2) + left;
return BinarySearchMin(arr, left, leftMiddle, rightMiddle, right);
}
if (arr[leftMiddle] == arr[rightMiddle])
{
left = leftMiddle;
right = rightMiddle;
leftMiddle = ((right - left) / 3) + left;
rightMiddle = ((right - left) / 3 * 2) + left;
return BinarySearchMin(arr, left, leftMiddle, rightMiddle, right);
}
return -1;
}
In the first array it works but not in the second and third arrays.
What am I missing here?
If the function has only one minimum, use Ternary Search:
ternary search algorithm is a technique for finding the minimum or maximum of a unimodal function.
The idea is to split the range in three equal segments, probe at the two search points and then "pull in" the one which does not contain the minimum. Assuming search points i1 on the left side of the interval and and i2 on the right:
If f[i1] < f[i2], then the minimum is between 0 and i2; pull in from right
If f[i1] > f[i2], then the minimum is between i1 and N; pull in from left
If f[i1] == f[i2], then the minimum is between i1 and i2; pull in from both sides.
The running time of the algorithm is O(log N).
I usually hate answering to homework questions, but I somewhat like this one.
First of all, think of the two "diagonal" cases as nothing special, just a different view on the hyperbole where the minimum happens to be on the edge.
Then, try something like binary search to find the minimum. Have a peek at the two middle elements, look at their relation and decide on which side the minimum will be. Repeat until only one element is left.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i need a way to compare two array and compute the Equivalence percentage
so if equivalence Percentage exceed (for example 60%) do some actions
used language is C# .NET 4.0
The question is poorly defined, so I've taken some broad assumptions, but here's a sample implementation that measures equivalence based on element equality:
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[] { 1, 7, 3, 4 };
int equalElements = a.Zip(b, (i, j) => i == j).Count(eq => eq);
double equivalence = (double)equalElements / Math.Max(a.Length, b.Length);
if (equivalence >= .6)
{
// 60%+ equivalent
}
Zip: "Applies a specified function to the corresponding elements of two sequences." In this case, we're comparing each element from a with the corresponding element from b, and producing true if they're equal. For example, we compare 1 with 1, 2 with 7, 3 with 3, and 4 with 4. We then count the number of equalities we encountered, storing this value into equalElements. Finally, we divide this by the total number of elements in the larger sequence, and thus get the equivalence ratio.
Assuming you're comparing two int lists (or arrays, it's the same) you can compute the percentage of equivalent elements between list1 and list2 this way:
List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
List<int> list2 = new List<int>() { 3, 5, 8 };
var res = list1.Intersect(list2).ToList().Count();
float perc = (float)list1.Count() / res;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's say I have array which contains unique random numbers (where numbers have small possible range of 0 to 20). For example:
[6, 3, 11, 9, 4, 5]
How can I convert following array to something like this:
[3, 0, 5, 4, 1, 2]
The second array starts from 0 and ends with (array.Length-1), but placement is relative to magnitude in the first array.
How can I implement this in an efficient way in C/C++/C#? (more interested in the method)
I gave just one example. It can be really anything:
[7, 10, 0, 19, 50, 33, 45, 100]
[1, 2, 0, 3, 6, 4, 5, 7]
Smallest number from array A is 0 in array B. Biggest number in array A is (array.Length-1) in array B. Array A can be completely random (just it will never contain two or more identical numbers), but array A have to contain all numbers from 0 to array.Length-1) in same order as in array A.
int[] list1 = new[] { 7, 10, 0, 19, 50, 33, 45, 100 };
var orderedList = list1.OrderBy(x => x).ToList();
int[] list2 = list1.Select(x => orderedList.IndexOf(x)).ToArray();
EDIT
Per #Blorgbeard's request
int[] list1 = new[] { 6, 3, 11, 9, 4, 5 };
var dict = list1.OrderBy(x => x)
.Select((i, inx) => new { i, inx })
.ToDictionary(x => x.i, x => x.inx);
int[] list2 = list1.Select(x => dict[x]).ToArray();
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#.