Text bombardment - c#

this is the program I'm trying to write:
Write a program that reads a text and line width from the console. The program should distribute the text so that it fits in a table with a specific line width. Each cell should contain only 1 character. It should then read a line with numbers, holding the columns that should be bombarded.
My code looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.Text_Bombardment
{
class Program
{
static void Main(string[] args)
{
var sentence = Console.ReadLine();
var bombing = int.Parse(Console.ReadLine());
var selected = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
Dictionary<int, bool> bombDict = new Dictionary<int, bool>();
var newSentence = sentence + new string(' ', bombing - sentence.Length % bombing); // whole row minus words left
for (int i = 0; i < selected.Length; i++)
{
bombDict.Add(selected[i], true);
}
var rows = newSentence.Length / bombing;
var cols = bombing;
var count = 0;
var arrSent = newSentence.ToCharArray();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (bombDict.ContainsKey(j) && bombDict[j] == true && arrSent[count] != ' ')
{
arrSent[count] = ' ';
try
{
if (arrSent[count + bombing] == ' ')
{
bombDict[j] = false;
}
else
{
bombDict[j] = true;
}
}
catch (IndexOutOfRangeException)
{
continue;
}
}
count++;
}
}
var finalSent = string.Join("", arrSent).TrimEnd();
Console.WriteLine(finalSent);
}
}
}
And it breaks on this sentence:
Vazov received his elementary education in hisnative town of Sopoandat Plovdiv. The son of a conservative, well-to-do merchant.
20
1 6 17 2 5 0 15
Current Output:
ov eceived i e en ry educa i n hi ative to n of opo dat Plov iv. T e s of a co serva ive well-to- o mer ha t.
Intended Output:
ov eceived i e en ry educa i n hi ative to n of opo dat Plov iv. T e s of a co serva ive well-to- o mer han .
Soo it only doesn't work on the end.
Can someone help me?
Any suggestions?
Additional notes:
For example, we read the text "Well this problem is gonna be a ride." and line width 10. We distribute the text among 4 rows with 10 columns. We read the numbers "1 3 7 9" and drop bombs on those columns in the table.
The bombs destroy the character they fall on + all the neighbouring characters below it.
Note: Empty spaces below destroyed characters stop the bombs (see column 7).
Finally, we print the bombarded text on the console: "W l th s p o lem i o na be a r de."
Note: The empty cells in the table after the text should NOT be printed.

Your solution is very difficult to understand, keep it simple give names to the variables that you can understand easily.
I modified your code, hope it helps you:
static void Main()
{
string sentence = "Well this problem is gonna be a ride.";
int numberOfColumns = int.Parse("10");
List<int> bombs = "1 3 7 9".Split(' ').Select(int.Parse).ToList();
// we need to convert to decimal, otherwise C# will ignore decimal part.
//example: 127/20 = 6.35, so we need 7 rows. if we don't convert to decimal we have 6
// the Ceiling says, always round up. so even 6.1 will be rounded to 7
int numberOfRows = (int)Math.Ceiling(sentence.Length / Convert.ToDecimal(numberOfColumns));
char[,] array = new char[numberOfRows, numberOfColumns];
int sentencePointer = 0;
for (int rowIndex = 0; rowIndex < numberOfRows; rowIndex++)
{
for (int colIndex = 0; colIndex < numberOfColumns; colIndex++)
{
// if you want to print the grid with the full text, just comment the 3 lines below,
//and keep only "array[rowIndex, colIndex] = sentence[sentencePointer];"
if (bombs.Contains(colIndex))
{
if (sentence[sentencePointer] == ' ') // bomb is deactivated
{
bombs.Remove(colIndex);
array[rowIndex, colIndex] = sentence[sentencePointer];
}
else
array[rowIndex, colIndex] = '*'; // * represents a bomb
}
else
array[rowIndex, colIndex] = sentence[sentencePointer];
sentencePointer++; // move next character
if (sentencePointer >= sentence.Length)
break; // we reach the end of the sentence.
}
}
PrintGrid(array, numberOfRows, numberOfColumns);
// just give some space to print the final sentence
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("");
for (int rowIndex = 0; rowIndex < numberOfRows; rowIndex++)
{
for (int colIndex = 0; colIndex < numberOfColumns; colIndex++)
{
Console.Write(array[rowIndex, colIndex]);
}
}
Console.ReadKey();
}
private static void PrintGrid(char[,] array, int numberOfRows, int numberOfColumns)
{
Console.WriteLine(new string('-', numberOfColumns * 2));
for (int rowIndex = 0; rowIndex < numberOfRows; rowIndex++)
{
Console.Write("|");
for (int colIndex = 0; colIndex < numberOfColumns; colIndex++)
{
Console.Write(array[rowIndex, colIndex]);
Console.Write("|");
}
Console.WriteLine("");
}
}

