C# having problems with using global variables - c#

So, I have finished majority of my code but one criteria required me to use a Procedure. So, when i decided to use a procedure i encountered several of problems. The main issue was that the variables which i have included in the first method(Generate Number and number) wont show up in my other methods.So can i make these variables global so that they work in all of my methods or is there another alternative solution to this problem?
Note: This is not my full code its just a piece out of it.
class Program
{
static void Main(string[] args)
{
Random GenerateNumber = new Random();
int[] number = new int[6];
Generating();
Ordering();
}
static void Generating()
{
Console.Clear();
Console.WriteLine("Stage 1 : 6 random numbers have been generated:\n");
for (int c = 0; c < number.Length; c++)
{
if (number[c] == 0)
{
number[c] = GenerateNumber.Next(1, 50);
Console.Write("Random number " + (c + 1) + " = " + number[c] + "\n");
}
}
}
static void Ordering()
{
Console.Clear();
for (int i = 0; i < number.Length; i++)
{
Array.Sort(number);
Console.Write("Number " + (i + 1) + " = " + number[i] + "\n");
}
}
}

Make them global is easiest but as said above, not the best way.
class Program
{
static Random GenerateNumber = new Random();
static int[] number = new int[6];
static void Main(string[] args)
{
Generating();
Ordering();
}
Better to use parameters
class Program
{
static void Main(string[] args)
{
Random GenerateNumber = new Random();
int[] number = new int[6];
Generating(GenerateNumber, number);
Ordering(number);
}
static void Generating(Random generateNumber, int[] number)
{
Console.Clear();
Console.WriteLine("Stage 1 : 6 random numbers have been generated:\n");
for (int c = 0; c < number.Length; c++)
{
if (number[c] == 0)
{
number[c] = generateNumber.Next(1, 50);
Console.Write("Random number " + (c + 1) + " = " + number[c] + "\n");
}
}
}
static void Ordering(int[] number)
{
Console.Clear();
for (int i = 0; i < number.Length; i++)
{
Array.Sort(number);
Console.Write("Number " + (i + 1) + " = " + number[i] + "\n");
}
}
}

If you have more methods like those working with your array of numbers then I'd suggest you create a CLASS that encapsulates the behaviors that you want. Something alone the lines of:
public class MyNumberArrayWithMethods
{
public int[] Numbers { get; set; }
public Action<int, int> Writer { get; set; }
//parametric constructor
public MyNumberArrayWithMethods(int length, Action<int, int> writer = null)
{
Numbers = new int[length];
Writer = writer;
}
public void Generating(int lowerBound = 1, int upperBound = 50)
{
for (int c = 0; c < Number.Length; c++)
{
if (Number[c] == 0)
{
Number[c] = GenerateNumber.Next(lowerBound, upperBound);
if(Writer != null)
Writer(c, Number[c])
}
}
}
public void Ordering()
{
Console.Clear();
Array.Sort(Number);
if(Writer != null)
for (int i = 0; i < Number.Length; i++)
Writer(i, Number[i]);
}
//... all other methods that work with "Number" array should go here
}
and then in your main
static void Main(string[] args)
{
Action<int, int> writer =
(pos, num) => { Console.Write("Number " + (pos + 1) + " = " + num + "\n"); }
var MyCtrl = new MyNumberArrayWithMethods(6, writer);
MyCtrl.Generating();
Ordering();
}
Please notice how I moved your Array.Sort call outside the loop. If you leave it inside you will sort the array as many times as the length of the array and I'm guessing you don't want that.

You could do it like this
class Program
{
public static void Main(string[] args)
{
Program p = new Program();
Random GenerateNumber = new Random();
int[] number = new int[6];
int[] generatedNumber = p.Generating(GenerateNumber, number);
p.Ordering(generatedNumber);
}
public int[] Generating(Random GenerateNumber, int[] number)
{
Console.Clear();
Console.WriteLine("Stage 1 : 6 random numbers have been
generated:\n");
for (int c = 0; c < number.Length; c++)
{
if (number[c] == 0)
{
number[c] = GenerateNumber.Next(1, 50);
Console.Write("Random number " + (c + 1) + " = " + number[c]
+ "\n");
}
}
return number;
}
public void Ordering(int[] number)
{
Console.Clear();
for (int i = 0; i < number.Length; i++)
{
Array.Sort(number);
Console.Write("Number " + (i + 1) + " = " + number[i] + "\n");
}
}
}
https://dotnetfiddle.net/3K6P54

Related

Need to limit every odd or even thread with a semaphore c#

so I'm in a bit confused as to how I'm supposed to do something. I've got 5 threads that are doing a basic task and they are generated with a for loop in main. I've already used a semaphore that limits the amount of threads running at a time as that's a part of the exercise, what I've got left is to make sure that threads that are next to each other (they're numbered 0-4 using the loop) don't run simultaneously. What I've got as an idea is to block every odd or even thread(it doesn't really matter) but I can't figure out how to both let two threads in and at the same time block every odd one. Is there a specific method for that, or maybe if there is another way, like letting three in at first and somehow not letting the second one in but letting the third one. I'll leave what I've got done so far:
edit: For clarification the way it has to be thought about is actually a bit different then what I initially asked about. So if 1 is running both 0 and 2 aren't allowed to run. But if 0 is running both 4 and 1 aren't allowed to run either. I'm pretty sure that it's obvious that if 4 is running 0 and 3 aren't allowed to work etc. .
using System.Threading;
namespace StudentProblem
{
public class StudentProblem
{
static Semaphore stop = new Semaphore(2,2);
static Semaphore gate = new Semaphore(3,3);
public static void Student(Object o)
{
var r = new Random();
var num = (int) o;
while (true)
{
Console.WriteLine(" Student " + num + " start learning.");
Thread.Sleep(r.Next(2000, 3000));
for (int i = 0; i < num; i++)
Console.Write("_");
//gate.WaitOne();
stop.WaitOne();
Console.WriteLine("> Student " + num + " start eating.");
Thread.Sleep(r.Next(2000, 3000));
for (int i = 0; i < num; i++)
Console.Write("_");
Console.WriteLine("< Student " + num + " stop eating");
//gate.Release();
stop.Release();
}
}
}
class Program
{
static void Main(string[] args)
{
var studentThreads = new Thread[5];
for (int i = 0; i < 5; i++)
{
studentThreads[i] = new Thread(StudentProblem.Student);
studentThreads[i].Start(i);
}
}
}
}
In the end I decided to ditch the whole multiple semaphore approach and went with the old and trusty way. I'll add my solution here. It's not that great, but it works.
using System;
using System.Collections.Generic;
using System.Threading;
namespace testing
{
public class StudentProblem
{
public static List<StudentProblem> allProblems = new List<StudentProblem>();
static Semaphore eatingGate = new Semaphore(2, 2);
private object id;
private bool eating = false;
public StudentProblem(object o)
{
id = o;
}
public object Id
{
get
{
return this.id;
}
}
public bool Eating
{
get
{
return this.eating;
}
}
public void DoStuff()
{
var r = new Random();
var num = (int)this.Id;
Console.WriteLine(" Student " + num + " start learning.");
Thread.Sleep(r.Next(2000, 3000));
while (true)
{
for (int i = 0; i < num; i++)
Console.Write("_");
int indexBehind = 0;
int indexFront = 0;
for (int i = 0; i < allProblems.Count; i++)
{
if(num == 0)
{
indexBehind = 4;
}
else
{
indexBehind = num - 1;
}
if(num == 4)
{
indexFront = 0;
}
else
{
indexFront = num + 1;
}
check:
if (allProblems[indexBehind].Eating != true && allProblems[indexFront].Eating != true)
{
if (eatingGate.WaitOne())
{
this.eating = true;
Thread.Sleep(250);//poigrai si s timeout-a
Console.WriteLine("> Student " + num + " start eating.");
Thread.Sleep(r.Next(1000, 2000));
for (int j = 0; j < num; j++)
Console.Write("_");
Console.WriteLine("< Student " + num + " stop eating");
this.eating = false;
eatingGate.Release();
Console.WriteLine(" Student " + num + " start learning.");
Thread.Sleep(r.Next(2000, 3000));
}
else
{
goto check;
}
}
else
{
goto check;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
var studentThreads = new Thread[5];
for (int i = 0; i < 5; i++)
{
StudentProblem.allProblems.Add(new StudentProblem(i));
studentThreads[i] = new Thread(StudentProblem.allProblems[i].DoStuff);
studentThreads[i].Start();
}
}
}
}

Is there a way to throw an exception when string is typed in an arrayc#?

I am new in this fascinating world of programming. I have done this array, but when I type a non integer it crashes. I have tried many ways like int.Parse(console.readLine)), tryparse(text, out int) and ConvertTo32 ,However it continues saying that "Input string was not in correct format." Thanks
using System;
namespace BubbleSort
{
class Program
{
public static void HelpME(int[] a, int t)
{
for (int j = 0; j <= a.Length - 2; j++)
{
for (int i = 0; i <= a.Length - 2; i++)
{
if (a[i] > a[i + 1])
{
t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
}
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
a[0 + x] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}
}
}
you should validate the user unput by using int.TryParse method. If the entered string can be converted to int then only it should be inserted into the array, otherwise the program should ignore that value.
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
int temp = 0;
string input = Console.ReadLine();
if(int.TryParse(input, out temp))
{
a[0 + x] = Convert.ToInt32(input);
}
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}

Minimal change algorithm for permutations

My teacher gave me this algorithm of generating permutations and said that it's minimal change algorithm. The problem is I can't implement it correctly - it loops forever. Here's my code:
class Program
{
private static int[] a;
private static int[] d;
private static int[] pos;
public static void Swap(int[] source, int index1, int index2)
{
int temp = source[index1];
source[index1] = source[index2];
source[index2] = temp;
}
static void Main(string[] args)
{
int n = 3;
a = new int[n + 2];
d = new int[n + 2];
pos = new int[n + 2];
for (int i = 1; i <= n; ++i)
{
a[i] = pos[i] = i;
d[i] = -1;
}
int m = 0;
a[0] = a[n + 1] = n + 1;
while (m != 1)
{
for (int i = 1; i <= n; ++i)
{
Console.Write(a[i] + " ");
}
Console.WriteLine();
m = n;
while(a[pos[m]+d[m]] > m)
{
d[m] = -d[m];
m = m - 1;
}
Swap(a, a[pos[m]], a[pos[m] + d[m]]);
Swap(pos, pos[m], pos[a[pos[m]] + d[m]]);
}
Console.ReadKey();
}
}
I was searching for this algorithm and found another pseudocode, it slightly different from first one, but it doesn't work either.
I would like to use Steinhaus-Johnson-Trotter algorithm or anything else, and I feel like given algorithm is wrong, but teacher insist that it's correct.
So are there any errors or I can ignore teacher and use what I want to?
one thing I noticed is that swap should receive indexes and you're sending the values of the cells you want to swap:
Swap(a, pos[m], pos[m] + d[m]);
Swap(pos, m, a[pos[m]] + d[m]);

C# Array C with a formula

im new to programming and I am stuck on a part of a question.
After i create two methods-one for inputing Array and one for summing the elements that are odd and can be dividible to 5.I have to do this to three arrays-A,B and C.I've done all of this,but this time i have to find the elements of C(again),but with this formula:
((An-Bn)(A1-B1),(An-1 - Bn-1)(A2-B2),....(A1-B1)(An-Bn))
or in other words:
((A[n]-B[n])(A[0]-B[0]),(A[n-1]-B[n-1])(A[2]-B[2]),....,(A[1]-B[1])(A[n]-B[n])
If someone can help me to figure this out.I've tried a couple of things and most of them give the "Index out of bounds".
Thank you in advance.
namespace MethodsArrays
{
class Program
{
//Tochka 1 a/ i b/
static void Array(int[] p)
{
for (int i = 0; i < p.Length; i++)
{
p[i] = int.Parse(Console.ReadLine());
}
}
static void Output(int [] p)
{
for (int i = 0; i < p.Length; i++)
{
Console.WriteLine();
Console.Write(p[i] + "");
Console.WriteLine();
}
}
static int Multiple(int[] p)
{
int br = 0;
for (int i = 0; i < p.Length; i++)
{
if (p[i] % 2 == 1 && p[i] % 5 == 0)
{
//for (int j = 0; j < p.Length;j++)
//{
br += p[i];
//}
}
}
return br;
}
//Tochka 2
public static void Main()
{
Console.WriteLine("Type the legth of the array.");
Console.WriteLine();
int n = int.Parse(Console.ReadLine());
Console.Write("n= "+ n);
Console.WriteLine();
int[] a = new int[n];
Array(a);
Console.Write("Array A: ");
Output(a);
Console.WriteLine();
Console.Write("Length of B = "+ n);
Console.WriteLine();
int[] b = new int[n];
Array(b);
Console.Write("Array B: ");
Output(b);
Console.WriteLine();
Console.Write("Length of C= " + n);
Console.WriteLine();
int[] c = new int[n];
Array(c);
Console.Write("Array C: ");
Output(c);
Console.WriteLine();
int br1 = Multiple(a); Console.WriteLine("br1=" + br1);
int br2 = Multiple(b); Console.WriteLine("br2=" + br2);
int br3 = Multiple(c); Console.WriteLine("br3=" + br3);
double srgeo = (br1 * br2 * br3);
double srg = Math.Pow(srgeo, (double)1 / 3);
Console.WriteLine("Srednogeometrichno= "+ srg);
There there are n elements in a and b then the i-th element of c is
c[i] = (a[n-i-1]-b[n-i-1])*(a[i]-b[i])
Or more specifically, try the method below for composing c
static int[] ComposeArray(int[] a, int[] b)
{
if (a.Length == b.Length)
{
int n = a.Length;
int[] c = new int[n];
for (int i = 0; i < n; i++)
{
c[i] = (a[n-i-1]-b[n-i-1])*(a[i]-b[i]);
}
return c;
}
throw new ArgumentException();
}
since no test data was given in the question, I made up some on my own:
static void Main(string[] args)
{
var a = Enumerable.Range(1, 5).Select((i) => i).ToArray();
// [1,2,3,4,5]
var b = Enumerable.Range(4, 5).Select((i) => i).ToArray();
// [4,5,6,7,8]
var c = ComposeArray(a, b);
// [9,9,9,9,9]
}

How do I find the lowest and highest value of an array as well as the array squared and the array reversed?

I'm trying to write a code that will give me the highest and lowest number in an array as well as the array squared and the reversed array. I keep getting 0's when I run the program but no other problem, so something is set equal to wrong but I can't figure out what's wrong because there's no error messages. Here's the code:
using System;
namespace ArrayMethods
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an array size: ");
int someArray = Convert.ToInt32(Console.ReadLine());
int[] Array = new int[someArray];
String input = Console.ReadLine();
int[] arrayPart3 = new int[10];
ReversedArray(arrayPart3);
for (int index = 0; index < arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
Console.WriteLine();
Console.WriteLine("Largest is:" + ArrayMax(arrayPart3));
Console.WriteLine("Smallest is:" + ArrayMin(arrayPart3));
SquaredArray(arrayPart3);
for (int index = 0; index<arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
Console.WriteLine();
ReversedArray(arrayPart3);
for (int index = 0; index < arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
}
public static int ArrayMax(int[] someArray)
{
int highest = someArray[0];
for (int index = 0; index < someArray.Length; index++)
{
if (someArray[index] > highest)
highest = someArray[index];
}
return highest;
}
public static int ArrayMin(int[] someArray)
{
int lowest = someArray[0];
for (int index = 0; index < someArray.Length; index++)
{
if (someArray[index] < lowest)
lowest = someArray[index];
}
return lowest;
}
public static void SquaredArray(int[]someArray)
{
for (int index = 0; index < someArray.Length; index++)
{
someArray[index] = someArray[index] * someArray[index];
}
}
public static void ReversedArray(int[] someArray)
{
for (int index = 0; index<someArray.Length; index++)
{
int temp = someArray[index];
someArray[index] = someArray[someArray.Length - 1 - index];
someArray[someArray.Length - 1 -index] = temp;
}
}
}
}
the code of parsing the input is missing
here is a compact linq based code:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var input = Console.ReadLine();
// or use a fixed input: var input = "1 2 3 4";
int[] arrayPart3 = input.Split(' ',',', ';').Select(s => int.Parse(s)).ToArray();
Console.WriteLine("Reversed: " + string.Join("| ", arrayPart3.Reverse()));
Console.WriteLine();
Console.WriteLine("Largest is:" + arrayPart3.Max());
Console.WriteLine("Smallest is:" + arrayPart3.Min());
Console.WriteLine("Squared: " + string.Join("| ", arrayPart3.Select(i => i*i)));
Console.WriteLine("Reversed Squared: " + string.Join("| ", arrayPart3.Reverse().Select(i => i*i)));
}
}
As mentioned by #user287107 System.Linq provides most of these functions out of the box, for the squaring you can use a simple Select extension method Func.
Here is an ArrayUtils class I quickly wrote to provide the functionality you are looking for:
using System.Linq;
namespace StackOverflow
{
public class ArrayUtils
{
public int GetMax(int[] arr)
{
return arr.Max();
}
public int GetMin(int[] arr)
{
return arr.Min();
}
public int[] GetReverse(int[] arr)
{
return arr.Reverse().ToArray();
}
public int[] SquareValues(int[] arr)
{
return arr.Select(x => x * x).ToArray();
}
}
}

Categories

Resources