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 :)
Related
My lab is about schedule and I use modified Kron algorithm.
When the button presses the form should print information on 4 richBoxes.
Sometimes everything is OK but sometimes the form freezes and don't answer. If I open the Task Manager window I see that my app takes about 30% CPU. Maybe it's because of cycle in the button? Maybe I should do more buttons? Or what? I don't understand..
So what's the prob?
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;
namespace LW3_OTPR_Forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBoxZ.Text = "3";
textBoxTasks.Text = "12";
textBoxProcs.Text = "4";
textBoxFrom.Text = "10";
textBoxTo.Text = "20";
}
private void buttonGetResult_Click(object sender, EventArgs e)
{
richTextBoxMatrix.Clear();
richTextBox1.Clear();
richTextBox2.Clear();
richTextBox3.Clear();
int z = Convert.ToInt32(textBoxZ.Text);
for (int i = 0; i < z; i++)
{
richTextBox1.Text += "========= Z = " + (i+1) +" ===========";
richTextBox1.Text += Environment.NewLine;
richTextBox2.Text += "========= Z = " + (i + 1) + " ===========";
richTextBox2.Text += Environment.NewLine;
richTextBox3.Text += "========= Z = " + (i + 1) + " ===========";
richTextBox3.Text += Environment.NewLine;
Work.start1(Convert.ToInt32(textBoxTasks.Text), Convert.ToInt32(textBoxProcs.Text),
Convert.ToInt32(textBoxFrom.Text), Convert.ToInt32(textBoxTo.Text));
richTextBoxMatrix.Text += "Матрица " + (i+1);
richTextBoxMatrix.Text += Environment.NewLine;
richTextBoxMatrix.Text += Work.strWork;
var processors = new Individ(Convert.ToInt32(textBoxTasks.Text),
Convert.ToInt32(textBoxFrom.Text),
Convert.ToInt32(textBoxTo.Text),
Convert.ToInt32(textBoxProcs.Text));
var procMonolit = new IndividMonolit(Convert.ToInt32(textBoxTasks.Text),
Convert.ToInt32(textBoxFrom.Text),
Convert.ToInt32(textBoxTo.Text),
Convert.ToInt32(textBoxProcs.Text));
var procKritWay = new IndividKritWay(Convert.ToInt32(textBoxTasks.Text),
Convert.ToInt32(textBoxFrom.Text),
Convert.ToInt32(textBoxTo.Text),
Convert.ToInt32(textBoxProcs.Text));
richTextBox1.Text += processors.print();
richTextBox2.Text += procKritWay.printKritWay();
richTextBox3.Text += procMonolit.printMonolit();
processors.proc.balance();
procKritWay.procKritWay.balanceKritWay();
procMonolit.procMonolit.balanceMonolit();
richTextBox1.Text += processors.proc.inf;
richTextBox2.Text += procKritWay.procKritWay.infKritWay;
richTextBox3.Text += procMonolit.procMonolit.infMonolit;
}
}
}
static class Work
{
public static string strWork;
static public List<List<int>> arrayTask2d { set; get; }
static public List<int> arrayTask { set; get; }
static public void start1(int countWork, int countProc, int t1, int t2)
{
strWork = string.Empty;
int temp = 0;
arrayTask = new List<int>();
arrayTask2d = new List<List<int>>();
List<int> taskRow = new List<int>();
for (int i = 0; i < countWork; i++)
{
temp = Constant.rnd.Next(t2 - t1) + t1 + 1;
arrayTask.Add(temp);
taskRow = new List<int>();
for (int j = 0; j < countProc; j++)
{
taskRow.Add(temp);
}
arrayTask2d.Add(taskRow);
}
for (int i = 0; i < countWork; i++)
{
for (int j = 0; j < countProc; j++)
{
strWork += arrayTask2d[i][j].ToString() + " ";
}
strWork += Environment.NewLine;
}
}
}
class Proc
{
public string inf;
public string infMonolit;
public string infKritWay;
private List<List<int>> procs;
public List<int> this[int i]
{
get
{
return procs[i];
}
set
{
procs[i] = value;
}
}
public int CountProc
{
get { return procs.Count; }
}
public int delta
{
get
{
return procs.Max((a) => { return a.Sum(); }) - procs.Min((a) => { return a.Sum(); });
}
}
public Proc(int countProc)
{
inf = string.Empty;
infMonolit = string.Empty;
infKritWay = string.Empty;
procs = new List<List<int>>();
for (int i = 0; i < countProc; i++)
procs.Add(new List<int>());
}
private int getIndexOfMax()
{
int result = 0;
for (int i = 0; i < procs.Count; i++)
{
if (procs[i].Sum() > procs[result].Sum())
result = i;
}
return result;
}
public int getIndexOfMin()
{
int result = 0;
for (int i = 0; i < procs.Count; i++)
{
if (procs[i].Sum() < procs[result].Sum())
result = i;
}
return result;
}
private void addInf()
{
for (int i = 0; i < procs.Count; i++)
{
inf += " Процессор " + (i + 1).ToString()+ ": ";
for (int j = 0; j < procs[i].Count; j++)
inf += procs[i][j] + " ";
inf += "|| sum = " + procs[i].Sum();
inf += Environment.NewLine;
}
inf += "Δ = " + delta + Environment.NewLine;
}
private void addInfMonolit()
{
for (int i = 0; i < procs.Count; i++)
{
infMonolit += " Процессор " + (i + 1).ToString() + ": ";
for (int j = 0; j < procs[i].Count; j++)
infMonolit += procs[i][j] + " ";
infMonolit += "|| sum = " + procs[i].Sum();
infMonolit += Environment.NewLine;
}
infMonolit += "Δ = " + delta + Environment.NewLine;
}
private void addInfKritWay()
{
for (int i = 0; i < procs.Count; i++)
{
infKritWay += " Процессор " + (i + 1).ToString() + ": ";
for (int j = 0; j < procs[i].Count; j++)
infKritWay += procs[i][j] + " ";
infKritWay += "|| sum = " + procs[i].Sum();
infKritWay += Environment.NewLine;
}
infKritWay += "Δ = " + delta + Environment.NewLine;
}
public void balance()
{
bool flag = true;
int max = 0;
int min = 0;
int dlt = 0;
while (flag != false)
{
max = getIndexOfMax();
min = getIndexOfMin();
for (int i = 0; i < procs[max].Count; i++)
{
dlt = procs[max].Sum() - procs[min].Sum();
if (procs[max][i] < dlt)
{
procs[min].Add(procs[max][i]);
procs[max].RemoveAt(i);
addInf();
balance();
}
}
for (int i = 0; i < procs[max].Count; i++)
{
for (int j = 0; j < procs[min].Count; j++)
{
if (procs[max][i] > procs[min][j] && procs[max][i] - procs[min][j] < delta)
{
//меняем местами
int temp = procs[max][i];
procs[max][i] = procs[min][j];
procs[min][j] = temp;
addInf();
balance();
}
}
}
flag = false;
}
}
public void balanceKritWay()
{
bool flag = true;
int max = 0;
int min = 0;
int dlt = 0;
while (flag != false)
{
max = getIndexOfMax();
min = getIndexOfMin();
for (int i = 0; i < procs[max].Count; i++)
{
dlt = procs[max].Sum() - procs[min].Sum();
if (procs[max][i] < dlt)
{
procs[min].Add(procs[max][i]);
procs[max].RemoveAt(i);
addInfKritWay();
balanceKritWay();
}
}
for (int i = 0; i < procs[max].Count; i++)
{
for (int j = 0; j < procs[min].Count; j++)
{
if (procs[max][i] > procs[min][j] && procs[max][i] - procs[min][j] < delta)
{
//меняем местами
int temp = procs[max][i];
procs[max][i] = procs[min][j];
procs[min][j] = temp;
addInfKritWay();
balanceKritWay();
}
}
}
flag = false;
}
}
public void balanceMonolit()
{
bool flag = true;
int max = 0;
int min = 0;
int dlt = 0;
while (flag != false)
{
max = getIndexOfMax();
min = getIndexOfMin();
for (int i = 0; i < procs[max].Count; i++)
{
dlt = procs[max].Sum() - procs[min].Sum();
if (procs[max][i] < dlt)
{
procs[min].Add(procs[max][i]);
procs[max].RemoveAt(i);
addInfMonolit();
balanceMonolit();
}
}
for (int i = 0; i < procs[max].Count; i++)
{
for (int j = 0; j < procs[min].Count; j++)
{
if (procs[max][i] > procs[min][j] && procs[max][i] - procs[min][j] < delta)
{
//меняем местами
int temp = procs[max][i];
procs[max][i] = procs[min][j];
procs[min][j] = temp;
addInfMonolit();
balanceMonolit();
}
}
}
flag = false;
}
}
}
class Individ
{
int numbJobs;
int numbProc;
private static uint CountIndivids { get; set; }
//массив для создания расписания
//(массив рандомных чисел каждое из которых соответствует заданию)
public List<int> arrayRandom { set; get; }
public List<int> arrayTasks { set; get; }
public List<int> arrayProc;
public Proc proc;
//public Proc procKritWay;
//максимальный порог рандома
int randLimit;
int x, y;
string inf;
public int Max
{
get
{
return arrayProc.Max();
}
}
public int NumberOfJobs
{
get
{
return arrayTasks.Count;
}
}
public int NumberOfProc
{
get
{
return proc.CountProc;
}
}
public int RandomLimit
{
get
{
return randLimit;
}
}
public Individ() { }
public Individ(Individ copy)
{
arrayRandom = new List<int>(copy.arrayRandom);
arrayTasks = new List<int>(copy.arrayTasks);
//arrayProc = new List<int>(copy.arrayProc);
numbJobs = copy.numbJobs;
numbProc = copy.numbProc;
randLimit = copy.randLimit;
x = copy.x;
y = copy.y;
inf = copy.inf;
}
public Individ(int numberOfJobs, int X, int Y, int numberOfProc, int randomLimit = 255)
{
numbJobs = numberOfJobs; numbProc = numberOfProc; randLimit = randomLimit; x = X; y = Y;
arrayTasks = new List<int>(Work.arrayTask);
arrayRandom = new List<int>();
//заполнили массив рандомных чисел и работы
for (int i = 0; i < numbJobs; i++)
arrayRandom.Add(Constant.rnd.Next(0, randLimit));
proc = new Proc(numbProc);
schedule();
}
private void addInf()
{
inf = "Случайный разброс на процессоры: ";
inf += Environment.NewLine;
for (int i = 0; i < numbProc; i++)
{
inf += " Процессор " + (i + 1).ToString() + ":";
for (int j = 0; j < proc[i].Count; j++)
inf += proc[i][j] + " ";
inf += "|| sum = " + proc[i].Sum();
inf += Environment.NewLine;
}
inf += "Δ = " + proc.delta + Environment.NewLine;
}
//построить расписание
void schedule()
{
inf = string.Empty;
int k = 0;
for (int i = 0; i < proc.CountProc; i++)
proc[i].Clear();
for (int i = 0; i < NumberOfJobs; i++)
{
k = Range.rangeToIndexProc(arrayRandom[i], proc.CountProc, randLimit);
proc[k].Add(arrayTasks[i]);
}
addInf();
}
public string getRandomInString()
{
string result = string.Empty;
foreach (var iter in arrayRandom)
result += iter.ToString() + ' ';
return result;
}
public string print()
{
addInf();
return inf;
}
private int getIndexMin(List<int> list)
{
int result = 0;
for (int i = 0; i < list.Count; i++)
if (list[i] < list[result])
result = i;
return result;
}
public delegate bool sort(int x, int y);
private void sortProc()
{
arrayProc.Sort((a, b) => { return a - b; });
}
}
What I want to do is to spread tasks over a number of servers randomly with very little bias if possible. So far what I worked on is able to randomly spread the tasks over a different servers. The problem is that whenever I spread the tasks over the servers, it spreads the 1-3 tasks per server. The load balancing method used is Power of Two Choices. Forgive me if I get the concept wrong.
Power of Two Choices is where two random queues are chosen, where the one with the least tasks, is assigned a task. Correct me if I'm wrong.
The photo below shows my current output.
What I want is this
My main file is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C1._2
{
class Program
{
static void details(Server[] server, int num)
{
int count = 0;
for (int i = 0; i < server.Length; i++)
{
if (server[i].Tasks == num)
{
count++;
}
}
Console.WriteLine("There are " + count + " servers with " + num + " tasks.");
}
static void Main(string[] args)
{
Random rand = new Random();
int n = 256; //number of tasks
int m; //number of servers
m = 64;//Convert.ToInt32(Console.ReadLine())
Console.WriteLine("Number of servers(m): " + m);
int d = 1; //random servers to be chosen
Console.WriteLine("Number of tasks(n): " + n);
Console.WriteLine("Number of randomly selected server(d): " + d);
//Main server setup
Server[] servers = new Server[m];
for (int i = 0; i < m; i++)
{
servers[i] = new Server(i);
}
if (d == 1)
{
for (int i = 0; i < n; i++)
{
int randS = rand.Next(m);
servers[randS].Tasks++;
}
}
//Power of Two choice algorithm is here
if (d == 2)
{
for(int i = 0; i < n; i++)
{
Server s1 = servers[rand.Next(m)];
Server s2 = servers[rand.Next(m)];
if (s1.Tasks < s2.Tasks)
{
for(int j = 0; j < m; j++)
{
if (servers[j].SNo == s1.SNo)
{
servers[j].Tasks++;
}
}
}
else
{
for (int j = 0; j < m; j++)
{
if (servers[j].SNo == s2.SNo)
{
servers[j].Tasks++;
}
}
}
}
}
//Server min max
Server maxServer = new Server();
maxServer = servers[0];
for (int i = 0; i < m; i++)
{
if (maxServer.Tasks < servers[i].Tasks)
{
maxServer = servers[i];
}
}
Console.WriteLine("\nIndex of servers with most tasks: " + "[" + maxServer.SNo + "]");
Console.WriteLine("Highest number of tasks: " + maxServer.Tasks+"\n");
Server minServer = new Server();
minServer = servers[0];
for (int i = 0; i < m; i++)
{
if (minServer.Tasks > servers[i].Tasks)
{
minServer = servers[i];
}
}
Console.WriteLine("\nIndex of servers with least tasks: " + "[" + minServer.SNo + "]");
Console.WriteLine("Lowest number of tasks: " + minServer.Tasks+"\n");
//details
details(servers, 0);
details(servers, 1);
details(servers, 2);
details(servers, 3);
details(servers, 4);
details(servers, 5);
details(servers, 6);
details(servers, 7);
details(servers, 8);
details(servers, 9);
}
}
}
Accompanied Server class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C1._2
{
class Server
{
private int server_number;
private int task;
public Server()
{
this.server_number = (int)0;
this.task = 0;
}
public Server(int sn)
{
this.server_number = sn;
this.task = 0;
}
public int SNo
{
get
{
return this.server_number;
}
set
{
this.server_number = value;
}
}
public int Tasks
{
get
{
return this.task;
}
set
{
this.task = value;
}
}
}
}
Any advice on how to do so?
When you say "random... where the one with the least tasks" means to me not random. But i think that I understand what you want. So we need to select the list of items that have least tasks and chose one of this randomic.
I rewrited a part of the class Program. Let me know if is this the expected result.
class Program
{
static void Main(string[] args)
{
//Random rand = new Random();
int numberOfTasks = 256; //number of tasks
int numberOfServers; //number of servers
numberOfServers = 64;//Convert.ToInt32(Console.ReadLine())
Console.WriteLine("Number of servers(m): " + numberOfServers);
//int d = 1; //random servers to be chosen
Console.WriteLine("Number of tasks(n): " + numberOfTasks);
//Console.WriteLine("Number of randomly selected server(d): " + d);
//Main server setup
Server[] servers = new Server[numberOfServers];
for (int i = 0; i < numberOfServers; i++)
{
servers[i] = new Server(i);
}
for(int i = 0; i < numberOfTasks; i++){
var minimumTasksValue = servers.Min(x => x.Tasks);
var listOfServersToSpread = servers.Where(x => x.Tasks == minimumTasksValue).ToList();
Random rand = new Random();
var randomServer = rand.Next(0, listOfServersToSpread.Count() - 1);
listOfServersToSpread[randomServer].Tasks++;
}
//Server min max
Server maxServer = new Server();
maxServer = servers[0];
for (int i = 0; i < numberOfServers; i++)
{
if (maxServer.Tasks < servers[i].Tasks)
{
maxServer = servers[i];
}
}
Console.WriteLine("\nIndex of servers with most tasks: " + "[" + maxServer.SNo + "]");
Console.WriteLine("Highest number of tasks: " + maxServer.Tasks + "\n");
Server minServer = new Server();
minServer = servers[0];
for (int i = 0; i < numberOfServers; i++)
{
if (minServer.Tasks > servers[i].Tasks)
{
minServer = servers[i];
}
}
Console.WriteLine("\nIndex of servers with least tasks: " + "[" + minServer.SNo + "]");
Console.WriteLine("Lowest number of tasks: " + minServer.Tasks + "\n");
//details
details(servers);
Console.ReadLine();
}
static void details(Server[] server)
{
var numberOfTasksAvailable = server.Select(x => x.Tasks).Distinct().OrderBy(x => x);
foreach(var numberOfTasks in numberOfTasksAvailable)
{
Console.WriteLine("There are " + server.Count(x => x.Tasks == numberOfTasks) + " servers with " + numberOfTasks + " tasks.");
}
}
}
Updated load balancing algorithm
if (d == 2)
{
for(int i = 0; i < n; i++)
{
int a = rand.Next(m);
int b = rand.Next(m);
servers[a < b ? a : b].Tasks++;
}
}
My problem was over-complicating the code. What it does above is that it randomly chooses two random servers from the total servers available. Compares which server has the least burden/tasks, and assigns a task to it.
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();
So the goal of my code is to pick two points in a grid of numbers and figure out with point gets the highest value of numbers when counting every other point in the grid closest to the two points. While typing this code I was trying to use private field variables to hold the current position of both pointers however I receive errors for the field variables I have and any calls that I make into this grid built.
namespace Program
{
private int xMe;
private int yMe;
private int zMe;
private int xEn;
private int yEn;
private int zEn;
private int dif = 0;
public class Castles
{
public static string Process(uint[,] grid)
{
int taxX = 0;
int taxY = 0;
for (int i = 0; i < grid.GetLength; i++)
{
for(int j = 0; j < grid[i]; j++)
{
for(int k = 0; k < grid.GetLength; k++)
{
for(int l = 0; l < grid[k]; l++)
{
if (distance(i, j, k, l) > 3)
{
if (grid[i, j] != 0 && grid[k, l] != 0)
{
for (int m = 0; grid.GetLength; m++)
{
for (int n = 0; grid[m]; n++)
{
if (grid[i, j] != grid[m, n] || grid[k, l] != grid[m, n])
{
if(distance(i,j,m,n) > distance(m, n, k, l))
{
taxX = taxX + distance[m, n];
}
else if(distance(i,j,m,n)< distance(m, n, k, l))
{
taxY = taxY + distance[m, n];
}
else
{
}
}
}
}
if(taxX - taxY > dif)
{
xMe = i;
yMe = j;
xEn = k;
yEn = l;
zMe = taxX;
zEn = taxY;
dif = taxX - taxY;
}
}
}
}
}
}
}
return "Your castle at (" + xMe + "," + yMe + ") earns " + zMe + ". Your nemesis' castle at (" + xEn + "," + yEn + ") earns " + zEn + ".";
}
public int distance(int x, int y, int a, int b)
{
int c = a - x;
int d = b - y;
return Math.Sqrt(c ^ 2 + d ^ 2);
}
static void Main(string[] args)
{
System.Console.WriteLine("");
}
}
}
This is my first exploration into c# so this could be a simple fix but any help would be useful
Just move the definitions of the fields to the inside of the class definition...
namespace Program
{
public class Castles
{
private int xMe;
private int yMe;
private int zMe;
private int xEn;
private int yEn;
private int zEn;
private int dif = 0;
public static string Process(uint[,] grid)
{
int taxX = 0;
int taxY = 0;
for (int i = 0; i < grid.GetLength; i++)
{
for(int j = 0; j < grid[i]; j++)
{
for(int k = 0; k < grid.GetLength; k++)
{
for(int l = 0; l < grid[k]; l++)
{
if (distance(i, j, k, l) > 3)
{
if (grid[i, j] != 0 && grid[k, l] != 0)
{
for (int m = 0; grid.GetLength; m++)
{
for (int n = 0; grid[m]; n++)
{
if (grid[i, j] != grid[m, n] || grid[k, l] != grid[m, n])
{
if(distance(i,j,m,n) > distance(m, n, k, l))
{
taxX = taxX + distance[m, n];
}
else if(distance(i,j,m,n)< distance(m, n, k, l))
{
taxY = taxY + distance[m, n];
}
else
{
}
}
}
}
if(taxX - taxY > dif)
{
xMe = i;
yMe = j;
xEn = k;
yEn = l;
zMe = taxX;
zEn = taxY;
dif = taxX - taxY;
}
}
}
}
}
}
}
return "Your castle at (" + xMe + "," + yMe + ") earns " + zMe + ". Your nemesis' castle at (" + xEn + "," + yEn + ") earns " + zEn + ".";
}
public int distance(int x, int y, int a, int b)
{
int c = a - x;
int d = b - y;
return Math.Sqrt(c ^ 2 + d ^ 2);
}
static void Main(string[] args)
{
System.Console.WriteLine("");
}
}
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]);