Finding employee that made the most from array? - c#

I have managed to get the "least" Calculated however the code for "most" is not working... what I have currently.
for (int i = 0; i < workerGrossIncome.Length; i++)
if (workerGrossIncome[i] > workerGrossIncome[maxIndex])
{
maxIndex = i;
workerMost = workerName[i];
workerRegularPayMost = workersRegularPay[i];
workerGrossIncomeMost = workerGrossIncome[i];
}
edit with full code: (Currently Learning cannot use built in array methods)
Program runs however uses the defaults when calculating for the worker that made the most during the work week.
const double FEDERAL_TAX_DEDUCTION = .10; //10% of Gross Income
const double STATE_TAX_DEDUCTION = .05; //5% of Gross Income
const double workerOvertimePay = 0.00; //If Employee Does No Overtime
static void Main(string[] args)
{
int MAX_LIST_VALUE;
Write("How Many Worker's Are Working? ");
MAX_LIST_VALUE = Convert.ToInt32(ReadLine());
string[] workerName = new string[MAX_LIST_VALUE];
for (int i = 0; i < MAX_LIST_VALUE; i++)
{
WriteLine("Please Enter The Worker's Name: ");
workerName[i] = ReadLine();
}
double[] workerWages = new double[MAX_LIST_VALUE];
for (int i = 0; i < MAX_LIST_VALUE; i++)
{
WriteLine("Please Enter The Worker's Hourly Wage: ");
workerWages[i] = Convert.ToDouble(ReadLine());
}
double[] workerWeeklyHours = new double[MAX_LIST_VALUE];
for (int i = 0; i < MAX_LIST_VALUE; i++)
{
Write("How many hours has {0} worked this week? ", workerName[i]);
workerWeeklyHours[i] = Convert.ToDouble(ReadLine());
}
double[] workersRegularPay = new double[MAX_LIST_VALUE];
double[] workerGrossIncome = new double[MAX_LIST_VALUE];
double[] workerStateTaxAmount = new double[MAX_LIST_VALUE];
double[] workerFederalTaxAmount = new double[MAX_LIST_VALUE];
double[] workerNetIncome = new double[MAX_LIST_VALUE];
for (int i = 0; i < MAX_LIST_VALUE; i++)
{
workersRegularPay[i] = workerWeeklyHours[i] * workerWages[i];
workerGrossIncome[i] = workerWeeklyHours[i] * workerWages[i];
workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
}
WriteLine("There Are " + MAX_LIST_VALUE + " Workers!");
for (int i = 0; i < MAX_LIST_VALUE; i++)
{
WriteLine("Worker's Name: " + workerName[i]);
WriteLine(workerName[i] + " Hourly Wage: " + workerWages[i].ToString("C"));
WriteLine(workerName[i] + " Hours Wokred This Week: " + workerWeeklyHours[i]);
WriteLine(workerName[i] + " Regular Pay: " + workersRegularPay[i].ToString("C"));
WriteLine(workerName[i] + " Gross Income Pay: " + workerGrossIncome[i].ToString("C"));
WriteLine(workerName[i] + " State Tax Amount: " + workerStateTaxAmount[i].ToString("C"));
WriteLine(workerName[i] + " Federal Tax Amount: " + workerFederalTaxAmount[i].ToString("C"));
WriteLine(workerName[i] + " Net Income: " + workerNetIncome[i].ToString("C"));
}
ForegroundColor = ConsoleColor.Red;
WriteLine("\nPress Enter To Continue For Worker's That Earned The Least & Most.");
ReadLine();
int minIndex = 0;
string workerLeast = "null";
double workerRegularPayLeast = 0,
workerGrossIncomeLeast = 0,
workerOverTimeLeast = 0;
int maxIndex = 0;
string workerMost = "null";
double workerRegularPayMost = 0,
workerGrossIncomeMost = 0,
workerOverTimeMost = 0;
for (int i = 0; i < workerGrossIncome.Length; i++)
if (workerGrossIncome[i] < workerGrossIncome[minIndex])
{
minIndex = i;
workerLeast = workerName[i];
workerRegularPayLeast = workersRegularPay[i];
workerGrossIncomeLeast = workerGrossIncome[i];
}
for (int i = 0; i < workerGrossIncome.Length; i++)
if (workerGrossIncome[i] > workerGrossIncome[maxIndex]) //Doesnt calc the most..... FIX
{
maxIndex = i;
workerMost = workerName[i];
workerRegularPayMost = workersRegularPay[i];
workerGrossIncomeMost = workerGrossIncome[i];
}
ForegroundColor = ConsoleColor.Green;
WriteLine("\nThe Worker That Earned The Least Is {0}!", workerLeast);
WriteLine("{0}'s Gross Income Was {1}.", workerLeast, workerGrossIncomeLeast.ToString("C"));
WriteLine("{0}'s Regular Pay Was {1}.", workerLeast, workerRegularPayLeast.ToString("C"));
WriteLine("{0}'s Overtime Pay Was {1}.", workerLeast, workerOverTimeLeast.ToString("C"));
ForegroundColor = ConsoleColor.Cyan;
WriteLine("\nThe Worker That Earned The Most Is {0}!", workerMost);
WriteLine("{0}'s Gross Income Was {1}.", workerMost, workerGrossIncomeMost.ToString("C"));
WriteLine("{0}'s Regular Pay Was {1}.", workerMost, workerRegularPayMost.ToString("C"));
WriteLine("{0}'s Overtime Pay Was {1}.", workerMost, workerOverTimeMost.ToString("C"));
ReadLine();
}
}
Error is in the loop for worker earning the most. The rest is fine for whats needed.

