Finding missing number in a sequence - c#

I need to find one missing number, from a sequence of numbers
such as
4 8 12 16 __ 24.
I need to find the missing number. How would I do that programmatically?
the numbers and the missing placement are not static, so they should be able to change.
Hope it is possible.

You could use some silly linq like this silly example :)
var numbers = new List<int>{4, 8, 12, 16, 24, 28, 36};
int first = numbers.First();
int last = numbers.Last();
var missing = Enumerable.Range(first, last).Where(n => n % first == 0).Except(numbers);
Returns:
20
32
-Bracing self for downvotes-

If you know that it is always an Arithmetic Progression, you can use the formula:
an = a1 + (n - 1) * d
being a1 the first element, d the difference between 2 elements and n the position to calculate, in your case:
an = 4 + (5 - 1) * 4 = 20
Check this: https://en.wikipedia.org/wiki/Arithmetic_progression

Related

C# Code to print out prime numbers from 5 to N

Prime Number Generator Code
Do know that this question should be quite basic but i have spent hours trying to figure out why my code is stuck in the loop as below. Have added a Console.WriteLine($"{counttemp} , {count1} "); in the if loop to check the 2 numbers and seems like it is not breaking out of the if condition when the condition is true
this is the console output for the writeline in the if loop
5 , 5
6 , 2
7 , 7
8 , 2
9 , 3
10 , 2
11 , 11
12 , 2
13 , 13
14 , 2
15 , 3
16 , 2
17 , 17
18 , 2
19 , 19
Problematic Loop??
for (count1 = 2; count1 <= counttemp ; ++count1)
{
if(counttemp % count1 == 0)
{
Console.WriteLine($"{counttemp} , {count1} ");
Console.ReadKey();
primetest1 = 0;
break;
}
}
full code sequence
static void Main(string[] args)
{
int prime1 = 10000, count1, primetest1, counttemp;
for (counttemp = 5; counttemp <= prime1; counttemp++)
{
primetest1 = 1;
for (count1 = 2; count1 <= counttemp ; ++count1)
{
if(counttemp % count1 == 0)
{
Console.WriteLine($"{counttemp} , {count1} ");
Console.ReadKey();
primetest1 = 0;
break;
}
}
if (primetest1 == 1)
{
Console.Write($"{counttemp}");
}
}
}
You're almost there. The problem is that you're checking if your candidate number is a prime by getting the remainder when divided by each number up to and including the number itself.
I think you'll find that N is a factor of N for all values of N. To fix this, you should only be checking up to but excluding the number.
And, as an aside, you don't really need to check all the way up to N - 1. You only need to go to the square root of N, adjusted up to the nearest integer. That's because, if it has a factor above the square root, you would already have found a factor below it.
Consider 24 as an example. It has 6, 8, and 12 as factors above the square root, but the matching values below the square root are 4, 3, and 2 respectively.
And there's a another trick you can use by realising that if a number is a multiple of a non-prime, it's also a multiple of every prime factor of that non-prime. In other words, every multiple of 12 is also a multiple of 2 and 3.
So you only need to check prime numbers up to the square root, to see if there's a factor. And prime numbers, other than two or three, are guaranteed to be of the form 6x-1 or 6x+1, so it's quite easy to filter out a large chunk of candidates very quickly, by checking only for those values.
In other words, check two and three as special cases. Then start at 5 and alternately add 2 and 4: 5, 7, 11, 13, 17, 19, .... Not every number in that set is prime (e.g, 25) every prime is guaranteed to be in that set.
You can check out an earlier answer of mine for more detail on why this is so, and how to do this sequence efficiently.

Using Recursion to get combinations of Numbers in C# that equal the same sum

