I am trying to write a small program to calculate the addition of two vectors from the user and storing it in the array.
I want to get two X and Y's (like this {x,y})from the user and then add them both together.
I tried to use a 2D array like so
int[,] array = new int[0, 1] {};
but I want the user to enter the values of it.
I don't know enough about c# so if anyone knows how can I solve this problem would apparitions your help
If you want to get a vector from user, you can try asking user to provide its components separated by some delimiter(s), e.g.
private static int[] ReadVector(string title) {
while (true) { // keep asking user until valid input is provided
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
string[] items = Console
.ReadLine()
.Split(new char[] { ' ', '\t', ';', ',' },
StringSplitOptions.RemoveEmptyEntries);
if (items.Length <= 0) {
Console.WriteLine("You should provide at least one component");
continue;
}
bool failed = false;
int[] result = new int[items.Length];
for (int i = 0; i < items.Length; ++i) {
if (int.TryParse(items[i], out int value))
result[i] = value;
else {
Console.WriteLine($"Syntax error in {i + 1} term");
failed = true;
break;
}
}
if (!failed)
return result;
}
}
Then you can use this routine like this:
// We don't want any 2D matrices here, just 2 vectors to sum
int[] A = ReadVector("Please, enter vector A");
int[] B = ReadVector("Please, enter vector B");
if (A.Length != B.Length)
Console.WriteLine("Vectors A and B have diffrent size");
else {
// A pinch of Linq to compute C = A + B
int[] C = A.Zip(B, (a, b) => a + b).ToArray();
Console.WriteLine($"[{string.Join(", ", A)}] + ");
Console.WriteLine($"[{string.Join(", ", B)}] = ");
Console.WriteLine($"[{string.Join(", ", C)}]");
}
Edit: Sure you can sum vectors with a help of good old for loop instead of Linq:
int[] C = new int[A.Length];
for (int i = 0; i < A.Length; ++i)
C[i] = A[i] + B[i];
Related
I need a way to check two strings to see if they have the same words in them but in different positions. I only need the number of words out of word, not the actual words. For example: string 1 is "this is an out of order test" and string 2 is "this is an order out of test" would return 1 as one word is out of order.
I've started with the following code:
public int OutOfOrder(string string1, string string2)
{
var search1 = string1.Split(' ');
var search2 = string2.Split(' ');
var OutOfOrder = 0;
for (int i = 0; i < search1.Count() - 1; i++)
{
if (search2.Contains(search1[i]))
{
for (int j=0; j < search2.Count()-1; j++)
{
if(search1[i] == search2[j] && i == j)
{
continue;
}
else if (search1[i] == search2[j] && i != j)
{
OutOfOrder++;
break;
}
}
}
}
return OutOfOrder;
}
However everything is out of order after the first one encountered and the number returned is not correct.
This does it
public static int OutOfOrder(string a, string b){
//not out of order issuex`
if (a.Length != b.Length) return -1;
foreach(string str in a.Split(' ')){
//not out of order issue
if (!b.Contains(str)) return -1;
}
//if out of order issue...
int count=0;
string[] awords = a.Split(' ');
string[] bwords = b.Split(' ');
for(int i=0; i<bwords.Length; i++){
if (!awords[i].Equals(bwords[i])) count++;
}
return (int)Math.Ceiling(0.0f + count/2);
//if one is out of order, then it's expected it renders another out of order too.
//so we need to divide it by 2 to get the one disturbing.
//and ceiling is used to help for odd number of words
}
Testing it now
public static void Main(string[] args)
{
string a = "This solves the problem";
string b = "This solves problem the";
Console.WriteLine(OutOfOrder(a, b));
}
It outputs 1
I want to print the string in reverse format in for loop:
Input: I'm Learning c#
Output: c# Learning I'm
No Split functions and reverse functions should be used, it has to do only with forloop.
for (int i = m.Length - 1; i >= 0; i--)
{
b[j]=a[i];
j++;
if(a[i]==' '|| a[i]==0)
{
for (int x = b.Length - 1; x >= 0; x--)
{
c[k] = b[x];
Console.Write(c[k]);
k++;
}
}
} Console.ReadKey();
You have to create an array of the words in the sentence:
var words = input.Split(' ');
Then you just loop through the above array from the end to the start:
for(int i=words.Length-1; i>=0; i--)
{
Console.Write(words[i]+" ");
}
With LINQ and string methods you can simplify it:
var reversedWords = input.Split().Reverse(); // Split without parameters will use space, tab and new-line characters as delimiter
string output = string.Join(" ", reversedWords); // build reversed words, space is delimiter
Use Stack<Queue<char>>
Hey if you want to show off your knowledge of data structures, use a queue and a stack! This makes for a very concise answer as well.
You want the sentence to be LIFO with respect to words but FIFO with respect to letters within words, so you need a stack (which are LIFO) of queues (which are FIFO). You can take advantage of the fact that a string, a queue<char>, and a stack<char> all expose IEnumerable<char> as well, so it's easy to convert back and forth; once you have all the characters ordered in your data structure, you can extract the whole thing as a character array using SelectMany(), which you can pass to a string constructor for the final answer.
This solution uses no Split() or Reverse() functions, as required.
public static string ReverseSentence(string input)
{
var word = new Queue<char>();
var sentence = new Stack<IEnumerable<char>>( new [] { word } );
foreach ( char c in input )
{
if (c == ' ')
{
sentence.Push( " " );
sentence.Push( word = new Queue<char>() );
}
else
{
word.Enqueue(c);
}
}
return new string( sentence.SelectMany( w => w ).ToArray() );
}
Usage:
public void Test()
{
var input = "I'm Learning c#";
var output = ReverseSentence(input);
Console.WriteLine(output);
}
Output:
c# Learning I'm
DotNetFiddle
Without split and reverse, I modify your logic little bit to achieve what you need
namespace MyNamespace
{
public class Program
{
public static void Main(string[] args)
{
var m="this is mystring";
var b = new char [m.Length];
var j=0;
//Your code goes here
for (int i = m.Length - 1; i >= 0; i--)
{
b[j]=m[i];
j++;
if(m[i]==' ' || i==0)
{
if(i==0)
{
b[j]=' ';
}
for (int x = b.Length - 1; x >= 0; x--)
{
Console.Write(b[x]);
}
b=new char[m.Length];
j=0;
}
}
Console.ReadKey();
Console.WriteLine("Hello, world!");
}
}
}
Input: "this is mystring"
Output: "mystring is this"
Here is a simple console application for your question
Without using Reverse and Split methods (just for loop)
class Program
{
static void Main()
{
string input = "I'm learning C#";
string[] result = new string[3];
int arrayIndex = 0;
string tempStr = "";
// Split string
for (int i = 0; i < input.Length; i++)
{
tempStr += input[i].ToString();
if (input[i] != ' ')
{
result[arrayIndex] = tempStr;
}
else
{
tempStr = "";
arrayIndex++;
}
}
// Display Result
for (int i = result.Length - 1; i >= 0; i--)
{
System.Console.Write(result[i] + ' ');
}
System.Console.WriteLine();
}
}
Press Ctrl + F5 to run the program
Output: C# learning I'm
I'm a relatively new student to C# programming and I'm having a lot of trouble with 2-D arrays. In this program the user is supposed to input names, verbs, and objects for an insult generator, but the problem is that I have to pointlessly store them all in one 2-D string array and generate the insults in a 1-D string array and I'm just completely lost. Can I store name, verb, and object into a single 2-D string array? Any help would be appreciated.
My issue is with initializing and storing the 2D string array and then converting to the 1D array.
private static void Generate(int insultnum, int sentnum)
{
int Ncounter = 1;
int Vcounter = 1;
int Ocounter = 1;
string[,] name = new string[sentnum,?];
string[,] verb = new string[sentnum,?];
string[,] insult = new string[sentnum,?];
do
{
Console.Write("Please enter name of #{0}: ", Ncounter);
//length and height 2D array for loop text is just a placeholder from an earlier project
for (int i = 0; i < length; i++)
{
for (int j = 0; j < height; j++)
{
name[Ncounter - 1, ??] = Console.ReadLine();
}
}
//
Ncounter++;
} while (Ncounter < sentnum);
do
{
Console.Write("Please enter name of #{0}: ", Vcounter);
verb[Vcounter-1, ?] = Console.ReadLine();
//2D array loop text
Vcounter++;
} while (Vcounter < sentnum);
do
{
Console.Write("Please enter name of #{0}: ", Ocounter);
insult[Ocounter-1, ?] = Console.ReadLine();
//2D array loop text
Ocounter++;
} while (Ocounter < sentnum);
Ncounter = 0;
Vcounter = 0;
Ocounter = 0;
string[] insults = new string[insultnum];
//insults = name[?,?] + " " + verb[?,?] + " " + object[?,?];
}
Example Output:
Enter the number of insults to generate: 3
Enter the number of names, verbs, and objects: 3
Please enter name #1: Bob
Please enter name #2: Rhys
Please enter name #3: Kaa
Please enter verb #1: licks
Please enter verb #2: touches
Please enter verb #3: tastes
Please enter object #1: dirt
Please enter object #2: cars
Please enter object #3: asphalt
Insults have been generated
Kaa licks dirt
Bob tastes asphalt
Bob licks cars
2D array i.e. string[,] is a bit strange collection to store the data, since it requires that
NameCounter == VerbCounter == ObjectCounter
More natural choice is a jagged array string[][] which allows arbitrary NameCounter, VerbCounter, ObjectCounter. And, please, decompose your solution, split it to number of easy to implement and test methods:
// Random generator for insulting
private Random rgen = new Random();
// 1st index - category (name/verb/insult), 2nd index item within category
private static string[,] data;
private static string[] categories = new string[] {
"name", "verb", "insult",
};
// Input single categore, e.g. Names or Verbs
private static void InputCategory(int category) {
for (int i = 0; i < data.GetLength(1); ++i) {
Console.Write($"Please enter {categories[category]} #{i + 1}: ");
data[category, i] = Console.ReadLine();
}
}
// Input all categories
private static void InputData() {
Console.Write($"Enter the number of names, verbs, and objects: ");
// simplest; more accurate implementation uses int.TryParse()
int n = int.Parse(Console.ReadLine());
data = new string[categories.Length, n];
foreach(var int i = 0; i < categories.Length; ++i)
InputCategory();
}
To write an insult generator you should combine random items from each category
private static string[] Insults(int count) {
string[] result = new string[count];
// take count times a item from each category
for (int i = 0; i < count; ++i) {
StringBuilder sb = new StringBuilder
for (int c = 0; c < categories.Length; ++c) {
if (c > 0)
sb.Append(' ');
sb.Append(data[c, rgen.Next(data.GetLength(1))]);
}
result[i] = sb.ToString();
}
return ressult;
}
Having these methods you can put easily
private static void Main() {
int numberOfInsults = ....
InputData();
foreach (var insult in Insults(numberOfInsults))
Console.Write(insult);
...
}
I have been trying to do a task I recieved a few days earlier. Basically the task is a console application in C# :
Prompt the user for input of 2 coordinates in untill the word "stop" is entered. Once the word "stop" is hit, print a "*"(star char) at each of the input coordinates. The field where the coordinates are printed is 20x20. I have tried doing this, but to no avail. If somebody could help me out and show me how to store the input x,y into a 2d array, that'd be great :)
How the application should work : http://imgur.com/a/SnC1k
The [0,5] [18,18]etc are the entered coordinates which are later on printed down below. The "#" chars dont need to be printed , they are here only to help with the understanding of the task.
How I tried to do it but DIDN'T work :
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool stopped = false;
int x=0;
int y=0;
while (stopped)
{
string[,] coordinates = Console.ReadLine();
string response = Console.ReadLine();
response = response.ToLower();
if (response == "STOP")
stopped = true;
else
{
string[] xy = coordinates.Split(',');
x = int.Parse(xy[0]);
y = int.Parse(xy[1]);
Console.SetCursorPosition(x, y);
Console.Write("*");
}
}
}
}
}
The code I did just doesn't do it. It shows multiple errors that I do not know how to fix and the only thing I was able to do is get it to print a char immediately when I enter the first coordinates, instead of printing a char at every entered coordinate, AFTER the word STOP is hit.
Create a 20x20 2d array. Prompt the user for the x and y. Once you have each store a 1 in your array[x,y] once the user hits stop loop through the array and print '#' if null or 0 and print '*' if its a 1.
Edit, something along these lines I didn't check if this works or compiles but should get you on the right track.
int[,] grid = new int[20,20];
while (!stopped)
{
string[,] coordinates = Console.ReadLine();
string response = Console.ReadLine();
response = response.ToUpper();
if (response == "STOP")
stopped = true;
else
{
string[] xy = coordinates.Split(',');
x = int.Parse(xy[0]);
y = int.Parse(xy[1]);
grid[x,y] = 1;
}
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (grid[i, j] > 0)
Console.Write("*");
else
Console.Write("#");
}
Console.WriteLine("");
}
}
As you only need to display a matrix-style output you don't need to use Console.SetCursorPosition(x, y);
Also you should read the user input somehow and set the proper value for the given position instead of store the coordinates.
Try this and let me know how this works for you. You can see it also on this fiddle. Enter the coordinates as two space-separated numbers and enter stop to print.
using System;
public class Program
{
public static void Main(string[] args)
{
int x=0;
int y=0;
char[,] coordinates = new char[20,20];
while (true)
{
//user must enter 2 3 for example.
string[] response = Console.ReadLine().Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries);
if (response[0].ToLower() == "stop")
break;
x = int.Parse(response[0]);
y = int.Parse(response[1]);
coordinates[x,y] = '*';
}
//Print the output
for(var i = 0; i < 20; i++)
{
for( var j = 0; j < 20; j++)
if (coordinates[i,j] == (char)0)
Console.Write('#');
else
Console.Write(coordinates[i,j]);
Console.WriteLine();
}
}
}
Hope this helps!
I suggest decomposing the task, cramming entire rountine into a single Main as bad practice; you should:
- ask user to enter coordinates
- print out the map
Let's extract the methods:
private static List<Tuple<int, int>> s_Points = new List<Tuple<int, int>>();
private static void UserInput() {
while (true) {
string input = Console.ReadLine().Trim(); // be nice, let " stop " be accepted
if (string.Equals(input, "stop", StringComparison.OrdinalIgnoreCase))
return;
// let be nice to user: allow he/she to enter a point as 1,2 or 3 4 or 5 ; 7 etc.
string[] xy = input.Split(new char[] { ',', ' ', ';', '\t' },
StringSplitOptions.RemoveEmptyEntries);
int x = 0, y = 0;
if (xy.Length == 2 && int.TryParse(xy[0], out x) && int.TryParse(xy[1], out y))
s_Points.Add(new Tuple<int, int>(x, y));
else
Console.WriteLine($"{input} is not a valid 2D point.");
}
}
Printing out
private static void PrintMap(int size = 20) {
// initial empty map; I prefer using Linq for that,
// you can well rewrite it with good old for loops
char[][] map = Enumerable.Range(0, size)
.Select(i => Enumerable.Range(0, size)
.Select(j => '#')
.ToArray())
.ToArray();
// fill map with points;
// please, notice that we must not print points like (-1;3) or (4;100)
foreach (var point in s_Points)
if (point.Item1 >= 0 && point.Item1 < map.Length &&
point.Item2 >= 0 && point.Item2 < map[point.Item1].Length)
map[point.Item1][point.Item2] = '*';
// The string we want to output;
// once again, I prefer Linq solution, but for loop are nice as well
string report = string.Join(Environment.NewLine, map
.Select(line => string.Concat(line)));
Console.Write(report);
}
Finally, all you have to do it to call the methods:
static void Main(string[] args) {
UserInput();
PrintMap();
Console.ReadKey();
}
i know how to make a console read two integers but each integer by it self like this
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers
what i want is if i entered 1 2 then it will take it as two integers
One option would be to accept a single line of input as a string and then process it.
For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
You need something like (no error-checking code)
var ints = Console
.ReadLine()
.Split()
.Select(int.Parse);
This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).
Then you should first store it in a string and then split it using the space as token.
Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:
string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)
var numbers = from Match number in new Regex(#"\d+").Matches(Console.ReadLine())
select int.Parse(number.Value);
string x;
int m;
int n;
Console.WriteLine("Enter two no's seperated by space: ");
x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);
Console.WriteLine("" + m + " " + n);
This Should work as per your need!
public static class ConsoleInput
{
public static IEnumerable<int> ReadInts()
{
return SplitInput(Console.ReadLine()).Select(int.Parse);
}
private static IEnumerable<string> SplitInput(string input)
{
return Regex.Split(input, #"\s+")
.Where(x => !string.IsNullOrWhiteSpace(x));
}
}
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
Try this:
string numbers= Console.ReadLine();
string[] myNumbers = numbers.Split(' ');
int[] myInts = new int[myNumbers.Length];
for (int i = 0; i<myInts.Length; i++)
{
string myString=myNumbers[i].Trim();
myInts[i] = int.Parse(myString);
}
Hope it helps:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortInSubSet
{
class Program
{
static int N, K;
static Dictionary<int, int> dicElements = new Dictionary<int, int>();
static void Main(string[] args)
{
while (!ReadNK())
{
Console.WriteLine("***************** PLEASE RETRY*********************");
}
var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value;
foreach (int ele in sortedDict)
{
Console.Write(ele.ToString() + " ");
}
Console.ReadKey();
}
static bool ReadNK()
{
dicElements = new Dictionary<int, int>();
Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space.");
string[] NK = Console.ReadLine().Split();
if (NK.Length != 2)
{
Console.WriteLine("Please enter N and K values correctly.");
return false;
}
if (int.TryParse(NK[0], out N))
{
if (N < 2 || N > 9999)
{
Console.WriteLine("Value of 'N' Should be Between 2 and 9999.");
return false;
}
}
else
{
Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000.");
return false;
}
if (int.TryParse(NK[1], out K))
{
Console.WriteLine("Enter all elements Separated by space.");
string[] kElements = Console.ReadLine().Split();
for (int i = 0; i < kElements.Length; i++)
{
int ele;
if (int.TryParse(kElements[i], out ele))
{
if (ele < -99999 || ele > 99999)
{
Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
dicElements.Add(i, ele);
}
else
{
Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
}
}
else
{
Console.WriteLine(" Invalid number ,Value of 'K'.");
return false;
}
return true;
}
}
}
I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").
Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work*
Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!
int temp=0;
int[] arrayOfNumbers = new int[5];
for (int i = 0; i < arrayOfNumbers.Length; i++)
{
switch (i + 1)
{
case 1:
Console.Write("\nEnter First number: ");
//notice the "\n" at the start of the string
break;
case 2:
Console.Write("\nEnter Second number: ");
break;
case 3:
Console.Write("\nEnter Third number: ");
break;
case 4:
Console.Write("\nEnter Fourth number: ");
break;
case 5:
Console.Write("\nEnter Fifth number: ");
break;
} // end of switch
temp = Int32.Parse(Console.ReadLine()); // convert
arrayOfNumbers[i] = temp; // filling the array
}// end of for loop
The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")
This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.