Insertion sort algorithm c# - c#

I am trying to implement the Insertion sort in one of my programs. What I have been trying to create is a sorting program (in both ascending or descending order) However I have tried with algorithms such as quicksort and merge-sort, I am really new to c# and coding. The problem I am facing here is the fact that my files includes both a string of code, as well as a double/integer (example: 75.350, 74.430, Thursday, Friday) and since this algorithm is designed for integers. Is there a way to convert it please?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
StreamReader sh1Open = new StreamReader("c:..\\Files\\SH1_Open.txt");
string Sh1OpenString = sh1Open.ReadToEnd();
int[] x = { Convert.ToInt32(Sh1OpenString) };
int j;
int temp;
for (int i = 1; i < x.Length; i++)
{
j = i - 1;
while (j >= 0 && x[j]>x[j+1])
{
temp = x[j];
x[j] = x[j + 1];
x[j + 1] = temp;
j = j - 1;
}
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
Console.ReadKey();
}
}
}

The best way is probably using generic method with IComparable constraint.
T[] InsertionSort(T[] x) where T : IComparable<T>
{
for (int i = 0; i < x.Length-1; i++)
{
int j = i+1;
while (j>0)
{
if (x[j-1].CompareTo(x[j]) > 1)
{
T temp = x[j-1];
x[j - 1] = x[j];
x[j] = temp;
}
j--;
}
}
return x;
}
or using algorithm from http://www.codecodex.com/wiki/Insertion_sort
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j=j-1;
}
array[j + 1] = value;
}
}
Also, there is probably a bug in this line:
int[] x = { Convert.ToInt32(Sh1OpenString) };
because you're trying to convert whole file to one integer.

Since in C# the comparison operators are defined for strings you could just replace all relevant int variables with string variables. The algorithm should run the same (albeit a bit slower)

Related

Memory error NZEC when using C# on HackerEarth

I am solving a question on HackerEarth. The test case passes successfully, but the rest of the cases show a NZEC error. I know NZEC stands for Non Zero Exit Code but I am not sure why this is happening here.
Any insight about why this happens and how I can optimize my code (preferably without changing the logic) will help.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int t = int.Parse(Console.ReadLine());
int[] arr = new int[3];
for(int m = 0; m < t; m++)
{
arr[m] = int.Parse(Console.ReadLine());
}
for (int n = 0; n < t; n++)
{
int i, j;
for (i = 0; i < arr[n]; i++)
{
for (j = 0; j < 2 * arr[n]; j++)
{
if (j <= i || j >= 2 * arr[n] - 1 - i)
{
Console.Write("*");
}
else
{
Console.Write("#");
}
}
Console.WriteLine("\n");
}
Console.WriteLine("\n");
}
}
}

A method to search Id inside a matrix -Trouble with output

I am new at programming and I am trying to create a method that allows me search Id inside a [10,4] matrix, however I don't get how to do it without using nested fors and also if and else statement. The problem is related to output, I know the structure isn't correct, but since I don't what else can be done I am trying make it as it is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace menu
{
class Program
{
enum header { id, name, surname, addres };
public static int id = 1;
static void Main(string[] args)
{
string[,] matrix = new string[10, 4];
insertStudent(matrix);
idSearch(matrix);
Console.ReadKey();
}
static int generateId()
{
return id++;
}
static void insertStudent(string[,] matrix)
{
int n = generateId();
matrix[n - 1, 0] = Convert.ToString(n);
for (int i = 1; i < matrix.GetLength(1); i++)
{
do
{
Console.WriteLine($"Insert {Enum.GetName(typeof(header), i)}");
matrix[n - 1, i] = Console.ReadLine();
}
while (String.IsNullOrEmpty(matrix[n - 1, i]));
}
}
static void idSearch(string[,] matrix)
{
int idChosen=0;
Console.WriteLine($"Insert ID you want to visualize:");
int.TryParse(Console.ReadLine(), out idChosen);
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
if (matrix[i, 0] == Convert.ToString(idChosen))
{
Console.WriteLine(matrix[i, j]);
}
else
{
Console.WriteLine("The chosen ID does not exist");
}
}
}
}
}
}
Right now you printing "The chosen ID does not exist" every time you check an index in your matrix. You want to move that statement to outside of your loop after you've already checked every index. Right now that check is really saying that your ID is not in that specific cell. I've altered your code slightly to reflect this. I also fixed your check to be on matrix[i,j] instead of matrix[i,0]
Also using a nested for loop is OK to use. I don't believe C# has any built in helper methods for searching multidimensional arrays.
bool found = false;
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
if (matrix[i, j] == Convert.ToString(idChosen))
{
//note that this will print your id
Console.WriteLine(matrix[i, j]);
//this would print where it found it
Console.WriteLine("Found at [" + i + "," + j + "]");
found = true;
}
}
}
if (!found)
{
Console.WriteLine("The chosen ID does not exist");
}

