Why won't this loop increment a variable? - c#

I am trying to do a calculation which involves a do while loop in c#
I want to execute the loop and minus the quantum from the remainingTime array and assign the new value to timeelapsed.
My loop should execute while timeelapsed is > 0 and stop once it hits 0
However, the loop does not carry out the - quantum part of the code, i don't understand why.
static void Main(string[] args)
{
int quantum, noOfProcesses, processNumber = 0; // noOfprocesses variable is to determine array sizes, processNumber tells user what process number they input
int timeelapsed, count = 0;
Console.WriteLine("Please enter the number of processes:");
noOfProcesses = Convert.ToInt32(Console.ReadLine()); // allows numerical input
int[] bursttime = new int[noOfProcesses];
int[] arrivalTime = new int[noOfProcesses];
int[] remainingTime = new int[noOfProcesses];
for (int i = 0; i < noOfProcesses; i++)
{
Console.WriteLine("Enter Burst time for process #" + processNumber);
bursttime[i] = Convert.ToInt32(Console.ReadLine());
processNumber++;
}
processNumber = 1; // resets the process number for user interface
for (int i = 0; i < noOfProcesses; i++)
{
Console.WriteLine("Enter arrival time for process #" + processNumber);
arrivalTime[i] = Convert.ToInt32(Console.ReadLine());
processNumber++;
}
Console.WriteLine("Enter the time quantum:");
quantum = Convert.ToInt32(Console.ReadLine()); // allows numerical input
// calculations
processNumber = 0;
if (count <= noOfProcesses)
{
// remainingTime[0] = bursttime[0] + arrivalTime[0]; // burst + arrival = remaining time
for (int i = 0; i < noOfProcesses; i++)
{
do
{
remainingTime[i] = bursttime[i] + arrivalTime[i]; // burst + arrival = remaining time
timeelapsed = remainingTime[i] - quantum; // - the quantum gives whats remaining
timeelapsed = timeelapsed - quantum;
}
while (timeelapsed > 0);
Console.WriteLine("#" + processNumber + " Time taken: " + timeelapsed + "ms");
processNumber++;
count++;
//timeelapsed = bursttime[i] + arrivalTime[i];
}
}
// Console.WriteLine(arrivalTime[j]);
Console.ReadLine();
}
Please note that the noOfProcesses and processNumber variables are defined in the program i don't believe these are causing the issue.

All you are doing in this loop is recalculating the same values over and over again:
do {
remainingTime[i] = bursttime[i] + arrivalTime[i]; // burst + arrival = remaining time
timeelapsed = remainingTime[i] - quantum; // - the quantum gives whats remaining
timeelapsed = timeelapsed - quantum;
} while (timeelapsed > 0);
For example, you might see this if you use real numbers:
do {
remainingTime = 100 + 100;
timeelapsed = 200 - 10
timeelapsed = 190 - 10;
} while (timeelapsed > 0);
The loop never ends. I'm not sure exactly what your goal is, but you probably need to keep a running total, like:
remainingTime[i] += bursttime[i] + arrivalTime[i];
Or
remainingTime[i] -= bursttime[i] + arrivalTime[i];

This is really debugging and tough to decide without having the code in front of me. I'm assuming that the 'quantum' code is the section in the do part of the loop. In which case, the only reason why it isn't running is one of the three:
noOfProcesses is less than 1
timeelapsed is <= 0
It is getting to the first iteration of the loop but an exception is being thrown.
Since you're using c#, and hopefully VS, you should use the debugger and step through your program.

Related

Calculating Estimated Time Left in Loop (When iteration number is very big and time required for each iteration is very low)

