Field methods in C# in the namespace - c#

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

Related

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

C# implementation of Ascii Minimum Delete Distance

How do you implement the ASCII Minimum Delete Distance in C#?
See description here with a Python solution.
Deletion distance between 2 strings
I derived the C# solution from this Java solution.
https://leetcode.com/articles/minimum-ascii-delete-sum-for-two-strings/#
static void TestAscMinDelDist()
{
List<string[]> l = new List<string[]> {
new string[]{"cat", "at", "99"},
new string[]{"aunt","ant", "117"},
new string[]{"sea", "eat", "231"},
new string[]{"boat", "got", "298"},,
new string[]{"toradol", "tramadol", "317"},
new string[]{"tattoo","platoon", "562"},
new string[]{"delete", "leet", "403"},
new string[]{"flomax", "volmax", "436"},
new string[]{"clozapine", "olanzapine", "522"},
new string[]{"Sam", "Samantha", "524"},
new string[]{"kitten", "sitting", "531" },
new string[]{"sloughs", "thought", "674"}, };
foreach (string[] a in l) {
CalcPrint(a[0], a[1], a[2]);
CalcPrint(a[1], a[0], a[2]);
}
}
static int AsciiMinimumDeleteDistance(String s1, String s2) {
int s1Len = s1.Length, s2Len = s2.Length;
int[,] dp = new int[s1Len + 1, s2Len + 1];
for (int i = s1Len - 1; i >= 0; i--) {
dp[i, s2Len] = dp[i + 1, s2Len] + (int)s1[i]; }
for (int j = s2Len - 1; j >= 0; j--) {
dp[s1Len, j] = dp[s1Len, j+1] + (int)s2[j]; }
for (int i = s1Len - 1; i >= 0; i--) {
for (int j = s2Len - 1; j >= 0; j--) {
if (s1[i] == s2[j]) {
dp[i, j] = dp[i+1, j+1];
} else {
dp[i, j] = Math.Min(dp[i+1, j] + (int)s1[i],
dp[i, j+1] + (int)s2[j]);
}
}
}
return dp[0,0];
}
static void CalcPrint(string s1, string s2, string s3)
{
int cost = AsciiMinimumDeleteDistance(s1, s2);
string result = cost == int.Parse(s3) ? "Passed" : "Failed: Expected: " + s3;
Console.WriteLine($"{s1} -> {s2} {cost} \t {result}");
}

Windows Forms freezes and don't answer

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

Is there an C# function or algorithm to sort my table data show at console code?

Array 2D of C# isn't sorted by column.
Minimum Year --> Maximum Year
Minimum Month --> Maximum Month
Minimum Day --> Maximum Day
string[,] A = new string[2, 7];
string[,] B = new string[7, 7];
int menu = 0;
int i = 0;
int L = 0;
Console.WriteLine("Main ============i" + i + " L " + L + " =Menu " + menu + "==================");
do
{
Console.WriteLine("Do Loop ============= " + i + " =====================");
//i = 0;
for (int j = 0; j < A.GetLength(1); j++)
{
A[0, j] = Console.ReadLine();
B[L, j] = A[0, j];
}
Console.WriteLine("Before copy===");
PriArr(A);
Console.WriteLine("After copy===");
PriArr(B);
Console.WriteLine("Do you add new one? [1.Yes 2.No] : ");
int Menu = int.Parse(Console.ReadLine());
switch (Menu)
{
case 1: menu = 0; L++; break;
case 2: menu = 1; break;
}
Console.WriteLine("After Switch (menu value):" + menu);
} while (menu == 0);
SortArr(B);
Console.WriteLine("After sorted===============");
PriArr(B);
}
static void PriArr(string[,] IN)
{
for (int i = 0; i < IN.GetLength(0); i++)
{
for (int j = 0; j < IN.GetLength(1); j++)
{
Console.Write("{0} ", IN[i, j]);
}
Console.WriteLine("||");
}
Console.WriteLine("----------");
}
static string[,] SortArr(string[,] IN)
{
int Y, Y1, M, M1, D, D1;
string c;
//Sort Year: Year min --> Year Max
for (int i = 0; i < IN.GetLength(0) - 1; i++)
{
for (int L = i; L < IN.GetLength(0); L++)
{
//Year index 2 convert to int
Y = Convert.ToInt32(IN[i, 2]);
Y1 = Convert.ToInt32(IN[L, 2]);
//Month index 1 convert to int
M = Convert.ToInt32(IN[i, 1]);
M1 = Convert.ToInt32(IN[L, 1]);
//Day index 0 convert int
//Month index 1 convert to int
D = Convert.ToInt32(IN[i, 0]);
D1 = Convert.ToInt32(IN[L, 0]);
if (D > D1)
{
if (M > M1)
{
if (Y > Y1)
{
for (int k = 0; k < IN.GetLength(1);k++)
{
c = IN[i, k];
IN[i, k] = IN[L, k];
IN[L, k] = c;
}
}
}
}
}
}
return IN;
I expect the output can show by sort of date as user input.
You can see more detail in Photo of table

How to find that one matrix is submatrix of the other in C#?

I want to find that a given matrix is a sub matrix of the other.
I have tried below piece of code but I am not sure that it would work:-
for (int i = 0; i < a.length - b.length + 1; i++) {
for (int j = 0; j < a[0].length - b[0].length + 1; j++) {
boolean submatrix = true; // at start we assume we have a submatrix
for (int k = 0; k < b.length; ++k) {
for (int l = 0; l < b[0].length; ++l) {
if (a[i + k][j + l] == b[k][l]) {
Console.WriteLine("a[" + (i + k) + "][" + (j + l) + "] = b[" + k + "][" + l + "]");
} else {
submatrix = false; // we found inequality, so it's not a submatrix
}
}
}
if (submatrix) {
Console.WriteLine("Found subatrix at " + i + "," + j + ".");
}
}
}
Please suggest??
Your suggested method is correct, there are only a few syntax and control flow issues which I've fixed.
It is important to point out that this method is only useful for detecting a submatrix of a 2D matrix, not any dimension matrix.
I assumed the datatype is a jagged array of int, though it can easily be changed.
private static bool IsSubMatrix(int[][] a, int[][] b)
{
for (int i = 0; i < a.Length - b.Length + 1; i++)
{
for (int j = 0; j < a[0].Length - b[0].Length + 1; j++)
{
bool found = true;
for (int k = 0; k < b.Length; ++k)
{
for (int l = 0; l < b[0].Length; ++l)
{
if (a[i + k][j + l] != b[k][l])
{
found = false;
break;
}
}
if (!found) break;
}
if (found) return true;
}
}
return false;
}
This is probably also not the fastest implementation.

Categories