Without LINQ
If you can't use LINQ, then change your maxIndex variable declaration to:
int? maxIndex = null;
And the start of your loop to:
for (int i = 0; i < workerGrossIncome.Length; i++)
if (maxIndex == null || workerGrossIncome[i] > workerGrossIncome[maxIndex.Value])
to ensure that the code work even when the first element is the largest one.
Your existing code does not work if the first element is the largest since workerGrossIncome[i] > workerGrossIncome[maxIndex] will be false and thus workerMost etc won't be set.
With LINQ
If you add the MoreLINQ Nuget Package then maxIndex can be calculated as follows:
// Sample Data
int[] workerGrossIncome = new[] {1, 2, 4};
var maxIndex = workerGrossIncome
.Select((value, index) => new {index, value})
.MaxBy(z => z.value)
.index;
var workerMost = workerName[i];
var workerRegularPayMost = workersRegularPay[i];
var workerGrossIncomeMost = workerGrossIncome[i];
Select will project the original data and the index. MaxBy will find the item with the largest value. index will return the index of that matching item.

Related

Loop incrementing operations for sugarcane replication

I'm creating an algorithm to calculate area for sugarcane replication.
I have an initial planted area of 5 hectares. These 5 hectares will be cut off when fully grown and then cloned in the proportion of 1:7 So my second area will have 35 Hectares (5*7)
The next areas will have a decreased propotion, because it gets lower at every cut.
So the third area will be (5*6) + (35*7)
forth area: (5*5) + (35*6) + (245 * 7) and so on. The user will input number for iteration and proportions to multiply.
doing by hand it would something like this:
area[0] = initialArea;
area[1] = area[0] * proportion[0]; // = 35
area[2] = area[0] * proportion[1] + area[1] * proportion[0];
area[3] = (area[0] * proportion[2]) + (area[1] * proportion[1]) + (area[2] * proportion[0]);
area[4] = (area[0] * proportion[3]) + (area[1] * proportion[2]) + (area[2] * proportion[1]) + (area[3] * proportion[0]);
area[5] = (area[0] * proportion[4]) + (area[1] * proportion[3]) + (area[2] * proportion[2]) + (area[3] * proportion[1]) + (area[4] * proportion[0]);
Is there a way I can put this inside a loop?
Yes, you can make that into a for-loop.
The loop for each iteration is:
for (int n = 0; n < iteration; n++)
{
area[iteration] += area[n] * proportion[iteration - n - 1];
}
which you can wrap with the number of iterations:
for (int i = 1; i <= iterations; i++)
{
for (int n = 0; n < i; n++)
{
area[i] += area[n] * proportion[i - n - 1];
}
}
you will have to intialize with area[0] = intialArea. With input:
Console.Write("Enter inital area: ");
double initialArea = double.Parse(Console.ReadLine());
Console.Write("Enter proportions, separate each proportion with spaces: ");
string input = Console.ReadLine();
double[] proportion = input.Split(' ').Select(x => double.Parse(x)).ToArray();
int iterations = proportion.Length;
Console.WriteLine($"Using {iterations} iterations");
double[] area = new double[proportion.Length + 1];
area[0] = initialArea;
for (int i = 1; i <= iterations; i++)
{
Console.Write($"Iteration = {i}: ");
for (int n = 0; n < i; n++)
{
area[i] += area[n] * proportion[i - n - 1];
Console.Write($"area[{n}] = {area[n]} ");
}
Console.WriteLine();
}
Console.ReadLine();