I'm trying to calculate total time remaining of a for loop. Total number of iterations can be more than ~1010000000. Total time required for doing "Real job done here" is much lower than a second and it doesnt change much. When i use my current solution time remaining increases for a long time and than starts to decrease.
I'm looking for a better solution. What can i do?
long totalTiles = ((((rightBottom.X) - (topLeft.X)) + 1) * (((rightBottom.Y) - (topLeft.Y)) + 1));
long currentTileProccessed = 0;
DateTime startTime = DateTime.Now;
for (long x = (topLeft.X); x <= (rightBottom.X); x++)
{
for (long y = (topLeft.Y); y <= (rightBottom.Y); y++)
{
**//Real job done here//**
TimeSpan timeRemaining = TimeSpan.FromTicks(DateTime.Now.Subtract(startTime).Ticks * (totalTiles - (currentTileProccessed + 1)) / (currentTileProccessed + 1));
this.Dispatcher.Invoke((Action)delegate () {
EstimatedTimeLeft_TextBlock.Text = "Days : " + timeRemaining.Days.ToString("D2") + ", Hours : " + timeRemaining.Hours.ToString("D2") + ", Minutes :" + timeRemaining.Minutes.ToString("D2") + ", Seconds :" + timeRemaining.Seconds.ToString("D2");
});
currentTileProccessed++;
}
}
Here I am using Stopwatch from System.Diagnostics to determine the average time for the last 100 tasks, which I multiply against the total expected number of tasks minus the number already run.
NOTE: Remaining time can still increase, if suddenly the last 100 tasks start running slower than the previous 10k, this will readjust your remaining time to match the recent runs.
long totalTiles = ((((rightBottom.X) - (topLeft.X)) + 1) * (((rightBottom.Y) - (topLeft.Y)) + 1));
long currentTileProccessed = 0;
Queue<long> taskTimes = new Queue<long>();
int taskTimeHistoryLimit = 100;
long taskTotal = (rightBottom.X - topLeft.X) * (rightBottom.Y - topLeft.Y);
Stopwatch watch = new Stopwatch();
long index = 0;
for (long x = (topLeft.X); x <= (rightBottom.X); x++)
{
for (long y = (topLeft.Y); y <= (rightBottom.Y); y++)
{
index++;
watch.Start();
//Real job done here//
watch.Stop();
taskTimes.Enqueue(watch.ElapsedTicks);
watch.Reset();
while (taskTimes.Count > taskTimeHistoryLimit)
{
taskTimes.Dequeue();
}
TimeSpan timeRemaining = new TimeSpan((taskTotal - index) * (long)taskTimes.Average());
this.Dispatcher.Invoke((Action)delegate () {
EstimatedTimeLeft_TextBlock.Text = "Days : " + timeRemaining.Days.ToString("D2") + ", Hours : " + timeRemaining.Hours.ToString("D2") + ", Minutes :" + timeRemaining.Minutes.ToString("D2") + ", Seconds :" + timeRemaining.Seconds.ToString("D2");
});
}
}

How to limit the number of cycles of a loop under some condition?

