c# - write a single row from a 2d array every second - c#

I'm working on a C# console app. The "app" is a poor mans matrix (ie. 1 and 0 fall down the screen).
I've managed to make two 2d arrays, one for int and one for string. The int array is filled by RNG, and those numbers are then converted into the string array.
What I would like to achive, is to print each row from the string array every second (ElapsedEventArgs).
What I'm thinking (but isn't working) is something like this...
static void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (_countDown-- <= 0)
{
Console.BackgroundColor = ConsoleColor.White;
Console.Clear();
aTimer.Enabled = false;
}
else
{
PrintSingleLine();
}
}
static void PrintSingleLine() // this should write a single line every second
{
for (int i = 0; i <=pnms.GetLength(0) - 1; i++)
{
foreach(string str in pnms)
{
Console.Write(str);
}
}
}
//if it helps, this is how you write the whole array
static void PrintArray()
{
for (int i = 0; i <= pnms.GetLength(0) - 1; i++)
{
for (int j = 0; j <= pnms.GetLength(1) - 1; j++)
{
Console.Write(nms[i, j]);
}
}
}
If I can provide any additional information, please let me know.
Thank you.
Edit 1:
So, since nothing was showing on the console, I decided to do it manually (one line per Console.ReadLine();. I figured out that i forgot to initalize the arrays (duh), and this is the code that prints the current line. It overwrites the previous one, but hey, it's something...
public static int col = 0;
static void PrintSingleLine()
{
for (int i = col; i <= pnms.GetLength(0) - 1;)
{
for (int j = 0; j <= pnms.GetLength(1) - 1; j++)
{
Console.Write(pnms[col, j]);
}
break;
}
col =+ 1;
}

Thanks to:
https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.elapsed?view=netcore-3.1
https://www.c-sharpcorner.com/article/generating-random-number-and-string-in-C-Sharp/
Not sure if this is what you're looking for, had some time to spare. This is the result. Good luck!
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Timers;
namespace PoorMatrix
{
class Program
{
private static Timer aTimer;
static void Main(string[] args)
{
aTimer = new System.Timers.Timer();
aTimer.Interval = 1000;
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
// Have the timer fire repeated events (true is the default)
aTimer.AutoReset = true;
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Green;
Console.Clear();
// Start the timer
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program at any time... ");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
GenerateRandomChars(100).ForEach(i => Console.Write("{0}\t", i));
}
private static List<string> GenerateRandomChars(int paramCharAmount)
{
List<string> tempChars = new List<string>();
for (int i = 0; i < paramCharAmount; i++)
{
int LetterNumberOrEmpty = RandomNumber(0, 100);
switch (LetterNumberOrEmpty)
{
case int n when n < 41:
tempChars.Add(RandomNumber(0, 1).ToString());
break;
case int n when n < 81:
tempChars.Add(RandomLetter(RandomBool()));
break;
case int n when n < 101:
tempChars.Add(" ");
break;
default:
break;
}
}
return tempChars;
}
private static bool RandomBool()
{
return new Random().NextDouble() >= 0.5;
}
public static int RandomNumber(int paramMin, int paramMax)
{
return new Random().Next(paramMin, paramMax);
}
public static string RandomLetter(bool paramIsLowerCase = false)
{
// Unicode/ASCII Letters are divided into two blocks
// (Letters 65–90 / 97–122):
// The first group containing the uppercase letters and
// the second group containing the lowercase.
// char is a single Unicode character
char offset = paramIsLowerCase ? 'a' : 'A';
const int lettersOffset = 26; // A...Z or a..z: length=26
var #char = (char)new Random().Next(offset, offset + lettersOffset);
return paramIsLowerCase ? #char.ToString().ToLower() : #char.ToString();
}
}
}

Related

Returning Fibonacci series c#

I need to make a method that returns the nth integer in the fibonacci series, the code that I wrote (edited) did not work, could anyone guide me in my for loop section. I need to use a webform and return the fibonacci series to a specific point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
{
public partial class Default : System.Web.UI.Page
{
int i, temp;
public void Page_Load(object sender, EventArgs e)
{
}
public int Fibonacci(int x)
{
if (x == 0)
{
return 1;
}
if (x == 1)
{
return 1;
}
else
{
return (Fibonacci(x - 2) + Fibonacci(x - 1));
}
}
public void btSubmit_Click(object sender, EventArgs e)
{
// getting input from user
int num = Convert.ToInt32(txtInput.Text);
// logic for fibonacci series
for (i = 0; i < num; i++)
{
lblResult.Text = Fibonacci(i).ToString();
}
}
}
}
First of all, we, usually, assume
F(0) = 0,
F(1) = 1,
...
F(N) = F(N - 1) + F(N - 2)
See https://oeis.org/A000045
If you want a serie, let's implement a serie (with a help of IEnumerable<T> and yield return):
using System.Linq;
...
//TODO: do you really want int as a return type? BigInteger seems to be a better choice
public static IEnumerable<int> Fibonacci() {
int n_2 = 1; // your rules; or start Fibonacci from 1st, not 0th item
int n_1 = 1;
yield return n_2;
yield return n_1;
while (true) {
int n = n_2 + n_1;
yield return n;
n_2 = n_1;
n_1 = n;
}
}
Having a generator we can easily take num first Fiboncacci numbers (Linq Take):
lblResult.Text = string.Join(", ", Fibonacci().Take(num));
In case num == 7 we'll get
1, 1, 2, 3, 5, 8, 13
If you want an individual item - ElementAt (index is zero based):
// 8
lblResult.Text = Fibonacci().ElementAt(5).ToString();
You can use an integer array to keep the Fibonacci numbers until n and returning the nth Fibonacci number:
public int GetNthFibonacci_Ite(int n)
{
int number = n - 1; //Need to decrement by 1 since we are starting from 0
int[] Fib = new int[number + 1];
Fib[0]= 0;
Fib[1]= 1;
for (int i = 2; i <= number;i++)
{
Fib[i] = Fib[i - 2] + Fib[i - 1];
}
return Fib[number];
}
and then you can call it like this:
GetNthFibonacci_Ite(7);
and it retuns 7th fibonacci number
Your mistake is that you overwrite the Text, rather then add to it. Change it to lblResult.Text += Fibonacci(i).ToString() to append.
Do however note that appending a lot of text from a Loop to a GUI Element is a problematic opreation. You incur a massive overhead reading and writing GUI Elemetns. It does not mater if you only do it once per user Triggered event, but from a loop you will notice it quickly.
It might be better to build the sequence in the code behind, then dispaly it in one go. I even wrote a example code to showcase that issues:
using System;
using System.Windows.Forms;
namespace UIWriteOverhead
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] getNumbers(int upperLimit)
{
int[] ReturnValue = new int[upperLimit];
for (int i = 0; i < ReturnValue.Length; i++)
ReturnValue[i] = i;
return ReturnValue;
}
void printWithBuffer(int[] Values)
{
textBox1.Text = "";
string buffer = "";
foreach (int Number in Values)
buffer += Number.ToString() + Environment.NewLine;
textBox1.Text = buffer;
}
void printDirectly(int[] Values){
textBox1.Text = "";
foreach (int Number in Values)
textBox1.Text += Number.ToString() + Environment.NewLine;
}
private void btnPrintBuffer_Click(object sender, EventArgs e)
{
MessageBox.Show("Generating Numbers");
int[] temp = getNumbers(10000);
MessageBox.Show("Printing with buffer");
printWithBuffer(temp);
MessageBox.Show("Printing done");
}
private void btnPrintDirect_Click(object sender, EventArgs e)
{
MessageBox.Show("Generating Numbers");
int[] temp = getNumbers(1000);
MessageBox.Show("Printing directly");
printDirectly(temp);
MessageBox.Show("Printing done");
}
}
}
As another commenter mentioned, you may want to go to some form of Multitasking too. Indeed my first Multitasking learnign experience was a Fibbonacci/Prime Number checker. They are good learning examples for that.
Use the method for Fibonacci:
public int Fibonacci(int n)
{
int a = 0;
int b = 1;
for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return a;
}
And replace:
lblResult.Text = Fibonacci(i).ToString();
To:
lblResult.Text += Fibonacci(i).ToString();

