Windows Forms freezes and don't answer - c#

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; });
}
}

Related

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

Field methods in C# in the namespace

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("");
}
}

How to visualize the steps of an algorithm

How can I delay execution of an algorithm to visually display the results of each iteration in the algorithm? When I try to update the height of the objects in the code below, it only shows the final result. How can I display what happened at each step?
namespace BubbleSortRappresentazione_grafica
{
public partial class MainWindow : Window
{
int[] v;
public MainWindow()
{
InitializeComponent();
Random rnd = new Random();
v = new int[10];
for (int j = 0; j < 10; j++)
{
v[j] = rnd.Next(0, 100);
}
_0.Height = v[0] + 20;
_1.Height = v[1] + 20;
_2.Height = v[2] + 20;
_3.Height = v[3] + 20;
_4.Height = v[4] + 20;
_5.Height = v[5] + 20;
_6.Height = v[6] + 20;
_7.Height = v[7] + 20;
_8.Height = v[8] + 20;
_9.Height = v[9] + 20;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// algoritmo ordinamento
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (v[j] > v[i])
{
int tmp = v[j];
v[j] = v[i];
v[i] = tmp;
_0.Height = v[0] + 20;
_0.Content = v[0];
_1.Height = v[1] + 20;
_1.Content = v[1] ;
_2.Height = v[2] + 20;
_2.Content = v[2];
_3.Height = v[3] + 20;
_3.Content = v[3] ;
_4.Height = v[4] + 20;
_4.Content = v[4];
_5.Height = v[5] + 20;
_5.Content = v[5];
_6.Height = v[6] + 20;
_6.Content = v[6];
_7.Height = v[7] + 20;
_7.Content = v[7];
_8.Height = v[8] + 20;
_8.Content = v[8];
_9.Height = v[9] + 20;
_9.Content = v[9];
Thread.Sleep(100);
}
}
}
}
}
}
I believe that what you're really looking for is Application.DoEvents method:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (v[j] > v[i])
{
//...
Thread.Sleep(100);
Application.DoEvents();
}
}
}
This will cause that whatever visual changes you're making inside the loop will be applied in each iteration. You can also consider removing the .Sleep(), as I'm not sure how useful it is for you.

Sorting string values without using any method/function