I make a loop like this :
int total;
total = ((toVal - fromVal) + 1) * 2;
RadProgressContext progress = RadProgressContext.Current;
progress.Speed = "N/A";
finYear = fromVal;
for (int i = 0; i < total; i++)
{
decimal ratio = (i * 100 / total);
progress.PrimaryTotal = total;
progress.PrimaryValue = total;
progress.PrimaryPercent = 100;
progress.SecondaryTotal = 100; // total;
progress.SecondaryValue = ratio;//i ;
progress.SecondaryPercent = ratio; //i;
progress.CurrentOperationText = "Step " + i.ToString();
if (!Response.IsClientConnected)
{
//Cancel button was clicked or the browser was closed, so stop processing
break;
}
progress.TimeEstimated = (total - i) * 100;
//Stall the current thread for 0.1 seconds
System.Threading.Thread.Sleep(100);
}
Now i want a specific method to run according to toVal & fromVal
in the previous loop but not with the same number of cycles
i want to to run it in a loop like this :
for (fromVal; fromVal < toVal ; fromVal++)
{
PrepareNewEmployees(calcYear, fromVal);
}
for example :
fromVal = 2014
toVal = 2015
so i want to run twice not 4 times! like this :
PrepareNewEmployees(calcYear, 2014);
PrepareNewEmployees(calcYear, 2015);
but in the previous loop for (int i = 0; i < total; i++)
You're missing the point of progress bar updating. You're not supposed to run 4 iterations and do some work every 2 iterations, but the oposite. Do a loop like:
for (int i = fromVal; i < toVal; i++)
{
PrepareNewEmployees(...);
decimal ratio = ((double)toVal-i)/(toVal-fromVal) *100;
//Some other things, that need to be done twice in an iteration
}
Because you are using Thread's already, consider to implement following:
public void ResetProgress()
{
SetProgress(0);
}
public SetProgress(int percents)
{
// set progress bar to a given percents/ratio
// you will have to use Invoke and blablabla
}
Then any your job will looks like this
ResetProgress();
// note: you need to remember from which value you start to be able to calculate progress
for (int i = startVal; i < toVal ; i++)
{
PrepareNewEmployees(calcYear, i);
SetProgress(100 * (i - startVal) / (toVal - startVal)); // in percents [0-100]
}
// optional, required if you exit loop or use suggestion below
SetProgress(100);
You can also optimise it, to do not update progress after each step, but after certain numbers of steps. To example, instead of calling SetProgress you do
if(i % 10 == 0)
SetProgress();
This will calls SetProgress ten times less often. Of course, there are some assumptions, like: i starts from 0 and if you want to have 100% bar at the end, then i should be dividable by 10. Just an idea to start.

Need help accepting 7 double values representing tips earned by a waiter each day during the week