Bucket sorting string arrays and merging sorted buckets. Indexing Issue

Here is the code it's able to run (w/ output issues):
Another "issue" when I output the buckets sorted with a loop it outputs the "blank" array spaces as well(as expected). How could I tell the program to "skip" empty entries on output to console? (bit lost atm) been trying for hours...
Bucket sort loses items from original array
The program takes the random data in the program and sorts by last name into buckets then sorting the "buckets" with a bubble sorts.
Thank you to anyone in advance.
Current issue is located lines:
int y = 0;
for (int a = 0; a < (studentInfo.Length - 1); a++)
{ //no idea...Errors at a = 14... because the a + 1 index...so uh
if (String.Compare(studentInfo[a].studentLastName, studentInfo[a + 1].studentLastName) > 0)
bucketOne[y] = studentInfo[a].studentLastName;
else
bucketTwo[y] = studentInfo[a].studentLastName;
y++;
}
Full/:
class Program
{
struct StudentIDs
{
public int studentIDs;
public string studentLastName;
public string studentFirstName;
}
struct UserStudentIDs
{
public int UserstudentIDs;
public string UserstudentLastName;
public string UserstudentFirstName;
}
static void Main(string[] args)
{
StudentIDs[] studentInfo = new StudentIDs[15];
studentInfo[0].studentIDs = 331;
studentInfo[0].studentLastName = "Thomas";
studentInfo[0].studentFirstName = "Joe";
studentInfo[1].studentIDs = 225;
studentInfo[1].studentLastName = "Smith";
studentInfo[1].studentFirstName = "Lisa";
studentInfo[2].studentIDs = 002;
studentInfo[2].studentLastName = "Jones";
studentInfo[2].studentFirstName = "Tina";
studentInfo[3].studentIDs = 333;
studentInfo[3].studentLastName = "White";
studentInfo[3].studentFirstName = "Bryan";
studentInfo[4].studentIDs = 998;
studentInfo[4].studentLastName = "Huff";
studentInfo[4].studentFirstName = "John";
studentInfo[5].studentIDs = 500;
studentInfo[5].studentLastName = "Street";
studentInfo[5].studentFirstName = "Zak";
studentInfo[6].studentIDs = 772;
studentInfo[6].studentLastName = "Abel";
studentInfo[6].studentFirstName = "Karen";
studentInfo[7].studentIDs = 222;
studentInfo[7].studentLastName = "Streit";
studentInfo[7].studentFirstName = "Susan";
studentInfo[8].studentIDs = 332;
studentInfo[8].studentLastName = "Thomas";
studentInfo[8].studentFirstName = "Dan";
studentInfo[9].studentIDs = 141;
studentInfo[9].studentLastName = "Bryient";
studentInfo[9].studentFirstName = "Bill";
studentInfo[10].studentIDs = 880;
studentInfo[10].studentLastName = "Forte";
studentInfo[10].studentFirstName = "Mary";
studentInfo[11].studentIDs = 900;
studentInfo[11].studentLastName = "Ferguson";
studentInfo[11].studentFirstName = "Fran";
studentInfo[12].studentIDs = 220;
studentInfo[12].studentLastName = "Worke";
studentInfo[12].studentFirstName = "Elaine";
studentInfo[13].studentIDs = 635;
studentInfo[13].studentLastName = "Knapp";
studentInfo[13].studentFirstName = "Justin";
studentInfo[14].studentIDs = 445;
studentInfo[14].studentLastName = "Dustin";
studentInfo[14].studentFirstName = "Tom";
WriteLine(" STUDENT INFO: (Unsorted Data) ");
for (int i = 0; i < studentInfo.Length; i++)
{
WriteLine("Student ID #: {0} ------ Last Name: {1} -- First Name: {2} ",
studentInfo[i].studentIDs, studentInfo[i].studentLastName, studentInfo[i].studentFirstName);
}
Write("\nPress Enter To Continue! ");
ReadLine();
string[] bucketOne = new string[15];
string[] bucketTwo = new string[15];
int y = 0;
for (int a = 0; a < (studentInfo.Length - 1); a++)
{//no idea...Errors at a = 14... because the a + 1 index...so uh
if (String.Compare(studentInfo[a].studentLastName, studentInfo[a + 1].studentLastName) > 0)
//if ((studentInfo[a].studentLastName.CompareTo(studentInfo[a + 1].studentLastName)) > 0)
bucketOne[y] = studentInfo[a].studentLastName;
else
bucketTwo[y] = studentInfo[a].studentLastName;
y++;
}
//sort two buckets now with bubble sorting counts swaps and compare
int swap = 0,
compare = 0;
string tempString = " ";
bool Swapping;
do
{
Swapping = false;
for (int index = 0; index < (studentInfo.Length - 1); index++)
{
compare++;
if (string.Compare(bucketOne[index], bucketOne[index + 1]) < 0)
{
tempString = bucketOne[index];
bucketOne[index] = bucketOne[index + 1];
bucketOne[index + 1] = tempString;
swap++;
Swapping = true;
}
}
} while (Swapping == true);
//Bubble Sort Two
int swapTwo = 0,
compareTwo = 0;
string tempStringTwo = " ";
bool SwappingTwo;
do
{
SwappingTwo = false;
for (int index = 0; index < (studentInfo.Length - 1); index++)
{
compareTwo++;
if (string.Compare(bucketTwo[index], bucketTwo[index + 1]) < 0)
{
tempStringTwo = bucketTwo[index];
bucketTwo[index] = bucketTwo[index + 1];
bucketTwo[index + 1] = tempStringTwo;
swapTwo++;
SwappingTwo = true;
}
}
} while (SwappingTwo == true);
WriteLine("Bucket One Sorted: ");
for (int i = 0; i < bucketOne.Length; i++)
{
WriteLine("\nLast Names (Bucket One): {0}", bucketOne[i]);
}
Write("\nPress Enter To Continue! ");
ReadLine();
WriteLine("\nBucket Two Sorted: ");
for (int i = 0; i < bucketTwo.Length; i++)
{
WriteLine("\nLast Names (Bucket Two): {0}", bucketTwo[i]);
}
Write("\nPress Enter To Continue! ");
ReadLine();
string[] FullBucket = bucketOne.Union(bucketTwo).ToArray(); // would remove any of the "same" name...
Array.Reverse(FullBucket);
foreach (var StudentLastName in FullBucket)
{
WriteLine(StudentLastName);
}
//string[] FullBucket = new string[15];
//for (int i = 0; i < FullBucket.Length; i++)
//{
// if (i >= bucketOne.Length) //- bucketOne.Length
// FullBucket[i] = bucketTwo[i];
// else
// FullBucket[i] = bucketOne[i];
//}
//string[] FullBucket = bucketOne.Concat(bucketTwo).ToArray();
//string[] FullBucket = new string[15];
//int numOne = 0, //i
// numTwo = 0, //j
// numThree = 0; //k
//// Traverse both array
//while (numOne < bucketOne.Length && numTwo < bucketTwo.Length)
//{
// // Check if current element of first
// // array is smaller than current element
// // of second array. If yes, store first
// // array element and increment first array
// // index. Otherwise do same with second array
// if (string.Compare(bucketOne[numOne], bucketTwo[numTwo]) < 0)//???????????????
// FullBucket[numThree = numThree + numThree] = bucketOne[numOne++];
// else
// FullBucket[numThree++] = bucketTwo[numTwo++];
//}
//// Store remaining elements of first array
//while (numOne < bucketOne.Length)
// FullBucket[numThree++] = bucketOne[numOne++];
//// Store remaining elements of second array
//while (numTwo < (bucketTwo.Length - 1))
// FullBucket[numThree++] = bucketTwo[numTwo++];
//WriteLine(" \nSTUDENT INFO: (Sorted Data) ");
//for (int i = 0; i < (FullBucket.Length - 1); i++) //Length -1 ?????
//{
// WriteLine("Student ID #: {0} ------ Last Name: {1} -- First Name: {2} ",
// studentInfo[i].studentIDs, studentInfo[i].studentLastName, studentInfo[i].studentFirstName);
//}
//ReadLine();
UserStudentIDs[] UserstudentInfo = new UserStudentIDs[20];
int RecordIndex = 0;
WriteLine("Enter Student ID #: ");
UserstudentInfo[RecordIndex].UserstudentIDs = Convert.ToInt32(ReadLine());
WriteLine("You May Enter Up To 20 Records: (Or 999 to Finish)");
while (UserstudentInfo[RecordIndex].UserstudentIDs != 999)
{
WriteLine("Enter Student First Name: ");
UserstudentInfo[RecordIndex].UserstudentFirstName = ReadLine();
WriteLine("Enter Student Last Name: ");
UserstudentInfo[RecordIndex].UserstudentLastName = ReadLine();
RecordIndex++;
WriteLine("Enter Student ID #: ");
UserstudentInfo[RecordIndex].UserstudentIDs = Convert.ToInt32(ReadLine());
}
WriteLine(" USER STUDENT INFO: (Unsorted Data) ");
for (int i = 0; i < RecordIndex; i++) //or user..info.length...etc
{
WriteLine("Student ID #: {0} ------ Last Name: {1} -- First Name: {2} ",
UserstudentInfo[i].UserstudentIDs, UserstudentInfo[i].UserstudentLastName, UserstudentInfo[i].UserstudentFirstName);
}
Write("\nPress Enter To Continue! ");
ReadLine();
string[] bucketThree = new string[20];
string[] bucketFour = new string[20];
int L = 0;
for (int a = 0; a < RecordIndex; a++) // or ? (studentInfo.Length - 1)
{//no idea here again....
if (String.Compare(UserstudentInfo[a].UserstudentLastName, UserstudentInfo[a + 1].UserstudentLastName) > 0)
bucketThree[L] = UserstudentInfo[a].UserstudentLastName;
else
bucketFour[L] = UserstudentInfo[a].UserstudentLastName;
L++;
}
int swapThree = 0,
compareThree = 0;
string tempStringThree = " ";
bool SwappingThree;
do
{
SwappingThree = false;//(studentInfo.Length - 1)
for (int index = 0; index < RecordIndex; index++)
{
compareThree++;
if (string.Compare(bucketThree[index], bucketThree[index + 1]) < 0)
{
tempStringThree = bucketThree[index];
bucketThree[index] = bucketThree[index + 1];
bucketThree[index + 1] = tempStringThree;
swapThree++;
SwappingThree = true;
}
}
} while (SwappingThree == true);
int swapFour = 0,
compareFour = 0;
string tempStringFour = " ";
bool SwappingFour;
do
{
SwappingFour = false; //(studentInfo.Length - 1) or record index?
for (int index = 0; index < RecordIndex; index++)
{
compareFour++;
if (string.Compare(bucketFour[index], bucketFour[index + 1]) < 0)
{
tempStringFour = bucketFour[index];
bucketFour[index] = bucketFour[index + 1];
bucketFour[index + 1] = tempStringFour;
swapFour++;
SwappingFour = true;
}
}
} while (SwappingFour == true);
WriteLine("Bucket Three Sorted: ");
for (int i = 0; i < bucketThree.Length; i++)
{
WriteLine("\nLast Names (Bucket One): {0}", bucketThree[i]);
}
Write("\nPress Enter To Continue! ");
ReadLine();
WriteLine("\nBucket Four Sorted: ");
for (int i = 0; i < bucketFour.Length; i++)
{
WriteLine("\nLast Names (Bucket Two): {0}", bucketFour[i]);
}
Write("\nPress Enter To Continue! ");
ReadLine();
string[] UserFullBucket = bucketThree.Union(bucketFour).ToArray();
Array.Reverse(UserFullBucket);
foreach (var UserStudentLastName in UserFullBucket)
{
WriteLine(UserStudentLastName);
}
ReadLine();
}
}

