How to put an if else statement in a loop [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
This is my code. So far this works but I need it to be in a loop, so I don't keep repeating the if else statement.
static void Main(string[] args)
{
int i, j, k, l, m, n;
int result;
string [] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
i = array[0].Length;
j = array[1].Length;
k = array[2].Length;
l = array[3].Length;
m = array[4].Length;
n = array[5].Length;
result = i * j;
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * k;
}
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * l;
}
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * m;
}
if (result == 16)
{
Console.WriteLine(array[0]+" * "+array[4]+" = "+result);
}
else
{
result = i * n;
}

If you create an outer loop that loops over all the entries and then an inner loop that loops over the entries after the one you're looking at in the outer loop, you can do something like this
string[] array = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
for (var i = 0; i < array.Length; i++)
{
for (var j = i + 1; j < array.Length; j++)
{
if (array[i].Length * array[j].Length == 16)
{
Console.WriteLine($"{array[i]} {array[j]}");
}
}
}
You then get the result which is abcw xtfn

One of the possible way to short your code.
You can iterate your array and compare first item with rest of the items as you mentioned in your question code-block. No need to access individual array elements.
Compare 1st element with rest
static void Main(string[] args)
{
int result;
string[] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
for (int i = 0; i < array.Length - 2; i++)
{
result = array[0].Length * array[i + 1].Length;
if (result == 16)
{
Console.WriteLine(array[0] + " * " + array[i+1] + " = " + result);
break;
}
}
Console.ReadLine();
}
Compare all element in between
for (var i = 0; i < array.Length; i++)
for (var j = i + 1; j < array.Length; j++)
if (array[i].Length * array[j].Length == 16)
Console.WriteLine(array[i] + " * " + array[j] + " = " + array[i].Length * array[j].Length);

string[] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
int result = 16;
for (var i = 0; i < array.Length; i++) {
int x = array[i].Length;
if (result % x != 0) {
continue;
}
for (var j = i + 1; j < array.Length; j++) {
if (x * array[j].Length == result) {
Console.WriteLine(array[i] + "*" + array[j] + "= " + result);
}
}
}

Related

char 2D array compression

