This question already has answers here:
How to reverse an array using the Reverse method. C# [closed]
(6 answers)
Closed 6 months ago.
using System;
using System.Linq;
namespace Array.ReversingArrayChar
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
char[] symbol = input.Split(' ').Select(char.Parse).ToArray();
symbol.Reverse();
for (int a = 0; a <= symbol.Length - 1; a++)
{
Console.Write(symbol[a] + " ");
}
}
}
}
When I run the code I get the Array printed but not in reversed order even tho I used .Reverse(). It's probably a really simple mistake but it's too late at night for my brain to figure it out.
Enumerable.Reverse is a LINQ extension that returns the sequence reversed, so you have to assign it to a variable. But here you want to use Array.Reverse:
Array.Reverse(symbol);
Use Enumerable.Reverse if you don't want to modify the original collection and if you want to support any kind of sequence. Use List.Reverse or Array.Reverse if you want to support only these collections and you want to modify it directly. Of course this is more efficient since the method knows the size and you need less memory.
Oh Man..! you are almost there, your code is fine but you need to use the output of the .Reverse() method. since the method won't modify the actual collection, it will return the reversed array. you can try the following:
string input = "A S D R F V B G T";
char[] symbols = input.Split(' ').Select(char.Parse).ToArray();
foreach (var symbol in symbols.Reverse())
{
Console.Write(symbol + " ");
}
You will get the output as T G B V F R D S A
Related
This question already has answers here:
Convert a list to a string in C#
(14 answers)
Closed 9 months ago.
I am a mere beginner and I am trying to learn a bit of LINQ. I have a list of values and I want to receive a different list based on some computation. For example, the below is often quoted in various examples across the Internet:
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
here the "computation" is done by simply multiplying a member of the original list by itself.
I wanted to actually use a method that returns a string and takes x as an argument.
Here is the code I wrote:
namespace mytests{
class program {
static void Main (string[] args)
{
List<string> nums = new List<string>();
nums.Add("999");
nums.Add("888");
nums.Add("777");
IEnumerable<string> strings = nums.AsEnumerable().Select(num => GetStrings(num));
Console.WriteLine(strings.ToString());
}
private static string GetStrings (string num){
if (num == "999")
return "US";
else if (num == "888")
{
return "GB";
}
else
{
return "PL";
}
}
}
}
It compiles but when debugging, the method GetStrings is never accessed and the strings object does not have any members. I was expecting it to return "US", "GB", "PL".
Any advice on what I could be doing wrong?
Thanks.
IEnumerable<string>.ToString() method does not work as you expected. Result will be
System.Collections.Generic.List`1[System.String]
If you want to see the values which are held in the collection, you should create iteration.
foreach (var i in strings)
Console.WriteLine(i);
This line does two things for you. One of them is writing the values which are held in the collection to console. The other operation is iterating the collection. During iteration, values are needed and linq will execute the necessary operation (in your case GetStrings method).
Currently your code does not use the collection values, so the code does not evaluate the values and does not trigger GetStrings method.
This question already has answers here:
Non-invocable member cannot be used like a method?
(6 answers)
Closed 5 years ago.
Hey StackOverflow users,
I'm working on a discord bot in C#. To keep my code clean, I'd like to use a function that adds more lines to a string.
An example of what I want to avoid is:
Description = $"Hey { username }! {Environment.NewLine + Environment.NewLine}{funMsg[randomNumber]}",
What I tried to do is:
public string inertlines(int i)
{
string st = "";
for (int c = 0; c < i; c++)
{
st += Environment.NewLine();
}
return st;
}
The visual studio compiler gives an error regarding the NewLine statement. "Non-invocable member 'Environment.NewLine' cannot be used like a method.
I'd really appreciate it if someone could tell me what do to avoid this and/or another method that could replace the Environment.NewLine() methode.
Finally I want to clearify that this is NOT a duplicate. For new programmers this post does explain alot more of a more specific problem. The post that got compared to mine had the same SOLUTION, however, not the same problem. It's even a whole different SUBJECT. On top of that, starters could copy the solution to easialy add extra lines to a string or understand how functions work better, as Environment.NewLine() is a well known and easy to understand methode under newer programmers.
Thanks in advance,
Jelle
Strings are immutable. If you're going to concatenate many of them, for effiency's sake, instead try using StringBuilder:
public string insertlines(string s, int i)
{
StringBuilder sb = new StringBuilder();
sb.Append(s); // create the string
for (int c = 0; c < i; c++)
{
sb.AppendLine(""); // add a line each time
}
return sb.ToString();
}
The answer turns out to be really simple
public string insertlines(int i)
{
string st = "";
for (int c = 0; c < i; c++)
{
//Environment.NewLine shouldn't have "()" in it's own class
st += Environment.NewLine;
}
return st;
}
The usage of this to create white lines in a string would be:
Console.WriteLine($"I want 2 {insertLines(2)} blanc lines under the 2"});
or to simplify that example:
Console.WriteLine("I want 2 " + insertLines(2) + " blanc lines under the 2");
For anyone reading this, please just use "\n" for new lines in a string. I've learned alot more about coding and think my question and answer were not the best, most helpful ones.
I have the following code but it takes 20sec to process the 52957 inputs of type BigInteger. This is the question that i want to solve https://www.hackerearth.com/problem/algorithm/girlfriends-demands/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace girldfriends_demands
{
class Program
{
private static string inputString = String.Empty;
private static int testCases=0;
private static BigInteger[,] indexArray;
static void Main(string[] args)
{
initialize();
printDemand();
Console.ReadLine();
}
private static void initialize()
{
inputString = Console.ReadLine();
testCases = int.Parse(Console.ReadLine());
indexArray = new BigInteger[testCases, 2];
for (int i = 0; i < testCases; i++)
{
string[] tokens = Console.ReadLine().Split();
indexArray[i, 0] = BigInteger.Parse(tokens[0]);
indexArray[i, 1] = BigInteger.Parse(tokens[1]);
}
}
private static void printDemand()
{
char[] convertedString = inputString.ToCharArray();
for (int i = 0; i < testCases; i++)
{
BigInteger length=inputString.Length;
BigInteger startf, endf; ;
BigInteger.DivRem(indexArray[i, 0] - 1,length,out startf);
BigInteger.DivRem(indexArray[i, 1]-1,length,out endf);
char c=convertedString[((int)startf)];
char e=convertedString[((int)endf)];
if(c==e)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
}
}
Please specify how to reduce the time complexity of the code.This program gets the letters at the specified position in a string and prints true if they are same else false. Also computing the range at prior to the loop isn't helping
Why you use BigInteger ?
In any case string.length is typeof int.
It mean that if your string exceed 2147483647 (2^31 -1) your program will be broken.
I think changing BigInteger to int will help.
Console.ReadLine().Split()
is the biggest of your problems. For every single line in the file, you create an array of strings, one letter per string. This is a huge performance drain, and almost certainly not what you intended - in particular, it would be wholy unnecessary to use BigInteger to store a single-digit number...
I assume that you actually want to split the line in two based on some delimiter. For example, if your numbers are separated by a comma, you can use
Console.ReadLine().Split(',')
Even then, there is little reason to use BigInteger at all. The operation you're trying to perform is distinctly string-based, and very easy to do with strings. However, I can't really help you more specifically, because your problem description is incredibly ambiguous for such a simple task, and the code is so obviously wrong it's entirely useless to guess at what exactly you're trying to do.
EDIT:
Okay, your link confirmed my assumptions - you are massively overcomplicating this. For example, code like this will do:
var word = Console.ReadLine();
var items = int.Parse(Console.ReadLine());
for (var _ = 0; _ < items; _++)
{
var indices =
Console.ReadLine()
.Split(' ')
.Select(i => (int)((long.Parse(i) - 1) % word.Length))
.ToArray();
Console.WriteLine(word[indices[0]] == word[indices[1]] ? "Yes" : "No");
}
First, note that the numbers will always fit in a long, which allows you to avoid using BigIntever. Second, you need to use Split properly - in this case, the delimiter is a space. Third, there's no reason not to do the whole processing in a single stream - waiting for the whole input, collecting it in memory and then outputting everything at once is a waste of memory. Fourth, note how easy it was to avoid most of the complex checks while incorporating the whole necessary mechanism in simple arithmetic operations.
This runs under 2 seconds on each of the input data, only using ~80kiB of memory.
I think that ideologically, this fits the site perfectly - it's very simple and straightforward and works for all the expected inputs - the perfect hack. Of course, you'd want extra checks if this was for an end-user application, but the HackerEarth site name implies hacks are what's expected, really.
In my experience, frequent Console.WriteLine calls can lead to huge execution times.
Instead of calling that function whenever you want to add some output, I think you should use a StringBuilder object, and append all your output to it. Then, after the for-loop, call Console.WriteLine once to print the StringBuilder's contents.
This might not be your program's biggest problem, but it will help quite a bit.
Myabe by removing casts in these line and using string.compare you cand decrease execution time
if(string.Compare(startf.ToString(), endf.ToString()))
{
Console.WriteLine("Yes");
continue;
}
Console.WriteLine("No");
This question already has answers here:
How can I print the contents of an array horizontally?
(12 answers)
How does the .ToString() method work?
(4 answers)
Closed 9 years ago.
I am trying to display array elements but always getting this output System.Int32[]
instead of integer elements.
using System.IO;
using System;
class Test
{
public static void Main()
{
int[] arr=new int [26];
for(int i = 0; i < 26; i++)
arr[i] = i;
Console.WriteLine("Array line : "+arr);
}
}
You could use string.Join
Console.WriteLine("Array line : "+ string.Join(",", arr));
You need to loop over the content and print them -
Console.WriteLine("Array line: ");
for(int i=0;i<26;i++)
{
arr[i]=i;
Console.WriteLine(" " + arr[i]);
}
Simply printing arr will call ToString() on array and print its type.
Printing an array will call the ToString() method of an array and it will print the name of the class which is a default behaviour. To overcome this issue we normally overrides ToString function of the class.
As per the discussion here we can not override Array.ToString() instead List can be helpful.
Simple and direct solutions have already been suggested but I would like to make your life even more easier by embedding the functionality in Extension Methods (framework 3.5 or above) :
public static class MyExtension
{
public static string ArrayToString(this Array arr)
{
List<object> lst = new List<object>();
object[] obj = new object[arr.Length];
Array.Copy(arr, obj, arr.Length);
lst.AddRange(obj);
return string.Join(",", lst.ToArray());
}
}
Add the above code in your namespace and use it like this: (sample code)
float[] arr = new float[26];
for (int i = 0; i < 26; i++)
arr[i] = Convert.ToSingle(i + 0.5);
string str = arr.ArrayToString();
Debug.Print(str); // See output window
Hope you will find it very helpful.
NOTE: It should work for all the data types because of type object. I have tested on few of them
You are facing this problem because your line
Console.WriteLine("Array line : "+arr);
is actually printing the type of arr. If you want to print element values you should use the index number to print the value like
Console.WriteLine("Array line : "+arr[0]);
This question already has answers here:
c# multi assignment
(7 answers)
Closed 8 years ago.
In some languages it is possible to initialize several variables at the same time from an array.
For example in PHP you can do something like this:
$array = array('a', 'b', 'c');
list($a, $b, $c) = $array;
Is it possible to do this in C# as well?
I want to apply this on a program where I read all lines from a file where I know every line is two words only (never more, never less).
I know I can create the function myself (and sending in variables by reference with outkeyword) but I would like to know if any built in functionality exists for it.
I would like to know this mostly for the reason that if it is possible the code might be more readable for other developers.
In C#,
string[] arr1 = new string[] { "one", "two", "three" };
string s1 = arr1[0];
string s2 = arr1[1];
string s3 = arr1[2];
If readability is the issue and if I understand you correctly - I don't know of an in-built way. But you can create a function for that.
void Doit(out string one, out string two, string[] input)
{
one = input[0];
two = input[1];
}
And use it thus:
string[] s = new string[] { "First", "Second" };
string a, b;
Doit(out a, out b, s);
I just realized that you don't need my answer. (I had initially understood "I know I can create the function myself..." differently.) Perhaps, though, it can help someone else.
char[] array = new char[] {'a','b','c'};
As far as I know there is no buit-in way to do that.
Maybe a good way to implement that functionality is by using extension methods in order to improve readability.
Simply write the needed code in a extension method that can be attached to the type you want to initialize like a list in your example above and take an array as input to that function:
public static class Extensions {
public static void initFromArray<T> (this List<T> list, T[] array) {
for (int i = 0; i < array.Length; i++) {
list[i] = array[i];
}
}
}
Then you can use this method for example like in the following:
int[] array = new int [] { 1, 4, 6, 2, 5 };
List<int> list = new List<int>();
for (int i = 0; i < 4; i++) list.Add(0);
list.initFromArray<T>(array);