Somewhat more elegant solution.
private static IEnumerable<char> Bomb(IEnumerable<char> text, IEnumerable<int> indexes, int length)
{
var indexArray = new List<int>(indexes);
var used = new object[length];
return text.Select(
(c, index) =>
{
if (c != ' ' && indexArray.Contains(index % length))
{
used[index % length] = new object();
return '\0';
}
if (c == ' ' && used[index % length] != null)
{
indexArray.Remove(index % length);
}
return c;
});
}

Related

Steganography extraction issue C#

I am able to hide my text inside an Image. But when I tried to extract the text from my image, I always only able manage to get only the first character. I don't know where went wrong?
My embed operation code:
public static Bitmap embedMessage(string hiddenText, Bitmap oriImage)
{
Color currentPixel;
int[] colorRGB = new int[3];
List<int> messageValue = new List<int>();
messageValue = ConvertMessage(messageValue, hiddenText);
int messageIndex = messageValue.Count;
int binaryCount = 0;
int zeroAdded = 0;
for(int row = 0; row < oriImage.Height; row++)
{
for(int col = 0; col < oriImage.Width; col++)
{
currentPixel = oriImage.GetPixel(col, row);
colorRGB[0] = ConvertEven(currentPixel.R);
colorRGB[1] = ConvertEven(currentPixel.G);
colorRGB[2] = ConvertEven(currentPixel.B);
for(int rgbIndex = 0; rgbIndex < colorRGB.Length; rgbIndex++)
{
if(messageIndex > 0)
{
colorRGB[rgbIndex] += messageValue[messageValue.Count - messageIndex] % 2;
messageValue[messageValue.Count - messageIndex] /= 2;
}
}
if (messageIndex == 0 && zeroAdded < 8)
{
oriImage.SetPixel(col, row, Color.FromArgb(colorRGB[0], colorRGB[1], colorRGB[2]));
zeroAdded++;
Console.WriteLine("Adding zero number: " + zeroAdded);
}
else
{
Console.WriteLine("Set Pixel");
oriImage.SetPixel(col, row, Color.FromArgb(colorRGB[0], colorRGB[1], colorRGB[2]));
}
if (zeroAdded == 8)
{
Console.WriteLine("Final Pixel Add");
oriImage.SetPixel(col, row, Color.FromArgb(colorRGB[0], colorRGB[1], colorRGB[2]));
return oriImage;
}
binaryCount++;
if (binaryCount % 8 == 0) { messageIndex--; Console.WriteLine("Message Index deducted"); }
}
}
return oriImage;
}
My embed implementation is the same to this example As for extraction I used the exact extraction code from the example. No matter what I tried, I am still only getting the first character of my embedded text. I tried checking my code by printing each operations and all of them fires without any issue which means the embed operation should be working as expected.
Just found my problem. Everything in my embed method should be in the R G B for loop.

How do I get rid of circular numbers in my list