I can't understand why my bubble sort is not showing any time taken for the second array

My code so far is this:
class Program
{
static void Main(string[] args)
{
Random r = new Random();
int n = r.Next(1, 10000);
int[] FortyKSet;
FortyKSet = new int[400];
for (int ndex = 0; ndex < FortyKSet.Length; ndex++)
{
FortyKSet[ndex] = r.Next(1, 80000);
}
int[] TenKSet;
TenKSet = new int[100];//populates the array with 100 integers
for (int index = 0; index < TenKSet.Length; index++)
{
TenKSet[index] = r.Next(1, 20000);//makes the 10,000 integers random
}
bubbleSort(TenKSet);
foreach (int i in TenKSet)
{
Console.Write(i + "," );
}
bubbleSort(FortyKSet);
foreach (int z in FortyKSet)
{
Console.Write(z + ",");
}
for (int space = 0; space < 2; space++)
{
Console.WriteLine("");
}
}
public static void swap(int[] array, int first, int second)
{
int temp = array[first];
array[first] = array[second];
array[second] = temp;
}
public static void bubbleSort(int[] array)
{
int start = 0;
bool swapMade = true;
while (start < array.Length - 1 && swapMade == true)
{
swapMade = false;
start++;
for (int first = 0; first < array.Length - start; first ++)
{
if(array[first] > array[first+1])
{
swap(array, first, first + 1);
swapMade = true;
}
}
}
DateTime begin = DateTime.Now;
TimeSpan time;
time = DateTime.Now.Subtract(begin);
Console.WriteLine("Time for bubblesort to complete: " + time.ToString(#"mm\:ss\.ffffff"));
}
}
When I run the program, it gives me the two sorted arrays (as it should.) Above the TenKSet array, I get the time it took to complete the sorting (ditto.) But when I run the FortyKSet, it shows a time of 0. Why is this? Shouldn't it take show twice the time it took to complete TenKSet (I believe the big-O notation here is O(sqrt(n)) but I could be wrong.)
Check exactly what statements you are measuring. That's the statements between your two measurements using DateTime.Now.
PS. Where you say "I could be wrong", you are wrong.
If you want to measure bubbleSort duration you should wrap the entire method:
public static void bubbleSort(int[] array)
{
// start measuring
DateTime begin = DateTime.Now;
int start = 0;
bool swapMade = true;
while (start < array.Length - 1 && swapMade == true)
{
...
}
// stop measuring
TimeSpan time = DateTime.Now.Subtract(begin);
Console.WriteLine(
"Time for bubblesort to complete: " + time.ToString(#"mm\:ss\.ffffff"));
}

Trying to create a histogram by using a string to print out the same amount of times equal to the value of an integer user input

Im completely new to coding and I've been given a challenge to create a histogram by asking a user to input a certain amount of numbers line by line. Which I have executed a for loop to handle with no issues. The difficulty I'm having is I'm trying to use a string which I've called (x) and contains (""). The challenge is to make the () symbol duplicate to the amount of the value entered by the user... Just wondering how I could code it in such a way so that it compares the user input value number to print the (*) the same amount equal to the number being entered!
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] userVal = new int[8];
string x = ("*");
for (int count = 0; count < userVal.Length; count++)
{
if (userVal[count] <= 10)
{
Console.WriteLine("Please enter Number");
userVal[count] = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("ERROR, Number too BIG!");
}
}
for (int count= 0; count < userVal.Length; count ++)
{
}
A simple way might be to iterate through the responses, and use the string(char,cnt) constructor https://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx.
It fills the string with a specific char, and specific length.
e.g.
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int numberToCollect = 10;
int[] answers = new int[numberToCollect];
int numberCollected = 0;
while(numberCollected<numberToCollect)
{
int parsedInt = 0;
if (int.TryParse(intConsole.ReadLine(),out parsedInt))
{
answers[numberCollected++] = parsedInt;
}
else
{
Console.WriteLine("Invalid number, try again!");
}
}
for(var cnt in answers)
{
Console.WriteLine(new String('*',cnt));
}
}
}
}
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] userVal = new int[8];
for (int count = 0; count < userVal.Length; count++)
{
if (userVal[count] <= 10)
{
Console.WriteLine("Please enter Number");
userVal[count] = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("ERROR, Number too BIG!");
}
}
foreach (var cnt in userVal)
{
Console.WriteLine(new String('*', cnt));
}
Console.ReadKey();
}
}
}

