Looping through an array without throwing exception - c#

Say I have an array of values:
string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };
Then I have a basic loop:
for (int i = 0; i <= 30; i++)
{
Console.WriteLine(i + " = " + text[i])
}
Obviously, this will cause an out of bounds exception, so what I want to do is when the counter reaches the upper bound of the array then go back to the start.
So
0 = val1
1 = val2
2 = val3
3 = val4
4 = val5
5 = val1
6 = val2
7 = val3
etc..

You could use the modulus operator:
Console.WriteLine(i + " = " + text[i % 5])

Take the modulus of the array length:
for (int i = 0; i < 30; ++i)
{
Console.WriteLine(i + " = " + text[i % text.Length]);
}

Try
for(int i=0;i<=30;i++)
{
Console.WriteLine(i + " = " + string[i % 5])
}

Shouldn't it be:
Console.WriteLine(i + " = " + text[i % text.length])
?

As a slightly less specific solution...
class Program
{
static void Main(string[] args)
{
string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };
int count = 0;
foreach (string t in text.ContinuousLoopTo(30))
{
Console.WriteLine(count.ToString() + " = " + t);
count++;
}
Console.ReadLine();
}
}
public static class Extensions
{
public static IEnumerable<T> ContinuousLoopTo<T>(this IList<T> list, int number)
{
int loops = number / list.Count;
int i = 0;
while (i < loops)
{
i++;
foreach (T item in list)
{
yield return item;
}
}
for (int j = 0; j < number % list.Count; j++)
{
yield return list[j];
}
}
}

what? like forever?
bool run = true;
int i = 0;
string[] text = new string[] {"val1", "val2", "val3", "val4", "val5"};
while(run)
{
Console.WriteLine(i + " = " + text[i])
i++;
if(i>=text.Length) i=0;
}

The writeline should be:
Console.WriteLine(i + " = " + text[i%5]);

Related

how to calculate totals and minimum spanning trees using arrays