Okay, I know that this code is crude, and all around a messy, but I am no programmer, so bear with me. I have this code that lists a bunch of numbers, but I want it to not list any circular copies of the numbers.
For example, if the number 111262 is on my list, I don't want 112621, 126211, 262111, 621112, or 211126 to be listed.
Sorry, that number cannot be on the list.
For a true example, if the number 111252 is on my list, I don't want 112521, 125211, 252111, 521112, or 211125 to be listed.
Any help is appreciated!
namespace Toric_Classes
{
class Program
{
static void Main(string[] args)
{
int number_of_perms=0;
bool badsubsum1;
bool badsubsum2;
int subsum1 = 0;
int subsum2 = 0;
int sum = 0;
int class_length=6;
int[] toric_class=new int[class_length];
// The nested for loops scroll through every possible number of length class_length, where each digit can have a value of 1,2,..., or class_length-1
// Each number is looked at as an array, and is not stored anywhere, only printed if it satisfies certain conditions
for(int i1=1; i1<class_length; i1++)
{
toric_class[0] = i1;
for (int i2 = 1; i2 < class_length; i2++)
{
toric_class[1] = i2;
for (int i3 = 1; i3 < class_length; i3++)
{
toric_class[2] = i3;
for (int i4 = 1; i4 < class_length; i4++)
{
toric_class[3] = i4;
for (int i5 = 1; i5 < class_length; i5++)
{
toric_class[4] = i5;
for (int i6 = 1; i6 < class_length; i6++)
{
badsubsum1 = false;
badsubsum2 = false;
toric_class[5] = i6;
// Find the value of the sum of the digits of our array.
// We only want numbers that have a total digit sum being a multiple of class_length
for (int k = 0; k < class_length; k++)
{
sum += toric_class[k];
}
// The follwong two nested loops find the value of every contiguous subsum of our number, but not the total subsum.
// We *do not* want any subsum to be a multiple of class_length.
// That is, if our number is, say, 121342, we want to find 1+2, 1+2+1, 1+2+1+3, 1+2+1+3+4, 2+1, 2+1+3, 2+1+3+4, 2+1+3+4+2, 1+3, 1+3+4, 1+3+4+2, 3+4, 3+4+2, and 4+2
// The following checks 1+2, 1+2+1, 1+2+1+3, 1+2+1+3+4, 2+1, 2+1+3, 2+1+3+4, 1+3, 1+3+4, and 3+4
for (int i = 0; i < class_length - 1; i++)
{
for (int j = i + 1; j < class_length - 1; j++)
{
for (int k = i; k < j; k++)
{
subsum1 += toric_class[k];
}
if (subsum1 % class_length == 0)
{
badsubsum1 = true;
break;
}
subsum1 = 0;
}
}
// The following checks 2+1, 2+1+3, 2+1+3+4, 2+1+3+4+2, 1+3, 1+3+4, 1+3+4+2, 3+4, 3+4+2, and 4+2
for (int i = 1; i < class_length; i++)
{
for (int j = i + 1; j < class_length; j++)
{
for (int k = i; k < j; k++)
{
subsum2 += toric_class[k];
}
if (subsum2 % class_length == 0)
{
badsubsum2 = true;
break;
}
subsum2 = 0;
}
}
// We only want numbers that satisfies the following conditions
if (sum % class_length == 0 && badsubsum1 == false && badsubsum2 == false)
{
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
number_of_perms++;
}
sum = 0;
subsum1 = 0;
subsum2 = 0;
}
}
}
}
}
}
Console.WriteLine("Number of Permuatations: "+number_of_perms);
Console.Read();
}
}
}
EDIT
To clarify, I am creating a list of all numbers with length n that satisfy certain conditions. Consider the number d1d2...dn, where each di is a digit of our number. Each di may have value 1,2,...,n. Our number is in the list if it satisfies the following
The sum of all the digits is a multiple of n, that is,
d1+d2+...+dn = 0 mod n
Every contiguous subsum of the digits is not a multiple of n, aside from the total sum, that is, if i !=1 and j != n, then
di+d(i+1)+...+dj != 0 mod n
I should mention again that a "number" does not strictly use the numbers 0-9 in its digits. It may take any value between 1 and n. In my code, I am using the case where n=6.
The code works by creating an array of length class_length (in the code above, I use class_length=6). We first have 6 nested for loops that simply assign values to the array toric_class. The first for assigns toric_class[0], the second for assigns toric_class[1], and so on. In the first go around, we are generating the array 111111, then 111112, up to 111115, then 111121, etc. So essentially, we are looking at all heximal numbers that do not include 0. Once we reach our sixth value in our array, we check the array toric_class and check its values to ensure that it satisfies the above conditions. If it does, we simply print the array in a line, and move on.
Here is my easy and inefficient way that should work with minimal changes to your code. It requires shared string list var strList = new List<string>(); to store the used numbers. Then this part:
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
number_of_perms++;
becomes something like this:
string strItem = " " + string.Join(" ", toric_class) + " "; // Example: int[] {1, 12, 123} becomes " 1 12 123 "
if (!strList.Any(str => str.Contains(strItem))) // Example: if " 1 12 123 1 12 123 " contains " 1 12 123 "
{
Console.WriteLine(strItem);
strItem += strItem.Substring(1); // double the string, but keep only one space between them
strList.Add(strItem);
}
number_of_perms++; // not sure if this should be in the if statement
The idea is that for example the string " 1 1 1 2 5 2 1 1 1 2 5 2 " contains all circular copies of the numbers {1, 1, 1, 2, 5, 2}. I used string as a lazy way to check if array contains sub-array, but you can use similar approach to store copy of the used numbers in a list of arrays new List<int[]>() and check if any of the arrays in the list is circular copy of the current array, or even better HashSet<int[]>() approach similar to #slavanap's answer.
The first version of my answer was the easiest, but it works only with array of single digit items.
List is almost the same as array (new List<string>() instead of new string[]), but makes it much easier and efficient to add items to it. For example {1,2}.Add(3) becomes {1,2,3}.
str => str.Contains(strItem) is shortcut for a function that accepts parameter str and returns the result of str.Contains(strItem). That "function" is then passed to the .Any LINQ extension, so
strList.Any(str => str.Contains(strItem))
is shortcut for something like this:
foreach(string str in strList)
{
if (str.Contains(strItem))
{
return true;
}
}
return false;
The following method:
private static List<int> GetCircularEquivalents(int value)
{
var circularList = new List<int>();
var valueString = value.ToString();
var length = valueString.Length - 1;
for (var i = 0; i < length; i++)
{
valueString = valueString.Substring(1, length) + valueString.Substring(0, 1);
circularList.Add(int.Parse(valueString));
}
return circularList;
}
will return a list of the circular numbers derived from the input value. Using your example, this method can be called like this:
var circularList = GetCircularEquivalents(111262);
var dirtyList = new List<int> { 1, 112621, 2, 126211, 3, 262111, 4, 621112, 5, 211126, 6 };
var cleanList = dirtyList.Except(circularList).ToList();
which would result in a cleanList made up of the numbers 1 through 6, i.e. the dirtyList with all the circular numbers derived from 111262 removed.
That's where OOP really benefits. Comments inlined.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3 {
struct MyInt : IEquatable<MyInt> {
private int _value;
public MyInt(int value) {
_value = value;
}
// make it look like int
static public implicit operator MyInt(int value) {
return new MyInt(value);
}
public static explicit operator int(MyInt instance) {
return instance._value;
}
// main difference in these 3 methods
private int GetDigitsNum() {
int temp, res;
for (res = 0, temp = Math.Abs(_value); temp > 0; ++res, temp /= 10);
return res;
}
public bool Equals(MyInt other) {
int digits = other.GetDigitsNum();
if (digits != this.GetDigitsNum())
return false;
int temp = other._value;
// prepare mul used in shifts
int mul = 1;
for (int i = 0; i < digits - 1; ++i)
mul *= 10;
// compare
for (int i = 0; i < digits; ++i) {
if (temp == _value)
return true;
// ROR
int t = temp % 10;
temp = temp / 10 + t * mul;
}
return false;
}
public override int GetHashCode() {
// hash code must be equal for "equal" items,
// that's why use a sum of digits.
int sum = 0;
for (int temp = _value; temp > 0; temp /= 10)
sum += temp % 10;
return sum;
}
// be consistent
public override bool Equals(object obj) {
return (obj is MyInt) ? Equals((MyInt)obj) : false;
}
public override string ToString() {
return _value.ToString();
}
}
class Program {
static void Main(string[] args) {
List<MyInt> list = new List<MyInt> { 112621, 126211, 262111, 621112, 211126 };
// make a set of unique items from list
HashSet<MyInt> set = new HashSet<MyInt>(list);
// print that set
foreach(int item in set)
Console.WriteLine(item);
}
}
}
Output:
112621