There is a .txt file what I have to read, compress and make an output txt for the compressed txt. Could anyone tell me what should I fix in my code?
My code:
namespace Tomorites
{
class Compression
{
public void Compress(char[,] source)
{
for (int i = 0; i < source.GetLength(0); i++)
{
int white = 0;
int red = 0;
for (int j = 0; j < source.GetLength(1); j++)
{
if (source[i, j] == 'P')
{
if (source[i, j] > 0)
{
red++;
Console.Write(red + " P ");
}
}
else if(source[i,j]=='F')
{
if (source[i, j] > 0)
{
white++;
Console.Write(white + " F ");
}
}
}
Console.WriteLine();
}
}
}
}
My console output
Source txt file
The compressed txt file which has to be
You was pretty close, but messed one important thing: reset first char counter when second char appear or second char counter when first char appear.
Also source[i, j] > 0 condition do nothing for you.
So at result we may have:
Fill source array:
static void Main(string[] args)
{
// Declare array
char[,] source = new char[7, 10];
// Fill array as at example
for (int i = 0; i < source.GetLength(0); i++)
for (int j = 0; j < source.GetLength(1); j++)
source[i, j] = i == 3 || j == 3 ? 'F' : 'P';
// Print filled array to Console
Console.WriteLine("Source:\n" + new string('-', 10));
for (int i = 0; i < source.GetLength(0); i++)
{
for (int j = 0; j < source.GetLength(1); j++)
Console.Write(source[i, j] + " ");
Console.WriteLine();
}
// Just new line
Console.WriteLine();
// Now "compress"
Console.WriteLine("Compressed:\n" + new string('-', 10));
Compress(source);
Console.ReadKey();
}
Source output:
Compress source array:
static void Compress(char[,] source)
{
// Declare counters for P and F chars
int PCount = 0, FCount = 0;
for (int i = 0; i < source.GetLength(0); i++)
{
for (int j = 0; j < source.GetLength(1); j++)
{
if (source[i, j] == 'P')
{
// If char is P - then count P's up
PCount++;
// If there was F char counted before (> 0) - print it and reset counter
if (FCount > 0)
{
Console.Write(FCount + " F ");
FCount = 0;
}
}
else if (source[i, j] == 'F')
{
// If char is P - then count F's up
FCount++;
// If there was P char counted before (> 0) - print it and reset counter
if (PCount > 0)
{
Console.Write(PCount + " P ");
PCount = 0;
}
}
}
// Before go to next "row" - print remained P or F counts and again, reset counters
if (PCount > 0)
{
Console.Write(PCount + " P ");
PCount = 0;
}
else if (FCount > 0)
{
Console.Write(FCount + " F ");
FCount = 0;
}
// Go new "row"
Console.WriteLine();
}
}
Compressed output:
UPD.
My answer is just solution for a provided example source and example output. #Dmitry Bychenko's solution is universal, not dependent on any two specific characters so in general use I recommend his way.
You can try something like this (you can fiddle with the code):
public static string Compress(char[,] source) {
if (null == source || source.GetLength(0) <= 0 || source.GetLength(1) <= 0)
return "";
StringBuilder sb = new StringBuilder();
for (int row = 0; row < source.GetLength(0); ++row) {
if (sb.Length > 0)
sb.AppendLine();
int count = 0;
char prior = '\0';
bool left = true;
for (int col = 0; col < source.GetLength(1); ++col) {
if (count == 0 || prior == source[row, col])
count += 1;
else {
if (!left)
sb.Append(' ');
left = false;
sb.Append($"{count} {prior}");
count = 1;
}
prior = source[row, col];
}
if (!left)
sb.Append(' ');
sb.Append($"{count} {prior}");
}
return sb.ToString();
}
Demo:
char[,] test = new char[,] {
{'a', 'a', 'a', 'a'},
{'a', 'b', 'c', 'c'},
};
Console.WriteLine(Compress(test));
Outcome:
4 a
1 a 1 b 2 c

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 :)

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.

Horner algorithm

