2D Array Input in same line - c#

How I take 2D array input in same line. in C# Console.ReadLine() allow us to take input one at a time .I want to take input as a row
int [,] arr = new int[m,n];
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
arr[i, j] = int.Parse(Console.ReadLine());
}
}
I want to take input this way
2 2,
10 20,
30 40

Entering a two-dimensional array on the command line is going to be error prone and frustrating for users. But if you MUST do it:
Figure out what symbols will separate values. (Commas, spaces?)
Figure out what symbols will separate array dimensions. (Pipes, perhaps? Whatever you choose, make sure it isn't the same symbol you use for separating values.)
Prompt the user for data and capture it into a string.
Validate the data.
Write a parser that parses your data into a multi-dimensional array.
I'd advise against trying to do this. But I don't dictate your requirements.

var delimiter = ' ';
for(var i = 0; i<n; i++) {
var row = Console.ReadLine();
var _arr = row.Trim().Split(delimiter);
for(var j=0; j<m; j++) {
arr[j, i] = int.Parse(_arr[j].Trim());
}
}
Update:
#mike-hofer, wholeheartedly agree with the "error prone and frustrating for users" characteristics of such way of input. I assume this is rather for a quick and dirty testing. Plus, exactly the same approach will be applied if you have to read the array from a file line by line, so there is some broader value in this question.
#rahi-ratul75, the code above does not do any error checking. The most likely error will be an entry which won't parse as an integer. You may want, therefore, to use int.TryParse(,) and, when false, ask to re-enter the line. The main logic, however, is there:
read the line
split it into an array
parse the entry into an integer

Related

how to copy received data from string into 1d char array c# forms

So im just learning C# and trying to use arrays, im getting input from user via a forms app and wish to copy it to an array called prevPos, in the format below
receiving data (string):
string1: "hello"
string2: "123"
//counting how many lines and using that to determine position associated with each
recieved
char[] prevPos;
prevPos = textBox_ReceievedData.Text.ToCharArray();
//count how many lines of receieved data in textbox
for (int i = 0; i < textBox_ReceievedData.Lines.Length; i++)
{
System.Console.WriteLine("charArray " +prevPos[i]);
}
right now if i wish to call it, i would get this, i do not want this fomat:
prevPos[1]=h
prevPos[2]=e
prevPos[3]=l
etc.
I want this output:
prevPos[1]=hello
prevPos[2]=123
please replace with the below and try
for (int i = 0; i < textBox_ReceievedData.Lines.Length; i++)
{
System.Console.WriteLine("Each Line " +textBox_ReceievedData.Lines[i]);
}
prevPos = textBox_ReceievedData.Text.Split('\n');
This will give you an array of all text separated by the new line character \n.
If that is the output you desire, then a string array (not a char array) is what you want. The Lines() property already gives you that, though:
string[] prevPos = textBox_ReceievedData.Lines;
for(int i=0; i< prevPos.Length; i++)
{
System.Console.WriteLine(prevPos[i]);
}

How can I set values in a 2D array from keyboard

I´m working on some codes in C# for school. But there is this exercise that is huge headache.
This is it: I have to develope a code that allows the user to set a value (put in an x) for a 2D array (5x5) from the keyboard. This means that when running the program the user should be able to set one value inside the array, something like "I wana set an "x" in 2,5 and 3,1". I just have no clue how to do that. it´s been already two weeks but i can´t figure it out.
This is what i have so far (updated, thnx to all, specially BradleyDotNET for support):
int[,] data = new int[5, 5];
public void load()
{
string[] input = Console.ReadLine().Split('=');
string[] coordinates = input[0].Split(',');
int[] intCoordinates = coordinates.Select(s => int.Parse(s)).ToArray();
data[intCoordinates[0]][intCoordinates[1]] = int.Parse(input[1]);
}
public void view()
{
Console.WriteLine("Matrix created is:");
for (int i = 0; i <= 4; i++)
{
Console.Write("\n");
for (int j = 0; j <= 4; j++)
{
Console.Write(data);
}
}
Console.ReadKey();
}
static void Main(string[] args)
{
Program objeto = new Program();
objeto.load();
objeto.view();
Console.ReadKey();
Console.Clear();
I also have to add a feature to let the user add as many "x" to the matriz as he wants, but im planning to do that with a "switch".
So, How do you set values inside the 2d array from keyboard?
Update: The mistake i get here is in line 10, inside "data". It says "Incorrect index number inside []. 2 was expected"
You didn't specify the format the input, so I"ll make one up. If the input was "2,4=10" (meaning set element[2][4] to 10), the code would be:
string[] input = Console.ReadLine().Split('=');
string[] coordinates = input[0].Split(',');
int[] intCoordinates = coordinates.Select(s => int.Parse(s)).ToArray();
matrix[intCoordinates [0]][intCoordinates [1]] = int.Parse(input[1]);
This code has a few problems with it, there is no range validation and if the user enters anything other than an int, it will throw. I'll leave those as an exercise to you, but feel free to ask if you run into trouble.
To explain, we use Console.ReadLine to get a whole line of input. Then we break it on the '=' character to get our coordinates and desired value. We then split the coordinates on ',' to get the different indices.
You can't use strings as array indices, so we call Select to invoke the int.Parse() function on each string, returning us a new array of ints.
Finally, we use the parsed indices to index into matrix and set it to the parsed value from the input.
Something like this should help you.
public void load()
{
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
Console.WriteLine("enter value for {0},{1}", i, j);
matrix[i,j]= int.Parse(Console.ReadLine());
}
}
}
BTW, in your view method start the loop from 0 to 4

