Sorting string values without using any method/function - c#

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

Related

Why I am not getting the last two entries from the CSV in my program?

Greetings fellow programmers, I need to ask you for a help.
I have this programm:
private void Import_CSV_Click(object sender, System.Windows.RoutedEventArgs e)
{
List<List<string>> x = new List<List<string>>();
try
{
List<string> row = new List<string>();
OpenFileDialog browseDialog = new OpenFileDialog();
browseDialog.Filter = "CSV Files (*.csv)|*.csv";
browseDialog.ShowDialog();
StreamReader sr = new StreamReader(browseDialog.FileName, Encoding.Default, true);
List<TOsoby> persons = new List<TOsoby>();
var file = sr.ReadToEnd();
var linesinthestream = file.Split(new char[] { '\n' });
for (int i = 0; i < linesinthestream.Count()-2; i++)
{
persons.Add(new TOsoby());
}
sr = new StreamReader(browseDialog.FileName, Encoding.Default, true);
string firstline = Akro.Helpers.String.RemoveDiacritics(sr.ReadLine().ToLower());
string[] values = firstline.Split(';');
for (int i = 0; i < values.Length; i++)
{
row.Add(values[i]);
}
x.Add(row);
while (!sr.EndOfStream)
{
row = new List<string>();
string lines = sr.ReadLine();
values = lines.Split(';');
for (int i = 0; i < values.Length; i++)
{
row.Add(values[i]);
}
x.Add(row);
}
for (int i = 0; i < x[0].Count-2; i++)
{
if (x[0][i] == "jmeno") //Tady je chyba J = 22. a count je 24 upakovaní neprojde.
{
for (int j = 0; j < x.Count-2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "name")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "firstname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "prijmeni")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "surname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "lastname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "familyname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "titul")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Titul = x[j][i].ToString();
}
}
else if (x[0][i] == "title")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Titul = x[j][i].ToString();
}
}
else if (x[0][i] == "email")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Email = x[j][i].ToString();
}
}
else if (x[0][i] == "")
{
return;
}
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].OsobaID = 0;
}
}
if (persons == null) //Musím odstranit [0], protože tam je uložený první řádek a taky potřebujeme tam dát 23 řádků, takže nám tam 2 entry chybí (Marie a Michal), ale 22. řádek je uložen jako "", takže to musíme nějak opravit.
{
return;
}
else
{
persons.RemoveAt(0); //Tohle opravý ten první řádek
EntitiesModel em = DB.GetDB();
em.Add(persons); //23 a 24 tam vůbec nejsou (lidi z excelu)
em.SaveChanges();
Checker.CheckAfterEverySave();
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
My quest is to read the CSV entries and save them into the database, my problem is that last two entries of my CSV are not inside the persons, also on the last index it is empty:
Here is my CSV example I generated:
How should I fix it please?
Have a look at this, I included comments where I did changes to your code.
var csvFile = "A;B;C\nA 1;B 1;C 1\nA 2;B 2;C 2\nA 3;B 3;C 3\nA 4;B 4;C 4\n";
List<List<string>> x = new List<List<string>>();
List<Foo> foos = new List<Foo>();
//use StringSplitOptions.RemoveEmptyEntries to remove potential empty line at the end
var linesinthestream = csvFile.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < linesinthestream.Length - 1; i++) //-1 instead of - 2
foos.Add(new Foo());
List<string> row = new List<string>();
string firstline = linesinthestream[0];
string[] values = firstline.Split(';');
for (int i = 0; i < values.Length; i++)
row.Add(values[i]);
x.Add(row);
//use linesinthestream instead of again reading a stream start for loop at 1 and not 0 to skip the header
//you could remove the above code to read the header with this and start at 0, you don't really do anything different
for (int i = 1; i < linesinthestream.Length; i++)
{
row = new List<string>();
string lines = linesinthestream[i];
values = lines.Split(';');
for (int j = 0; j < values.Length; j++)
row.Add(values[j]);
x.Add(row);
}
//remove -2 to read all columns
for (int i = 0; i < x[0].Count; i++)
{
if (x[0][i] == "A")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderA = x[j][i].ToString();
}
else if (x[0][i] == "B")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderB = x[j][i].ToString();
}
else if (x[0][i] == "C")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderC = x[j][i].ToString();
}
}
//moved this loop outside of the previous loop, don't need to do it for every column
for (int j = 1; j < x.Count; j++)
foos[j-1].Id = 0;
foreach(var foo in foos)
Console.WriteLine($"Id: {foo.Id} | HeaderA: {foo.HeaderA} | HeaderB: {foo.HeaderB} | HeaderC: {foo.HeaderC}");
Find a demo here:
https://dotnetfiddle.net/tj0azu
As was already pointed out you should consider usign a library eg.
https://github.com/JoshClose/CsvHelper
and you can achieve the same result with this code:
using System;
using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;
using System.IO;
public class Program
{
public static void Main()
{
var csvFile = "A;B;C\nA 1;B 1;C 1\nA 2;B 2;C 2\nA 3;B 3;C 3\nA 4;B 4;C 4\n";
using (var reader = new StringReader(csvFile))
using (var csvReader = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = ";" }))
{
csvReader.Context.RegisterClassMap<FooMap>();
var foos = csvReader.GetRecords<Foo>();
foreach(var foo in foos)
Console.WriteLine($"Id: {foo.Id} | HeaderA: {foo.HeaderA} | HeaderB: {foo.HeaderB} | HeaderC: {foo.HeaderC}");
}
}
}
public class Foo
{
public int Id {get;set;}
public string HeaderA {get;set;}
public string HeaderB {get;set;}
public string HeaderC {get;set;}
}
public sealed class FooMap : ClassMap<Foo>
{
public FooMap()
{
AutoMap(CultureInfo.InvariantCulture);
Map(m => m.Id).Ignore();
Map(m => m.HeaderA).Name("A");
Map(m => m.HeaderB).Name("B");
Map(m => m.HeaderC).Name("C");
}
}
Find a demo here:
https://dotnetfiddle.net/1jaYNw
I recommend using FileHelpers. There is a nuget package available. I have used this for parsing several CSV files with no issue.
Here is some example code that will read a CSV file through a Stream and create a List<T> of the class that is provided:
using FileHelpers;
using System;
using System.Collections.Generic;
using System.IO;
public class DataFileConverter<T> : IDisposable where T : class
{
private readonly IFileHelperAsyncEngine<T> _engine;
private bool _disposed = false;
public DataFileConverter()
{
_engine = new FileHelperAsyncEngine<T>();
}
~DataFileConverter()
{
Dispose(false);
}
public bool RemoveHeaderRow
{
get => _engine.Options.IgnoreFirstLines == 1;
set => _engine.Options.IgnoreFirstLines = value ? 1 : 0;
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_engine != null)
{
_engine.Close();
}
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public List<T> ReadDataFile(Stream stream)
{
List<T> data = new List<T>();
using var streamReader = new StreamReader(stream);
using (_engine.BeginReadStream(streamReader))
{
foreach (T datum in _engine)
{
data.Add(datum);
}
}
return data;
}
}
using FileHelpers;
using System;
[DelimitedRecord(",")]
public class SomeClass
{
[FieldCaption("column1")]
public string SomeProperty1 { get; set; }
[FieldCaption("column2")]
[FieldConverter(ConverterKind.Date, "yyyy-MM-dd")]
public DateTime SomeProperty2 { get; set; }
}
public class SomeService
{
using DataFileConverter<SomeClass> converter = new DataFileConverter<SomeClass>
{
RemoveHeaderRow = true
};
List<SomeClass> data = converter.ReadDataFile(System.IO.File.OpenRead("path/to/file"));
// do whatever logic with data
}