How to print star like below in console application? I/p 5 O/p like = 1 212 32123 4321234 543212345 [duplicate]

My question is how to make a pyramid using * and 'space' in C#? The output will be like this.
*
* *
* * *
* * * *
* * * * *
We only need to use "for loop" for this program. I only know how to make this one.
*
**
***
****
*****
I made a program like this:
static void Main(string[]args)
{
int i=o;
int j=o;
for(i=5;1>=1;i--)
for(j=1;j<=5;j++)
{
Console.Write("*");
}
Console.WriteLine(" ");
}
I'm confused when it comes to pyramid because it includes spaces. Thanks for your help!
think about how you'd print the pyramid manually.
suppose 5 levels deep.
1st line: 4 spaces, 1 star,
2nd line: 3 spaces, star, space, star
3rd line: 2 spaces, star space star space star
etc.
doesn't matter whether you print spaces after the last star or not - won't make a difference to how it looks.
what do we see?
if we have a total of X levels
line 1: (x-1) spaces, (star space)
line 2: (x-2) spaces, (star space) twice
line 3: (x-3) spaces, (star space) three times
line 4: (x-4) spaces, (star space) four times
that's the pattern. I'll leave the coding to you.
using System;
class Program
{
static void Main(string[] args)
{
int num, i, j, k;
Console.Write("enter the level:");
num=Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= num; i++)
{
for (j = 1; j < num-i+1; j++)
{
Console.Write(" ");
}
for (k = 1; k <= i; k++)
{
Console.Write(i);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
Your problem is spaces, therefore I suggest you think about the spaces. Tell me this: how many spaces are on each row to the left of the first star? You'll likely be able to solve your own problem if you think about this.
Try to think of it as a grid or a matrix and see where you want the '*' in each row and how it relates to your loop index.
sorry I missed this was homework... will give a strategy ... instead
it helps if you do it in notepad and think about what you are doing... you will start to understand the relationship between the line you are on and the spaces and what not...
Post my answer after 3 hours. I think now you have almost finished it under #iluxa's advice?
int height = 20;
for (int level = 1; level <= height; level++)
{
string text = string.Join(" ", Enumerable.Repeat("*", level));
Console.WriteLine(text.PadLeft(height - level + text.Length));
}
I used some build-in methods e.g. Enumerable.Repeat and String.PadLeft, not the pure C-language way. The purpose is that I want to tell you since you have chosen C# as the programming language(not C/Java/etc), you should resolve problems in the C# way.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pyramid_star
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter a number:");
int n = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
for (int x = i; x <= n; x++)
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)
{
Console.Write("*"+" ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
Program o = new Program();
o.show();
Console.ReadKey();
}
void show()
{
for (int i = 1; i <= 12; i++)
{
for (int j = 1; j <= 9 - i / 2; j++)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(" * ");
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
Console.Write("*");
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
}
}
Try this and follow this same logic in c, c++, php, java
using System;
class pyramid {
static void Main() {
/** Pyramid stars Looking down
Comment this if u need only a upside pyramid **/
int row, i, j;
// Total number of rows
// You can get this as users input
//row = Int32.Parse(Console.ReadLine());
row = 5;
// To print odd number count stars use a temp variable
int temp;
temp = row;
// Number of rows to print
// The number of row here is 'row'
// You can change this as users input
for ( j = 1 ; j <= row ; j++ ) {
// Printing odd numbers of stars to get
// Number of stars that you want to print with respect to the value of "i"?
for ( i = 1 ; i <= 2*temp - 1 ; i++ )
Console.Write("*");
// New line after printing a row
Console.Write("\n");
for ( i = 1 ; i <= j ; i++ )
Console.Write(" ");
// Reduce temp value to reduce stars count
temp--;
}
/** Pyramid stars Looking up
Comment this if u need only a downside pyramid **/
int rowx, k, l;
// Total number of rows
// You can get this as users input
// rowx = Int32.Parse(Console.ReadLine());
rowx = 5;
// To print odd number count stars use a temp variable
int tempx;
tempx = rowx;
//Remove this if u use
Console.Write("\n");
// Number of rows to print
// The number of row here is 'rowx'
for ( l = 1 ; l <= rowx ; l++ ) {
// Leaving spaces with respect to row
for ( k = 1 ; k < tempx ; k++ )
Console.Write(" ");
// Reduce tempx value to reduce space(" ") count
tempx--;
// Printing stars
for ( k = 1 ; k <= 2*l - 1 ; k++ )
Console.Write("*");
// New line after printing a row
Console.Write("\n");
}
}
}
The following code might help:
public static void print(int no)
{
for (int i = 1; i <= no; i++)
{
for (int j = i; j <= no; j++)
{
Console.Write(" ");
}
for (int k = 1; k < i * 2; k++)
{
if(k % 2 != 0)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
Console.ReadLine();
}
Here I have created a number pyramid:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("This is a number pyramid....");
var rows = 5;
for(int i = 1; i <= rows; i++)
{
for(int lsc = (-rows); lsc <= -2; lsc ++)
{
if(lsc < (-1)*i)
{
//write left sided blank spaces
Console.Write(" ");
}
else
{
//write left sided numbers
Console.Write(-1*(lsc));
}
}
for(int rsc = 1; rsc <= rows; rsc++)
{
//write right sided blank spaces
Console.Write(" ");
}
else
{
//Write sided numbers
Console.Write(rsc);
}
}
Console.WriteLine();
}
}
}
I have described here https://utpalkumardas.wordpress.com/2018/04/20/draw-number-pyramid
Out put is:
The is a number pyramid....
1
212
32123
4321234
543212345
I know it's javascript but might help
let n = 6;
for (let i = 1; i <= n; i++) {
let spaces = n-i;
let str = '';
for (let j=0; j < spaces; j++) {
str+=' ';
}
for (let j=0; j < i; j++) {
str+='* ';
}
console.log(str)
}
I have found two approaches:
//1st approach
int n = 6;
for (int i = 0; i < n; i++)
{
// need to print spaces
for (int j = 0; j < n - i - 1; j++)
{
Console.Write(" ");
}
// need to print * with one space
for (int k = 0; k <= i; k++)
{
Console.Write("* ");
}
Console.WriteLine();
}
// 2nd Approach
int rows = 6;
int temp = 0;
bool toggle = false;
for (int j = 0; j < rows; j++)
{
int counter = 0;
for (int i = 0; i < 2 * rows - 1; i++)
{
if (i < rows - temp - 1)
{
Console.Write(" ");
}
else
{
if (counter <= j + temp)
{
if (!toggle)
{
Console.Write("*");
toggle = true;
}
else
{
Console.Write(" ");
toggle = false;
}
}
counter++;
}
}
Console.WriteLine();
temp++;
toggle = false;
}

how to read matrix row elements in single line in C# console

I want to read a 5 X 5 matrix from input in console and I want to read row elements in a single line and not in separate lines, like this:
25 16 14 12
10 15 11 10
2 10 9 8 8
7 6 11 20
5 4 1 0 3
Multi line version:
private static int[,] ReadMatrix()
{
var mtr = new int[5, 5];
for (var i = 0; i < 5; i++)
{
var line = Console.ReadLine();
var spl = line.Split(' ');
if (spl.Length != 5) throw new FormatException();
for (var j = 0; j < 5; j++)
mtr[i, j] = int.Parse(spl[j]);
}
return mtr;
}
Single line version:
private static int[,] ReadMatrix()
{
var mtr = new int[5, 5];
var line = Console.ReadLine();
if (string.IsNullOrWhiteSpace(line)) throw new FormatException();
var spl = line.Split(' ');
if (spl.Length != 25) throw new FormatException();
for (var i = 0; i < 25; i++)
mtr[i/5, i%5] = int.Parse(spl[i]);
return mtr;
}
I think this could help: reading two integers in one line using C#
Basicly the string[] tokens = Console.ReadLine().Split(); and then you could call tokens.Length to see how many columns there r going to be.
i used this function to read elements
static int readIndex()
{
string num = string.Empty;
ConsoleKeyInfo cr;
do
{
cr = Console.ReadKey(true);
int n;
if (int.TryParse(cr.KeyChar.ToString(), out n))
{
num += cr.KeyChar.ToString();
Console.Write(cr.KeyChar.ToString());
}
else if (cr.Key == ConsoleKey.Backspace)
{
if (num.Length > 0)
{
Console.Write("\b");
num = num.Remove(num.Length - 1);
}
}
} while (cr.Key != ConsoleKey.Enter);
Console.Write(" ");
return int.Parse(num);
}
then we need just a loop to read elements like this
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
mat[i, j] = (int)readIndex();
}
Console.WriteLine();
}