When I ref bubble sort method and try to print only gives one value?

I am fetching the Grade of the Students. I am trying to fetch Student Grades in sorted order. But when i printed the testgrade variable its just showing only one record at the end.
namespace EX4_GradesMethod
{
class Program
{
static void Main(string[] args)
{
int namelength;
string names;
double grade, max, min, testgradeaverage;
Console.WriteLine("Please enter the amount of names you wish to enter: ");
namelength = Convert.ToInt32(Console.ReadLine());
string[] name = new string[namelength];
double[] testgrades = new double[namelength];
for (int i = 0; i < testgrades.Length; i++)
{
Console.WriteLine("Please enter the names of each student");
names = Convert.ToString(Console.ReadLine());
name[i] += names;
}
for (int i = 0; i < name.Length; i++)
{
Console.WriteLine("Please enter the final grade for " + name[i]);
grade = Convert.ToDouble(Console.ReadLine());
testgrades[i] += grade;
}
max = testgrades.Max();
min = testgrades.Min();
testgradeaverage = testgrades.Average();
Console.WriteLine("The highest grade is: " + max);
Console.WriteLine("The Lowest Grade is:" + min);
Console.WriteLine("The class average is: " + testgradeaverage);
for ( int k = 0; k < namelength - namelength + 1; k++)
{
Console.WriteLine(testgrades[k]);
}
Console.ReadLine();
}
public static void sorted(ref double [] testgrades)
{
double temp = 0;
for (int write = 0; write < testgrades .Length; write++)
{
for (int sort = 0; sort < testgrades.Length - 1; sort++)
{
if (testgrades [sort] > testgrades [sort + 1])
{
temp = testgrades[sort + 1];
testgrades [sort + 1] = testgrades [sort];
testgrades [sort] = temp;
}
}
}
}
}
}

