Dont know how to read this method - c#

What is this function, I mean for the part where is 0x30? Hex value that points to ASCII table?
This is probably basic stuff, and I'm without knowledge currently.
getCompleteCode("11111");
private string getCompleteCode(string code)
{
var b1 = 10;
var b2 = 20;
var sum = 0;
for (var i = code.Length - 1; i >= 0; i--)
{
var z = code[i] - 0x30;
sum = sum + (z + b1) * b2;
}
Console.WriteLine(sum);
return code;
}

A wonderful example of how one should not implement a logic:
// why not static?
private string getCompleteCode(string code)
{
// what does "b1" as well as "b2" stand for?
var b1 = 10;
var b2 = 20;
var sum = 0;
// the reason for the loop being in reversed order?
for (var i = code.Length - 1; i >= 0; i--)
{
// the question put - what does 0x30 stand for - it's ascii code of '0' char
// so, why magic code 0x30 instead of evident '0'?
var z = code[i] - 0x30;
sum = sum + (z + b1) * b2;
}
// what if I want to compute it in, say, WinForms??
// Never mix business logic (computing some code) and UI (output)
Console.WriteLine(sum);
// we've done a lot of stuff just to return the initial input??
return code;
}
My suggestion for the implementation (providing that code is guaranteed to be a correct input):
//TODO: think on a better name for the method
private static int getCompleteCode(string code) {
return code.Sum(c => (c - '0' + 10) * 20);
}
...
Console.WriteLine(getCompleteCode("11111"));

As others have explained, var z = code[i] - 0x30 is standard code to get the value of a digit character. As Glorin Oakenfoot mentioned, this code doesn't do any bounds checking. So it works great for '0' - 0x30 (effectively, that's '0' - '0', by the way), and for '9' - 0x30. But it will also produce weirdness like 'A' - 0x30 = 32.
Glorin's comment is also right - the rest of the numbers seem very context specific. It seems likely to be a hash function - it calculates a mostly-unique number for a given string. I'll walk you through the loop, but what it's doing doesn't make any real sense. Rather than inputting "11111", let's look at "12345":
1st time through loop: i = 4, code[i] = '5', z = 5, sum = 0 + 15 * 20 = 300
2nd time through loop: i = 3, code[i] = '4', z = 4, sum = 300 + 14 * 20 = 580
3rd time through loop: i = 2, code[i] = '3', z = 3, sum = 580 + 13 * 20 = 840
4th time through loop: i = 1, code[i] = '2', z = 2, sum = 840 + 12 * 20 = 1080
5th time through loop: i = 0, code[i] = '1', z = 1, sum = 1080 + 11 * 20 = 1300
As I mentioned, it's likely this is used for hashing. Every string of digits you enter is likely to have a unique integer code. Hashing of strings can improve efficiency. If nothing else, it gives you a fairly robust test for comparison. See https://en.wikipedia.org/wiki/Hash_function
Of course, most string hash functions don't do the conversion from digit to int. And if the function requires that the input be only digits, as seems to be implied by the conversion to int, the simplest hash for this string is to just parse it to an integer.
The other thing this reminds me of is an attempt to parse an integer string to a digit. That would be very similar, but note the differences below:
var sum = 0
for (var i = 0; i < code.Length; i++)
{
var z = code[i] - '0' // this is the same as - 0x30, but more clear to read
sum = sum * 10 + z
}
Considering the name of the function, though, it seems much more likely that it's intended as a hash function.

0x30 is the ascii value of '0' ... it is normally used to subtract from a character, e.g. '8' - 0x30 = 8 after casting to an integer (either implicitly or explicitly like here).

0x30 y the hex ASCII code for number 0, so z will actually give you the digit in number type.

It removes decimals. It = whatever number rounded.

Related

how to do text box characters convert to ascii and multiplication in C#