Multiplication matrix on vector

I need to multiply the matrix on the vector and print the result. There are classes of integer vector and integer matrix. When outputting, displays only the first element. Can you tell me what the error is? Below I show the overloading of the * operator that I made, the method for displaying the matrix and exactly how I display it. Here is an example
public class VectorInt//class VectorInt
{
protected int[] IntArray;
protected uint size;
protected int codeError;
protected static uint num_vec;
public VectorInt()
{
codeError = 1;
size = 1;
IntArray = new int[size];
IntArray[0] = 0;
num_vec++;
}
public VectorInt(uint n)//конструктор з одним параметром
{
codeError = 1;
size = n;
IntArray = new int[size];
for (int i = 0; i < n; i++)
{
IntArray[i] = 0;
}
num_vec++;
}
public VectorInt(uint n, int b)
{
codeError = 1;
size = n;
IntArray = new int[size];
for (int i = 0; i < n; i++)
{
IntArray[i] = b;
}
num_vec++;
}
~VectorInt()
{
num_vec--;
Console.WriteLine("Dipsosed");
}
public void Input()
{
Console.WriteLine("\nSize of vector: ");
size = uint.Parse(Console.ReadLine());
IntArray = new int[size];
for (int i = 0; i < size; i++)
{
Console.WriteLine("Element {0}: ", i);
Console.WriteLine(" v [ {0} ] = {1} ", i, IntArray[i] = int.Parse(Console.ReadLine()));
}
}
public void Output()
{
Console.WriteLine("\nMatrix");
for (int i = 0; i < n; i++)//n-amount of rows
{
for (int j = 0; j < m; j++)//m-amount of columns
{
Console.Write(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j]);
}
Console.WriteLine();
}
}
public uint Size
{
get
{
return (uint)IntArray.Length;
}
}
public int[] NewIntArray
{
get => IntArray;
}
////////////////////////////////////////////////////////
public class MatrixInt//class MatrixInt
{
protected int[,] IntArray;
protected int n, m;
protected int codeError;
protected static int num_m;
public MatrixInt()
{
n = 1; m = 1;
IntArray = new int[n, m];
IntArray[0, 0] = 0;
num_m++;
}
public MatrixInt(int r, int c)
{
n = r; m = c;
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
IntArray[i, j] = 0;
}
num_m++;
}
public MatrixInt(int r, int c, int b)
{
n = r; m = c;
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
IntArray[i, j] = b;
}
num_m++;
}
~MatrixInt()
{
num_m--;
Console.WriteLine("Disposed");
}
public void Input()
{
Console.WriteLine("Number of rows: ");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Number of columns: ");
m = int.Parse(Console.ReadLine());
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.WriteLine("Element {0}{1}: ", i, j);
Console.WriteLine(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j] = int.Parse(Console.ReadLine()));
}
}
}
public void Output()
{
Console.WriteLine("\nMatrix");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j]);
}
Console.WriteLine();
}
}
public int Rows
{
get
{
return n;
}
}
public int Columns
{
get
{
return m;
}
}
/////////////////////////////////////////////////////////////
public static MatrixInt operator *(MatrixInt obj, VectorInt obj1)
{
MatrixInt obj3 = new MatrixInt();
if (obj.Columns != obj1.NewIntArray.Length)
{
throw new Exception("Error!");
}
obj3.IntArray = new int[obj.Rows, 1];
for (int i = 0; i < obj.Rows; i++)
{
obj3.IntArray[i, 0] = 0;
for (int j = 0; j < obj.Columns; j++)
{
obj3.IntArray[i, 0] += obj.IntArray[i, j] * obj1.NewIntArray[j];
//Console.WriteLine(" m [ {0}{1} ] = {2} ", i, j, obj3.IntArray[i, 0]);
}
}
return obj3;
}
////////////////////////////////////////////////////////
MatrixInt obj = new MatrixInt();
VectorInt obj1 = new VectorInt();
obj.Input();
obj.Output();
obj1.Input();
obj1.Output();
obj *= obj1;
obj.Output();