I trying to do sorting without use of any method or function
My Code :
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length; i++)
{
for (int j = i + 1; j < names.Length; j++)
{
for (int c = 0; c < names.Length; c++)
{
if (names[i][c] > names[j][c])
{
name = names[i];
names[i] = names[j];
names[j] = name;
}
}
}
Console.WriteLine(names[i]);
}
Please let me bring any solution for this code ?
In this code i am getting "Index was outside the bounds of the array" exception
int temp = 0;
int[] arr = new int[] { 20, 65, 98, 71, 64, 11, 2, 80, 5, 6, 100, 50, 13, 9, 80, 454 };
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] > arr[j])
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
Console.WriteLine(arr[i]);
}
Console.ReadKey();
You need to implement a sorting algorithm.
A very simple algorithm you can implement is the insertion sort:
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
for (int i = 0; i < names.Length; i++)
{
var x = names[i];
var j = i;
while(j > 0 && names[j-1].CompareTo(x) > 0)
{
names[j] = names[j-1];
j = j-1;
}
names[j] = x;
}
string[] names = { "Flag", "Next", "Cup", "Burg", "Yatch", "Nest" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length; i++)
{
int c = 0;
for (int j = 1; j < names.Length; j++)
{
if (j > i)
{
Sort:
if (names[i][c] != names[j][c])
{
if (names[i][c] > names[j][c])
{
name = names[i];
names[i] = names[j];
names[j] = name;
}
}
else
{
c = c + 1;
goto Sort;
}
}
}
Console.WriteLine(names[i]);
}
I you were conflicting in length of names array and comparing string. Below is the working solution . I have tested it it's working now
static void Main(string[] args)
{
int min=0;
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length-1; i++)
{
for (int j = i + 1; j < names.Length;j++ )
{
if(names[i].Length < names[j].Length)
min =names[i].Length;
else
min =names[j].Length;
for(int k=0; k<min;k++)
{
if (names[i][k] > names[j][k])
{
name = names[i].ToString();
names[i] = names[j];
names[j] = name;
break;
}
else if(names[i][k] == names[j][k])
{
continue;
}
else
{
break;
}
}
}
}
for(int i= 0;i<names.Length;i++)
{
Console.WriteLine(names[i]);
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] {9,1,6,3,7,2,4};
int temp = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length;j++)
{
if(arr[i]>arr[j])
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
Console.Write(arr[i]+",");
}
Console.ReadLine();
}
for (int i = 0; i < names.Length; i++)
{
string temp = "";
for (int j = i + 1; j < names.Length; j++)
{
if (names[i].CompareTo(names[j]) > 0)
{
temp = names[j];
names[j] = names[i];
names[i] = temp;
}
}
}
public int compareing(string a, string b)
{
char[] one = a.ToLower().ToCharArray();
char[] two = b.ToLower().ToCharArray();
int ret = 0;
for (int i = 0; i < one.Length; i++)
{
for (int j = 0; j < two.Length; j++)
{
Loop:
int val = 0;
int val2 = 0;
string c = one[i].ToString();
char[] c1 = c.ToCharArray();
byte[] b1 = ASCIIEncoding.ASCII.GetBytes(c1);
string A = two[j].ToString();
char[] a1 = A.ToCharArray();
byte[] d1 = ASCIIEncoding.ASCII.GetBytes(a1);
int sec = d1[0];
int fir = b1[0];
if (fir > sec)
{
return ret = 1;
break;
}
else
{
if (fir == sec)
{
j = j + 1;
i = i + 1;
if (one.Length == i)
{
return ret = 0;
}
goto Loop;
}
else
{
return 0;
}
}
}
}
return ret;
}
public void stringcomparision(List<string> li)
{
string temp = "";
for(int i=0;i<li.Count;i++)
{
for(int j=i+1;j<li.Count;j++)
{
if(compareing(li[i],li[j])>0)
{
//if grater than it throw 1 else -1
temp = li[j];
li[j] = li[i];
li[i] = temp;
}
}
}
Console.WriteLine(li);
}
for (int i = 0; i < names.Length - 1; i++)
{
string temp = string.Empty;
for (int j = i + 1; j < names.Length; j++)
{
if (names[i][0] > names[j][0])
{
temp = names[i].ToString();
names[i] = names[j].ToString();
names[j] = temp;
}
}
}
for (int i = 0; i < names.Length - 1; i++)
{
int l = 0;
if (names[i][0] == names[i + 1][0])
{
string temp = string.Empty;
if (names[i].Length > names[i + 1].Length)
l = names[i + 1].Length;
else
l = names[i].Length;
for (int j = 0; j < l; j++)
{
if (names[i][j] != names[i + 1][j])
{
if (names[i][j] > names[i + 1][j])
{
temp = names[i].ToString();
names[i] = names[i + 1].ToString();
names[i + 1] = temp;
}
break;
}
}
}
}
foreach (var item in names)
{
Console.WriteLine(item.ToString());
}
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string temp = "";
int tempX = 0, tempY = 0;
int tempX1 = 0, tempY1 = 0;
for (int i = 0; i<names.Length; i++)
{
for (int j = i+1; j<names.Length; j++)
{
if (((string)names[i])[0] > ((string)names[j])[0])
{
temp=(string)names[i];
names[i]=names[j];
names[j]=temp;
}
else if (((string)names[i])[0] == ((string)names[j])[0])
{
tempX=0; tempY=0;
tempX1=names[i].Length;
tempY1=names[j].Length;
while (tempX1 > 0 && tempY1 >0)
{
if (((string)names[i])[tempX] !=((string)names[j])[tempY])
{
if (((string)names[i])[tempX]>((string)names[j])[tempY])
{
temp=(string)names[i];
names[i]=names[j];
names[j]=temp;
break;
}
}
tempX++;
tempY++;
tempX1--;
tempY1--;
}
}
}
}
You can do it using bubble sort:
Assume you have the array of names called name
The tempName is just to not change the original array (You can use the original array instead)
void sortStudentsAlphabetically()
{
int nameIndex;
string temp;
string[] tempName = name;
bool swapped = true;
for(int i = 0; i < name.Length-1 && swapped ; i++)
{
swapped = false;
for(int j = 0; j < name.Length-1; j++)
{
nameIndex = 0;
recheck:
if (name[j][nameIndex]> name[j+1][nameIndex])
{
temp = tempName[j];
tempName[j] = tempName[j+1];
tempName[j+1] = temp;
swapped = true;
}
if (name[j][nameIndex] == name[j + 1][nameIndex])
{
nameIndex++;
goto recheck;
}
}
}
foreach(string x in tempName)
{
Console.WriteLine(x);
}
}
User Below code :
int[] arrayList = new int[] {2,9,4,3,5,1,7};
int temp = 0;
for (int i = 0; i <= arrayList.Length-1; i++)
{
for (int j = i+1; j < arrayList.Length; j++)
{
if (arrayList[i] > arrayList[j])
{
temp = arrayList[i];
arrayList[i] = arrayList[j];
arrayList[j] = temp;
}
}
}
Console.WriteLine("Sorting array in ascending order : ");
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
Console.ReadLine();
Output:
Sorting array in ascending order : 1 2 3 4 5 7 9

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