Starpattern in console app

I need to create the following pattern:
It is homework, this question I failed the first time.
I read now that I should have only used "*" one time, but how would this even work in that case?
Would appreciate if anyone could give me some insight in how to think.
My code is down below:
using System;
class StarPattern
{
public static void Main()
{
for (int i = 0; i < 5; i++)
{
Console.Write("*");
}
for (int a = 0; a <= 0; a++)
{
Console.WriteLine("");
Console.Write("*");
}
for (int c = 0; c <= 0; c++)
{
Console.WriteLine(" *");
}
for (int d = 0; d <= 1; d++ )
{
Console.Write("*");
Console.WriteLine(" *");
}
for (int e = 0; e < 5; e++ )
{
Console.Write("*");
}
Console.ReadLine();
}
}
You can simplify your code by nesting loops so outer (i) = rows and inner (j) = columns. From looking at your sample, you want to write out if you're on the boundary of either so you can add a condition to just write out on min and max.
private static void Main(string[] args)
{
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
if (i == 0 || i == 4 || j == 0 || j == 4)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
Console.ReadKey();
}
I'd probably replace 0 with a constant called MIN and 4 with a constant called MAX to save duplicating them. That way, you could increase the size of the square by just changing the constants.
Hardly anyone is commenting their code for you. How disappointing!
The trick here is to focus on what is important and define values that you will;
be using many times in the code
only want to change once if requirements need tweeking
These values are height and width - the core components of a rectangle.
The golden rule for the pattern is: If the row and column of each character is on the edge of the square, print a *
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stars
{
class Program
{
static int Width = 5; //define the width of the square in characters
static int Height = 5; //define the height of the square in characters
static void Main(string[] args)
{
for (int row = 0; row <= Height; row++) //Each iteration here is one row.
{
//loop representing columns. This is NESTED within the rows so
//that each row prints more than one column
for (int column = 0; column <= Width; column++)
{
if (IsCentreOfSquare(row, column)) //calculate if the current row and column coordinates are the interior of the square
{
Console.Write(" ");
}
else
{
Console.Write("*");
}
}
Console.WriteLine(); //this row is over. move to the next row
}
Console.ReadLine(); //pause so that the user can admire the pretty picture.
}
/// <summary>
/// Calculates if the row and column indexes specified are in the interior of the square pattern
/// </summary>
/// <returns></returns>
private static bool IsCentreOfSquare(int row, int col)
{
if (row > 0 && row < Height)
{
if (col > 0 && col < Width)
{
return true;
}
}
return false;
}
}
}
This might be overkill for such a simple program, but make it scalable and add some const ints to make the design able to be modified whenever you'd like!
Good question. It's fun to feel like I'm tutoring again! Glad to see you at least gave it an honest attempt :)
class Program
{
// Use string if you are okay with breaking the current pattern.
// private static string myDesign = "*";
// Use char if you want to ensure the integrity of your pattern.
private static char myDesign = '*';
private const int COLUMN_COUNT = 5;
private const int ROW_COUNT = 5;
private const int FIRST_ROW = 0;
private const int LAST_ROW = 4;
private const int FIRST_COLUMN = 0;
private const int LAST_COLUMN = 4;
static void Main(string[] args)
{
// Iterate through the desired amount of rows.
for (int row = 0; row < ROW_COUNT; row++)
{
// Iterate through the desired amount of columns.
for (int column = 0; column < COLUMN_COUNT; column++)
{
// If it is your first or last column or row, then write your character.
if (column == FIRST_COLUMN || column == LAST_COLUMN || row == FIRST_ROW || row == LAST_ROW)
{
Console.Write(myDesign);
}
// If anywhere in between provide your blank character.
else
{
Console.Write(" ");
}
}
Console.WriteLine("");
}
Console.Read();
}
}
It is not that difficult to do. You need to create two loops: one for the rows and one for the columns and then determine whether to print a star or not. Only the first and the last rows and columns have a star.
In my example I use two counters that start from 0 and count to 4. If the remainder of either counter value divided by 4 equals to 0 then I print a star, otherwise a space.
using System;
namespace Stars
{
internal static class StarPattern
{
private static void Main()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write((i%4 == 0) | (j%4 == 0) ? '*' : ' ');
}
Console.WriteLine();
}
}
}
}
You need to print a certain number of lines with a certain sequence of characters per line.
One approach would be to create or find a method that prints whatever character sequence you need. Then create a method to sequence calls to to that. Finally, print the result of all that.
private void PrintBox(char c, int width, int height)
{
var result = new List<string>();
result.Add(new string(c, width)); // First line
for (var i = 0; i < height - 2; i++)
{
string iLine;
int spaceCount = width - 2;
iLine = new string(c, 1) + new string(' ', spaceCount) + new string(c, 1);
result.Add(iLine);
}
result.Add(new string(c, width)); // Last line
// FYI, there's a StringBuilder class that makes all this easier
foreach (var line in result)
{
Console.WriteLine(line);
}
}
The important OOP concept here is that we made use of a single reusable method for constructing a sequence of characters - new string(char, int). If we wanted to create a Circle, we could create a BuildCircle method based on the same principle.