How to get all possible 2x2 sub matrices in a 3x3 matrix in C#?

If matrix A of size (3x3), then should i use the method of finding determinants, like grabbing the rows and column of first element and removing it from the array 2D array to get the remaining elements and then moving to the next element and repeating the same steps ?
[{1,2,3},
{4,5,6},
{7,8,9}]
I finally was able to do it, here's what I did :
enter image description here
class program
{
public static void Main()
{
int[,] arr = new int[3, 3];
Console.WriteLine("Enter elements of " + (arr.GetUpperBound(0) + 1) + "x" + (arr.GetUpperBound(1) + 1) + " matrix:");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
arr[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Matrix entered: ");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
Console.Write("\t" + arr[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("Possible sub-matrices: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j< 3; j++)
{
TrimArray(i,j,arr);
}
}
}
public static int[,] TrimArray(int row, int column, int[,] original)
{
int[,] resultant = new int[original.GetLength(0) - 1, original.GetLength(1) - 1];
for (int i = 0, j = 0; i < original.GetLength(0); i++)
{
if (i == row)
continue;
for (int k = 0, u = 0; k < original.GetLength(1); k++)
{
if (k == column)
continue;
resultant[j, u] = original[i, k];
u++;
}
j++;
}
Console.WriteLine();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j< 2; j++)
{
Console.Write("\t"+resultant[i,j]);
}
Console.WriteLine();
}
return resultant;
}
}
I did this for you yesterday, I created a method that will return a square matrix, given a parent matrix and the length.
static void Main(string[] args)
{
int[][] parentMatrix = new int[][]
{
new int [] { 1, 2, 3 },
new int [] { 4, 5, 6 },
new int [] { 7, 8, 9 }
};
var chunks = GetSubMatrices(parentMatrix, 2);
Console.WriteLine(chunks);
}
static List<int[][]> GetSubMatrices(int[][] parentMatrix, int m)
{
int n = parentMatrix.Length > m ? parentMatrix.Length : throw new InvalidOperationException("You can't use a matrix smaller than the chunk size");
var chunks = new List<int[][]>();
int movLimit = n - m + 1;
var allCount = Math.Pow(movLimit, 2);
for (int selRow = 0; selRow < movLimit; selRow ++)
{
for (int selCol = 0; selCol < movLimit; selCol ++)
{
// this is start position of the chunk
var chunk = new int[m][];
for (int row = 0; row < m; row++)
{
chunk[row] = new int[m];
for (int col = 0; col < m; col++)
{
chunk[row][col] = parentMatrix[selRow + row][selCol + col];
}
}
chunks.Add(chunk);
}
}
return chunks;
}
If you have any problems using it, you can simply comment below.
I needed to solve a problem like and came up with this answer. Hope it adds to your library of answers. If the submatrix specified is not greater than 1, do nothing.
public static void GetSubMatrixes(int[,] arr, int size)
{
int parentMatrixRowLength = arr.GetLength(0);
int parentMatrixColLength = arr.GetLength(1);
var overall = new List<object>();
if(size > 1)
{
for (int i = 0; i < parentMatrixRowLength; i++)
{
//get the columns
for (int j = 0; j < parentMatrixColLength; j++)
{
var subMatrix = new int[size, size];
/*if the new matrix starts from second to the last value in either the row(horizontal or column)
* do not proceed, go to the row or column in the parent matrix
* */
if (j < parentMatrixColLength - (size - 1) && i < parentMatrixRowLength - (size - 1))
{
//add
for (int m = 0; m < subMatrix.GetLength(0); m++)
{
for (int n = 0; n < subMatrix.GetLength(1); n++)
{
/*check the sum of current column value and the sum of the current row value
* of the parent column length and row length if it goes out of bounds
*/
var row = i + m; var col = j + n;
//actual check here
if (row < parentMatrixRowLength && col < parentMatrixColLength)
{
subMatrix[m, n] = arr[i + m, j + n];
}
}
}
overall.Add(subMatrix);
}
}
}
//display the sub matrixes here
for (int i = 0; i < overall.Count; i++)
{
var matrix = overall[i] as int[,];
for (int y = 0; y < matrix.GetLength(0); y++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
Console.Write(string.Format("{0} ", matrix[y, x]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine();
}
}
}

Failed Gauss-Jordan elimination implementation in C#

Based on the alorithm given here https://en.wikipedia.org/wiki/Gaussian_elimination#Pseudocode,
I tried to implement a C# version of the Gaussian Elimination:
public Matrix GaussianElimination(double epsilon = 1e-10)
{
var result = Copy();
var kMax = Math.Min(result.RowCount, result.ColumnCount);
for (var k = 0; k < kMax; k++)
{
// Find k-th pivot, i.e. maximum in column max
var iMax = result.FindColumnAbsMax(k);
if (Math.Abs(result[iMax, k]) < epsilon)
{
throw new ArithmeticException("Matrix is singular or nearly singular.");
}
// Swap maximum row with current row
SwapRows(k, iMax);
// Make all rows below the current one, with 0 in current column
for (var i = k + 1; i < result.RowCount; i++)
{
var factor = result[i, k] / result[k, k];
for (var j = k + 1; j < result.ColumnCount; j++)
{
result[i, j] = result[i, j] - result[k, j] * factor;
}
result[i, k] = 0;
}
}
return result;
}
It works in most cases (note that this is not performing the back substitution step). However, for the first example given in Wikipedia, the algorithm stop on the singular matrix case and throw the related exception on the row echelon form right before back substitution step with:
public class Program
{
public static void Main(string[] args)
{
var matrix = Matrix.Parse("[1 3 1 9; 1 1 -1 1; 3 11 5 35]");
Console.WriteLine(matrix);
Console.WriteLine(matrix.GaussianElimination());
Console.ReadKey();
}
}
k = 2
kMax = 3
iMax = 2
result = [1 3 1 9; 0 -2 -2 -8; 0 0 0 0]
[EDIT]
The Matrix implementation is a bit lengthy but here is what it is used in regard to the string parsing and the elimination method:
public class Matrix
{
public const string MatrixStart = "[";
public const string MatrixStop = "]";
public const char RowSeparator = ';';
public const char RowCellSeparator = ' ';
public int RowCount { get; }
public int ColumnCount { get; }
public int CellCount => _data.Length;
public bool IsSquare => RowCount == ColumnCount;
public bool IsVector => ColumnCount == 1;
private readonly double[] _data;
public double this[int rowIndex, int columnIndex]
{
get => _data[Convert2DIndexTo1DIndex(rowIndex, columnIndex)];
set => _data[Convert2DIndexTo1DIndex(rowIndex, columnIndex)] = value;
}
public Matrix(Matrix matrix)
: this(matrix.RowCount, matrix.ColumnCount)
{
for (var i = 0; i < _data.Length; i++)
{
_data[i] = matrix._data[i];
}
}
public Matrix(int size, double placeHolder = 0)
: this(size, size, placeHolder)
{
}
public Matrix(int rowCount, int columnCount, double initializationValue = 0)
{
if (rowCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(rowCount));
}
if (columnCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(columnCount));
}
RowCount = rowCount;
ColumnCount = columnCount;
_data = new double[RowCount * ColumnCount];
if (Math.Abs(initializationValue) > 0)
{
Set(initializationValue);
}
}
public Matrix(int rowCount, int columnCount, double[] initializationValues)
{
if (rowCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(rowCount));
}
if (columnCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(columnCount));
}
if (initializationValues.Length != rowCount * columnCount)
{
throw new ArgumentOutOfRangeException(nameof(initializationValues));
}
RowCount = rowCount;
ColumnCount = columnCount;
_data = new double[initializationValues.Length];
initializationValues.CopyTo(_data, 0);
}
private int Convert2DIndexTo1DIndex(int rowIndex, int columnIndex)
{
return rowIndex * ColumnCount + columnIndex;
}
public void Set(double value)
{
for (var i = 0; i < _data.Length; i++)
{
_data[i] = value;
}
}
public Matrix Transpose()
{
var result = new Matrix(ColumnCount, RowCount);
for (var i = 0; i < result.RowCount; i++)
{
for (var j = 0; j < result.ColumnCount; j++)
{
result[i, j] = this[j, i];
}
}
return result;
}
public Matrix Copy()
{
return new Matrix(this);
}
private int FindColumnAbsMax(int index)
{
return FindColumnAbsMax(index, index);
}
private int FindColumnAbsMax(int rowStartIndex, int columnIndex)
{
var maxIndex = rowStartIndex;
for (var i = rowStartIndex + 1; i < RowCount; i++)
{
if (Math.Abs(this[maxIndex, columnIndex]) <= Math.Abs(this[i, columnIndex]))
{
maxIndex = i;
}
}
return maxIndex;
}
public void SwapRows(int rowIndexA, int rowIndexB)
{
for (var j = 0; j < ColumnCount; j++)
{
var indexA = Convert2DIndexTo1DIndex(rowIndexA, j);
var indexB = Convert2DIndexTo1DIndex(rowIndexB, j);
_data.Swap(indexA, indexB);
}
}
public void SwapColumns(int columnIndexA, int columnIndexB)
{
for (var i = 0; i < RowCount; i++)
{
var indexA = Convert2DIndexTo1DIndex(i, columnIndexA);
var indexB = Convert2DIndexTo1DIndex(i, columnIndexB);
_data.Swap(indexA, indexB);
}
}
public static Matrix Parse(string matrixString)
{
if (!matrixString.StartsWith(MatrixStart) || !matrixString.EndsWith(MatrixStop))
{
throw new FormatException();
}
matrixString = matrixString.Remove(0, 1);
matrixString = matrixString.Remove(matrixString.Length - 1, 1);
var rows = matrixString.Split(new[] { RowSeparator }, StringSplitOptions.RemoveEmptyEntries);
if (rows.Length <= 0)
{
return new Matrix(0, 0);
}
var cells = ParseRow(rows[0]);
var matrix = new Matrix(rows.Length, cells.Length);
for (var j = 0; j < cells.Length; j++)
{
matrix[0, j] = cells[j];
}
for (var i = 1; i < matrix.RowCount; i++)
{
cells = ParseRow(rows[i]);
for (var j = 0; j < cells.Length; j++)
{
matrix[i, j] = cells[j];
}
}
return matrix;
}
private static double[] ParseRow(string row)
{
var cells = row.Split(new [] { RowCellSeparator }, StringSplitOptions.RemoveEmptyEntries);
return cells.Select(x => Convert.ToDouble(x.Replace(" ", string.Empty))).ToArray();
}
}
And the 1D Array extension for swapping two items:
public static class ArrayHelpers
{
public static void Swap<TSource>(this TSource[] source, int indexA, int indexB)
{
var tmp = source[indexA];
source[indexA] = source[indexB];
source[indexB] = tmp;
}
}