How to go about storing multiple values from a loop, and displaying asterisks based on input

This question asks to write a program that accepts input for five 'stores'. The input should ideally be a range from 100 to 2000. Each input should be divided by 100, and have that amount displayed in asterisks (i.e. 500 is *, etc.). I believe I have the first part, but I've got no idea how to go about doing the rest. I cannot use arrays, as I have not learned them yet, and I want to be learn this myself instead of just copy-pasting from another student. So far, I only have
int loop;
loop = 1;
while (loop <= 5)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//store value?
loop = loop + 1;
input1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 10;
}
Not sure if I understand what you're trying to do. But maybe this will help. This is untested, but it should do what I THINK you are asking, but I am unsure what you wanted done with the asterisks. Please explain more if this isn't what you were getting at.
string Stored = "";
for (int i=0; i < 5; i++;)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//Adds to existing Stored value
Stored += input1 + " is ";
//Adds asterisk
iinput1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 100;
for(int j = 0; j < asteriskcount1; j++)
{
Stored += "*";
}
//Adds Comma
if(i != 4)
Stored += ",";
}
Console.WriteLine(Stored); //Print Result
Don't want to write it out for you but here's some thoughts ...
first, you can do a for loop for the 5 stores:
for (int loop = 0; loop < 5; loop++)
You'll probably want asterickCount (not asterickCount1) since you're in a loop. You'll also want to divide by 100 since you're range is up to 2000 and you have 80 chars on a console. That means it will print up to 20 astericks.
You'll want a PrintAstericks(int count); function that you call right after calculating the asterickCount that you call. That function simply loos and calls Console.Write (not WriteLine) to write an asterick n times (new string has overload to take char and count).
But, that pattern will print the astericks after you take each input. If you want the pattern to be (1) accept the counts for the five stores and then (2) print the asterick rows for all five, you'll need an array with 5 slots to store the inputs then loop through the array and print the asterick rows.
Finally, you'll want to put some validation on the inputs. Look at Int32.TryParse:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Super easy
int asteriskCount = int.Parse(input1)/ 100;
string output = new string('*', asteriskCount );

Time complexity of a powerset generating function