i have a text "vpn123" in my textbox and i want to convert that all the text in the textbox into ASCII and the ASCII value of "123" multiply by 5 and the characters ASCII values multiply by 5 then want to add multiplied values add to the next letter ASCII value.I try to do coding but get nothing.Please help!
v => convert to ASCII * 5 = 590 = 590
p => convert to ASCII * 5 = 560 + 590 = 1150
n => convert to ASCII * 5 = 550 + 560 = 1100
1 => convert to ASCII * 5 = 245
2 => convert to ASCII * 5 = 250
3 => convert to ASCII * 5 = 255
I Want to Get the answer = '59011501100245250255' in my massage box
how can i solve this problem using c#?
string s = new string(Encoding.ASCII.GetBytes(textBox2.Text).SelectMany(b => b.ToString()).ToArray());
ulong multi = 5;
ulong pass = multi * Convert.ToUInt64(s);
MessageBox.Show(" " + pass);
Here is a solution not using LINQ, but a for loop, which might be easier to construct and understand:
string text = "vpn123";
var result = new StringBuilder();
for (var i = 0; i < text.Length; i++)
{
// multiply character code by 5
var number = text[i] * 5;
if (char.IsLetter(text[i]) && i > 0 && char.IsLetter(text[i - 1]))
{
// if this character is a letter and the previous one also was a letter,
// add the multiplied value of the previous letter
number += text[i - 1] * 5;
}
result.Append(number);
}
Console.WriteLine(result.ToString());
Prints: 59011501110245250255

Is this the correct code for the defined problem?

