Print ASCII of a triangle shape with variable input - c#

Struggling with the print. I know it should be two for loops to print out the repeated letters, however, having problems to indent the lines. it should be a simple console C# program to print out the shape like below with a input 3.
XXXXX
XXX
X
With input 4 it should be like
XXXXXXX
XXXXX
XXX
X
Here is my code. Two for loops get the letters correctly but the lines all lined up at the left, not center.
static void Main(string[] args)
{
string num = Console.ReadLine().Trim();
int n = Convert.ToInt32(num);
int k=1;
for(int i = n; i>=1; i--)
{
Console.WriteLine("\n");
Console.WriteLine("".PadLeft(n));
for (int j = (2*i-1); j>=1;j--)
{
Console.Write("0");
}
}
Console.Read();
}

The statement:
Console.WriteLine("".PadLeft(n));
is the right idea but it's not quite there.
In your case, n is the number of lines you wish to print and is invariant. The number of spaces you need at the start of each line should begin at zero and increase by one for each line.
In any case, printing any number of spaces followed by newline (because it's WriteLine) is not what you want, you should be using Write instead.
So the code between int n = Convert.ToInt32(num); and Console.Read(); would be better off as something like:
for (int lineNum = 0; lineNum < n; lineNum++) {
int spaceCount = lineNum;
int xCount = (n - lineNum) * 2 - 1;
Console.Write("".PadLeft(spaceCount));
Console.WriteLine("".PadLeft(xCount, 'X'));
}
You'll notice some other changes there. First, I've used more meaningful variable names, something I'm a bit of a stickler for - using i is okay in certain circumstances but I often find it's more readable to use descriptive names.
I've also used PadLeft to do the X string as well, so as to remove the need for an inner loop.

Related

Is there such a thing as an array without size?

I am playing with C#. I try to write program that frames the quote entered by a user in a square of chars. So, the problem is... a user needs to indicate the number of lines before entering a quote. I want to remove this moment, so the user just enters lines of their phrase (each line is a new element in the string array, so I guess a program should kinda declare it by itself?..). I hope I explained clear what I meant x).
I've attached the program code below. I know that it is not perfect (for example, when entering the number of lines, I use the conversion to an integer, and if a user enters a letter, then this may confuse my electronic friend, this is a temporary solution, since I do not want to ask this x) The program itself must count these lines! x)) Though, I don't understand why the symbols on the left side are displayed incorrectly when the program displays output, but I think this also does not matter yet).
//Greet a user, asking for the number of lines.
Console.WriteLine("Greetings! I can put any phrase into beautiful #-square."
+ "\n" + "Wanna try? How many lines in the quote: ");
int numberOfLines = Convert.ToInt32(Console.ReadLine());
//Asking for each line.
string[] lines = new string[numberOfLines];
for (int i = 0; i < numberOfLines; i++)
{
Console.WriteLine("Enter the line: ");
lines[i] = Console.ReadLine();
}
//Looking for the biggest line
int length = 0;
for (int i = 0; i < numberOfLines; i++)
{
if (length < lines[i].Length) length = lines[i].Length;
}
//Starting framing
char doggy = '#';
char space = ' ';
length += 4;
string frame = new String(doggy, length);
Console.WriteLine(frame);
for (int i = 0; i < numberOfLines; i++)
{
string result = new string(space, length - 3 - lines[i].Length);
Console.WriteLine(doggy + space + lines[i] + result + doggy);
}
Console.WriteLine(frame);
Console.ReadLine();
}
}
}
There is performance gap and functionality between "Generic Lists" and arrays, you can read more about cons and pros of this two objects in the internet,
for example you can use list as Dai mentioned in comment like this
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
or you can use arraylist
ArrayList arraylist = new ArrayList();
arraylist.Add();
or even you can change the size of array any times but it erase data in it
int[] arr = new int[100];
there is a function called ToArray() you can use it to change generic list to array
Your problem of the left side output is, that you add two values of char. This is not what you expect to be. You must convert the char to a string to append it to other strings:
Console.WriteLine(doggy.ToString() + space.ToString() + lines[i] + result + doggy.ToString());

