I have a char array like this:
char[] true_false = new char[2]{'V','F'};
A variable random:
Random rand = new Random();
I have a string called generate_code, with the initial value is true_false[rand.Next(0, 2)].ToString();
string generate_code = true_false[rand.Next(0, 2)].ToString();
And the user will set the int lenght_of;
int lenght_of = int.Parse(Console.ReadLine());
So, what I am trying to do is: the user will define the lenght_of that will be the lenght of the generate_code like this:
for(int i =0; i < lenght_of;i++){
generate_code = generate_code + (char)true_false[rand.Next(0, 2)];
}
But the problem is that I need a fixed variable like :
generate_code = (char)true_false[rand.Next(0, 2)] + (char)true_false[rand.Next(0, 2)];
if lenght_of =2; and I have a loop that will change the generate_code value ten times.How can I do that? **I hope that u guys understand it is hard to explain.
Example:
lenght_of = 2;
//Example "FF";
generate_code = true_false[rand.Next(0, 2)] + true_false[rand.Next(0, 2)];
for(int i =0; i < 10;i++) {
Console.WriteLine(generate_code);
} //Output expected: "FF" "VV" "FV" "VF" "FF"
Your problem is that you're adding two char's together. char is a numeric type.. therefore you're getting numbers as the result. Also, your generate_code assignment must be inside your loop:
for(int i =0; i < 10;i++) {
generate_code = string.Format("{0}", generateCodeWithLength(rand, true_false, lenght_of));
Console.WriteLine(generate_code);
}
Wrap the code generation in a method that accepts the length:
public string generateCodeWithLength(Random rand, char[] true_false, int length) {
var result = new StringBuilder(length);
for (var i = 0; i < length; i++) {
result.Append(true_false[rand.Next(0, 2)]);
}
return result.ToString();
}
Or better yet.. a StringBuilder. Clicky clicky live example.
Alternatively you can also do something like:
for(int i =0; i < 10;i++) {
Console.WriteLine(string.Format("{0}{1}", true_false[rand.Next(0, 2)] + true_false[rand.Next(0, 2)]));
}
You need to refresh generate_code in each iteration of the loop:
for(int i =0; i < 10;i++) {
int loopCounter = 0;
while (loopCounter < length_of)
{
generate_code += true_false[rand.Next(0, 2)]; //Add one more char to generate_code
loopCounter += 1;
}
Console.WriteLine(generate_code);
} //Output expected if length_of = 3: "FFV" "VFV" "FVF" "FFF" "VVV"
That way, each output will be random.
Related
I need to write a factorial using an array but the problem is only Show 120 five times and what i want is 1, 2, 6, 24, 120 showing in the textBox
int factProg = 1;
public void factArray(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
factProg = factProg * arr[i];
}
}
int[] arr = {1,2,3,4,5};
for (int i = 0; i < arr.Length; i++)
{
factArray(arr);
textBox1.Text += Convert.ToString(factProg);
textBox1.Text += Environment.NewLine;
}
Simply put - your factArray method always calculates the factorial for the length of the whole array which is a fixed size. You need to pass an extra parameter - being the position in the array you want to stop calculating
Try this if you want to calculate using your array :
int factProg;
public void factArray(int[] arr, int len)
{
factProg = arr[0];
for (int i = 1; i <= len; i++)
{
factProg = factProg * arr[i];
}
}
int[] arr = {1,2,3,4,5};
for (int i = 0; i < arr.Length; i++)
{
factArray(arr, i);
textBox1.Text += Convert.ToString(factProg);
textBox1.Text += Environment.NewLine;
}
You would need to add a check in the method that you are not exceeding the array length.
Please find the code below
public static void FactorialJohn(int[] arr)
{
List<int> Resarr = new List<int>();
arr.ToList().ForEach(x => Resarr.Add(Enumerable.Range(1, x).Aggregate((a, b) => a * b)));
foreach (var item in Resarr)
{
Console.WriteLine(item);
}
}
The above code gets you factorial of every element in the array.
I have the below code.
int[] a = new int[] { 8, 9 };
for(int i=0;i<n;i++)
{
print i;
int z;
//during first iteration
z=8;
during second iteration
z=9;
}
Output should be something like this.
during first iteration i=0 and z=8
during second iteration i=1 and z=9
array a contains 2 elements. N and number of elements in array a will be always same. next my for loop will execute. during first iteration want z value should be 8(first element of array ) and second iteration my z value should be 9. I want to map 1st element of integer array to first iteration of for loop and so on.
try
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
int z = a[i]; // this line will get value from a one by one, 0, 1, 2, 3 and so on...
}
Edit 1 -
After seeing the comments on the other answer, the array 'a' turns out is a dynamic array which have size n (which is 2)
the revised edition:
int n = 2;
int[] a = new int[n];
string input = null;
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
input = Console.ReadLine();
try {
a[i] = int.Parse(input);
Console.WriteLine(string.Format(
"You have inputted {0} for the {1} element",
input, i
));
} catch { Console.WriteLine("Non integer input"); i -= 1; }
}
you can try this
int [] a = {8,9};
for(int i=0; i< a.Length; i++)
{
int z = a[i]; //for taking value from array at the specific ith position
Console.WriteLine("i: " + i + " z:" + z);
}
try this
List<int> a = new List<int>();
int n = 2; // you can change it according to your need
for (int i = 0; i < n; i++)
{
string str = Console.ReadLine(); // make sure you enter an integer and conver it
int z = int.Parse(str);
a.Add(z);
}
foreach (int k in a)
{
Console.WriteLine(k);
}
I would like to create an array of an array from a text file...
There are 20000 line with 21 strings in each line separated by ',' .
I would like to read each line and make it into an array , each line being a new array within.
So I wanted to create the jagged array by starting it like this:
string[][] SqlArray = new string[200000][21];
But it gives: ERROR MESSAGE : Invalid rank specifier: expected ',' or ]
How would I create this array or initialize it?
I will be populating the data in the array like this:
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
for (int i = 0; i < workingArray.Length; i++)
{
for (int k = 0; k < 20; k++)
{
SqlArray[i][k] = workingArray[k];
}
}
}
Thank you
That type of initialization only works in Java. You must declare an array of arrays then initialize each in a loop.
string[][] SqlArray = new string[21][];
for(int index = 0; index < SqlArray.Length; index++)
{
SqlArray[index] = new string[2000000];
}
Alternatively, you can use a non-jagged array. It will probably work for what you need.
string[,] SqlArray = new string[21 , 2000000];
It can be accessed like so:
SqlArray[2,6264] = x;
To anyone who is interested this is how I ended up implementing it:
TextReader readIn = File.OpenText("..\\..\\datafile.txt");
string[][] SqlArray = new string[rowNumCreate][];
int e = 0;
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
SqlArray[e] = new string[valuesInRow +1];
for (int k = 0; k < workingArray.Length; k++)
{
SqlArray[e][k] = workingArray[k];
}
e++;
}
The file being read is a simple mock database set as a flat file that was auto-generated to test an algorithm that I am implementing, which works with jagged arrays; hence instead of working with a data base I just created this for ease of use and to increase and decrease size at will.
Here is the code to build the text file:
Random skill_id;
skill_id = new Random();
// int counter =0;
string seedvalue = TicksToString();
int rowNumCreate = 200000;
int valuesInRow = 20;
string lineInFile = seedvalue;
string delimiter = ",";
for (int i = 0; i < rowNumCreate; i++)
{
for (int t = 0; t < valuesInRow; t++)
{
int skill = skill_id.Next(40);
string SCon = Convert.ToString(skill);
lineInFile += delimiter + SCon;
}
if (rowNumCreate >= i + 1)
{
dataFile.WriteLine(lineInFile);
lineInFile = "";
string userPK = TicksToString();
lineInFile += userPK;
}
}
dataFile.Close();
public static string TicksToString()
{
long ms = DateTime.Now.Second;
long ms2 = DateTime.Now.Millisecond;
Random seeds;
seeds = new Random();
int ran = seeds.GetHashCode();
return string.Format("{0:X}{1:X}{2:X}", ms, ms2, ran).ToLower();
}
I am still a student so not sure if the code is A-grade but it works :)
Inside a For loop I do not understand following behavior of string.Substring(i,j)
having the code
String line = "TTACCTTAAC";
int k = 3; //this is variable but for simplicity is 3
String _pattern = "";
for (int i = 0; i <= line.Length - k; i++) {
_pattern = line.Substring(i, i + k );
//do something...
}
I am expecting the loop to walk over string Line (TACCTTAAC) (from 0 to 10-3 = 7)like:
TTA
ACC
CCT
CTT
TTA
TAA
AAC
However I get
TTA
ACCT
etc...
What am I missing?
Second parameter of Substring is length, not end, so you should just pass k instead of doing your math:
String line = "TTACCTTAAC";
int k = 3; //this is variable but for simplicity is 3
String _pattern = "";
for (int i = 0; i <= line.Length - k; i++) {
_pattern = line.Substring(i, k);
//do something...
}
substring function in c# is used as string.Substring(int startindex, int Length)
so you should use
_pattern = line.Substring(i, k);
Is there a method that will remove a set amount of characters from a string, placing the removed characters into a separate string and leaving the original x amount of characters shorter?
I need to parse a string into 10 individual strings, each 10 characters long. I would like to be able to do sommething simple like this, but I do not know if there is a method that works like this in C#
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
errorCodes[i] = retrievedMessage.removeFromSubstring(0, 10);
}
You could try this:
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
errorCodes[i] = retrievedMessage.Substring(0, 10);
retrievedMessage = retrievedMessage.Substring(10);
}
The line retrievedMessage = retrievedMessage.Substring(10); will effectively remove the first 10 characters from the original string. This way in each iteration you will be able to use the first 10 characters and assign them to the errorCodes[i]
Also you could try to avoid using substrings:
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
errorCodes[i] = retrievedMessage.Substring(i*10, 10);
}
Edit
Now tested, seems to work fine for me
var errorCodes = "longstringgggggggggggggggggggggggggg";
var count = 10;
List<string> s = new List<string>();
for (int i = 0; i < errorCodes.Length; i += count)
{
if (i + count > errorCodes.Length)
count = errorCodes.Length - i;
s.Add(errorCodes.Substring(i, count));
}
foreach (var str in s)
Console.WriteLine(str);
Console.ReadLine();
This should work for you
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
errorCodes[i] = retrievedMessage.Substring(10*i, 10);
}
Here is an option that will remove from the string retrievedMessage
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
//option to remove from string
errorCodes[i] = retrievedMessage.Substring(0, 10);
retrievedMessage = retrievedMessage.Remove(0,10); //will remove from string
}
Same basic concept as other answers but with a little checking for variable string length. If you know that your string is always 100 chars in length, then use one of the simpler answers.
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
int startIndex = i * 10;
if (retrievedMessage.Length > startIndex)
{
int length = 10;
if (retrievedMessage.Length < (startIndex + length))
{
length = retrievedMessage.Length - startIndex;
}
errorCodes[i] = retrievedMessage.Substring(startIndex, length);
}
}
Note: Since errorCodes is always instantiated with a length of 10, this will have null strings if the length of retrievedMessage is <= 90. If you expect variable length, better to use a List<string> than a string[].