Can anybody help me with the of bit swapping in c#. It actually goes like this that the function accepts a number then it will convert it into binary and then swap its any bits and then convert it into decimal and the return the number.
Here is what I have tried:
DectoBin(int num) {
stringBuilder strBin = new StringBuilder();
while (num / 2 ! =1) {
strBin.Append((num % 2).ToString());
num = num / 2;
}
String str = strBin.ToString();
int BinDec(string str)
int DecNum = 0;
for (int i = str.length - 1; i >= 0; i++) {
DecNum = +DecNum
int.parse(str[k++] * pow(2, i);
}
return DecNum;
}
I need c# code of this problem soon. If anybody can provide me the code, I would be really thankful.
Your question is vague one, however, I can provide some suggestions. First, let's represent the initial int as a convenient string:
int value = ...
// Meanful bits only : 5 -> "101" (without leading zeroes)
string bits = Convert.ToString(unchecked((uint) value), 2);
// All 32 bits : 5 -> "00000000000000000000000000000101"
string allBits = Convert.ToString(unchecked((uint) value), 2).PadLeft(32, '0');
Time to query; let's use Linq whcih can be very convenient. Depending on what does swap mean it can be
using System.Linq;
...
// reversed bits: "101" -> "101", "100" -> "001", etc.
// but either "bits" or "allBits" as an argument
string result = string.Concat(bits.Reverse());
Or
// each '0' truns into "1" and vice versa: "101" -> "010", "100" -> "011" etc
// but either "bits" or "allBits" as an argument
string result = string.Concat(bits.Select(b => b == '1' ? '0' : '1'));
Finally, let's take int back with a help of Convert:
int outcome = unchecked((int)Convert.ToUInt32(result, 2));

C# For loop index returns ascii instead of current iteration

I need to make a program that calculates the factorial of a number and sums the different numbers.
I'm stuck at the point where I need to take the current number in the for loop to do it's factorial (e.g. the number 145 and I can't take the 5). I've tried the following:
for (int i = length-1; i >= 0; i--)
{
int currentNumber = inputString[i];
currentSum = currentSum * i;
sum += currentSum;
}
inputString is the length of the given number.
The problem is that in this way currentNumber becomes the ascii equivalent (if i = 3 currentSum becomes 51). How do I make currentSum become 3?
Alternatively you could use:
int currentNumber = int.Parse(inputString[i].ToString());
I'd like to suggest an alternative:
int num = int.Parse(inputString); // Convert whole input to int
int sum = 0;
while( num != 0 ) // >0 is not enough, num could be negative.
{
sum += num % 10; // Sum up least significant place
num = num / 10; // "Decimal shift right"
}
With your example "145" this would mean:
Iteration 1:
sum += 145 % 10 => sum = 0 + 5 = 5
num = num / 10 => num = 145 / 10 = 14
Iteration 2:
sum += 14 % 10 => sum = 5 + 4 = 9
num = num / 10 => num = 14 / 10 = 1
Iteration 3:
sum += 1 % 10 => sum = 9 + 1 = 10
num = num / 10 => num = 1 / 10 = 0
num == 0 => end while , sum = 10
Disclaimer: This assumes, the input is in fact a valid integer value. I'd strongly suggest to validate that, first. "Never trust user input."
Assuming inputString is numeric only, you can get away with:
int currentNumber = inputString[i] - '0';
Short explanation: character representation of number '3' is 51, but they are in order (so '0' is 48, '1' is 49, etc.) and you can get the "numerical value" of a character by removing the offset (which is the value of '0').

Algorithm to get which values make sum of a given number from array

I don't know to search or google it so I ask it here.
I have an array of integers with fixed size and exactly with this logic.
sample [1,2,4,8,16,32]
Now I am given a number for example 26. And I shall find the numbers whose sum will make this number, in this case is [2,8,16]
for a number of 20 it will be [4,16]
for 40 it is [8,32]
and for 63 it is all of these numbers [1,2,4,8,16,32]
What is the proper algorithm for that?
I know strictly that there is always this continuation that the number is double of the previous value.
as well as only the numbers from the given array will sum up to the given number and each number will be used only for once or none
If it will be in C# method that takes array of ints and an int value and returns the array of ints that contains the ints that sum up this number from the given array will be preferred.
Thank you
As you can see, the number are base-2, which means you can easily use shift.
You could try this:
private IEnumerable<int> FindBits(int value)
{
// check for bits.
for (int i = 0; i < 32; i++)
{
// shift 1 by i
var bitVal = 1 << i; // you could use (int)Math.Pow(2, i); instead
// check if the value contains that bit.
if ((value & bitVal) == bitVal)
// yep, it did.
yield return bitVal;
}
}
This method will check what bits are set and return them as an ienumerable. (which can be converted to an array of list)
Usage:
// find the bits.
var res = FindBits(40).ToArray();
// format it using the string.join
var str = $"[{string.Join(",", res)}]";
// present the results
Console.WriteLine(str);
Results in [8,32]
Extra info:
counter
00000001 = 1 = 1 << 0
00000010 = 2 = 1 << 1
00000100 = 4 = 1 << 2
00001000 = 8 = 1 << 3
00010000 = 16 = 1 << 4
00100000 = 32 = 1 << 5
01000000 = 64 = 1 << 6
10000000 = 128 = 1 << 7
Instead of writing all combinations you make a for loop which does the counter.
Some extra non-sense:
If you like lambda's, you could replace the FindBits with this:
private Func<int, IEnumerable<int>> FindBits = (int value) => Enumerable
.Range(0, 31)
.Select(i => 2 << i).Where(i => (value & i) == i);
But it's better to keep it simpel/readable.
First you should notice that
( 1 2 4 8 16 ... ) = (2^0 2^1 2^2 2^3 2^4 ... )
And that this is the same as finding a binary encoding for a decimal number. What you are looking for is an algorithm to transform a decimal or base 10 number to a binary or base 2 number.
The algorithm is pretty simple:
public List<int> dec_to_bin(int num)
{
List<int> return_list = new List<int>();
int index = 0;
int remainder = num;
int bit = 0;
while (remainder > 0)
{
bit = remainder % 2;
if (bit == 1 )
{
return_list.Add((int)Math.Pow(2, index));
}
remainder = remainder / 2;
index = index + 1;
}
return return_list;
}
There is a better way however that just uses the underlying encoding of the number which is already binary.
public List<int> dec_to_bin(int num)
{
List<int> return_list = new List<int>();
int value = 1;
while( value < num )
{
if( (value & num) == value )
{
return_list.Add(value);
}
value = value * 2;
}
return return_list;
}
Another way to state your requirement is "What are the unique powers of 2 that sum to a given integer?" Since computers work with powers of 2 natively, there are built-in goodies in most languages to do this very succinctly.
As a bonus, you can use existing .Net types and methods to eliminate the need to write your own loops.
Here's one approach:
IEnumerable<int> GetCompositePowersOf2(int input) =>
//convert to enumerable of bools, one for each bit in the
//input value (true=1, false=0)
new BitArray(new[] { input }).Cast<bool>()
// get power of 2 corresponding to the position in the enumerable
// for each true value, gets 0 for false values.
.Select((isOne, pos) => isOne ? (1 << pos) : 0)
//filter out the 0 values
.Where(pow => pow > 0);
I don't quite get the " takes array of ints " part, since this creation of sums only works with numbers that are the power of 2.
private int[] count (int num)
{
int factor = 0;
List<int> facts = new List<int>();
while (num > 0)
{
int counter = 0;
int div = num;
int remainder = 0;
while (remainder == 0)
{
remainder = div % 2;
div = div / 2;
counter++;
}
factor = 1;
for (int i = 1; i < counter; i++)
factor *= 2;
num = num - factor;
facts.Add(factor);
}
return (facts.ToArray());
}

What is the algorithm to convert an Excel Column Letter into its Number?

I need an algorithm to convert an Excel Column letter to its proper number.
The language this will be written in is C#, but any would do or even pseudo code.
Please note I am going to put this in C# and I don't want to use the office dll.
For 'A' the expected result will be 1
For 'AH' = 34
For 'XFD' = 16384
public static int ExcelColumnNameToNumber(string columnName)
{
if (string.IsNullOrEmpty(columnName)) throw new ArgumentNullException("columnName");
columnName = columnName.ToUpperInvariant();
int sum = 0;
for (int i = 0; i < columnName.Length; i++)
{
sum *= 26;
sum += (columnName[i] - 'A' + 1);
}
return sum;
}
int result = colName.Select((c, i) =>
((c - 'A' + 1) * ((int)Math.Pow(26, colName.Length - i - 1)))).Sum();
int col = colName.ToCharArray().Select(c => c - 'A' + 1).
Reverse().Select((v, i) => v * (int)Math.Pow(26, i)).Sum();
Loop through the characters from last to first. Multiply the value of each letter (A=1, Z=26) times 26**N, add to a running total. My string manipulation skill in C# is nonexistent, so here is some very mixed pseudo-code:
sum=0;
len=length(letters);
for(i=0;i<len;i++)
sum += ((letters[len-i-1])-'A'+1) * pow(26,i);
Here is a solution I wrote up in JavaScript if anyone is interested.
var letters = "abc".toUpperCase();
var sum = 0;
for(var i = 0; i < letters.length;i++)
{
sum *= 26;
sum += (letters.charCodeAt(i) - ("A".charCodeAt(0)-1));
}
alert(sum);
Could you perhaps treat it like a base 26 number, and then substitute letters for a base 26 number?
So in effect, your right most digit will always be a raw number between 1 and 26, and the remainder of the "number" (the left part) is the number of 26's collected? So A would represent one lot of 26, B would be 2, etc.
As an example:
B = 2 = Column 2
AB = 26 * 1(A) + 2 = Column 28
BB = 26 * 2(B) + 2 = Column 54
DA = 26 * 4(D) + 1 = Column 105
etc
Shorter version:
int col = "Ab".Aggregate(0, (a, c) => a * 26 + c & 31); // 28
To ignore non A-Za-z characters:
int col = " !$Af$3 ".Aggregate(0, (a, c) => (uint)((c | 32) - 'a') > 25 ? a : a * 26 + (c & 31)); // 32
Here is a basic c++ answer for those who are intrested in c++ implemention.
int titleToNumber(string given) {
int power=0;
int res=0;
for(int i=given.length()-1;i>=0;i--)
{
char c=given[i];
res+=pow(26,power)*(c-'A'+1);
power++;
}
return res;
}
in Excel VBA you could use the .Range Method to get the number, like so:
Dim rng as Range
Dim vSearchCol as variant 'your input column
Set rng.Thisworkbook.worksheets("mySheet").Range(vSearchCol & "1:" & vSearchCol & "1")
Then use .column property:
debug.print rng.column
if you need full code see below:
Function ColumnbyName(vInput As Variant, Optional bByName As Boolean = True) As Variant
Dim Rng As Range
If bByName Then
If Not VBA.IsNumeric(vInput) Then
Set Rng = ThisWorkbook.Worksheets("mytab").Range(vInput & "1:" & vInput & "1")
ColumnbyName = Rng.Column
Else
MsgBox "Please enter valid non Numeric column or change paramter bByName to False!"
End If
Else
If VBA.IsNumeric(vInput) Then
ColumnbyName = VBA.Chr(64 + CInt(vInput))
Else
MsgBox "Please enter valid Numeric column or change paramter bByName to True!"
End If
End If
End Function
I guess this essentially works out pretty much the same as some of the other answers, but it may make a little more clear what's going on with the alpha equivalent of a numeric digit. It's not quite a base 26 system because there is no 0 placeholder. That is, the 26th column would be 'A0' or something instead of Z in base 26. And it's not base 27 because the 'alpha-gits' don't represent powers of 27. Man, it really makes you appreciate what a mess arithmetic must have been before the Babylonians invented the zero!
UInt32 sum = 0, gitVal = 1;
foreach (char alphagit in ColumnName.ToUpperInvariant().ToCharArray().Reverse())
{
sum += gitVal * (UInt32)(alphagit - 'A' + 1)
gitVal *= 26;
}
Like some others, I reversed the character array so I don't need to know anything about exponents.
For this purpose I use only one line:
int ColumnNumber = Application.Range[MyColumnName + "1"].Column;

Categories