Index was outside the bounds of the array - integers - c#

I have just run across a problem which is common but I'm not sure why it's happening in this instance.
string s;
int c1, c2, c3, c4;
private void button2_Click(object sender, EventArgs e)
{
String number;
s = textBox1.Text;
int[] d = s.Select(c => (int)c - (int)'0').ToArray();
try
{
c1 = (4 * d[1] + 10 * d[2] + 9 * d[3] + 2 * d[4] + d[5] + 7 * d[6]) % 11;
c2 = (7 * d[1] + 8 * d[2] + 7 * d[3] + d[4] + 9 * d[5] + 6 * d[6]) % 11;
c3 = (9 * d[1] + d[2] + 7 * d[3] + 8 * d[4] + 7 * d[5] + 7 * d[6]) % 11;
c4 = (d[1] + 2 * d[2] + 9 * d[3] + 10 * d[4] + 4 * d[5] + d[6]) % 11;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
number = d[1]+d[2]+d[3]+d[4]+d[5]+d[6]+c1+c2+c3+c4.ToString();
textBox2.Text = number;
}
It will accept the number in the first TextBox(es) fine. As soon as it moves onto the catch section it will pop up with an error Index was outside the bounds of the array Is there something obvious I'm missing? or is this quite unique to my program?

I bellieve that you think your array goes from 1 to 6.
Its from 0 to 5.

You should ensure that your TextBox contains at least 6 characters else it gives an exception:
if(textBox1.Text.Length >= 6)
{
//your code here
}
else
MessageBox.Show("You must insert at least 6 characters");
And then remember that the index of the array starts from 0 not 1.

How many chars are in the input string s = textBox1.Text;?
You don't perform any check on the user input.
For example
textBox1.Text = "1234"; // only 4 digits
then, when you try to use index 4/5/6 you get the error.
Of course, you should also consider that arrays indexes start at zero not at one.
In my input above, you will have only index from 0 to 3.
A simple check should be (Assuming you've already ruled out non-numeric data by other means)
s = textBox1.Text;
if(s.Length != 6)
MessageBox.Show("6 digits required!");
else
.......

Related

Difficulty understanding logic of the implemented algorithm - C#

I am finding it hard to understand the logic of the following algorithm that outputs 8,8. I would appreciate if you could provide some insight.
using System;
namespace Console_Example
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(g(4) + g(5) + "," + g(6));
Console.ReadKey();
}
static int g(int k)
{
if ((k == 1) || (k == 2))
return 1;
else
return g(k - 1) + g(k - 2);
}
}
}
Just a recursive function. You have to follow all steps.
if k = 1:
return 1;
if k = 2:
return 1;
if k = 3:
return (g(2) + g(1)) result is: 1 + 1 = 2
if k = 4:
return (g(3) + g(2)) result is: (1 + 1) + 1 = 3
if k = 5:
return (g(4) + g(3)) result is: 5 + 3 = 5
if k = 6:
return (g(5) + g(4)) result is: 5 + 3 = 8
This looks very similar to the Fibonacci sequence (wikipedia), where each number is the sum of the two previous numbers.
Because it is a recursive function, look at the return g(k - 1) + g(k - 2); where it calls itself, you must follow all the recursion until it ends.
g(1): 1 -- Because the return 1;
g(2): 1 -- Because the return 1;
g(3): g(2) + g(1) = 1 + 1 = 2 -- Here starts the recursion
g(4): g(3) + g(2) = 2 + 1 = 3
g(5): g(4) + g(3) = 3 + 2 = 5
g(6): g(5) + g(4) = 5 + 3 = 8
So g(4) + g(5) +"," +g(6) would be:
3 + 5 , 8 = 8, 8
Pretty much the sum of the F4 F5 resulting in the F6 value.
A better implementation of the Fibonacci sequence would be
static int Fibonacci(int k)
{
if(k < 0)
throw new ArgumentException("Fibonnaci works with numbers >= 0");
if (k == 0 || k == 1)
return k;
else
return Fibonacci(k - 1) + Fibonacci(k - 2);
}

Wrong sum is calculated in c# when trying to generate a valid number

