Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
How can I write a code in C# to find the sum of letters
If A=0;B=1,C=A+B,D=B+C,E=C+D.....
Example CD=1+2=3,
I have tried this way where input is string and output is sum of letter
using System;
public class Test
{
public static (int output1)
public static void Main(string input1)
{
// your code goes here
}
}
An answer without using dictionary list
class Program
{
static void Main(string[] args)
{
string test = "abcdef";
int sum = 0;
foreach (char c in test)
{
int letterNumber = char.ToUpper(c) - 64;
sum += rtnDegint(letterNumber);
}
Console.WriteLine(sum);
}
int rtnDegint(int n)
{
int first = 0, second = 1, next = 0, c;
for (c = 0; c < n; c++)
{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
}
return next;
}
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have let's say millions of strings with or without trailing spaces. I want to count the number of trailing spaces in each string.
I am doing this for each string.
int count = input.Length - input.TrimEnd().Length;
But I think this is inefficient because I am creating an unnecessary string by using TrimEnd() method for each string.
I have thought of using another method to count the trailing spaces by traversing the string in the reverse direction for each character and check till the first nonspace character (increment the count by 1).
Is there any faster and efficient way to do this? strings are small but in millions.
EDIT: I've done no profiling, and made it it in to an extension method:
void Main()
{
string test = "StackOverflow ";
int count = test.WhiteSpaceAtEnd();
}
public static class StringExtensions
{
public static int WhiteSpaceAtEnd(this string self)
{
int count = 0;
int ix = self.Length - 1;
while (ix >= 0 && char.IsWhiteSpace(self[ix--]))
++count;
return count;
}
}
Here are 2 possible solutions, one using a for loop and the other using Linq. These are both in the form of extension methods.
public static class StringExtensions {
public static int CountTrailingSpaces(this string s) {
int count = 0;
for (int i = s.Length- 1; i >= 0; i--) {
if (Char.IsWhiteSpace(s[i])) {
count++;
}
else {
return count;
}
}
return count;
}
public static int CountTrailingSpacesLinq(this string s) {
return s.Reverse().TakeWhile(Char.IsWhiteSpace).Count();
}
}
Then you can call these as follows:
static void Main(string[] args) {
string s = "test ";
Console.WriteLine(s.CountTrailingSpaces());
Console.WriteLine(s.CountTrailingSpacesLinq());
}
The output I receive using this test code is:
2
2
To add some quick performace metrics. My strong recomendation would be to use CountTrailingSpaces. As shown below this is significantly faster.
The total number of ticks taken using the for loop to do 1,000,000 operations on a string vs the linq method is significantly different.
For: 803529 ticks
Linq: 7171201 ticks
The performance testing code is shown below:
class Program {
private static Random Random;
private static Stopwatch Stopwatch;
static void Main(string[] args) {
Random = new Random(Guid.NewGuid().GetHashCode());
Stopwatch = new Stopwatch();
decimal forLoop = 0;
decimal linq = 0;
for (int i = 0; i < 1000000; i++) {
string s = RandomString(100);
Stopwatch.Restart();
s.CountTrailingSpaces();
Stopwatch.Stop();
forLoop += Stopwatch.ElapsedTicks;
Stopwatch.Restart();
s.CountTrailingSpacesLinq();
Stopwatch.Stop();
linq += Stopwatch.ElapsedTicks;
}
Console.WriteLine($"For:\t{forLoop}");
Console.WriteLine($"Linq:\t{linq}");
}
private static string RandomString(int length) {
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[Random.Next(s.Length)]).ToArray());
}
}
public static class StringExtensions {
public static int CountTrailingSpaces(this string s) {
int count = 0;
for (int i = s.Length - 1; i >= 0; i--) {
if (Char.IsWhiteSpace(s[i])) {
count++;
}
else {
return count;
}
}
return count;
}
public static int CountTrailingSpacesLinq(this string s) {
return s.Reverse().TakeWhile(Char.IsWhiteSpace).Count();
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
using System;
namespace Zadacha
{
class Zadacha
{
static int Read(int x, int y)
{
Random rnd = new Random();
Console.WriteLine("Vuvedete minimalna velichina");
string MinValue = Console.ReadLine();
Console.WriteLine("Vuvedete maximalna velichina");
string MaxValue = Console.ReadLine();
int.TryParse(MinValue, out x);
int.TryParse(MaxValue, out y);
int value = rnd.Next(x, y);
Console.WriteLine("Proizvodnoto chislo e: " + value);
Console.ReadKey(true);
return value;
}
static void Main()
{
}
}
}
This is my code, program just starts and shutdowns after a second with no text in the console app. Everything seems fine and i do not know what is wrong. It is a uni task.
You don't do anything in your Main method - you need to call your Read(x,y) method at least, and/or Console.ReadLine(); in order for something to happen.
For example
static void Main()
{
Read(1,2);
}
Is this what you are trying to achieve? Console apps start from Main() so you'll have to put something in there for the program to work. I guess you don't actually want to feed Read() two int you want to get the users input?
using System;
namespace Zadacha
{
class Zadacha
{
static int Read()
{
int x = 0;
int y = 0;
Random rnd = new Random();
Console.WriteLine("Vuvedete minimalna velichina");
string MinValue = Console.ReadLine();
Console.WriteLine("Vuvedete maximalna velichina");
string MaxValue = Console.ReadLine();
int.TryParse(MinValue, out x);
int.TryParse(MaxValue, out y);
int value = rnd.Next(x, y);
Console.WriteLine("Proizvodnoto chislo e: " + value);
Console.ReadKey(true);
return value;
}
static void Main()
{
Read();
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to print
*
**
***
****
*****
and
*****
****
***
**
*
using 'While' and 'do - while'.
But I have no idea how to approach this problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 0;
while (a <= 0)
{
while (b <= a)
{
Console.Write("*");
b++;
}
a++;
Console.WriteLine();
}
Console.ReadLine();
}
}
}
I've kept trying to approach like above, but I think It never works ever!
P.S How would I improve my logic about programming? I feel like I'm lack of thinking logically.
I figure this is a homework problem and I usually don't answer them, but I think this may help you understand how to program better, so let me try explain...
Think through what you're trying to do - You want to print 1 star first and then stop at 5 stars and then print the reverse.
So, firstly, name your variables to make sense:
int numStars = 1;
int maxNumStars = 5;
Next, you can loop something along the lines of:
while( numStars <= maxNumStars) { ... }
Firstly, it lets you understand your problem better, secondly, it becomes readable and debug-able.
Your final procedure can look something as follows:
static void Main(string[] args)
{
int numStars = 1;
int maxNumStars = 5;
// Print the ascending number of stars
while(numStars <= maxNumStars)
{
// Write numStars number of stars to the console using the string constructor:
Console.WriteLine(new string('*', numStars));
numStars++;
}
// Print the descending number of stars
while (numStars >= 1)
{
// Write numStars number of stars to the console using the string constructor:
Console.WriteLine(new string('*', numStars));
numStars--;
}
}
Again, not a fan of doing work for a person, but I hope it makes enough sense to actually help you figure out similar problems like this in the future.
Edit:
For completeness sake, to use loops everywhere, your code / loop could look something like this:
// Declare a variable for writing the stars to the console:
int numWritten;
// Print the ascending number of stars
while(numStars <= maxNumStars)
{
// Reset the number of stars written:
numWritten = 0;
// Write the stars with a loop:
while (++numWritten <= numStars)
Console.Write("*");
// End the line and increment the numStars variable:
Console.WriteLine();
numStars++;
}
This is one of many ways to do it:
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 0;
int c = 4;
while (a <= c)
{
b = 0;
while (b <= a)
{
Console.Write("*");
b++;
}
a++;
Console.WriteLine();
}
Console.WriteLine();
if (a > c)
{
a--;
while (a >= 0)
{
b = a;
while (b >= 0)
{
Console.Write("*");
b--;
}
a--;
Console.WriteLine();
}
}
Console.ReadLine();
}
}
}
Probably work in this direction:
int a = 0;
int b = 0;
string s = string.Empty;
while (a < 5)
{
while (b <= a)
{
s += "*";
b++;
}
Console.Write(s);
s = string.Empty;
a++;
b = 0;
}
Hope it gives you some idea...
using while loops can be confusing so I came up with this recursive solution (for science)
public static void Main()
{
test();
}
public static void test(string lastOutPut = "",int maxBound = 5,bool goingup = true,int cursor = 0,int maxOutputs = 10){
if(cursor>maxOutputs)return;
Console.Write("\n");
if(goingup){
Console.Write(lastOutPut+="*");
cursor++;
test(lastOutPut,maxBound,lastOutPut.Length <= maxBound,cursor,maxOutputs);
}else{
lastOutPut=lastOutPut.Substring(0,lastOutPut.Length-1);
Console.Write(lastOutPut);
cursor++;
test(lastOutPut,maxBound,lastOutPut.Length <= 0,cursor,maxOutputs);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am making a program that finds the area of square. The calculation is done on another class. I have to use an array with values 1-10. I have to find the squares of those numbers in the array using the property from the other class. I am confused on how to do that. This is what I have done so far.
using System;
using Square;
namespace DemoSquares
{
public class DemoSquares
{
static void Main()
{
int[] numbers = new int[10];
Squares asquare = new Squares();
asquare.Length = numbers[0];
foreach (int i in numbers)
{
Console.WriteLine("{0}", i, asquare.Area);
}
}
}
}
This is the class.
using System;
namespace Square
{
class Squares
{
private int length;
private int area;
public int Length
{
get
{
return length;
}
set
{
length = value;
CalcArea();
}
}
public int Area
{
get
{
return area;
}
}
private void CalcArea()
{
area = Length * Length;
}
}
}
First populate the array with some values, possibly something like this:
int[] numbers = new int[10];
int counter = 1;
for (int i = 0; i < numbers.Length; i++) {
numbers[i] = counter;
counter++;
}
then you can find the area of each square like so:
foreach (int i in numbers)
{
Squares asquare = new Squares();
asquare.Length = i;
Console.WriteLine("{0}", i, asquare.Area);
}
Another alternative
int[] numbers = {
1,2,3,4,5,6,7,8,9,10 // enter your numbers here
};
numbers.ToList().ForEach(n => {
Squares asquare = new Squares();
asquare.Length = n;
Console.WriteLine("{0}", n, asquare.Area);
});
note - if you decide to go with the latter, ensure you import:
using System.Linq;
I'am not shure if I understand you but this may work:
foreach (int i in numbers)
{
asquare.Length = i;
asquare.CalcArea();
Console.WriteLine("Area for {0}: {1}", i, asquare.Area);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I know how to calculate a factorial using a loop. Below is the code for loop, but I am getting an error while doing it by recursion. Below are both the code samples. How can I fix this?
namespace factorial
{
class Program
{
static void Main(string[] args)
{
int i, number, fact;
Console.WriteLine("Enter the Number");
number = int.Parse(Console.ReadLine());
fact = number;
for (i = number - 1; i >= 1; i--)
{
fact = fact * i;
}
Console.WriteLine("\nFactorial of Given Number is: "+fact);
Console.ReadLine();
}
}
}
Factorial using recursion:
Is there something as where I am going wrong? When am I calculating it using recursion?
Factorial using loop:
public double factorial_Recursion(int number)
{
if (number == 1)
return 1;
else
return number * factorial_recursion(number - 1);
}
public double factorial_WhileLoop(int number)
{
double result = 1;
while (number != 1)
{
result = result * number;
}
return result;
}
Your call name is not equal to your method name:
factorial_Recursion is the method name.
factorial_recursion is the call.
This worked for me:
namespace Testing
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(factorial_Recursion(5));
Console.WriteLine("press any Key");
Console.ReadLine();
}
public static double factorial_Recursion(int number)
{
if (number == 1)
return 1;
else
return number*factorial_Recursion(number - 1);
}