Matrix smallest number - c#

So this code should work, but i cant figure out the problem.
It worked me once before... But now i only get back 0 as a result.
I know it should be obvious but i cant see it.
namespace ConsoleApp5
{
class Program
{
private static void Main(string[] args)
{Console.WriteLine("The SmallestNumber in the given matrix is : {0}", SmallestNumber());
Console.ReadKey();
}
public static int SmallestNumber()
{
int n = 10;
int m = 10;
int[,] TempMatrix = new int[n, m];
Random r = new Random();
int smallest = TempMatrix[0,0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
TempMatrix[i, j] = r.Next(10, 3000);
if (smallest > TempMatrix[i,j])
{
smallest = TempMatrix[i, j];
}
Console.WriteLine(string.Format("{0}\t", TempMatrix[i, j]));
}
}
return smallest;
}
}
}

When you initialize smallest, TempMatrix[0,0] has the value 0. All the random numbers you generate are between 10 and 3000, so all the numbers in the matrix are greater than smallest, since it is 0.
Setting smallest initially to int.MaxValue should solve the problem.

Related

can someone help me with this (most likely simple) error? [duplicate]

This question already has answers here:
Making an array of random ints
(2 answers)
Closed last month.
I have just started to learn coding and was hoping someone with a little more skill would help me out a bit.
Here is the code and when i run it the displayarray is coming up as just zeros and then the sum of the array is also zero I just cant grasp why thats happening so it would be awesome if someone could help me out.
namespace random_array_2._0
{
class Program
{
static void Main(string[] args)
{
int[] array;
int sum = 0;
int arraySum;
array = CreateArray();
DisplayArray(array);
arraySum = SumTheArray(array, sum);
}
static int[] CreateArray()
{
Random Array = new Random();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Array.Next(1, 100));
}
return new int[10];
}
static void DisplayArray(int[] array)
{
Console.WriteLine();
Console.WriteLine("Sorted array in ASC order");
Array.Sort(array);
foreach (int i in array)
{
Console.Write(i + " ");
}
}
static int SumTheArray (int[] array, int sum)
{
for (int i = 0; i < array.Length; i++)
{
sum += array[i];
}
Console.WriteLine($"all together equals to: {sum}");
Console.ReadKey();
return sum;
}
}
}
Your CreateArray function is printing 10 random numbers and then returning a new array. The default value for int is 0, so this array contains 10 zeros.
You should first create the array and then populate it with random values:
static int[] CreateArray()
{
Random Array = new Random();
var a = new int[10];
for (int i = 0; i < a.Length; i++)
{
a[i] = Array.Next(1, 100);
}
return a;
}
There you go:
static int[] CreateArray()
{
Random randomNumberGenerator = new Random();
int[] array = new int[10];
for (int i = 0; i < array.Length; i++)
{
int randomNumber = randomNumberGenerator.Next(1, 100);
array[i] = randomNumber;
}
return array;
}
My advise to you is to stop using Console.WriteLine statements and start using the debugger. Console.WriteLine often lies; the debugger tends to never lie.
Your CreateArray function is not storing anything into Array, and it's returning an array with 10 zeroes (default value when none in given).
Try with
static int[] CreateArray()
{
Random rnd = new Random();
int[] Array = new int[10];
for (int i = 0; i < 10; i++)
{
Array[i] = rnd.Next(1, 100);
}
return Array;
}

No Output for MergeSort Algorithm c#