Counting Sort Implementation in C#

I am implementing counting sort But some thing is wrong with my code
I am new in Programming Please help me to find an error.
I am implenting it step by step .
namespace ConsoleApplication1
{
class Program
{
public static int[] a = { 0,0,0,5,4,8,9,9,7,3, 3, 2, 1 };
public static void Sorting()
{
int j = 0, i = 0, smallestvalue = 0, largestvalue = 0, n = a.Length, lengthof_B = 0, temp = 0, anothersmallestvalue;
smallestvalue = largestvalue = a[0];
for (i = 0; i < n; i++)
{
if (smallestvalue > a[i])
{
smallestvalue = a[i];
}
else if (largestvalue < a[i])
{
largestvalue = a[i];
}
}
int x = anothersmallestvalue = smallestvalue;
lengthof_B = largestvalue - smallestvalue + 1;
int[] b = new int[lengthof_B];
for (i = 0; i < lengthof_B && smallestvalue <= largestvalue; i++)
{
for (j = 0; j < n; j++)
{
if (smallestvalue == a[j])
{
b[i] = b[i] + 1;
}
}
b[i] = temp + b[i];
temp = b[i];
smallestvalue++;
}
int[] c = new int[a.Length];
// I think error here
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp - 1] = anothersmallestvalue;
b[j] = b[j];
}
anothersmallestvalue++;
}
}
for (i = 0; i < c.Length; i++)
{
Console.WriteLine("c[i] : " + c[i]);
}
}
}
class Demo
{
static void Main(string[] args)
{
Program.Sorting();
Console.ReadLine();
}
}
}
Desired Output is
000123457899
But output of my program is
000120457809
This Is Your Code Here I found a mistake.
And your Code is too complex Please Go through your code Once more.
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp - 1] = anothersmallestvalue;
b[j] = b[j] -1 ;// Possible Mistake I think here
}
anothersmallestvalue++;
}
}
the very simple and stylish way is described and shown here.
en.wikipedia.org/wiki/Counting_sort#The_algorithm
Normal sorting your two loops should look like this
for (i = 0; i < lengthof_B - 1; i++)
{
for (j = i + 1; j < lengthof_B; j++)
{
}
}​

Categories