C# How to get the length of chars in a string

I have a []string retry and I have some strings inside of it let's say:
a 2 , a 3 , h 9, asd 123 and so on. They all have intervals between the letter and the integer. Now I need to get how long is the letter part (in this case "qwe 2" the letter length is 3 and the integer part is 2). I'm later using .substring from the specified index at which the letter part finishes and the integer one starts.
string[] s = new string[5];
List<string> retry = new List<string>();
int max = 1;
for (int i = 0; i < s.Length; i++)
{
s[i] = Console.ReadLine();
}
Console.WriteLine(" ");
Array.Sort(s);
for (int j = 0; j < s.Length; j++)
{
if (j > 0)
{
if (s[j] == s[j - 1])
{
max++;
if (retry.Any(x => x.Contains(s[j])))
{
retry.Add(s[j] + " " + max);
}
else
{
if (j <= s.Length - 1)
{
if (s[j-1] != s[j])
{
retry.Add(s[j] + " " + max);
}
else
{
retry.Add(s[j] + " " + max);
}
}
}
}
else
{
max = 1;
}
}
}
for (int j = 0; j < retry.ToArray().Length; j++)
{
for (int k = j + 1; k < retry.ToArray().Length; k++)
{
var a1=retry[j].Substring(0,1);
var a2 = retry[k].Substring(0,1);
if(a1==a2)
{
var b1 = retry[j].Substring(2);
var b2 = retry[k].Substring(2);
if(int.Parse(b1)>int.Parse(b2))
{
retry.Remove(a2 + " "+ b2);
}
else
{
retry.Remove(a1 + " " + b1);
}
}
}
Console.WriteLine(retry[j]);
}
Console.ReadKey();
This only works for 1 letter.
The code below should get the result as expected:
string [] entries = {"xyz 1","q 2","poiuy 4"};
for(int i=0;i<entries.Length;i++)
{
var parts = entries[i].Split(' ');
var txtCount = parts[0].Length;
Console.WriteLine(String.Format("{0} {1}", txtCount, parts[1]));
}
How about...
string[] test = new [] { "qwe 2", "a 2", "b 3", "asd 123" };
foreach (var s in test)
{
var lastLetterIndex = Array.FindLastIndex(s.ToCharArray(), Char.IsLetter);
var lastNumberIndex = Array.FindLastIndex(s.ToCharArray(), Char.IsNumber);
Console.WriteLine(s);
Console.WriteLine("Letter Length : " + (lastLetterIndex + 1));
Console.WriteLine("Number Length : " + (lastNumberIndex - lastLetterIndex));
}
Console.ReadKey();
This iterates through all of the strings and counts the length of the chars, and stores the value of the number, as well as its index. Note that this information is lost upon each iteration, but I'll leave it to you to worry about storing that if you need that information for longer than the duration of an iteration.
int letterLength = 0, number = 0, index = 0;
string[] testString = { "a 2", "a 3", "h 9", "asd 123", "sw", "swa23", "swag 2464" };
foreach (string str in testString)
{
letterLength = 0;
index = -1;
int i = 0;
for (; i < str.Length; i++)
{
char c = str[i];
if (Char.IsLetter(c)) letterLength++;
else if (Char.IsNumber(c)) break;
}
StringBuilder strBuilder = new StringBuilder();
for (; i < str.Length; i++)
{
char c = str[i];
if (index == -1) index = str.IndexOf(c);
strBuilder.Append(c);
number = Int32.Parse(strBuilder.ToString());
}
Console.WriteLine($"String: {str}\nLetter Length: {letterLength} Number: {number} Index: {index}\n");
}