In my project I've implemented MergeSort, bubble sort, and sequential search algorithms, however the Merge sort is not giving any output to the console, while the others work. I've tried debugging with no real luck.
public static void mergeSort(int[] a)
{
int inputLength = a.Length;
//sets the middle index to the total length divided by 2
int midIndex = a.Length / 2;
//sets the last index to the length minus one (minus one included so
an out of bounds exception is avoided
int endIndex = a.Length - 1;
//left side set to the middle index size
int[] leftArray = new int[midIndex];
//right side set to the total length minus the middle length
int[] rightArray = new int[inputLength - midIndex];
//looping from zero to middle of the array
for (int i = 0; i < midIndex; i++)
{
leftArray[i] = a[i];
}
//looping from the middle to the end of the array
for(int i = midIndex; i < inputLength; i++)
{
rightArray[i - midIndex] = a[i];
}
//recursively called the method to sort these two sides
mergeSort(leftArray);
mergeSort(rightArray);
//this calls the merge method to put the two halves together
merge(a, leftArray, rightArray);
}
private static void merge(int[] a, int[] leftHalf, int[] rightHalf)
{
int leftSize = leftHalf.Length;
int rightSize = rightHalf.Length;
int i = 0, j = 0, k = 0;
//loops until no more elements in left or right array
while(i < leftSize && j < rightSize)
{
if(leftHalf[i] <= rightHalf[j])
{
//sets the element at iteration k to the elements at i in the
left half if
//it is smaller than the right half
a[k] = leftHalf[i];
i++;
}
else
{
//if the right half is smaller, set element at iteration k
equal to the
//element at index j of the right half
a[k] = rightHalf[j];
j++;
}
k++;//iterate K
}
//these account for leftover elements after the above while loop.
while (i < leftSize)
{
a[k] = leftHalf[i];
i++;
k++;
}
while (j < rightSize)
{
a[k] = rightHalf[j];
j++;
k++;
}
}
My main method is here:
static void Main(string[] args)
{
try{
TextFileReader reader = new TextFileReader();
int[] numberArray = reader.ReadFile("numbers.txt");
//printArray(numberArray);
Sorts sorts = new Sorts();
//sorts.bubbleSort(numberArray);
//printArray(numberArray);
//sorts.selectionSort(numberArray);
Searches searches = new Searches();
//searches.SequentialSearch(numberArray, 897);
//searches.binarySearch(numberArray, 9992);
//Console.WriteLine("\n\nArray length: " + numberArray.Length);
mergeSort(numberArray);
printArray(numberArray);
}
catch(IOException ex)
{
Console.WriteLine("IO Exception Found.");
}
}
public static void printArray(int[] numberArray)
{
foreach(int i in numberArray)
{
Console.WriteLine(i);
}
}
}
}
This is driving me crazy because the other algorithms are working and outputting correctly, but when the MergeSort is ran it gives no exceptions or errors.

C# Am I doing "Bays & Durham Randomization by Shuffling" correctly?

I tried to improvise a random number generator by using the "Bays & Durham Randomization by Shuffling" algorithm. I followed a tutorial online and made this code:
public int[] GenerateRandomSequence_Improved(int n, int min, int max)
{
int[] seq = new int[n];
for(int i = 0; i < n; i++)
{
int rand = GenerateNextRandomNumber(min, max);
rand = min + rand % (max + 1 - min);
seq[i] = rand;
}
return seq;
}
I wanna know if I did it correctly or not..
EDIT: This is the code for the GenerateNextRandomNumber method
public int GenerateNextRandomNumber(int min, int max)
{
return cSharpRNG.Next(min,max);
}
According to Knuth TAOCP Vol. 2 p. 34 Algorithm B, the proper algorithm is the following,
public class BaysDurham
{
private readonly int[] t;
private int y; // auxiliary variable
// Knuth TAOCP Vol. 2 p. 34 Algorithm B
public BaysDurham(int k)
{
t = new int[k];
for (int i = 0; i < k; i++)
{
t[i] = rand.Next();
}
y = rand.Next();
}
public int Next()
{
var i = (int)((t.Length * (long) y) / int.MaxValue); // mitigates the bias
y = t[i];
t[i] = rand.Next();
return y;
}
private readonly Random rand = new Random();
}
I let you adapt the range of the output, but just know that the formula you use with the modulo introduce significant bias and makes the distribution non-uniform please look at this.
Here is what I believe proper implementation of the Bays-Durham shuffling. Warning wrt bias in indexing due to modulo operation is right though.
.NET Core 2.2, x64 Win10
using System;
using System.Diagnostics;
namespace BaysDurhamShuffling
{
public class BaysDurhamRNG
{
public int[] _table;
public int _xnext;
public Random _rng = null;
public BaysDurhamRNG(int n, int seed = 312357) {
Debug.Assert(n > 1);
_rng = new Random(seed);
_table = new int [n];
for(int k = 0; k != n; ++k) {
_table[k] = _rng.Next();
}
_xnext = _rng.Next();
}
public int next() {
var x = _xnext; // store return value
var j = _xnext % _table.Length; // form the index j into the table
_xnext = _table[j]; // get jth element of table and to copy it to the output stream on next call
_table[j] = _rng.Next(); // replace jth element of table with next random value from input stream
return x; // return what was stored in next value
}
}
class Program
{
static void Main(string[] args)
{
var rng = new BaysDurhamRNG (16, 12345);
for(int k = 0; k != 30; ++k) {
var x = rng.next();
Console.WriteLine($"RV = {x}");
}
}
}
}

2D-array display error