HeapSort Algorythm from txt file to list of arrays doesn't Sort the numbers

So I have to make HeapSort Algorythm for University using pseudocode I was given (only for heapsort). And I have to use input and output file. But for now I have only made input file which is working fine since it loads the txt file and writes down all the numbers in Console. So the problem is that after adding sorting methods to Main nothing changes. Also I decided to make a test for every method and all of them writes down my numbers once and that is it. I am not really good with sorting so it is hard for me to find the issue. Also because it is from pseudocode I had to use and no the code I could do for myself. So Do You know what cause thats issue that the sorting doesn't occure?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
using System.Windows.Forms;
namespace Zad4
{
class Program
{
void Heapify(List<int> array, int i, int n)
{
int largest, temp;
int parent = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && array[left] > array[parent])
{
largest = left;
}
else
{
largest = parent;
}
if (right < n && array[right] > array[largest])
{
largest = right;
}
if (largest != i)
{
temp = array[i];
array[i] = array[largest];
array[largest] = temp;
Heapify(array, largest, n);
}
}
void BuildHeap(List<int> array, int n)
{
int i;
for (i = (n - 1) / 2; i >= 0; i--)
{
Heapify(array, i, n);
}
}
void HeapSort(List<int> array, int n)
{
int i, temp;
for (i = n - 1; i >= 0; i--)
{
temp = array[0];
array[0] = array[n - 1];
array[n - 1] = temp;
n = n - 1;
Heapify(array, 0, n);
Console.WriteLine(string.Join(" ", array));
}
}
static void Main(string[] args)
{
int n = 0;
Program A = new Program();
StreamReader myFile =
new StreamReader("C:\\Users\\dawid\\Desktop\\C#\\Heapsort\\dane.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
char rc = (char)10;
String[] listLines = myString.Split(rc);
List<List<int>> listArrays = new List<List<int>>();
for (int i = 0; i < listLines.Length; i++)
{
List<int> array = new List<int>();
String[] listInts = listLines[i].Split(' ');
for (int j = 0; j < listInts.Length; j++)
{
if (listInts[j] != "\r")
{
array.Add(Convert.ToInt32(listInts[j]));
}
}
listArrays.Add(array);
A.BuildHeap(array, n);
A.HeapSort(array, n);
}
foreach (List<int> array in listArrays)
{
foreach (int i in array)
{
Console.WriteLine(string.Join(" ", array));
}
}
Console.WriteLine();
Console.ReadLine();
}
}
}
So the solution I found is just changing the way I read my txt file and the most important one was bad use of my methods. So that is how it looks now and it sorting well. Maybe I shouldn't ask a question since I got an answer on my own. But well. There You go:
static void Main(string[] args)
{
Program A = new Program();
string[] array = System.IO.File.ReadAllLines(#"C:\Users\dawid\Desktop\C#\Heapsort\dane.txt");
int[] arrayInt = Array.ConvertAll(array, int.Parse);
A.BuildHeap(arrayInt, arrayInt.Length);
A.HeapSort(arrayInt, arrayInt.Length);
Console.WriteLine(string.Join(" ", arrayInt));
Console.ReadLine();
}

How can define a 26x2 array and then use LINQ on its rows?

Grrrr I have C# and multidimensional arrays. For some reason, coming from a C/C++ background, they really annoy me.
So when I run
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int T = Int32.Parse(Console.ReadLine());
for(int t = 0; t < T; ++t)
{
string str = Console.ReadLine();
if(str.Length % 2 == 1)
{
Console.WriteLine(-1);
continue;
}
int n = str.Length / 2;
// determine how many replacements s1 needs to be an anagram of s2
string s1 = str.Substring(0, n);
string s2 = str.Substring(n, n);
int[][] counter = new int[26][2];
int ascii_a = (int)'a';
for(int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a][0] += 1;
counter[(int)s2[i] - ascii_a][1] += 1;
}
int count = counter.Select((pair => Math.Abs(pair[0] - pair[1]))).Sum();
Console.WriteLine(count);
}
}
}
I get
solution.cs(22,42): error CS0029: Cannot implicitly convert type int'
toint[][]' Compilation failed: 1 error(s), 0 warnings
No idea why.
I can change it to
int[,] counter = new int[26,2];
int ascii_a = (int)'a';
for(int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a, 0] += 1;
counter[(int)s2[i] - ascii_a, 1] += 1;
}
int count = counter.Select((pair => Math.Abs(pair[0] - pair[1]))).Sum();
but then, of course, my LINQ statement breaks.
If you change
int[][] counter = new int[26][2];
to
int[][] counter = new int[26][];
for (int i = 0; i < counter.Length; i++)
counter[i] = new int[2];
code compiles. You can test the rest as you like. As you haven't provided necessary input in OP.
You can't define jagged array like that:
int[][] counter = new int[26][2];
I recommend reading on jagged arrays:
https://msdn.microsoft.com/en-us/library/2s05feca.aspx
https://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
In your case I'd suggest using not jagged, but multi-dimentional array:
var counter = new int[26,2];
What you are using here is a jagged array, and you can't new one like that:
int[][] counter = new int[26][2];
You have to declare the inner array separately :
int[][] counter = new int[26][];
for (int i = 0; i < 26; i++)
{
counter[i] = new int[2];
}
Alternatively, as #IvanStoev suggested, you can also use a LINQ one liner:
var counter = Enumerable.Range(0, 26).Select(_ => new int[2]).ToArray();
You can also use a 2-dimensional array, such as this one :
// notice there is only one bracket
int[,] counter = new int[26,2];
int ascii_a = (int)'a';
for(int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a, 0] += 1;
counter[(int)s2[i] - ascii_a, 1] += 1;
}
// and, you will need to update your query,
// as linq would implicitly flatten the array
var count = Enumerable.Range(0, 26)
.Select(x => counter[x, 0] - counter[x, 1])
.Sum();
I would suggest defining a Counter struct then use an array of those instead of a multi-dimensional array.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
struct Counter
{
public int c1;
public int c2;
}
static void Main(String[] args)
{
int T = Int32.Parse(Console.ReadLine());
for (int t = 0; t < T; ++t)
{
string str = Console.ReadLine();
if (str.Length % 2 == 1)
{
Console.WriteLine(-1);
continue;
}
int n = str.Length / 2;
// determine how many replacements s1 needs to be an anagram of s2
string s1 = str.Substring(0, n);
string s2 = str.Substring(n, n);
Counter[] counter = new Counter[26];
int ascii_a = (int)'a';
for (int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a].c1 += 1;
counter[(int)s2[i] - ascii_a].c2 += 1;
}
int count = counter.Select((pair => Math.Abs(pair.c1 - pair.c2))).Sum();
Console.WriteLine(count);
}
}
}