PadRight in string of arrays doesn't add chars

I created array of strings which includes strings with Length from 4 to 6. I am trying to PadRight 0's to get length for every element in array to 6.
string[] array1 =
{
"aabc", "aabaaa", "Abac", "abba", "acaaaa"
};
for (var i = 0; i <= array1.Length-1; i++)
{
if (array1[i].Length < 6)
{
for (var j = array1[i].Length; j <= 6; j++)
{
array1[i] = array1[i].PadRight(6 - array1[i].Length, '0');
}
}
Console.WriteLine(array1[i]);
}
Right now the program writes down the exact same strings I have in array without adding 0's at the end. I made a little research and found some informations about that strings are immutable, but still there are some example with changing strings inside, but I couldn't find any with PadRight or PadLeft and I fell like there must be a way to do it, but I just can't figure it out.
Any ideas on how to fix that issue?
The first argument to PadRight is the total length you want. You've specified 6 - array1[i].Length - and as all your strings start off with at least 3 characters, you're padding to at most 3 characters, so it's not doing anything.
You don't need your inner loop, and your outer loop condition is more conventionally written as <. This is one way I'd write that code:
using System;
public class Test
{
static void Main()
{
string[] array =
{
"aabc", "aabaaa", "Abac", "abba", "acaaaa"
};
for (var i = 0; i < array.Length; i++)
{
array[i] = array[i].PadRight(6, '0');
Console.WriteLine(array[i]);
}
}
}
In fact I'd probably use foreach, or even Select, but that's a different matter. I've left this using an array to be a bit closer to your original code.

Dynamic Array Depth/Width Code