Queue that stores User's entered Array and displays it

So i have a simple program that i have set up to ask the user for an array size then it gets them to enter the elements then prints them, i would like to set up a Queue so it prints a whole of the array, for example.
History
1 2 3 4 //Length of the Array
3 4 5 6 //User Guess for this round
After this every time the user re enters the array that array would show up in the history also.
History
1 2 3 4 //Length of the Array
3 4 5 6 //User Guess for this round
2 6 7 8 //User second input
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Random_test
{
class Program
{
public int n;
public int[] UserArray;
public int i;
public int reEnter;
public int rear = -1;
public int front = -1;
public int[] history;
public void main()
{
Console.WriteLine("Please enter the Length of Your array");
n = Convert.ToInt32(Console.ReadLine());
UserArray = new int[n];
history = new int[n];
do
{
for (i = 0; i < n; i++)
{
Console.WriteLine("Your Elements");
UserArray[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < n; i++)
{
Console.WriteLine("Your Array: {0} ", UserArray[i]);
}
Console.WriteLine("Would you like to re-enter your array");
reEnter = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < 1; i++)//loop for history
{
insert();
delete();
showHistory();
}
} while (reEnter == 1);
}
public void insert()
{
if (rear == -1)
{
front = 0;
rear++;
history[rear] = UserArray[i];
}
else
{
rear++;
history[rear] = UserArray[i];
}
}
public void delete()
{
if (front == -1)
{
Console.WriteLine("There is no history availible");
}
else
{
front++;
}
}
public void showHistory()
{
if (rear == -1)
{
Console.WriteLine("There is no history availible");
}
else
{
Console.WriteLine("History");
for (int i = 0; i < n; i++)
{
Console.Write(" {0} ");
Console.Write(" - ");
Console.WriteLine(" {0} ", history[i]);
}
}
}
static void Main(string[] args)
{
Program main = new Program();
main.main();
Console.WriteLine("Game Over");
Console.ReadKey();
}
}
}
This was just a quick jot up program as you can see i have attempted to do the Queue, it works but prints only the first element of the User Array each turn. Unfortunately this is where i do not know how implement what i talked about at the start of the post. I would like to stick to this method of creating the Queues, i do not want to use the queue class, the idea is to keep it clean and simple.
Many Thanks.
Sorry for my evil comments before. I think this might suite your level... happy coding.
public class Program
{
static void Main(string[] args)
{
(new Program()).Ask();
}
private void Ask()
{
string history = "";
while (true)
{
Console.Write("Len > ");
int len = int.Parse(Console.ReadLine());
int[] arr = new int[len];
for (int i = 0; i < len; i++)
{
Console.Write("El{0} > ", i);
arr[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine();
string str = string.Join(",", arr);
Console.WriteLine("Arr > {0}", str);
Console.WriteLine("His > {0}", history);
history += string.Format("[{0}] ", str);
Console.WriteLine("Again?");
if (Console.ReadLine().Length == 0)
break;
Console.WriteLine();
}
}
}

Categories

Resources