UPDATE: Okay I've revamped this question due to some negative people that merely want to complain rather than attempt to provide some sort of constructive help.
I know variations of this question have been asked, but I'm fairly certain mine is different.
I'm trying to do something similar to the tic tac toe Magic Box, but with a variation.
Traditionally, the Magic TicTacToe box refers to the numbers 1-9 and you're asked to arrange them in the tictactoe box in such a way that every iteration of the sets of 3 equal the same. In that sense, each run of 3 numbers would have to equal 15. With every possible direction, there's 8 sequences to test. The important part of the calculation is that the total sum of 1-9 is 45 and that divided by 3 is what tells you each run of 3 should equal 15.
Now, as I understand it, there's a form of recursion that would have to take place to run through the combinations of numbers, but I'm not quite sure how to do that. I'd like to be able to put a number (divisible by 3 and 9) in for an input and have it not only determine the unique (non-recurring) numbers it takes to get to that total, but how those numbers should be used.
Example:
I know I can simply divide a number by 9 to determine the median, which in this case already gives me one letter, which would be E in this case. I know I can simply run a couple for loops to get the remaining numbers. What I'm not sure how to do is figure out the recursion process to determine the correct assignment of each number.
Here's the example of the letter assignment:
G | F | A
H | E | B
I | D | C
You'd need the following combinations:
A+B+C
F+E+D
G+H+I
A+E+I
G+E+C
G+F+A
H+E+B
I+D+C
Now, what I'm not sure of, and the effect it could have, is the frequency in which each number is used. I know each of the above sequences would need to equal the number input divided by 3 would in this case would be 30, but I'm not sure what important facts can be used to create the proper nested for loops and/or if statements that sort through the list or array of numbers created and properly assign them based on their relevance.
Considering E is used 4 times (which is why it's the center), A,C,I, and G are used 3 times, and H,B,D, and F are used 2 times.
So, for clarification, I would like all of this to output what A,B,C, etc. should be equal to given the restrictions.
Thanks for any help.
As an additional request, although not required, but extremely appreciated - if you do provide an answer, explaining some of the important portions of the recursions, functions used and how it achieves my desired outcome would be great.
I think I've made my question clear at this point. In regards to someone's comment, yes I'm asking for the code, because I one am not proficient enough to figure out the complex use of recursion it would take to constantly check the needed constraints required, and two, no other questions really get into the kind of detail I feel I'm trying to go to. Most just what a normal statistical use of Combinations and Permutations, but it doesn't seem there's as many restrictions on the results, and/or their end goal is different.
For the sake of making some things clear, here's another edit:
Below is what I have to first generate the list of all the numbers that will be used.
int A, B, C, D, E, F, G, H, I;
Console.WriteLine("Choose a number that's all 9 spots added together.");
Console.WriteLine("Make sure the number is divisble by 3 and 9.");
int myNumber = int.Parse(Console.ReadLine());
int sums = myNumber / 3;
E = myNumber / 9;
if (E%1 != 0)
{
Console.WriteLine("You did not enter a value divisible by 3 and 9");
Console.WriteLine("Try again.");
Console.ReadLine();
}
else
{
List<int> list = new List<int>();
int lowest = E - 4;
for (int x = lowest;x < E; x++)
{
list.Add(x);
}
int highest = E + 4;
for (int y=E;y<highest;y++)
{
list.Add(y+1);
}
//Testing output
foreach (int i in list)
{
Console.WriteLine(i);
}
I made this to first see if I could establish the numbers that would be used, then go into finding all the variations of the numbers that would make all the lines equal the same. For example: if they entered 45, all directions would have to equal 15; if they entered 90, all directions would have to equal 30, etc.
Here you go. Knock yourself out.
Func<IEnumerable<int>, IEnumerable<int[]>> permutate = null;
permutate = ns =>
{
if (!ns.Skip(1).Any())
{
return new [] { ns.ToArray() };
}
else
{
return
from n in ns
from ns2 in permutate(ns.Except(new [] { n }))
select new [] { n }.Concat(ns2).ToArray();
}
};
var results =
permutate(Enumerable.Range(1, 9))
.Where(ns => Enumerable.Range(0, 3).All(n => ns[n * 3] + ns[n * 3 + 1] + ns[n * 3 + 2] == 15))
.Where(ns => Enumerable.Range(0, 3).All(n => ns[n] + ns[3 + n] + ns[6 + n] == 15))
.Where(ns => Enumerable.Range(0, 3).All(n => ns[0] + ns[4] + ns[8] == 15))
.Where(ns => Enumerable.Range(0, 3).All(n => ns[2] + ns[4] + ns[6] == 15));
This gives:
2, 7, 6
9, 5, 1
4, 3, 8
2, 9, 4
7, 5, 3
6, 1, 8
4, 3, 8
9, 5, 1
2, 7, 6
4, 9, 2
3, 5, 7
8, 1, 6
6, 1, 8
7, 5, 3
2, 9, 4
6, 7, 2
1, 5, 9
8, 3, 4
8, 1, 6
3, 5, 7
4, 9, 2
8, 3, 4
1, 5, 9
6, 7, 2
I understand what #tekGiant is asking but I do not know how to answer it yet...
G | F | A
H | E | B
I | D | C
You'd need the following combinations:
A+B+C=X
F+E+D=X
G+H+I=X
A+E+I=X
G+E+C=X
G+F+A=X
H+E+B=X
I+D+C=X
Where X is the initial number that you designate to be the one that each of the different combinations add up to.

How to find combination of segments to build a track: possible Subset Sum

There are many Subset-sum questions and answers around at SO, but somehow I can't find a solution for my specific problem.
I need to find the quantity and length of track-segments to build a track of length n.
The segments are of length: 8, 10, 12, 14, 16, 18, 20, 22, 24 ft
The quantity can be up to 4 segments
The track length is ~ between 20 and 100 ft. (and always an even number)
This is a real track. Order of segments does not matter. However, there are preferred size combinations.
All of equal length or close to each other is preferred over Large/small combinations.
i.e:
70 => 20,20,20,10 would be an easy pick, but 16,18,18,18 would be preferred
60 => 20,20,20 is better then 14,14,14,18
I can trow on more examples if required.
I'm not looking for the one best solution, but a small set of possible best fit solution. Ultimately a person will choose, this is about suggestion best options.
What I did so far is the following. It is working, just seems way to complex.
I took the basic algorithm from this post Algorithm to find which numbers from a list of size n sum to another number.
All I changed in this code is turn it into integer. It return all possible combinations. up to 5 or more tracks.
To further reduce result set, I do a few Linq's
List<int> nums = new List<int>() { 8, 8, 8, 8, 10, 10, 10, 10, 12, 12, 12, 12, 14, 14, 14, 14, 16, 16, 16, 16, 18, 18, 18, 18, 20, 20, 20, 20, 22, 22, 22, 22, 24, 24, 24, 24 };
int width = 60;
Console.WriteLine("Total width: " + width);
Solver solver = new Solver();
List<List<int>> res = solver.Solve(width, nums.ToArray());
Console.WriteLine("total :"+res.Count);
var res1 = res.Distinct(new SequenceComparer<List<int>, int>()).ToList();
Console.WriteLine("total res1:" + res1.Count);
var res2 = res1.Where(l => l.Count == 4).ToList();
Console.WriteLine("total res2:" + res2.Count); //reduce to 4 integer solutions
var res3 = (from row in res2
where row[0] == row[1] || row[0] == row[2] || row[0] == row[3] ||
row[1] == row[2] || row[1] == row[3] ||
row[2] == row[3]
select row).ToList();
Console.WriteLine("total res3:" + res3.Count); //reduce to at least two of equal length
var res4 = (from row in res3
where row[0] == row[1] && row[0] == row[2] ||
row[0] == row[1] && row[0] == row[3] ||
row[1] == row[2] && row[1] == row[3]
select row).ToList();
Console.WriteLine("total res4:" + res4.Count); //reduce to three of equal length
var res5 = (from row in res4
where row[0] == row[1] && row[0] == row[2] && row[0] == row[3]
select row).ToList();
Console.WriteLine("total res5:" + res5.Count); //reduce to 4 of equal length
Console.WriteLine("-------------------------------------");
Console.WriteLine("res4:");
foreach (List<int> result in res4)
{
foreach (int value in result)
{
Console.Write("{0}\t", value);
}
Console.WriteLine();
}
Console.WriteLine("-------------------------------------");
Console.WriteLine("res5:");
foreach (List<int> result in res5)
{
foreach (int value in result)
{
Console.Write("{0}\t", value);
}
Console.WriteLine();
}
Console.ReadLine();
This code will produce the following outcome, run with 60
Total width: 60
total :10726
total res1:74
total res2:31
total res3:20
total res4:3
total res5:0
-------------------------------------
res4:
12 12 12 24
12 16 16 16
14 14 14 18
-------------------------------------
res5:
or with 80 this
Total width: 80
total :101560
total res1:237
total res2:15
total res3:13
total res4:3
total res5:1
------------------------------------
res4:
8 24 24 24
14 22 22 22
20 20 20 20
------------------------------------
res5:
20 20 20 20
So my final results (4&5) are, in fact, close to what I need.
BUT I would have to code the same again for any possible 3 track solution, and maybe 2 tracks.
Then does results would need to be compared to each other (somehow, not sure how). ALL of this makes me feel like I am missing something. It feels to complex, it feels wrong. What am I missing?
AM I using the wrong algorithm to begin with? Are their better once out their for my problem?
Let's divide everything by 2 since everything is even.
We now have track pieces with length 4 to 12 for a total length of about 10 to 50.
Name n the length we have to achieve. For every possible number k of track pieces (1 to 4 in general, but 1 to 3 for n<16 or 3 to 4 for n>36 for example), suggest taking n%k pieces of length n/k+1 and k-n%k pieces of length n/k.
'/' designates integer division and '%' the remainder.
You really have a special case of the sum-set. While it's NP-hard, the solution space is restricted enough that brute force would probably work fine, as there are only 10000 (10 ^ 4) possible solutions total (which is about equal to the actual number of time steps needed), since you also have to consider 0 as a possible length.
Here is the code, in psudo-Python. Thought about trying it in C#, but not actually familiar with it, and so it probably wouldn't work out well.
lengths = [0, 8, 10, 12, 14, 16, 18, 20, 22, 24]
solutions = []
for len1 in lengths:
for len2 in lengths:
for len3 in lengths:
for len4 in lengths:
if (len1 + len2 + len3 + len4) == n:
solutions.append([len1,len2,len3,len4])
return solutions
Once you have all the valid solutions, you can then simply determine which one(s) you want to show the user, or you can simply write an algorithm to pick the best one. Of course, you'll probably want to not actually include any lengths of size 0.
You can improve this algorithm somewhat using a greedy method that will only find all valid solutions. However, again, the problem as it's stated isn't likely to be complex enough to need it unless things are very constricted in terms of space or time.
As a bonus, if you are expecting multiple queries (for example user asks for n = 40 and later n = 50), you can remove the if statement and simply store all 10000 solutions in a hash-table keyed to the sum value, allowing for O(1) querying.
Narrowing down the solution set:
What you need here is a comparison algorithm that basically compares this solution to that solution and says, "this solution is better/worst than that solution". This allows you to write a sorting algorithm that you can use to sort the solutions to get the best so many, or you can simply just find the best solution.
You can resolve the vast majority of cases by simply calculating the standard deviation for each solution then compare the standard deviations. This will give a number that shows how much variance is in the lengths of the solution. If you use "lower standard deviation is better", then that'll give you "All of equal length or close to each other is preferred over Large/small combinations". The algorithm for standard deviation is fairly straightforward, so I'll leave it to you try to implement. Actually, there's a good chance that C# has the function built in. Just be sure not to include any zero lengths, actually they should probably be removed before you add them to the solution set to avoid issues, which requires a bit of tweaking to the code I gave.
However, you then have the tricky part, dealing with cases where different solutions have the same standard deviation. I'm thinking there are only two cases where this happens.
The first occurs only there are multiple ideal solutions. Such as if n = 24, then three of the solutions will be [8,8,8], [12,12], and [24].
The second occurs due to the brute force nature of the algorithm, and is why there are so many solutions. This is because for every solution like [8,10,12,14] (four unique lengths) there are 24 ways to arrange those lengths, such as [14,12,10,8] and [12,10,14,8]. So the best way to improve upon the brute force algorithm is to have an algorithm that multichooses 4 elements from [0, 8, 10, 12, 14, 16, 18, 20, 22, 24]. This narrows the solution set to only 715 solutions. Of course, if you actually want [8,10,12,14], [14,12,10,8] and [12,10,14,8] as different solutions, then there isn't much you can do.
The above two paragraphs fall squarely in the realm of "it depends". You'll have to decide what rules the algorithm should follow in each case, but I'm thinking those are the only two cases where you could find identical standard deviations.
Math to the rescue!
You can check that every even number larger than 8 is a linear combination of elements from this set - ask on Math Overflow for a proof ;).
So let's rephrase the question in math:
We have an overcomplete dictionary of basis vectors (because 16, for example, is a multiple of 8),
in which we can represent every even number larger than 8 as a linear combination of these basis vectors, and
we are trying to minimize the zero "norm" of this input vector.
The good news: This is a very interesting problem, with many application domains, so it is pretty well researched.
The bad news: this is still a hard (NP-hard) problem.
But, hey, at least now you know.
edit:
And just so I don't get accused of handwaving philosophical answer, here's a modified (completely non-optimized) version of Solver.recursiveSolve that exhaustively searches for a combination of segments that match the goal; and a zero norm comparer class with which you can sort your results:
private void RecursiveSolve(int goal, int currentSum,
List<int> included, List<int> segments, int startIndex)
{
for (int index = 0; index < segments.Count; index++)
{
int nextValue = segments[index];
if (currentSum + nextValue == goal)
{
List<int> newResult = new List<int>(included);
newResult.Add(nextValue);
mResults.Add(newResult);
}
else if (currentSum + nextValue < goal)
{
List<int> nextIncluded = new List<int>(included);
nextIncluded.Add(nextValue);
RecursiveSolve(goal, currentSum + nextValue,
nextIncluded, segments, startIndex++);
}
}
}
class ZeroNormAndSDComparer : IComparer<List<int>>
{
private int l0_norm(List<int> v)
{
int norm = 0;
HashSet<int> seen = new HashSet<int>();
for (int i = 0; i < v.Count; ++i)
{
if (!seen.Contains(v[i]))
{
norm++;
seen.Add(v[i]);
}
}
return norm;
}
private static double StandardDeviation(List<int> v)
{
double M = 0.0;
double S = 0.0;
int k = 1;
foreach (double value in v)
{
double tmpM = M;
M += (value - tmpM) / k;
S += (value - tmpM) * (value - M);
k++;
}
return Math.Sqrt(S / (k - 1));
}
public int Compare(List<int> x, List<int> y)
{
int normComparison = l0_norm(x).CompareTo(l0_norm(y));
if (normComparison == 0)
{
return StandardDeviation(x).CompareTo(StandardDeviation(y));
}
return normComparison;
}
}
And your modified Main (now sorting is done after results have been reduced to distinct, 4-segment results):
List<int> nums = new List<int>() { 8, 10, 12, 14, 16, 18, 20, 22, 24 };
int width = 80;
Console.WriteLine("Total width: " + width);
Solver solver = new Solver();
List<List<int>> res = solver.Solve(width, nums.ToArray());
Console.WriteLine("total :" + res.Count);
var res1 = res.Distinct(new SequenceComparer<List<int>, int>()).ToList();
Console.WriteLine("total res1:" + res1.Count);
var res2 = res1.Where(l => l.Count == 4).ToList();
Console.WriteLine("total res2:" + res2.Count); //reduce to 4 integer solutions
res2.Sort(new ZeroNormAndSDComparer());

C# How to calculate first 10 numbers out a bill number of 12?

Lets assume i have a bill number that has 12 numbers: 823 45678912
My question is how exactly do i do calculations with the first 10 numbers?
To verify if a given in billnumber is correct i have to perform the following calculation:
(first 10 numbers) % 97 = result
And if the result of the calculation is the same as the last 2 numbers of my bill number, then it is verified.
Thanks in advance.
(n / 100) % 97 == n % 100
It looks like you have a bill number that is actually a string with spaces. I would use #Marcelo's solution, but first you'll need to convert it to a long integer. This should help with that.
var billAsNumber = long.Parse( billNumber.Replace(" ","") );
var valid = (billAsNumber / 100) % 97 == billAsNumber % 100;
If your bill number is stored in a long variable, shift it right two places and there you have it:
var first10Digits = billNumber / 100;
var checksum = first10Digits % 97;
Note that your bill number might have more than 12 digits and the resulting integer would not fit into an existing data type. While searching for solutions on how to do MOD 97 division on very large numbers i've found this algorithm that worked well for me.

Append a digit to an integer and make sure sum of each digits ends with 1

What is the algorithm in c# to do this?
Example 1:
Given n = 972, function will then append 3 to make 9723, because 9 + 7 + 2 + 3 = 21 (ends with 1). Function should return 3.
Example 2:
Given n = 33, function will then append 5 to make 335, because 3 + 3 + 5 = 11 (ends with 1). Function should return 5.
Algorithms are language independent. Asking for "an algorithm in C#" doesn't make much sense.
Asking for the algorithm (as though there is only one) is similarly misguided.
So, let's do this step by step.
First, we note that only the last digit of the result is meaningful. So, we'll sum up our existing digits, and then ignore all but the last one. A good way to do this is to take the sum modulo 10.
So, we have the sum of the existing digits, and we want to add another digit to that, so that the sum of the two ends in 1.
For the vast majority of cases, that will mean sum + newDigit = 11. Rearranging gives newDigit = 11 - sum
We can then take this modulo 10 (again) in order to reduce it to a single digit.
Finally, we multiply the original number by 10, and add our new digit to it.
The algorithm in general:
(10 - (sum of digits mod 10) + 1) mod 10
The answer of the above expression is your needed digit.
sum of digits mod 10 gives you the current remainder, when you subtract this from 10 you get the needed value for a remainder of 0. When you add 1 you get the needed value to get a remainder of 1. The last mod 10 gives you the answer as a 1 digit number.
So in C# something like this:
static int getNewValue(string s)
{
int sum = 0;
foreach (char c in s)
{
sum += Convert.ToInt32(c.ToString());
}
int newDigit = (10 - (sum % 10) + 1) % 10;
return newDigit;
}
Another alternative using mod once only
int sum = 0;
foreach (char c in s)
sum += Convert.ToInt32(c.ToString());
int diff = 0;
while (sum % 10 != 1)
{
sum++;
diff++;
}
if (diff > 0)
s += diff.ToString();
Well, it's easier in C++.
std::string s = boost::lexical_cast<string>( i );
i = i * 10 + 9 - std::accumulate( s.begin(), s.end(), 8 - '0' * s.size() ) % 10;
Addicted to code golf…

Categories