Does someone know how to solve this C# Math Algorithm?
The control number calculates by multiplying each number in a "social security number" with changing 2 and 1 (starting with 2). Then it calculates and adds together.
The control number should be equal divided with 10 to be correct and pass.
Ex, 720310-1212 "Social security number"
7* 2 = 14 --> 1+4
2* 1 = 2 --> 2
0* 2 = 0 --> 0
3* 1 = 3 --> 3
1* 2 = 2 --> 2
0* 1 = 0 --> 0
1* 2 = 2 --> 2
2* 1 = 2 --> 2
1* 2 = 1 --> 2
2* 1 = 2 --> 2
Then add them 1+4+2+0+3+2+0+2+2+2+2 = 20
20/10 = 2 Pass!
You need:
a counter to accumulate the numbers,
a loop to iterate over the input string,
char.GetNumericValue to get the numeric value of each input character,
a boolean flag that is changed each iteration to indicate whether to multiply by 1 or 2,
the modulus operator % to calculate the remainder of the division by 10 at the end.
Should be simple enough. Homework?
Edit
LINQ solution:
var valid = "720310-1212"
.Where(c => char.IsDigit(c))
.Select(c => (int)char.GetNumericValue(c))
.Select((x, i) => x * (2 - i % 2))
.Select(x => x % 10 + x / 10)
.Sum() % 10 == 0;
I think you're describing the Luhn algorithm (also known as mod 10). It's used to validate credit cards (and other things). There is a C# implementation at E-Commerce Tip: Programmatically Validate Credit Card Numbers.
Related
I am building a tournament schedule with round robin style match order. I have an algorithm set up to build the matches, however the match order is not what I am looking for. I am struggling to develop an algorithm that will build the matches in my desired order. See example below with a 6 team bracket. Each vertical line represents a row in the tournament. The far left number represents the base team seed and who they will play in each round.
Note: The only thing that is really important to me is that the 1 and 2 seed play in the last round of the tournament. And preferably that 1 v 6, 2 v 5, 3 v 4 happens in the first round of the tournament. All other matches aren't as important. Thank you in advance for any help you can provide.
1: 6 5 4 3 2
2: 5 4 3 6 1
3: 4 6 2 1 5
4: 3 2 1 5 6
5: 2 1 6 4 3
6: 1 3 5 2 4
Here is my current code:
int numTeams = teamList.Count;
int rounds = (numTeams - 1);
int halfSize = numTeams / 2;
List<Team> teams = new List<Team>();
teams.AddRange(teamList); // Copy all the elements.
teams.RemoveAt(0); // To exclude the first team.
int teamSize = teams.Count;
for (int round = 0; round < rounds; round++)
{
int teamIdx = round % teamSize;
Team baseTeam1 = teams[teamIdx];
Team baseTeam2 = teamList[0];
// save each team to a match
for (int idx = 1; idx < halfSize; idx++)
{
int firstTeamIdx = (round + idx) % teamSize;
int secondTeamIdx = (round + teamSize - idx) % teamSize;
Team subTeam1 = teams[firstTeamIdx];
Team subTeam2 = teams[secondTeamIdx];
// save each team to a match
}
}
Sometimes asking the question helps figure out the answer. As it turns out, my current algorithm was creating what I wanted, just in opposite order. What I did to fix was create a new varible inside the first for loop called actualRound:
int actualRound = rounds - round; // this will reverse the round order
I have the following data in a SQL Server database:
service_id delivery_id price_increase
---------- ----------- --------------
1 1 0.4
1 2 0.3
1 3 0.2
1 4 0.1
1 5 0
2 1 0.4
2 2 0.3
2 3 0.2
2 4 0
2 5 0
4 1 0.5
4 2 0.3
4 3 0.25
4 4 0.15
4 5 0
Some points:
all the service_id values will always have a full complement of delivery_id values (i.e., there's a requirement to have delivery_ids 1-5)
there doesn't have to be a full complement of service_id values (as you can see above, service_id 3 has no entry)
for the purposes of this question, there's no limit on the number of service_id entries
These values will be parsed into the following class hierarchy:
ServicePricing
- ServiceId
- IEnumerable<DeliveryPricing>
where
DeliveryPricing
- DeliveryId
- PriceIncrease
What's the easiest way to query these values from the DB and then use C# to parse them? I could do it in a fairly trivial but tedious manner, checking to see whether a service_id has already been declared in code and so on, but is there any way to group the results so that I can more easily loop through them and have a clear boundary at which to declare a new instance of either of the classes?
For example, is it possible to put all results from the same service_id into an individual result set?
[Just for clarification, I'm looking for a SQL-based suggestion, not how to parse a result set in C#.]
select service_id, delivery_id, price_increase
from table order by service_id, delivery_id
int? serviceID = null;
ServicePricing sp;
List<ServicePricing> sps;
while (rdr.Read())
{
if(rdr.GetInt(0) <> serviceID)
{
if(sp != null)
sps.Add(sp);
serviceID = rdr.GetInt(0);
sp = new ServicePricing(serviceID);
}
sp.DeliveryPricings.Add(new DeliveryPricing(rdr.GetInt(1), rdr.GetDecimal(2));
}
sps.Add(sp);
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).
If you have a NxN matrix of positive integers, and you are asked to select exactly one element from each row and column, so that the sum of the selected elements is minimized, how can it be solved?
I think it is about Dynamic Programming. I have tried to minimize the time O(n!) using memoization:
Dictionary<byte[,], int>[] memo = new Dictionary<byte[,], int>[17];
int rec(byte[,] arr)
{
if (arr.Length == 1) return arr[0, 0];
int opt = find(arr);
if (opt != -1) return opt;
opt = 1 << 25;
for (int i = 0; i < arr.GetLength(1); ++i)
opt = Math.Min(opt, arr[0, i] + rec(divide(arr, i)));
add(arr, opt);
return opt;
}
This chooses an element from row 0 of the current matrix and then divides the matrix and calls itself recursively to solve the submatrix. Function divide divides the current matrix according to the selected element. The sub-matrix size is then (N-1)x(N-1). Function find performs linear search in memo[n], and add adds the solution to memo[n] But this is too slow as it will compare each matrix with other.
Do you have some inhancements? Is there a faster DP algorithm? Any help is appreciated
EXAMPLE
1 2 3 4
8 7 6 5
9 11 10 12
13 14 16 15
The optimal solution: 1 + 5 + 10 + 14
Steps:
7 6 5
11 10 12
14 16 15
11 10
14 16
14
This is actually the assignment problem. It can be solved in polynomial time using the Hungarian algorithm, among other methods.
I have solved the project Euler problem 16 but discovered this rather novel approach but I cannot get my head around the technique employed (from http://www.mathblog.dk/project-euler-16/):
int result = 0;
BigInteger number = BigInteger.Pow(2, 1000);
while (number > 0) {
result += (int) (number % 10);
number /= 10;
}
My version seems more conventional but I think the above approach is cooler.
var result = BigInteger
.Pow(2, 1000)
.ToString()
.Aggregate(0, (total, next) => total + (int) Char.GetNumericValue(next));
How does the mathematics work on the first approach, it is cool, but I need some explanation to help me understand, so if someone would be so kind to explain to me I would really appreciate it.
NOTE: If I have posted in the wrong section please let me know the better place to ask.
value % 10 will return the last digit (remainder after dividing by 10). Dividing the integer by 10 will remove this number.
Think of the number as a list, and you're just dequeuing the list and summing the values.
The modulus operator provides the remainder from the division. So, mod 10 is going to be the one's place in the number. The integer division by 10 will then shift everything so it can be repeated.
Example for the number 12345:
12345 % 10 = 5
12345 / 10 = 1234
1234 % 10 = 4
1234 / 10 = 123
123 % 10 = 3
123 / 10 = 12
12 % 10 = 2
12 / 10 = 1
1 % 10 = 1
1 / 10 = 0 (loop ends)
The addition is performed on the result of each modulus so you'd get 5+4+3+2+1
number % 10 extracts the least significant decimal digit. e.g. 12345 => 5
number / 10 removes the least significant decimal digit. This works because integer division in C# throws away the remainder. e.g. 12345 => 1234
Thus the above code extracts each digit, adds it to the sum, and then removes it. It repeats the process until all digits have been removed, and the number is 0.
It's quite simple:
Imagine this:
number = 54
It uses modulo to get the remainder of this divded by 10
e.g. 54 / 10 = 5 remainder 4
It then adds this digit (4) to the result, then divides the number by 10 (storing into int which discards decimal places)
so then number = 5
same again, 5 / 10 = 0 remainder 5
Adds them togther, result is now 9
and so on until the number is 0 :)
(in this case 9 is the answer)
They found the number 2^1000.
Modulo 10 gets the least significant digit.
E.G. 12034 % 10 = 4
Dividing by 10 strips the least significant digit.
E.G. 12034 / 10 = 1203
They sum up these least significant digits.