Here's the problem:
Write a program named TipsList that accepts seven double values
representing tips earned by a waiter each day during the week. Display
each of the values along with a message that indicates how far it is
from the average.
This is what I have figured out so far.
static void Main(string[] args)
{
double[] tips;
tips = new double[7];
double one = tips[0];
double two = tips[1];
double three = tips[2];
double four = tips[3];
double five = tips[4];
double six = tips[5];
double seven = tips[6];
double average = (one + two + three + four + five + six + seven) / 7;
//Now I am trying to take the tip 1,2,3,4,5,6, and 7 that the user has entered
//And display the diffrence of tip 1,2,3,4,5,6, and 7 from the average
//So one-average = tip 1 console.Write tip1 ??????
for (int i = 0; i <= 6; i++)
{
Console.Write("Please enter the amount of tips earned by waiter #" + i + ".");
tips[i] = Console.Read();
Console.Write("tips 1????????????HELP");
}
}
}
I have an understanding of how I would try and do it and think I should do
one-average = tip 1 console.Write tip1 ?????
but C# doesn't like it. I just don't get it still does C# only let me do it in 1 determined way.
I just realised this is for a class so I'd stay away from Linq, it would be too obvious for any teacher.
Simply just write out the value of each taken away from the average
foreach(double tip in tips)
{
Console.WriteLine(Average - tip);
}
Edit Just realised the problem is getting the input.
Your better off to use TryParse as this will handle invalid input
while(!double.TryParse(Console.ReadLine(), out tips[i]))
{
Console.WriteLine("Thats not a valid number");
}
Use somthing like this:
double[] tips = new double[7];
for (int i = 0; i < tips.Length; i++)
{
Console.Write("Please enter the amount of tips earned by waiter #" + i + ": ");
tips[i] = double.Parse(Console.ReadLine());
}
double average = tips.Average();
//without linq
/*
double sum = 0;
for (int i = 0; i < tips.Length; i++)
{
sum = sum + tips[i];
}
double average = sum / tips.Length;
*/
for (int i = 0; i < tips.Length; i++)
{
Console.WriteLine("Tip #" + i + " is: " + tips[i] + " - The difference between the average is: " + Math.Abs(tips[i] - average));
}
Console.ReadLine()
I was doing this program myself, and i realized that it is actually asking for a 2D array hence the 7 inputs for the 7 days of the week. you can accomplish that by usingdouble[,] tips = new double[7, 7];Then you would use 2 loops to access each index element
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 7; j++)
{
tips[i, j] = int.Parse(Console.ReadLine());
}
}`
Then you would first get an average(i.e add the sum of all indexes per day(7) or for the week(49) depending on how accurate you would want your data to be, then divide)

Console Application, App Freezes No Errors

Okay at the moment I my self am new to programming and learning it slowly. At the moment I am taking programming classes to help better understand programming. I have ran in to a problem that has stumped me.
Now while I can do the assignment in a different way and manner as compared to what I provided. My question is, why is this happening? I get no errors, what so ever, the only thing that happens is after the input the Console Fezzes. I want to know what I did wrong.
static void Main(string[] args)
{
double[] Population = new double[6];
string[] Years = { "2", "3", "4", "5", "6", "7" };
double GrowthPercentage = 0.0;
double MathPercentage = 0.0000;
double ActualGrowth = 0.0;
int WhileCounter = 0;
//Ask user for Population of Roarkville
Console.WriteLine("Enter the Population of RoarkVille: ");
//Read Population and store
Population[0] = Convert.ToDouble(Console.ReadLine());
//Ask user for Growth percentage
Console.WriteLine("Enter the Growth percentage ");
//Read Growth Percentage
GrowthPercentage = Convert.ToDouble(Console.ReadLine());
//Calculation of Growth Percentage: Growth Percentage/100 = Math Percentage
MathPercentage = GrowthPercentage / 100;
//ActualGrowth = Population * Math Percentage
//Population2 = ActualGrowth + Population
while (WhileCounter < 5)
{
ActualGrowth = Population[WhileCounter] + MathPercentage;
WhileCounter++;
Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
//Display 2012 Population
//Display 2013 Population
//Display 2014 Population
//Display 2015 Population
//Display 2016 Population
//Display 2017 Population
Console.ReadLine();
}
so what happen is that when you input on the growth percentage using this code:
while (Counter < 5)
{
ActualGrowth = Population[Counter] + MathPercentage;
Counter++;
Population[Counter] = ActualGrowth + Population[Counter--];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
the numbers that will you input will be infinite on the growth percentage:
this one can help you also
while (Counter < 5)
{
ActualGrowth = Population[Counter] + MathPercentage;
Counter++;
Population[Counter] = ActualGrowth + Population[Counter-1];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
The ++ operator changes the actual value of the variable, so WhileCounter++ increases the variable by 1
The -- operator does the same, which is not what you want to do in the line
Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
Instead, use WhileCounter - 1 , like so
Population[WhileCounter] = ActualGrowth + Population[WhileCounter - 1];
WhileCounter++;
Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
The value of WhileCounter never changes as far as the loop is concerned. In the loop body you increment WhileCounter and proceed to immediately decrement it, so the condition WhileCounter < 5 is always true.
You may as well have written
int WhileCounter = 0;
while(WhileCounter < 5)
{
WhileCounter += 1; // WhileCounter == 1
WhileCounter -= 1; // WhileCounter == 0
}
// aint never gunna happen
You should read up on the following operators and understand what they actually do:
--
++

C# - Getting a RawFraction Performance Counter to show a persistent value

I've created a performance counter that shows a fraction of an incremented value (RawFraction type) over a base value (RawBase).
Unfortunately, when monitoring this value, it only shows the percentage when one of the counters is incremented. At all other times it it is sampled, it shows 0. Is there some way to tell the counter to hold onto the last value until the next time it needs to recalculate the fraction?
It's hard to know what went wrong for you without seeing any of your code but here's an example of it being used correctly (from: http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecountertype.aspx)
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
public class App
{
private static PerformanceCounter PC;
private static PerformanceCounter BPC;
public static void Main()
{
ArrayList samplesList = new ArrayList();
// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the counters.
if (SetupCategory())
return;
CreateCounters();
CollectSamples(samplesList);
CalculateResults(samplesList);
}
private static bool SetupCategory()
{
if (!PerformanceCounterCategory.Exists("RawFractionSampleCategory"))
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData rf = new CounterCreationData();
rf.CounterType = PerformanceCounterType.RawFraction;
rf.CounterName = "RawFractionSample";
CCDC.Add(rf);
// Add the base counter.
CounterCreationData rfBase = new CounterCreationData();
rfBase.CounterType = PerformanceCounterType.RawBase;
rfBase.CounterName = "RawFractionSampleBase";
CCDC.Add(rfBase);
// Create the category.
PerformanceCounterCategory.Create("RawFractionSampleCategory",
"Demonstrates usage of the RawFraction performance counter type.",
PerformanceCounterCategoryType.SingleInstance, CCDC);
return (true);
}
else
{
Console.WriteLine("Category exists - RawFractionSampleCategory");
return (false);
}
}
private static void CreateCounters()
{
// Create the counters.
PC = new PerformanceCounter("RawFractionSampleCategory",
"RawFractionSample",
false);
BPC = new PerformanceCounter("RawFractionSampleCategory",
"RawFractionSampleBase",
false);
PC.RawValue = 0;
BPC.RawValue = 0;
}
private static void CollectSamples(ArrayList samplesList)
{
Random r = new Random(DateTime.Now.Millisecond);
// Initialize the performance counter.
PC.NextSample();
// Loop for the samples.
for (int j = 0; j < 100; j++)
{
int value = r.Next(1, 10);
Console.Write(j + " = " + value);
// Increment the base every time, because the counter measures the number
// of high hits (raw fraction value) against all the hits (base value).
BPC.Increment();
// Get the % of samples that are 9 or 10 out of all the samples taken.
if (value >= 9)
PC.Increment();
// Copy out the next value every ten times around the loop.
if ((j % 10) == 9)
{
Console.WriteLine("; NextValue() = " + PC.NextValue().ToString());
OutputSample(PC.NextSample());
samplesList.Add(PC.NextSample());
}
else
Console.WriteLine();
System.Threading.Thread.Sleep(50);
}
}
private static void CalculateResults(ArrayList samplesList)
{
for (int i = 0; i < samplesList.Count; i++)
{
// Output the sample.
OutputSample((CounterSample)samplesList[i]);
// Use .NET to calculate the counter value.
Console.WriteLine(".NET computed counter value = " +
CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i]));
// Calculate the counter value manually.
Console.WriteLine("My computed counter value = " +
MyComputeCounterValue((CounterSample)samplesList[i]));
}
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
// Formula from MSDN -
// Description - This counter type shows the ratio of a subset to its set as a percentage.
// For example, it compares the number of bytes in use on a disk to the
// total number of bytes on the disk. Counters of this type display the
// current percentage only, not an average over time.
//
// Generic type - Instantaneous, Percentage
// Formula - (N0 / D0), where D represents a measured attribute and N represents one
// component of that attribute.
//
// Average - SUM (N / D) /x
// Example - Paging File\% Usage Peak
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
private static Single MyComputeCounterValue(CounterSample rfSample)
{
Single numerator = (Single)rfSample.RawValue;
Single denomenator = (Single)rfSample.BaseValue;
Single counterValue = (numerator / denomenator) * 100;
return (counterValue);
}
// Output information about the counter sample.
private static void OutputSample(CounterSample s)
{
Console.WriteLine("+++++++++++");
Console.WriteLine("Sample values - \r\n");
Console.WriteLine(" BaseValue = " + s.BaseValue);
Console.WriteLine(" CounterFrequency = " + s.CounterFrequency);
Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp);
Console.WriteLine(" CounterType = " + s.CounterType);
Console.WriteLine(" RawValue = " + s.RawValue);
Console.WriteLine(" SystemFrequency = " + s.SystemFrequency);
Console.WriteLine(" TimeStamp = " + s.TimeStamp);
Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec);
Console.WriteLine("++++++++++++++++++++++");
}
}

Categories