How to get whole list of processes in decreasing order of their thread count ( C# ) [duplicate]

This question already has answers here:
How to count the amount of concurrent threads in .NET application?
(2 answers)
Closed 7 years ago.
How to get whole list of processes in decreasing order of their thread count ( C# )
You could try this,
Process[] processList = Process.GetProcesses().OrderByDescending(x => x.Threads.Count).ToArray();
You could do the following:
private void fuc()
{
System.Diagnostics.Process[] procArray;
procArray = System.Diagnostics.Process.GetProcesses();
List<KeyValuePair<string, int>> threads = new List<KeyValuePair<string,int>>();
for (int i = 0; i < procArray.Length; i++)
{
var element = new KeyValuePair<string, int>(procArray[i].ProcessName, procArray[i].Threads.Count);
threads.Add(element);
}
threads.Sort(OrderAsc);
}
static int OrderAsc(KeyValuePair<string, int> a, KeyValuePair<string, int> b)
{
return a.Value.CompareTo(b.Value);
}
Its a big code (can become more compact)......but finally got the answer....thank you so much #kuruban #Gnqz #utility #derape
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process[] procArray;
procArray = System.Diagnostics.Process.GetProcesses();
String[,] arr = new String[300,2];
String max, maxi;
int k;
for (k = 0; k < procArray.Length; k++)
{
arr[k, 0] = procArray[k].ProcessName;
arr[k, 1] = (procArray[k].Threads.Count).ToString();
}
for (int i = 0; i < procArray.Length; i++)
{
for (int j = i; j < procArray.Length; j++)
{
if (int.Parse(arr[i, 1]) < int.Parse(arr[j, 1]))
{
max = arr[j, 0];
arr[j, 0] = arr[i, 0];
arr[i, 0] = max;
maxi = arr[j, 1];
arr[j, 1] = arr[i, 1];
arr[i, 1] = maxi;
}
}
}
for (int i = 0; i < procArray.Length; i++)
{
Console.WriteLine("{0} {1}", arr[i, 0], arr[i, 1]);
}
}
}
}

Categories

Resources