I have a question about my console program.
It has to count using Horner algorithm. There is no exception thrown, however, it does not give the right results.
If anyone could help me I would be very grateful, because I do not know what to do ...
Here is the code of my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Consola_Horner_Rekurencyjnie
{
class Program
{
static void Main(string[] args)
{
int n;
Console.WriteLine("Podaj stopień wielomioanu: ");
n = Convert.ToInt32(Console.ReadLine());
int[] a = new int[++n];
Console.WriteLine("Podaj wartosc a: ");
for (int i = 0; i < n; i++)
{
Console.WriteLine("a [" + i + "] = ");
a[i] = Convert.ToInt32(Console.ReadLine());
}
int x;
Console.WriteLine("Podaj x:");
x = Convert.ToInt32(Console.ReadLine());
int Horner;
Horner = a[0];
for (int i = 1; i < n; i++)
{
Horner = Horner * (i - 1) * x + a[i];
}
Console.WriteLine("Wynik to:" + Horner);
Console.ReadLine();
}
}
}
This is the second option calculates the code, but the counts are all wrong:
Func<int, int> Horner = null;
Horner = (i) => (i == 0) ? a[0] : Horner(i - 1) * x + a[i];
Console.WriteLine("Wynik to:" + Horner(x));
Console.ReadLine();
I wanted to rewrite the original code from C + + (in the form of a recursive algorithm).
The original code looks like:
int Horner;
int n;
int *a = new int[n];
int x;
int main()
{
cout <<"Podaj stopień wielomianu: ";
cin >> n;
cin.ignore();
cout << "Podaj wartość a: \n";
for (int i = 0; i <= n; i++)
{
cout <<"a[" <<i<<"] = ";
cin >> a[i];
cin.ignore();
}
cout <<"Podaj x: ";
cin >> x;
cin.ignore();
cout <<"Wynik to: " << Horner(n);
getchar ();
return 0;
}
int Horner (int i)
{
if (i == 0)
return a[0];
else
return Horner (i - 1) * x + a[i];
}
Already I do not know how to do it ... Wandering still in the same place ...
You're unnecesarily multiplying by (i-1) in your loop.
Change it to:
int Horner;
Horner = a[0];
for (int i = 1; i < n; i++)
{
Horner = Horner * x + a[i];
}
or even better to:
int Horner = 0;
foreach (int wspolczynnik in a)
{
Horner = Horner * x + wspolczynnik;
}
You probably saw some implementation that had Horner(i-1) * x + a(i), but the (i-1) is an array index in this case, not a multiplier.
edit:
On the other hand your recursive version takes one parameter - the degree of the polynomial, and you tried to call it with x. Do it with n!
int result = Horner(n);
IMO it would be much clearer if it took 2 parameters - degree of the polynomial, and x:
Func<int, int, int> Horner = null;
Horner = (i, x) => (i == 0) ? a[0] : Horner(i - 1, x) * x + a[i];
int result = Horner(n, x);
I found here "good" source code in c# for Horner scheme:
private IEnumerable<int> getDivisors(int n)
{
if (n == 0)
return (IEnumerable<int>)new int[] { 0 };
else
return Enumerable.Range(-Math.Abs(n), 2 * Math.Abs(n) + 1)
.Where(a => a != 0)
.Where(a => (n % a) == 0);
}
private bool findRootWithHornerScheme(int[] coefficientsA, int x, out int[] coefficientsB)
{
var lenght = coefficientsA.Length;
var tmpB = new int[lenght];
coefficientsB = new int[lenght - 1];
tmpB[0] = coefficientsA[0];
for (int i = 1; i < lenght; i++)
{
tmpB[i] = tmpB[i - 1] * x + coefficientsA[i];
}
//ak je posledny koefiecient B == 0 ,tak zadane x je korenom polynomu
if (tmpB[lenght - 1] == 0)
{
Array.Copy(tmpB, coefficientsB, lenght - 1);
return true;//bol najdeny koren
}
//nebol najdeny koren a metoda vrati false
return false;
}

Looping through an array without throwing exception

Say I have an array of values:
string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };
Then I have a basic loop:
for (int i = 0; i <= 30; i++)
{
Console.WriteLine(i + " = " + text[i])
}
Obviously, this will cause an out of bounds exception, so what I want to do is when the counter reaches the upper bound of the array then go back to the start.
So
0 = val1
1 = val2
2 = val3
3 = val4
4 = val5
5 = val1
6 = val2
7 = val3
etc..
You could use the modulus operator:
Console.WriteLine(i + " = " + text[i % 5])
Take the modulus of the array length:
for (int i = 0; i < 30; ++i)
{
Console.WriteLine(i + " = " + text[i % text.Length]);
}
Try
for(int i=0;i<=30;i++)
{
Console.WriteLine(i + " = " + string[i % 5])
}
Shouldn't it be:
Console.WriteLine(i + " = " + text[i % text.length])
?
As a slightly less specific solution...
class Program
{
static void Main(string[] args)
{
string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };
int count = 0;
foreach (string t in text.ContinuousLoopTo(30))
{
Console.WriteLine(count.ToString() + " = " + t);
count++;
}
Console.ReadLine();
}
}
public static class Extensions
{
public static IEnumerable<T> ContinuousLoopTo<T>(this IList<T> list, int number)
{
int loops = number / list.Count;
int i = 0;
while (i < loops)
{
i++;
foreach (T item in list)
{
yield return item;
}
}
for (int j = 0; j < number % list.Count; j++)
{
yield return list[j];
}
}
}
what? like forever?
bool run = true;
int i = 0;
string[] text = new string[] {"val1", "val2", "val3", "val4", "val5"};
while(run)
{
Console.WriteLine(i + " = " + text[i])
i++;
if(i>=text.Length) i=0;
}
The writeline should be:
Console.WriteLine(i + " = " + text[i%5]);

Categories