I'm working on an app that is a "poor man's matrix" ie. 1 and 0 fall down the screen.
So far I have managed to get the 2d array to display one row on 1st user input, 2 rows on 2nd user input, 3 rows on 3rd user input etc.
The problem is, that the 1st row always stays at the top and I can't get the "drop-down" effect. It always appends an additional row of 1 and 0 bellow the previous row/row on user input.
Example - how it works so far:
my 2d array:
1 0 1 0 1 1 1 (1st row)
0 1 0 1 0 1 0 (2nd row)
0 0 1 0 1 0 1 (3rd row)
1 0 0 1 0 1 0 (4th row)
1st user input (Console.ReadKey();):
1 0 1 0 1 1 1 (1st row)
2cnd user input (Console.ReadKey();):
1 0 1 0 1 1 1 (1st row)
0 1 0 1 0 1 0 (2nd row)
3rd user input:
1 0 1 0 1 1 1 (1st row)
0 1 0 1 0 1 0 (2nd row)
0 0 1 0 1 0 1 (3rd row)
etc.
What I would like to achive is something similar but in "reverse" order.
Example - what I would like to achive:
1st user input:
1 0 1 0 1 1 1 (1st row)
2cnd user input:
0 1 0 1 0 1 0 (2nd row)
1 0 1 0 1 1 1 (1st row)
3rd user input:
0 0 1 0 1 0 1 (3rd row)
0 1 0 1 0 1 0 (2nd row)
1 0 1 0 1 1 1 (1st row)
So, to summerise, I would like to modify my existing code, so that the 1st row is always added last. Or possible start reading from the end of the array - last row. I have tried this, but I constantly get outOfRange error...
Any help would be welcome.
The code that just adds additional rows below an existing one:
public static int row = 0;
static void PrintRelevantLines()
{
Console.Clear();
if (rowl <= pnms.GetLength(0) - 1)
{
for (int i = 0; i <= row; i++)
{
for (int j = 0; j <= pnms.GetLength(1) - 1; j++)
{
Console.Write(pnms[i, j]);
}
Console.WriteLine();
}
}
row += 1;
}
Edit: The anwser I requested was
for (int i = row; i >= 0; i--;)
which was provided by: Pranav Hosangadi
But I accepted the anwser from Caius Jard, as he went over and beyond what I asked for.
Thank you.
Here you go; this is a matrix effect:
int width = 60; //draw 60 columns
int height = 20; //draw 20 rows
var chars = "1234567890-=qwertyuiop[]asdfghjkl;'#zxcvbnm,./!\"£$%^&*()_+QWERTYUIOP{}ASDFGHJKL:#~ZXCVBNM<>?".ToCharArray(); //create an array of chars to randomly choose and pump onto screen
var r = new Random(); //make only one Random. Never make a Random in a loop
while (true) //forever
{
int randCol = r.Next(0, width); //pick which column we will draw now
for (int i = 0; i < height; i++) { //for every row from top to bottom
Console.SetCursorPosition(randCol, i); //put the cursor there
Console.Write(chars[r.Next(chars.Length)]); //pump a random char
Thread.Sleep(200); //it's a bit fast otherwise
}
}
I haven't out and out given the solution for your exercise, because it looks like a homework (and I don't do homework), but I hope you can step through this and look at how it's working, and make the adaptations that you need to your program to get the result you're after
Perhaps, for example, you can keep your lines in a 2D buffer, and you can decide on a column randomly (like I did), and you can render it down the screen row by row, by reading down the column (or up), writing to the screen, the same column as you selected from the buffer, then select another column
Perhaps you can periodically insert lines into the buffer (scrolling new data through it).
Perhaps also, yoou can write the char first in white, then later overwrite it in grey just before you write the new char in white (the effect is hard to see when the screen has filled up)
Then you can write multiple chars at different offsets at the same time..
..then you can give it to the peeps at codegolf.se.com and they'll write you a version in like, 15 chars of 05AB1E or something
Related
for (int row = 0; row < 5; row++)
{
// PRINTS CORRECT NUMBER OF SPACES
for (int space = 0; space < 5 - row - 1; space++)
{
Console.Write(" ");
}
// PRINTS CORRECT NUMBER OF STARS
for (int star = 0; star < row * 2 + 1; star++)
{
Console.Write("*");
}
// JUMPS ONTO NEXT LINE AFTER EVERY ITERATION OF THE FIRST LOOP
Console.WriteLine();
}
How do the conditions "5 - row - 1", and "row * 2 + 1" work in this code?
This is all about noticing patterns in a pyramid. The comment for the first for loop says that it is printing the correct number of spaces before the actual pyramid (i.e. the asterisks).
Let's look at how many spaces there are at each level:
* level 0 - 4 spaces
*** level 1 - 3 spaces
***** level 2 - 2 spaces
******* level 3 - 1 space
********* level 4 - 0 spaces
Notice how as the level number increases, the number of spaces decreases? They are inversely proportional. What would be a function that maps the level number n into the number of spaces? It would be
f(n) = 4 - n
Or more generally,
f(n) = k - n - 1
where k is the number of levels.
This is why we wrote 5 - row - 1. It maps row (i.e. n) into the number of spaces that should be printed!
The same goes for the second for loop, which figures out how many asterisks should be printed.
* level 0 - 1 asterisks
*** level 1 - 3 asterisks
***** level 2 - 5 asterisks
******* level 3 - 7 asterisk
********* level 4 - 9 asterisks
This time the pattern is even simpler. It is just an arithmetic sequence. The function that maps the level number into the number of asterisks is
f(n) = 2 * n + 1
This explains the 2 * row + 1 in the second for loop.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I would like to generate all the possible numbers that have length n and each digit of my number has a value from the set {1,2,...,n-1}, as an array. In other words, I would like to list all the base n numbers with length n that do not include 0.
Right now, the only way I can think to do it is by nesting n for loops, and assigning myArray[i] with the (i+1)th loop, i.e.
int n;
int[] myArray = new int[n];
for (int i1 = 1; i1 < n; i1++)
myArray[0]=i1;
for (int i2 = 1; i2 < n; i2++)
myArray[1]=i2;
// and so on....
for (int in = 1; in < n; in++)
{
myArray[n]=in;
foreach (var item in myArray)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
}
and then printing each array at the innermost loop. The obvious issue is that for each n, I need to manually write n for loops.
From what I've read, recursion seems to be the best way to replace nested for loops, but I can't seem figure out how to make a general method for recursion either.
EDIT
For example, if n=3, I would like to write out 1 1 1, 1 1 2, 1 2 1, 1 2 2, 2 1 1, 2 1 2, 2 2 1, 2 2 2.
We are not limited to n<11. For example, if n=11, we would output
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 2
1 1 1 1 1 1 1 1 1 1 3
...
1 1 1 1 1 1 1 1 1 1 10
1 1 1 1 1 1 1 1 1 2 1
1 1 1 1 1 1 1 1 1 2 2
1 1 1 1 1 1 1 1 1 2 3
...
1 1 1 1 1 1 1 1 1 9 10
1 1 1 1 1 1 1 1 1 10 1
1 1 1 1 1 1 1 1 1 10 2
1 1 1 1 1 1 1 1 1 10 3
...
10 10 10 10 10 10 10 10 10 9 10
10 10 10 10 10 10 10 10 10 10 1
10 10 10 10 10 10 10 10 10 10 2
...
10 10 10 10 10 10 10 10 10 10 10
So, a digit of a number may be any value between and including 1 and 10. The array myArray is simply used to get one of these numbers, then we print it, and go on to the next number and repeat.
As always, when thinking in recursive solutions, try to solve the problem using immutable structures; everything is much simpler to understand.
So first of all, lets build ourselves a fast little immutable stack that will help us keep track of the number we are currently generating (while not worrying about what other numbers are being generated in the recursive call...remember, immutable data can't change!):
public class ImmutableStack<T>: IEnumerable<T>
{
public static readonly ImmutableStack<T> Empty = new ImmutableStack<T>();
private readonly T first;
private readonly ImmutableStack<T> rest;
public int Count { get; }
private ImmutableStack()
{
Count = 0;
}
private ImmutableStack(T first, ImmutableStack<T> rest)
{
Debug.Assert(rest != null);
this.first = first;
this.rest = rest;
Count = rest.Count + 1;
}
public IEnumerator<T> GetEnumerator()
{
var current = this;
while (current != Empty)
{
yield return current.first;
current = current.rest;
}
}
public T Peek()
{
if (this == Empty)
throw new InvalidOperationException("Can not peek an empty stack.");
return first;
}
public ImmutableStack<T> Pop()
{
if (this == Empty)
throw new InvalidOperationException("Can not pop an empty stack.");
return rest;
}
public ImmutableStack<T> Push(T item) => new ImmutableStack<T>(item, this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
That's easy. Note how the stack reuses data. How many empty immutable structs will there be in our little program? Only one. And stacks containing the sequence 1->2->4? Yup, only one.
Now, we implement a recursive function that just keeps adding numbers to the stack until we reach our "bail out" condition. Which is? When the stack contains n elements. Easy peasy:
private static IEnumerable<int> generateNumbers(ImmutableStack<string> digits, IEnumerable<string> set, int length)
{
if (digits.Count == length)
{
yield return int.Parse(string.Concat(digits));
}
else
{
foreach (var digit in set)
{
var newDigits = digits.Push(digit);
foreach (var newNumber in generateNumbers(newDigits, set, length))
{
yield return newNumber;
}
}
}
}
Ok, and now we just need to tie it alltogether with our public method:
public static IEnumerable<int> GenerateNumbers(int length)
{
if (length < 1)
throw new ArgumentOutOfRangeException(nameof(length));
return generateNumbers(ImmutableStack<string>.Empty,
Enumerable.Range(1, length - 1).Select(d => d.ToString(CultureInfo.InvariantCulture)),
length);
}
And sure enough, if we call this thing:
var ns = GenerateNumbers(3);
Console.WriteLine(string.Join(Environment.NewLine,
ns.Select((n, index) => $"[{index + 1}]\t: {n}")));
We get the expected output:
[1] : 111
[2] : 211
[3] : 121
[4] : 221
[5] : 112
[6] : 212
[7] : 122
[8] : 222
Do note that the total amount of numbers generated of a specified length n is (n - 1) ^ n which means that for relatively small values of length you are going to get quite an amount of numbers generated; n = 10 generates 3 486 784 401...
like the title suggests my problem is that I have a query/Stored Procedure that selects a data from a view and its working just fine at the management studio, the problem is when I try to call this data from my application( using linq to entites) I get wrong data(wrong as in a single row is repeated 10 times when the query should return 5 different rows/records)
Here is my management studio Query :
select * from dbo.v_RouteCardDetails_SizeInfo
where Trans_TransactionHeader = 0
AND Direction = 0
AND RoutGroupID = 1
AND Degree = '1st'
Result Returned:
Size SizeQuantity Trans_TransactionHeader RoutGroupID Direction Degree
XS 10 0 1 0 1st
S 2 0 1 0 1st
M 0 0 1 0 1st
L 5 0 1 0 1st
XXL 2 0 1 0 1st
and here is my Linq Query:
(from x in context.v_RouteCardDetails_SizeInfo
where x.Trans_TransactionHeader == 0
&& x.Direction == 0
&& x.RoutGroupID == 1
&& x.Degree.ToLower() == "1st"
select x).ToList<_Model.v_RouteCardDetails_SizeInfo>();
And the result returned is :
Size SizeQuantity Trans_TransactionHeader RoutGroupID Direction Degree
XS 10 0 1 0 1st
XS 10 0 1 0 1st
XS 10 0 1 0 1st
XS 10 0 1 0 1st
XS 10 0 1 0 1st
XS 10 0 1 0 1st
XS 10 0 1 0 1st
XS 10 0 1 0 1st
XS 10 0 1 0 1st
XS 10 0 1 0 1st
for 2 days I've been trying to fix this, will appreciate your help
Thanks
Undoubtedly the fields that Entity Framework has guessed as primary key of the view are not unique in the view. Try to add fields to the PK in the edmx designer (or code-first mapping) until you've really got a unique combination.
EF just materializes identical rows for each identical key value it finds in the result set from the SQL query.
Because it is not possible to have sme enviroment as your I suggest you do following things:
Check in debbuger what exactly is in list. The printed result suggest that you somehow display data returned form database and in this code could be an error.
Preview LINQ query. You can use LinqPad for this.
I've been looking into combinations lately, I've tried various 3rd party solutions, and tried to get my head around it myself. Without success I might add.
I need to generate a 13 length string with all possible combinations of say.. int 0-2, I.E
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 0 0 0 1 0
...
2 2 2 2 2 2 2 2 2 2 2 2 2
You probably get the drill, I'm aware I could just wrap this up in loops if I wanted a dirty solution. Any guidance or pointers are appreciated.
I'd be happy to write the code for you, but it seems like you are looking for intuition into the problem. So maybe this feels more like a "teach a man to fish" moment.
So let me ask you a few questions:
Let's generalize the problem to strings of length N. What does the N=1 case look like? It's
0
1
2
And what does the N=2 case look like? It's
00
01
02
10
11
12
20
21
22
I wonder if you can see how, given the N=1 case, we can easily derive (aka generate) the N=2 case in a very mechanical fashion. Now if you see the pattern for this specific case, can you say what the pattern is for the general case? i.e. If you happened to already have in your hand the answer for strings of length N, and I asked you to provide me with the answer for strings of length N+1 could you do so? If so you have the very definition of a recursive algorithm.
PS I think I'd call these combinations rather than permutations.
I can't help thinking of this as just adding number in a N-based numeric system (in your example a 3-base system).
I would write one method (if not already there in the framework or a library) that would allow you to switch bases. I.E:
String transformNumberFrom10BaseToXBase(int number, int base)
then just write a for loop (sorry, pseudo-c-like-code :) ):
for (int i = 0; i < base ^ 13; i++) {
print transformNumberFrom10BaseToXBase(i, base)
}
Ok, hope that helps or give you an idea on how to solve it :)
I've written quickly function that returns list of permutations, so if you have not time to write your own method, you can use it. length is permutation length, max is maximum number (in your case, it would be 2)
static List<int[]> getPermutationList(int length, int max)
{
List<int[]> perm_list = new List<int[]>();
int[] perm = new int[length];
for (int i = 0; i < length; ++i)
perm[i] = 0;
while(true)
{
for (int i = length - 1; ; --i)
{
if (i == -1)
return perm_list;
if (perm[i] < max)
{
perm[i]++;
for (int j = i + 1; j < length; ++j)
perm[j] = 0;
break;
}
}
int[] perm_copy = new int[length];
for (int i = 0; i < length; ++i)
{
perm_copy[i] = perm[i];
}
perm_list.Add(perm_copy);
}
return perm_list;
}
I need to print data from a DataGridView on both sides of a preprinted form but:
Each side has different arrangement for that info.
Each side can only hold info from tree rows, so:
1st, 2nd and 3rd row go on side 1;
4th, 5th and 6th row go on side 2;
7th, 8th and 9th row go on side 1;
10th, 11th and 12th go on side 2; and so on.
I will select which group to print.
I’m planning to do it this way:
((row.Index) +1) / 3,
round it up, with no decimals, to get an integer, (like in the above excel
image),
MOD that integer by 2, (like in the above excel image).
If the result of that MOD by 2 is 1, then it will print Side 1 arrangement,
if the result of that MOD by 2 is 0, then it will print Side 2 arrangement.
How do I do it in C#? I'm using VS2010 Express Edition. Also, I
wanted to use System.Math.Ceiling but I get a Namespace, decimal,
double-precision and floating-point number warnings or errors.
I don't see that you need to use anything like that:
int zeroBasedRow = row - 1;
int side = ((zeroBasedRow / 3) % 2) + 1;
Test code:
using System;
class Test
{
static void Main(string[] args)
{
for (int row = 1; row <= 12; row++)
{
int zeroBasedRow = row - 1;
int side = ((zeroBasedRow / 3) % 2) + 1;
Console.WriteLine("Row {0} goes on side {1}", row, side);
}
}
}
Output:
Row 1 goes on side 1
Row 2 goes on side 1
Row 3 goes on side 1
Row 4 goes on side 2
Row 5 goes on side 2
Row 6 goes on side 2
Row 7 goes on side 1
Row 8 goes on side 1
Row 9 goes on side 1
Row 10 goes on side 2
Row 11 goes on side 2
Row 12 goes on side 2