I'm working on a C# assignment in which i have to create a minimum spanning tree through the use of arrays. My code is made up of three arrays which track the nodes and whether or not they have been reached. I have to find the smallest total for all of the randomly generated links to be added up to visit all of the nodes. However, for some reason it is not quite working. The totals being produced are not correct and just wondered if anyone could help me work out why.I believe the error must be between the calculating of the total or how the minimum value is being decided or possible both however i am unsure.
So far i have tried changing the way it is calculated to involve a sum variable to store the values seperately. Ive attempted to add another if statement that would stop the min value from being anything above 98 ( the void value is 99) i have also tried to alter the earlier code to see if how i am testing the values in the SP array are the desired ones. still no results
int n = 5; //n = number of values
int m = 50; //m = max value in arra
int VoidValue = 99; // if i = j value = void value
int Total = 0; //Total value for spanning tree
int sum = 0; //Sum for total value for spanning tree
Random Rand = new Random(); //Create randomise value
int[,] c = new int[n + 1, n + 1]; //Cost array
int[] SP = new int[n + 1]; //Spanned array
int[,] AD = new int[n + 1, n + 1]; //Adjacency array
for (int i = 1; i <= n; i++)
{
SP[i] = 0;
for (int j = 1; j <= n; j++)
{
if (i == j)
{
c[i, j] = VoidValue; // give void spaces the value of 99
AD[i, j] = 0;
}
else
{
c[i, j] = Rand.Next(1, m); // Populate the array with randomised values
AD[i, j] = 0;
}
}
}
//Output all arrays to screen
Console.WriteLine("Cost Array: At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("c[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("c[" + i + "," + j + "] = " + c[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Spanned Array : At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Adjacency Array : At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("A[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("A[" + i + "," + j + "] = " + AD[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
// Random Starting Point
int startPoint = Rand.Next(1, n + 1);
Console.WriteLine("Start at node " + startPoint);
SP[startPoint] = 1;
//Check the spanned array
Console.WriteLine("");
Console.WriteLine("Spanned Array : After the starting point has been chosen ");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
// Find minimum vallue link, repeatedly follow these links until spanned array is full
for (int p = 1; p < n; p++) // For every value of the spanned array
{
int MinValue = VoidValue, MinValuei = 0, MinValuej = 0; // declare variables
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++) // I and J are for both variables of the cost and adjacent array
if (i != j)
{
if (SP[i] == 1) //Spanned node
{
if (SP[j] == 0) //Unspanned node
{
if (c[i, j] < MinValue)
{
MinValue = c[i, j];
MinValuei = i;
MinValuej = j;
}
}
}
}
AD[MinValuei, MinValuej] = 1;
SP[MinValuej] = 1;
}
Console.WriteLine("");
Console.WriteLine("The min value is: " + MinValue);
Total = Total + MinValue;
Console.WriteLine("");
Console.WriteLine("The total is: " + Total);
}
//Finally output spanned and adjacent arrays
Console.WriteLine("");
Console.WriteLine("Spanned Array: After spanning tree");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Adjacency Array : After spanning tree");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("A[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("A[" + i + "," + j + "] = " + AD[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
//Output total value for the spanning tree
Console.WriteLine("");
Console.WriteLine("The total value for the spanning tree: " + Total);
Console.WriteLine("");
Console.ReadLine();

Print a List of ints as a matrix

I have a List of 9 integers and I want to print all elements from the list as a matrix 3,3. And I have to avoid unnecessary white space on the end of every line.
Is it possible to use String.Join ?
Thanks.
Here's my code:
int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray();
int[][] matrix = new int[input[0]][];
for (int i = 0; i < input[0]; i++)
{
int[] line = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
matrix[i] = line;
}
List<int> arr = new List<int>(9);
List<int> arr1 = new List<int>(9);
arr = Enumerable.Repeat(0, 9).ToList();
//for (int i = 0; i < 9 ; i++) sum[i%3, i/3] = 0;
for (int row = 0; row < input[0] - 2; row++)
{
for (int col = 0; col < input[1] - 2; col++)
{
arr1.Add(matrix[row][col]);
arr1.Add(matrix[row][col + 1]);
arr1.Add(matrix[row][col + 2]);
arr1.Add(matrix[row + 1][col]);
arr1.Add(matrix[row + 1][col + 1]);
arr1.Add(matrix[row + 1][col + 2]);
arr1.Add(matrix[row + 2][col]);
arr1.Add(matrix[row + 2][col + 1]);
arr1.Add(matrix[row + 2][col + 2]);
if (arr1.Sum() > arr.Sum())
{
arr = arr1.Select(a => a).ToList();
}
arr1.Clear();
}
}
Console.WriteLine($"Sum = {arr.Sum()} ");
// print the list as a matrix
This is how I would print it using String.Join:
List<int> asd = new List<int> {1,2,3,4,5,6,7,8,9};
for (int i = 0; i < asd.Count; i +=3)
{
Console.WriteLine(string.Join(" ",asd.Skip(i).Take(3)));
}
Explanation: Walk in steps of 3. Skip the amount of numbers equal to the stepsize and take 3 to combine a row of the matrix.
You should reconsider the accepted answer because the performance is poorly with many items.
It may be irrelevant for your current count of items but still hear my warning.
I ran the following code snippet:
var sb = new StringBuilder();
for (int i = 0; i < asd.Count; i +=3)
sb.AppendLine(string.Join(" ", asd.Skip(i).Take(3)));
Console.WriteLine(sb.ToString());
used a StringBuilder to remove the time relevant Console.WriteLine(); for every item in the loop.
This approach takes 756,115ms to complete, with 1,000,000 items.
Created the asd list like this:
var asd = Enumerable.Range(0, 1000000).ToList();
Every other answer given so far will perform way better.
The reason why the accepted solution performs this poorly is because of the .Skip() that is getting called inside the loop, it doesn't actually skip and go directly to this Position instead it again and again loops the list till it reaches this point.
My solution would be:
Console.WriteLine(string.Concat(asd.Select((x, i) => (i + 1) % 3 != 0 ? x + " " : x + Environment.NewLine)));
Which executes the same task in 8,610ms
For completness:
Wojtek's solution takes: 7,932ms
Nirmal Subedi' solution takes: 8,088ms
Note:
Changed it so that it uses a StringBuilder to build the string and only output the string once to the console, instead of calling Console.WriteLine() in a loop
Here my complete test routine:
var asd = Enumerable.Range(0, 1000000).ToList();
var sw1 = new Stopwatch();
sw1.Start();
Console.WriteLine(string.Concat(asd.Select((x, i) => (i + 1) % 3 != 0 ? x + " " : x + Environment.NewLine)));
sw1.Stop();
var sw2 = new Stopwatch();
sw2.Start();
var sb1 = new StringBuilder();
for (int i = 0; i < asd.Count; i += 3)
sb1.AppendLine(string.Join(" ", asd.Skip(i).Take(3)));
Console.WriteLine(sb1.ToString());
sw2.Stop();
var sw3 = new Stopwatch();
sw3.Start();
var sb2 = new StringBuilder();
int counter = 0;
string output = "";
foreach (int value in asd)
{
counter++;
if (counter % 3 == 0)
{
output += value;
sb2.AppendLine(output);
output = string.Empty;
}
else
output += value + " ";
}
Console.WriteLine(sb2.ToString());
sw3.Stop();
var sw4 = new Stopwatch();
sw4.Start();
var sb3 = new StringBuilder();
for (int i = 0; i <asd.Count / 3; i++)
{
int index = i * 3;
sb3.AppendFormat("{0} {1} {2}", asd[index], asd[index + 1], asd[index + 2]);
sb3.AppendLine();
}
Console.WriteLine(sb3.ToString());
sw4.Stop();
Console.WriteLine("MySolution: " + sw1.ElapsedMilliseconds);
Console.WriteLine("Mong Zhu's Solution: " + sw2.ElapsedMilliseconds);
Console.WriteLine("Wojtek's Solution: " + sw3.ElapsedMilliseconds);
Console.WriteLine("Nirmal Subedi's Solution: " + sw4.ElapsedMilliseconds);
Console.ReadKey();
Now You have your code pasted. Anyway, I created the sample to print the 3x3 matrix.
class Program
{
static void Main(string[] args)
{
StringBuilder stringBuilder = new StringBuilder();
List<int> numbers = new List<int>() {1,2,3,4,5,6,7,8,9 };
for (int i = 0; i <3; i++)
{
int index = i * 3;
stringBuilder.AppendFormat("{0}{1}{2}", numbers[index], numbers[index + 1], numbers[index + 2]);
stringBuilder.AppendLine();
}
Console.Write(stringBuilder.ToString());
Console.ReadLine();
}
}
Is that what you meant?
string output = string.Empty;
List<int> myList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int counter = 0;
foreach (int value in myList)
{
output += value.ToString();
counter++;
if (counter % 3 == 0)
{
Console.WriteLine(output);
output = string.Empty;
}
}

How to put an if else statement in a loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
This is my code. So far this works but I need it to be in a loop, so I don't keep repeating the if else statement.
static void Main(string[] args)
{
int i, j, k, l, m, n;
int result;
string [] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
i = array[0].Length;
j = array[1].Length;
k = array[2].Length;
l = array[3].Length;
m = array[4].Length;
n = array[5].Length;
result = i * j;
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * k;
}
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * l;
}
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * m;
}
if (result == 16)
{
Console.WriteLine(array[0]+" * "+array[4]+" = "+result);
}
else
{
result = i * n;
}
If you create an outer loop that loops over all the entries and then an inner loop that loops over the entries after the one you're looking at in the outer loop, you can do something like this
string[] array = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
for (var i = 0; i < array.Length; i++)
{
for (var j = i + 1; j < array.Length; j++)
{
if (array[i].Length * array[j].Length == 16)
{
Console.WriteLine($"{array[i]} {array[j]}");
}
}
}
You then get the result which is abcw xtfn
One of the possible way to short your code.
You can iterate your array and compare first item with rest of the items as you mentioned in your question code-block. No need to access individual array elements.
Compare 1st element with rest
static void Main(string[] args)
{
int result;
string[] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
for (int i = 0; i < array.Length - 2; i++)
{
result = array[0].Length * array[i + 1].Length;
if (result == 16)
{
Console.WriteLine(array[0] + " * " + array[i+1] + " = " + result);
break;
}
}
Console.ReadLine();
}
Compare all element in between
for (var i = 0; i < array.Length; i++)
for (var j = i + 1; j < array.Length; j++)
if (array[i].Length * array[j].Length == 16)
Console.WriteLine(array[i] + " * " + array[j] + " = " + array[i].Length * array[j].Length);
string[] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
int result = 16;
for (var i = 0; i < array.Length; i++) {
int x = array[i].Length;
if (result % x != 0) {
continue;
}
for (var j = i + 1; j < array.Length; j++) {
if (x * array[j].Length == result) {
Console.WriteLine(array[i] + "*" + array[j] + "= " + result);
}
}
}

Misunderstanding With If and Else

I'm new to C# and would like some help!
I am working on some code that allows the user to find out if specific cows on his farm aren't producing enough milk.
On line 75 the if statement is supposed to print out the cows that 'are not good enough' or Tell the user that everything is OK. But instead it permanently try's to print the Bad Cows.
Console.WriteLine("How many cows are in your herd?");
int CowNum = int.Parse(Console.ReadLine());
int Temp;
double TempD;
string TempS;
int MinimumVal = 6;
int MDIR = 4;
string[] BadList = new string[CowNum];
int[] Counter = new int[CowNum];
double[] Total = new double[CowNum];
string[] Days = new string[7] {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
string[] CowID = new string[CowNum];
double[,] CowYield = new double[CowNum, 7];
Random r = new Random();
for (int n = 0; n < CowNum; n++) // Sets Cow ID's
{
Console.WriteLine("What is the ID of Cow: " + (n + 1) + "?" );
TempS = (Console.ReadLine());
CowID[n] = TempS;
}
for (int n = 0; n < CowNum; n++) // Sets the Yield of each cow to a certin day
for (int x = 0; x < Days.GetLength(0); x++)
{
Console.WriteLine("What was the Yeild for Cow: " + CowID[n] + " on " + Days[x] + "?");
TempD = double.Parse(Console.ReadLine());
CowYield[n, x] = TempD;
if (TempD < MinimumVal)
{
Counter[n] = Counter[n] + 1;
Console.WriteLine(Counter[n]);
}
//Console.WriteLine("What was the Yeild for Cow: " + CowID[n] + " on " + Days[x] + "?"); //Randomly Generated 'Saves Time'
//Temp = r.Next(0, 20);
//Console.WriteLine(Temp);
//CowYield[n, x] = Temp;
}
for (int n = 0; n < CowNum; n++)
for (int x = 0; x < Days.GetLength(0); x++)
Total[n] = Total[n] + CowYield[n, x];
for (int n = 0; n < CowNum; n++)
{
if (Counter[n] > MDIR)
{
BadList[n] = CowID[n];
Console.WriteLine("asd" + BadList[n]);
}
}
int index = Array.IndexOf(Total, Total.Max()); // Gets index of Highest producing cow
TempS = CowID[index];
Console.WriteLine("\nThe Highest producing cow is Cow: " + TempS + ". with a whopping " + Total[index] + "L of Milk!\n");
if (BadList.GetLength(0) > 0)
{
Console.WriteLine(BadList.GetLength(0));
for (int n = 0; n < BadList.GetLength(0); n++)
{
Console.WriteLine(BadList[n]);
}
}
else
{
Console.WriteLine("None of your cows had less than 6L of milk for four or more days in a row!");
}
Console.ReadLine();
}
In short your code fails beause
(For ease of all of us, heres a simplified one)
string[] thing = new string[200]
if (thing.Length>0)
{ Console.WriteLine("All wrong");}
else
{ Console.WriteLine("OK");}
Your Length of thing is always 200 because you made it that big. So output is always "All wrong"
However if you had
List<String> thing = new List<String>();
//process list here, and use thing.Add(badcow)
if (thing.Count() >0 )
{ Console.WriteLine("All wrong");}
else
{ Console.WriteLine("OK");}
then it will work because there maybe 0 entries in the list. It may produce both answers and will pick as you expected.

SJF Algorithm Sorting C#

Thats my code . I want to use a faster sorting algorithm maybe quick sort or comb sort. i sorted the list twice first according to arrival then to brust time.
i need help implementing a faster sorting algorithm My main mwthod
static void Main(string[] args)
{
//----------------------------------------Reading I/O File--------------------------------------
string s = Environment.CurrentDirectory.ToString(); // returns the directory of the exe file
if (File.Exists(s + #"\input.txt")) //checking if the input files exists
Console.WriteLine("File Exists");
else
{
Console.WriteLine("File Not Found");
Console.WriteLine("-----------------------------------------------------");
return;
}
Console.WriteLine("-----------------------------------------------------");
//----------------------------------------Data Into List--------------------------------------
string FileText = File.ReadAllText(s + #"\input.txt"); //reading all the text in the input file
string[] lines = FileText.Split('\n'); //splitting the lines
List<Process> processes = new List<Process>();
for (int i = 1; i < lines.Length; i++)
{
string[] tabs = lines[i].Split('\t');//splitting the tabs to get objects' variables
Process x = new Process(tabs[0], int.Parse(tabs[1]), int.Parse(tabs[2]), int.Parse(tabs[3]));//creating object
processes.Add(x);//adding object to the list
}
// ----------------------------------------Sorting The List--------------------------------------
Process temp;
for (int k = 0; k < processes.Count; k++)
{
for (int i = k + 1; i < processes.Count; i++)
{
if (processes[k].arrivalTime > processes[i].arrivalTime)
{
temp = processes[i];
processes[i] = processes[k];
processes[k] = temp;
}
}
}
int tempClock = 0;
for (int i = 0; i < processes.Count; i++)
{
if (processes[i].arrivalTime > tempClock)
tempClock = processes[i].arrivalTime;
for (int k = i + 1; k < processes.Count; k++)
{
if (processes[k].arrivalTime <= tempClock && processes[k].brust < processes[i].brust)
{
temp = processes[i];
processes[i] = processes[k];
processes[k] = temp;
}
}
tempClock += processes[i].brust;
}
Console.WriteLine("Processes After Sorting");
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("Name\tArrival\tBrust\tPriority");
for (int i = 0; i < processes.Count; i++)
{
Console.Write(processes[i].name + "\t" + processes[i].arrivalTime + "\t" + processes[i].brust + "\t" + processes[i].priority);
Console.WriteLine();
}
Console.WriteLine("-----------------------------------------------------");
//----------------------------------------Gantt Chart--------------------------------------
Console.WriteLine("Gantt Chart");
Console.WriteLine("-----------------------------------------------------");
int counter = 0;
for (int i = 0; i < processes.Count; i++)
{
Console.Write(processes[i].name + "\t");
if (processes[i].arrivalTime < counter)
printSpaces(counter);
else
{
printSpaces(processes[i].arrivalTime);
counter = processes[i].arrivalTime;
}
printHashes(processes[i].brust);
counter += processes[i].brust;
Console.WriteLine();
}
Console.WriteLine("-----------------------------------------------------");
//-----------------------------------Completing Data And final Table-------------------------
int clock = 0, totalwait = 0, totalturnAround = 0;
for (int i = 0; i < processes.Count; i++)
{
if (processes[i].arrivalTime > clock)
{
processes[i].start = processes[i].arrivalTime;
clock += processes[i].start - processes[i].arrivalTime;
clock += processes[i].brust;
}
else
{
if (i > 0)
processes[i].start = processes[i - 1].end;
clock += processes[i].brust;
}
if (processes[i].start > processes[i].arrivalTime)
processes[i].wait = processes[i].start - processes[i].arrivalTime;
else processes[i].wait = 0;
processes[i].end = processes[i].start + processes[i].brust;
processes[i].turnAround = processes[i].wait + processes[i].brust;
totalwait += processes[i].wait;
totalturnAround += processes[i].turnAround;
}
Console.WriteLine("Name\tArrival\tBrust\tStart\tEnd\tWait\tturnaround");
for (int i = 0; i < processes.Count; i++)
{
Console.Write(processes[i].name + "\t" + processes[i].arrivalTime + "\t" + processes[i].brust + "\t" + processes[i].start + "\t" + processes[i].end + "\t" + processes[i].wait + "\t" + processes[i].turnAround);
Console.WriteLine();
}
double att = 0, awt = 0;
awt = (double)totalwait / (double)processes.Count;
att = (double)totalturnAround / (double)processes.Count;
Console.WriteLine("A.W.T= {0}", awt + "\t A.T.T= " + att);
Console.ReadKey();
}
Class Process
class Process
{
public Process(string name, int arrivalTime, int brust, int priority)
{
this.name = name;
this.arrivalTime = arrivalTime;
this.brust = brust;
this.priority = priority;
}
public Process()
{
}
public string name;
public int arrivalTime;
public int brust;
public int priority;
public int wait;
public int end;
public int start;
public int turnAround;
}
I would recommend you to have look at Parallel Sort Algorithm for inspiration.
I am also assuming that you want some kind of help implementing it, which with the above solution would be something like
// The contents of processes must implement IComparable<T>
QuicksortParallelOptimised(processes, 0, processes.Count);
But do please try to state a clear question :)
Adding the definition of the IComparable interface to your process-class;
partial class Process : IComparable<Process>
{
public override int CompareTo(Process otherProcess)
{
if (this.arrivalTime == otherProcess.arrivalTime)
return this.brust.CompareTo(otherProcess.brust);
return this.arrivalTime.CompareTo(otherProcess.brust);
}
}
Doing what I've stated so far would leave you with one round of sorting, and it would also make your code a hell of a lot more readable :)
If you have any questions just ask :)

Categories