c# Loops with stars and spaces

I am currently breaking my head over this simple assignment for loops that I have to do.
Basically what I want to achieve is:
1) User gives imput how long the star pyramid should be
2) Make a pyramid with a for loop.
It needs to look something like this:
(If it needs to be 5 stories high; first row is 5 spaces 1 star; second row 4 spaces 2 stars and so on.
*
**
***
****
(Hard to format but you get my intention.)
I currently have this
public void Pyramid()
{
Console.WriteLine("Give the hight of the pyramid");
_aantal = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= _aantal; i++) // loop for hight
{
for (int d = _aantal; d > 0; d--) // loop for spaces
{
Console.Write(_spatie);
}
for (int e = 0; e < i; e++) // loop for stars
{
Console.Write(_ster);
}
Console.WriteLine();
}
}
The output is always the inserted number amount of spaces and it is not decremented correctly.
Although if I debug it it counts down correctly.
Thank you for responding.
You could use the constructor of the string class to create the repetition for you, and then print both values at once, then you don't need the extra for loops
static void Main(string[] args)
{
int rowHeight = 5;
for (int row = 1; row <= rowHeight; row++)
{
string spaces = new string(' ', rowHeight - row);
string stars = new string('*', row);
Console.WriteLine("{0}{1}", spaces, stars);
}
Console.ReadLine();
}
UPDATE
for the semantics, i will then also show it with 2 for loops
static void Main(string[] args)
{
int rowHeight = 5;
for (int row = 1; row <= rowHeight; row++)
{
int totalSpaces = rowHeight - row;
for (int j = 0; j < totalSpaces; j++)
{
Console.Write(" ");
}
for (int j = 0; j < row; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadLine();
}
well, your problem is
for (int d = _aantal; d > 0; d--) // loop for spaces
you really want
for (int d = _aantal - i ; d > 0; d--) // loop for spaces
but it really just mirrors what you currently have, and still doesn't create the pyramid look you seem to want.
I think the closest you'll get in a console app is by subtracting a space every other row:
for (int d = _aantal-i; d > 0; d-=2) // loop for spaces
which will give output:
Give the hight of the pyramid:
10
*
**
***
****
*****
******
*******
********
*********
**********
Got it !
static void Main(string[] args)
{
Console.WriteLine("Give the hight of the pyramid");
string _spatie = " ";
string _ster = "*";
int _aantal = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= _aantal; i++) // loop for height
{
for (int d = i; d < _aantal; d++) // loop for spaces
{
Console.Write(_spatie);
}
for (int e = 1; e <= i; e++) // loop for stars
{
Console.Write(_ster);
}
Console.WriteLine();
}
Console.ReadKey();
}
Check this out..!! You were missing out the iterator 'i' of the height loop inside the spaces loop.
You will get the triangle :-
*
**
***
****
You will need odd number of stars always for a symmetrical pyramid.
I know you wanted to do this as a console app but if you adapt this code it should work fine
Replace textbox1/2 with Consle.Readline/Write
int pyramidstories = int.Parse(TextBox2.Text);
int I = 1;
while (I <= pyramidstories)
{
for (int spacecount = 0; spacecount < (pyramidstories - I); spacecount++)
{
TextBox1.Text += " ";
}
for (int starcount = 1; starcount < I + 1; starcount++)
{
TextBox1.Text += "*";
}
TextBox1.Text += Environment.NewLine;
I++;
}
As your question states you need:
4 spaces 1 star
3 spaces 2 stars
2 spaces 3 stars
etc..
so your pyramid should look something like
*
**
***
****
*****
The code sample above displays a pyramid as illustrated above
To get a pyramid (with proper spacing) like this:
You can use:
static void Main(string[] args)
{
// The length of the pyramid
int lengte = 18;
// Loop through the length as given by the user
for (int i = 0; i <= lengte; i++)
{
// If its an even number (we don't want 1-2-3.. but 1-3-5.. stars)
if (i % 2 == 0)
{
// Calculate the length of the spaces we need to set
int spatieLengte = (lengte / 2) - (i / 2);
// Display spaces
for (int spaties = 0; spaties <= spatieLengte; spaties++)
{
Console.Write(" ");
}
// Display stars
for (int sterren = 0; sterren <= i; sterren++)
{
Console.Write("*");
}
// Newline
Console.WriteLine();
}
}
Console.ReadLine();
}
Obviously the if block and spaceLengte variable aren't really needed. But I thought it would make it somewhat easier for OP to read.
Good luck / Succes ermee ;)

Categories