I'm trying to figure out the time complexity of a function that I wrote (it generates a power set for a given string):
public static HashSet<string> GeneratePowerSet(string input)
{
HashSet<string> powerSet = new HashSet<string>();
if (string.IsNullOrEmpty(input))
return powerSet;
int powSetSize = (int)Math.Pow(2.0, (double)input.Length);
// Start at 1 to skip the empty string case
for (int i = 1; i < powSetSize; i++)
{
string str = Convert.ToString(i, 2);
string pset = str;
for (int k = str.Length; k < input.Length; k++)
{
pset = "0" + pset;
}
string set = string.Empty;
for (int j = 0; j < pset.Length; j++)
{
if (pset[j] == '1')
{
set = string.Concat(set, input[j].ToString());
}
}
powerSet.Add(set);
}
return powerSet;
}
So my attempt is this:
let the size of the input string be n
in the outer for loop, must iterate 2^n times (because the set size is 2^n).
in the inner for loop, we must iterate 2*n times (at worst).
1. So Big-O would be O((2^n)*n) (since we drop the constant 2)... is that correct?
And n*(2^n) is worse than n^2.
if n = 4 then
(4*(2^4)) = 64
(4^2) = 16
if n = 100 then
(10*(2^10)) = 10240
(10^2) = 100
2. Is there a faster way to generate a power set, or is this about optimal?
A comment:
the above function is part of an interview question where the program is supposed to take in a string, then print out the words in the dictionary whose letters are an anagram subset of the input string (e.g. Input: tabrcoz Output: boat, car, cat, etc.). The interviewer claims that a n*m implementation is trivial (where n is the length of the string and m is the number of words in the dictionary), but I don't think you can find valid sub-strings of a given string. It seems that the interviewer is incorrect.
I was given the same interview question when I interviewed at Microsoft back in 1995. Basically the problem is to implement a simple Scrabble playing algorithm.
You are barking up completely the wrong tree with this idea of generating the power set. Nice thought, clearly way too expensive. Abandon it and find the right answer.
Here's a hint: run an analysis pass over the dictionary that builds a new data structure more amenable to efficiently solving the problem you actually have to solve. With an optimized dictionary you should be able to achieve O(nm). With a more cleverly built data structure you can probably do even better than that.
2. Is there a faster way to generate a power set, or is this about optimal?
Your algorithm is reasonable, but your string handling could use improvement.
string str = Convert.ToString(i, 2);
string pset = str;
for (int k = str.Length; k < input.Length; k++)
{
pset = "0" + pset;
}
All you're doing here is setting up a bitfield, but using a string. Just skip this, and use variable i directly.
for (int j = 0; j < input.Length; j++)
{
if (i & (1 << j))
{
When you build the string, use a StringBuilder, not creating multiple strings.
// At the beginning of the method
StringBuilder set = new StringBuilder(input.Length);
...
// Inside the loop
set.Clear();
...
set.Append(input[j]);
...
powerSet.Add(set.ToString());
Will any of this change the complexity of your algorithm? No. But it will significantly reduce the number of extra String objects you create, which will provide you a good speedup.

C# program where size of array index and elements are from user input and then search for a specific element

I'm trying to create a program where the size of array index and its elements are from user input.
And then the program will prompt the user to search for a specific element and will display where it is.
I've already come up with a code:
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main(String [] args)
{
int a;
Console.WriteLine("Enter size of index:");
a= int.Parse(Console.ReadLine());
int [] index = new int [a];
for (int i=0; i<index.Length;i++)
{
Console.WriteLine("Enter number:");
index[i]=int.Parse(Console.ReadLine());
}
}
}
}
The problem with this is that I can't display the numbers entered and I don't have any idea how to search for an array element.
I'm thinking of using if statement.
Another thing, after entering the elements the program should display the numbers like Number 0 : 1
Is this correct: Console.WriteLine("Number"+index[a]+":"+index[i]);?
And where should I put the statement? after the for loop or within it?
You're on the right track. Look carefully at how you stuffed values into the array, and you might find a clue about "how to search for an array element" with specific value. This is a core introductory algorithm, so no shortcuts! You need to find the answer on your own :-).
What is the last line Console.WriteLine(index[i]);? It seems like you are using the loop variable outside the loop.
To display entered numbers (ie. if I understand well, the numbers in the array), you have just to walk through the array like this:
for (int i = 0; i < index.length; i++)
{
Console.WriteLine(index[i]);
}
Since you want display numbers only after every number is entered, you may put this code only after finishing the loop where the user is entering the numbers:
// The user is entering the numbers (code copied from your question).
for (int i = 0; i < index.Length; i++)
{
Console.WriteLine("Enter number: ");
index[i] = int.Parse(Console.ReadLine());
}
// Now display the numbers entered.
for (int i = 0; i < index.length; i++)
{
Console.WriteLine(index[i]);
}
// Finally, search for the element and display where it is.
int elementToSearchFor;
if (int.TryParse(Console.ReadLine(), out elementToSearchFor))
{
// TODO: homework to do.
}
To search for a number, you can either walk through the array again and compare each element until finding a good one, or use Linq TakeWhile() method. (I suppose that your intent is not to use Linq, so I don't provide any further detail in this direction.)
You could use Array.IndexOf,
int a;
Console.WriteLine("Enter size of Array:-");
a = int.Parse(Console.ReadLine());
int[] array = new int[a];
Console.WriteLine("Enter the Elements of the Array:-");
for (int i = 0; i < array.Length; i++)
{
array[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe Elemets of the Array are:-");
for (int j = 0; j < array.Length; j++)
{
Console.WriteLine(array[j]);
}
Just try to break down what you've done and what you still need to do
Create a program where:
1) size of its array elements comes from user input (check)
2) array elements come from user input (check)
3) Prompt the user to search for a specific element (TODO)
4) Display where it is (TODO)
From the code you've written so far I would think you have most of what you need to do #3 & #4
An if statement may come into play when finding the location of the element the user specifies.

Categories

Resources