I'm trying to generate a random number in the range specified and then decide if its valid or not based on some simple arithmetic.
The sum (right after the DEBUG comment) is supposed to be, for example
222 222 222
121 212 121
(the 121 212 121 coefficients are added to each digit. if the product of the numbers is more than 9, then the sum of the digits of the product is recorded otherwise just the product is recorded (21 or 22 in this situation.)
using 222 222 222 as an example number the sum would be...
21 + 22 + 21 + 22 + 21 + 22 + 21 + 22 + 2*1 = 26 in this situation.
The above operations are supposed to be made to the random number generated above, from the specified range. The problem is that this sum is incorrect, when checking it by hand. Please help...
private void button1_Click(object sender, EventArgs e)
{
bool sinvalid = false;
Random randomsin = new Random();
//do until a valid sin is found
do
{
int rsin = randomsin.Next(100000000, 799999999); //get a new random sin
if (Validate(rsin.ToString()) == true) //if validate returns true
{
textBox1.Text = rsin.ToString(); //put the valid sin in the textbox
sinvalid = true; //set current sin to valid
}
} while (sinvalid == false);
}
bool Validate(String sin)
{
int sum = Cdig(sin[0], 1) + Cdig(sin[1], 2) + Cdig(sin[2], 1) + Cdig(sin[3], 2) + Cdig(sin[4], 1) + Cdig(sin[5], 2) + Cdig(sin[6], 1) + Cdig(sin[7], 2) + Cdig(sin[8], 1);
//DEBUG: show this sum, which is always calculated WRONG!~ WHY
label1.Text = sum.ToString();
if (sum % 10 == 0) //if sum is divisible by 10
{
return true;
}
else
{
return false;
}
}
int Cdig(int dig, int n )
{
int dm = dig * n;
if (dm > 9)
{
return 1 + (dm % 10);
}
else
{
return dm;
}
}
i had to convert the chars from sin[0], sin[1] ..etc. to integers.
int sum = Cdig(sin[0]-'0', 1) + Cdig(sin[1]-'0', 2) + Cdig(sin[2]-'0', 1) + Cdig(sin[3]-'0', 2) + Cdig(sin[4]-'0', 1) + Cdig(sin[5]-'0', 2) + Cdig(sin[6]-'0', 1) + Cdig(sin[7]-'0', 2) + Cdig(sin[8]-'0', 1);
strange but it works
Because you're summing char not int
You can use Char.GetNumericValue or you can getbytes from string and use unsafe code
var sum = 0;
var n = 1;
for (int i = 0; i < sin.Length; i++)
{
//int sum = Cdig
var dig = (int) Char.GetNumericValue(sin[i]);
sum += Cdig(dig, n);
if (n == 1)
n = 2;
if (n == 2)
n = 1;
}

C# How do i reverse modulus when using a ^ sign

At the moment i have this formula:
13^2 mod 5 = 4
I want to calculate back the 2 here like:
13^X mod 5 = 4
X = ?
I found several formula's/codes to do this online but i didn't find any which do it with a ^ symbol.
Would appreciate some help
My client received everything besides the TEST_PRIVATE so i want to calculate that.
This is the code i use (server sided)
(This is the encryption, not the decryption)
string TEST_GENERATED = "13";
string TEST_PRIVATE = "2";
string TEST_PRIME = "5";
BigIntegerTEST TESTMOD_1 = new BigIntegerTEST(TEST_GENERATED, 10);
BigIntegerTEST TESTMOD_2 = new BigIntegerTEST(TEST_PRIVATE, 10);
BigIntegerTEST TESTMOD_3 = new BigIntegerTEST(TEST_PRIME, 10);
BigIntegerTEST TESTMOD_4 = TESTMOD_1.modPow(TESTMOD_2, TESTMOD_3);
So basicly i want to reverse TESTMOD_4 to TESTMOD_2
By only using TESTMOD_4, TESTMOD_3 and TESTMOD_1
(I know modPow usually has 3 parameters i'm using a special class for it)
TDLR;
Working example:
(6 + 7) MOD 10 = 3
(3 - 6 + 10) MOD 10 = 7
This is the main result i want:
( I want to retrieve the 7)
(6^7) MOD 10 = 6
? = 7
it is here and much simple like this function:
public double DoCalc(double Number1, double Number2, double Number3)
{ return (Math.Pow(Number1, Number2)) % Number3; }
Then call it from the button click event, like this:
private void btmDoCalc_Click(object sender, EventArgs e)
{
// Here show it up in message box directly.
MessageBox.Show("DoCalc= " + DoCalc(13, 2, 5).ToString());
// Here assign it to some double variables.
double N1 = 0, N2 = 0, N3 = 0;
N1 = DoCalc(13, 2, 4);
N2 = DoCalc(13, 2, 3);
N3 = DoCalc(13, 2, 2);
MessageBox.Show("DoCalc= " + N1);
MessageBox.Show("DoCalc= " + N2);
MessageBox.Show("DoCalc= " + N3);
}
Here is some more images for the results.
I hope this answers your questions ^_^

What will be the output of this and how?

The output of this code is
0 1 2 3
But I am not getting the factorial part. I mean 1!=1 (i.e. i factorial equals to 1), so it does not satisfy the condition, so type for input 2 and 3, but they get printed as output?
static void Main(string[] args)
{
int i = 0;
int b = 8, a = 32;
for (i = 0; i <= 10; i++)
{
if ((a / b * 2)== 2)
{
Console.WriteLine( i + " ");
continue;
}
else if (i!=4)
Console.Write(i + " ");
else
break;
}
Console.ReadLine();
}
OK, let's see:
int b = 8, a = 32;
...
a / b * 2 == 32 / 8 * 2 == 4 * 2 == 8
That's why if ((a / b * 2) == 2) will never succeed, and so we can drop this if and simplify the loop into
for (i = 0; i <= 10; i++)
if (i != 4) // i != means "i doesn't equal", not "i factorial equals"
Console.Write(i + " "); // print 0, 1, 2, 3
else
break; // break on 4
Here we can clearly see that the routine will be printing out i up to 4 So you have
0 1 2 3
Side note: in order to avoid such errors, format out your code and let the compiler help you:
i!=4 // Bad, it can be read in different ways (not equal or factorial)
i != 4 // i is not equal to 4
i! = 4 // assign 4 to i factorial: compile time error
i! == 4 // i factorial equals to 4: compile time error - C# doesn't have factorials

Get range in multiplication of 5

I have a number. For instance, my number is 19 . Then I want to populate my drop down with range in multiplication of 5. So my dropdownlist will consist of items of:
1-5
6-10
11-15
16-19
I tried modulus and division, however, I can't seems to get the range. Is there a fixed method?
Sample code
List<string> range = new List<string>();
int number = 19;
int numOfOccur = (19/5);
for (int i = 1; i < numOfOccur ; i++)
{
range.Add(i + " - " + (i * 5))
}
Sometime I think that old school code, without fancy linq is a bit more clear
int maximum = 19;
int multiple = 5;
int init = 1;
while (init + multiple <= maximum )
{
string addToDDL = init.ToString() + "-" + (init + multiple - 1).ToString();
Console.WriteLine(addToDDL);
init += multiple;
}
if(init <= maximum)
{
string last = init.ToString() + "-" + maximum.ToString();
Console.WriteLine(last);
}
Linq solution (modern techs allow us to put it consize):
int number = 19;
int div = 5;
List<string> range = Enumerable
.Range(0, number / div + (number % div == 0 ? 0 : 1))
.Select(i => $"{i * div + 1} - {Math.Min((i + 1) * div, number)}")
.ToList();
Test
Console.Write(string.Join(Environment.NewLine, range));
Returns
1 - 5
6 - 10
11 - 15
16 - 19
When using modulo arithmetics, do not forget about remainders: you have an error in int numOfOccur = (19/5); line. It should be
int numOfOccur = 19 / 5 + (19 % 5 == 0 ? 0 : 1);
for the last incomplete 16 - 19 range to be proceeded.
Add this package to your project : https://www.nuget.org/packages/System.Interactive/
Then you can do this:
IEnumerable<IList<int>> buffers2 = Enumerable.Range(1, 19).Buffer(5);
IList<int>[] result2 = buffers2.ToArray();
// { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, ...
Don't forget to add System.Interactive namespace to your using block.

Categories