How am I supposed to display my 2D array? Or the average sum of my array? It won't let me.
The code is supposed to display a 2D array, add all those numbers, calculate the average and display the average.
// It gives me a richTextBox error. I tried to change 'float' to 'void' - gives
// me a return error.
//
// It says the object require non static field?
richTextBox1.AppendText(array[ i, j] + " ");
richTextBox1.AppendText(" "+ sum.ToString());
return avg; // <<< Error here
static float Avg(int[,] array)
{
return (float)array.OfType<int>().Average();
richTextBox1.Clear(); // <<<<==================== Here
Random rand = new Random();
float sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < cols; j++)
{
int value = rand.Next(-100, 100);
array[i, j] = value;
richTextBox1.AppendText(value + " "); // <<<<<<<===== Here
if (value <= 0)
sum += value;
float avg = sum / value;
}
return avg;//<<<========here
}
richTextBox1.AppendText(" Total Average is: " + avg.ToString()); // <<<==== Here
}
private void button6_Click(object sender, EventArgs e)
{
Avg(A);
}
Try this:
static float Avg(int[,] array)
{
return (float)array.OfType<int>().Average();
}
Then you use it like this:
var array = new int [2,3] {{1,2, 3}, {4,5, 6}};
Console.WriteLine(Avg(array));
Update - for jagged arrays
static float Avg(int[][] array)
{
return (float)array.SelectMany(a => a).Average();
}
void Main()
{
int[][] array =
{
new int[] {1,2,3},
new int[] {4,5}
};
Console.WriteLine(Avg(array));
}
Update 2
if you want to do it your way try this:
private void Avg(int [,] array)
{
richTextBox1.Clear();
float sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
richTextBox1.AppendText(array[i,j] + " ");
sum += array[i,j];
}
}
richTextBox1.AppendText(" Total Average is: " + (float)sum/(rows*cols));
}
Because we do not really know, what do you try to make with the Avg method. I just try to sumarize:
static float Avg: you cannot use static where you use Form instance members (like richTextBox1). Please remove 'static' or move usage of richTextBox1 just in the OnClick method.
Don't use return where you want. Everything after it will not process (if not using try/finally). If you want to use the returned value, call it on the last line after everything in method processed.
return avg: avg is not known in the current context, whether is defined in the previous closure (do you know what have your neighbour behind the closed doors?)
For the final solution, refer to Ned's answer.

How do I get my code to work?

I have a one assignment
I have to make one dimension array with 20 numbers - first 10 numbers are from 1 do 10. others 10 numbers I have to get in method called Dopolni - where I have to sum together array with one another like - p11 = p0+p1, p12 = p1+p2, p14 = p2+p3 and so on - I dont know how to arrange it to get those other 10 numbers - help please
my code till now is
static void Dopolni(int[] p)
{
for (int i = 11; i < 20; i++)
{
p[i] = p[i] + 1;
}
}
static void Main(string[] args)
{
int[] p = new int[20];
for (int i = 1; i < 20; i++)
{
if (i <= 10)
{
p[i] += i;
}
Console.WriteLine("{0}", p[i]);
}
Dopolni(p);
Console.WriteLine(p);
Console.ReadKey(true);
}
All numbers I have to write out in main window. Hope someone can help out
The indices of the first 10 numbers range from 0 to 9, the others from 10 to 19. But since you always sum two consecutive numbers, you will only get 9 sums! In order to get 10 sums, you could start by summing 0 with p[0]:
int previous = 0;
for (int i = 0; i < 10; i++) {
p[i + 10] = previous + p[i];
previous = p[i];
}
public static void Main()
{
int[] p = new int[20];
for (int i = 0; i < 10; i++)
{
p[i] = i + 1;
ยจ
Console.WriteLine(p[i]);
}
Dopolni(p);
}
static void Dopolni(int[] p)
{
for (int i = 10; i < 20; i++)
{
p[i] = p[i - 10] + p[i - 9];
Console.WriteLine(p[i]);
}
}
This looks like trouble:
int[] p = new int[20];
Console.WriteLine(p);
What you want is to loop through p and print each element, not rely on the array implementation of ToString().
Try:
foreach (var n in p)
Console.WriteLine(n);
Do you need to have it in a function? Its really quite simple...
Notice I use 'out int[]', thats what your missing in your code. Out specifies you want in/out param, not just in ;)
static void Main()
{
int[] p = new int[20];
// First 10 numbers
for (int i = 0; i < 10; i++)
p[i] = i + 1;
Dolpini(out p);
foreach (int m in p)
Console.WriteLine(m);
}
static void Dolpini(out int[] numbers)
{
// Next 10 numbers
for (int k = 10; k < 20; k++)
p[k] = p[k-10] + p[k-9];
}

Categories

Resources