I apologize if this question is too vague because I haven't actually built out any code yet, but my question is about how to code (perhaps in C# in a Unity3d script, but really just generically) the dynamically changing unit depth/width in total war games.
In TW games, you can click and drag to change a unit from an nx2 formation to 2xn formation and anything in between. Here's a video (watch from 15 seconds in to 30 seconds in):
https://www.youtube.com/watch?v=3aGRzy_PzJQ
I'm curious, generically speaking, about the code that would permit someone to on the fly exchange the elements of an array like that. I'm assuming here that the units in the formation are elements in an array
so, you might start with an array like this:
int[,] array = new int[2, 20];
and end up with an array like this:
int[,] array = int[20, 2];
but in between you create the closest approximations, with the last row in some cases being unfilled, and then the elements of that last row would have to center visually until the column width was such that the number of elements in all the rows are equal again.
It kind of reminds me of that common intro to programming problem that requires you to write to the console a pyramid made of *'s all stacked up and adding one element per row with spaces in between, but a lot more complicated.
Most of the lower-tech formation tactics games out there, like Scourge of War just let you choose either Line Formation (2 rows deep) or column formation (2 columns wide), without any in between options, which was perhaps an intentional design choice, but it makes unit movement so awkward that I had to assume they did it out of technical limitations, so maybe this is a hard problem.
I wrote some code to clarify the question a bit. The method form() takes parameters for the number of units in the formation and the width of the formation, without using an array, and just prints out the formation to the console with any extra men put in the last row and centered:
x = number of men
y = width formation
r = number of rows, or depth (calculated from x and y)
L = leftover men in last row if y does not divide evenly into x
Space = number spaces used to center last row
form() = method called from the class Formation
I figured it should take the depth and number of men because the number of men is set (until some die but that's not being simulated here) and the player would normally spread out the men to the desired width, and so the number of rows, and number of men in those rows, including the last row, and the centering of that last row, should be taken care of by the program. At least that's one way to do that.
namespace ConsoleApplication6
{
class Formation
{
public int x;
public int y;
public Formation(int x, int y)
{
this.x = x;
this.y = y;
}
public void form()
{
int r = x / y;
int Left = x % y;
int Space = (y - Left)/2;
for (int i = 0; i < r;i++)
{
for (int j = 0; j < y; j++)
{
Console.Write("A");
}
Console.WriteLine();
if (i == r - 1)
{
for (int m = 0; m < Space; m++)
{
Console.Write(" ");
}
for (int k = 0; k < Left; k++)
{
Console.Write("A");
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter the number of men: ");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the formation width: ");
int b = Convert.ToInt32(Console.ReadLine());
Formation testudo = new Formation(a,b);
testudo.form();
Console.ReadKey();
}
}
}
So, I think what I'm trying to do to improve this is have the above code run repeatedly in real time as the user inputs a different desired width (y changes) and men die (x changes)
But, if it were actually to be implemented in a game I think it would have to be an array, so I guess the array could take the x parameter as its max index number and then i would do a kind of for loop like for(x in array) or whatever print x instead of just console logging the letter A over and over

Use Substring method to count specific character from a string

So I am new to programming and one of my exercises involves using a substring within a loop to count the number of iterations of a specific character with a user's input.
As far as I can tell for the exercise, and what I know in C sharp so far, using a substring in this will only help read the position of a character within the input, and will not count it. I can not make heads or tails of this, and am at a loss.
I want to know how to understand this, and what ways I am missing the point of the exercise.
I need an idea of how to set the substring to read the number of a certain character type from the end-user's input from console.
This is the original question:
There is a method called Substring that we can use with a string to look at a portion of a string.
For example, the following code will print the letter a.
string input = "abcdef";
Console.WriteLine(input.Substring(0, 1));
Assignment:
Given the following input, create a loop that uses the Substring method to count the number of times the letter ā€˜zā€™ occurs in a string input by the user.
asdfojiaqweb;ounqwrb;ounwqen;zzzn bnaozonza
Edit: So Far I have the code to count the number of times that Z is used, but I don't know how to incorporate a substring into it
int total = 0;
var letter = new HashSet<char> { 'z' };
Console.WriteLine("Please enter your letters:");
// asdfojiaqweb;ounqwrb;ounwqen;zzzn bnaozonza
string sentence = Console.ReadLine().ToLower();
for (int i = 0; i < sentence.Length; i++)
{
if (letter.Contains(sentence[i]))
{
total++;
}
}
Console.WriteLine("Total number of Z uses is: {0}", total);
// Console.WriteLine(sentence.Substring(0, 1));
If you must use Substring, then replace your loop by this
for (int i = 0; i < sentence.Length; i++)
{
if (sentence.Substring(i, 1) == "z")
{
total++;
}
}
And if you need to both count uppercase and lowercase z, then use following code
for (int i = 0; i < sentence.Length; i++)
{
if (string.Equals(sentence.Substring(i, 1), "z", StringComparison.OrdinalIgnoreCase))
{
total++;
}
}

whats wrong in this logic of finding longest common child of string

i came up with this logic to find longest common child of two strings of equal length but it runs successfuly only on simple outputs and fails others,pls guide me what i am doing wrong here.
String a, b;
int sum = 0;
int[] ar,br;
ar = new int[26];
br = new int[26];
a = Console.ReadLine();
b = Console.ReadLine();
for (int i = 0; i < a.Length; i++)
{
ar[(a[i] - 65)]++;
br[(b[i] - 65)]++;
}
for(int i =0;i<ar.Length;i++)
{
if (ar[i] <= br[i]) { sum += ar[i]; }
else sum += br[i];
}
Console.Write(sum);
Console.ReadLine();
output:
AA
BB
0 correct.
HARRRY
SALLY
2 correct
for both above input it runs but when i submit for evaluation it fails on their test cases.i cant access their testacase on which my logic fails.i wanna know where does my logic fails.
Your second loop is all wrong. It is simply finding the count of characters that occur in both the array and the count is only updated with the the no. of the common characters contained in the string containing the least no. of these common characters.
refer this link for the correct implementation.
http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Retrieve_the_Longest_Substring
Also convert your input to uppercase characters using String.ToUpper before you use the input string.

Categories