Calculating minimum/maximum/average ping reponse

So here is an application which tests each server of popular RuneScape game. I am running ping on each of 139 servers and add lag value to array. While looping through list entries I can calculate the average, minimum, and maximum lag for each server.
Now, in my code when one of the unreachable servers is noted the lowest lag displays as 0. I'm not sure how to handle if my ping response has reached it's timeout and posts 0 to array list.
What can I do to avoid that 0 as my lowest ping when server is down?
using System;
using System.Net.NetworkInformation;
using System.Collections.Generic;
namespace RuneScape_Ping_Tool
{
class Program
{
static void Main(string[] args)
{
Console.Write(Environment.NewLine + "Start the test? (y/n): ");
if (Console.Read() == char.Parse("y"))
{
Console.WriteLine();
Ping();
}
}
static void Ping()
{
List<int> lag = new List<int>();
for (int server = 1; server <= 139; server++)
{
string url = "world" + server.ToString() + ".runescape.com";
Console.WriteLine("Checking world " + server + "...");
Ping ping = new Ping();
PingReply reply = ping.Send(url);
lag.Add(int.Parse(reply.RoundtripTime.ToString()));
}
for (int i = 1; i <= 139; i++)
{
Console.WriteLine("World " + i + ": " + lag[i - 1]);
}
int average = 0;
int highest = 1;
int lowest = 1000;
int highestWorld = 0;
int lowestWorld = 0;
for (int i = 1; i <= 139; i++)
{
average = average + lag[i - 1];
}
for (int i = 1; i <= 139; i++)
{
if (highest < lag[i - 1])
{
highest = lag[i - 1];
highestWorld = i;
}
}
for (int i = 1; i <= 139; i++)
{
if (lowest > lag[i - 1])
{
lowest = lag[i - 1];
lowestWorld = i;
}
}
Console.WriteLine();
Console.WriteLine("Average lag: " + average / 139);
Console.WriteLine("Highest lag: " + highest + " in world " + highestWorld);
Console.WriteLine("Lowest lag: " + lowest + " in world " + lowestWorld);
Console.Write(Environment.NewLine + "Start the test? (y/n): ");
if (Console.Read() == char.Parse("y"))
{
Console.WriteLine();
Ping();
}
}
}
}
Can you just skip over zeroes? Also, you might as well put all the calculations inside a single loop.
int n = 0 // number of data points
for (int i = 0; i < 139; ++i) {
if (lag[i] == 0) {
continue; // skip 0 values
}
++n;
sum += lag[i];
if (highest < lag[i]) {
highest = lag[i];
highestWorld = i + 1;
}
if (lowest > lag[i]) {
lowest = lag[i];
lowestWorld = i + 1;
}
average = sum / n; // Note: you may want to round this.
}
First consider running everything in parallel (4 at a time here):
var servers = Enumerable.Range(1, 139).Select(i => String.Format("world{0}.runescape.com",i));
var results = servers.AsParallel()
.WithDegreeOfParallelism(4)
.Select(server => new Ping().Send(server))
.ToList();
Then collect just the valid results, note using PingReply.Status rather than checking for 0:
var validResults = results.Where(r => r.Status == IPStatus.Success)
.Select(r => r.RoundtripTime);
Here's the info you need:
Console.WriteLine("Total Results: {0}", results.Count());
Console.WriteLine("Valid Results: {0}", validResults.Count());
Console.WriteLine("Min from Valid: {0}", validResults.Min());
Console.WriteLine("Max from Valid: {0}", validResults.Max());
Console.WriteLine("Avg from Valid: {0}", validResults.Average());
You can get the min, max and average with these functions.
var nozeros = lag.Where(i => i > 0);
int lowest = nozeros.Min();
int lowestWorld = lag.IndexOf(lowest);
int highest = nozeros.Max();
int highestWorld = lag.IndexOf(highest);
int average = (int)nozeros.Average();

Categories

Resources