Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm doing a counting program and i need to multiple all digits of x number by it self.
for example: number 123456789;
1*2*3*4*5*6*7*8*9=362,880
A good solution is provided in the comments, but it isn't very easy to follow if you are trying to figure out what you are actually doing. The following code is a bit more verbose, but shows you what is actually happening each step of the way:
using System;
class MainClass {
public static void Main () {
int myNumber = 123456789; //store original number
int newNumber = (int)Math.Abs(myNumber); //changes the number to positive if it is negative to prevent string formatting errors.
int product = 1; //store product start point
string myString = newNumber.ToString(); //convert number to string
foreach(char number in myString){ //loop through string
string numberString = number.ToString(); //convert chars to strings to ensure proper output
int oneDigit = Convert.ToInt32(numberString); //convert strings to integers
product = product*oneDigit; //multiply each integer by the product and set that as the new product
}
if(myNumber < 0){product = -product;}
//if the number is negative, the result will be negative, since it is a negative followed by a bunch of positives.
//If you want your result to reflect that, add the above line to account for negative numbers.
Console.WriteLine(product); //display product
}
}
Output>>> 362880 //The output that was printed.
So we start by converting our number into a string so we can iterate through it. Then we have a foreach loop that goes through each character in the string, converts it into an integer, and multiplies it by the product of the previous numbers. Each time a new multiplication is performed, the product is updated, until, when you reach the end of the number, you have the product of all digits. This is a good project to become familiar with looping. I would recommend playing around with variations of it such as multiplying each number by the original number, multiplying together only multiples of 3, only multiplying numbers less than 5, or only multiplying the first 5 numbers to get a better handle on what's happening in a loop.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a function that generates a double number between 0 and 2.2:
Random random = new Random();
double value= random.NextDouble() * (2.2 - 0) + 0;
This works great but what I need is to generate the next number with a delta not exceeding 0.2 (positive or negative), i.e. the next random value is within 0.2 of the previously generated one.
For example: If the first random number is: 1.3434434, the next random number should be in the range between 1.5434434 and 1.1434434. The numbers can have a trend going up and then could go down but the difference between the previously generated and the new one cant be greater than 0.2.
Any easy way to achieve this?
I wrote a couple of extension methods to aid with this task. GenerateTrend will generate an infinite enumerable of numbers, and the difference between two consecutive numbers is never going to be larger than delta.
public static class RandomExtensions
{
public static IEnumerable<double> GenerateTrend(this Random random, double start, double delta)
{
var last = start;
while (true)
{
yield return last;
last = random.NextDouble(last - delta, last + delta);
}
}
public static double NextDouble(this Random random, double from, double to)
=> random.NextDouble() * (to - from) + from;
}
Use like this:
var random = new Random();
var start = random.NextDouble(0, 2.2);
var numbers = random.GenerateTrend(start, 0.2).Take(20).ToArray();
As you can see, this being an infinite generator, the calling code is responsible for limiting the amount of random numbers it's taking. In this example, I limit the generation to 20 items by using Take(20).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I had a beginning question to read in a two digit number and give it back splittet into its numbers but I soon saw, that the code I created was not really handy, when wrong inputs where done.
So I did a research about if-statemants, .length feature, regex method and comperative operators. What came back was my rudimental first script for input a two digit number, prove if it is 2 digits long, prove if it is a number and give it back. Now I have some questions to You specialists (it is a console application btw.):
Was it the right way to use regex with the IsMatch method, or would be another method saver and cleaner (maybe also another variant of regex)
Is it possible to shorten the code, Iam not so far atm, maybe there are classes or objects to use, to make the code clearer.
Was it the right way to use conditional "and" instead of regular "and", in the if statements?
Are the if statements possible to be shorten, I read about conditional expressions, but I was not sure how far I could nest them (my reference: https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/operators/conditional-operator). Maybe some of You can give me an example on my script.
Is the new operator on regex the right way to implement it, or is there another way to implement regex?
The script works, but maybe there are better and handier solutions.
using System;
using System.Text.RegularExpressions;
namespace TwoDigitSplit
{
class FromTrexToRegex
{
static void Main(string[] args)
{
int digit, digit1, digit2;
string entry;
// Search for one or more decimal numbers with Regex
Regex regex = new Regex("[0-9]+");
// Read in a two-digit number
Console.WriteLine("Enter a two-digit number:");
entry = Console.ReadLine();
// Check for length longer than two-digit and also check if it is numbers
if (entry.Length>2 && regex.IsMatch(entry))
{
Console.WriteLine("The number is longer than two-digit, please try again!");
}
// Check for length smaller than two-digit and also check if it is numbers
else if (entry.Length<2 && regex.IsMatch(entry))
{
Console.WriteLine("The number is shorter than two-digit, please try again!");
}
// Check for integer numbers and if the number is between 10 inklusiv and 100 exklusiv
else if(Int32.TryParse(entry, out digit) && digit >= 10 && digit <100)
{
// Evaluate the number and write it
digit1= digit / 10;
digit2 = digit % 10;
Console.WriteLine("The number has on the first place {0} and on the second place {1}", digit1, digit2);
}
// If no number has been plottet
else
{
Console.WriteLine("You did not enter a number!");
}
}
}
}
There are no error results atm. I could see, I only had some questions about the methods, classes and operators.
Answers
regex = new Regex(...) ... regex.IsMatch(...) is possible, but I suggest static Regex.IsMatch as more readable here
Yes, some conditions are redundant
I suggest separated regex condition (testing for value) and length (testing for length)
Ternary operator ? : must return a value, in you case you want to call a method - Console.WriteLine; stick to if
regex = new Regex(...) is possible, but I don't think it's good in the context. You want to test just once: Regex.IsMatch(...) is more readable
Code:
Console.WriteLine("Enter a two-digit number:");
// Trim: let us be nice and tolerate leading and trailing spaces
// (esp. in case user put it with copy-pasting)
entry = Console.ReadLine().Trim();
// Just check the length
if (entry.Length > 2)
{
Console.WriteLine("The number is longer than two-digit, please try again!");
}
// Check for length smaller than two-digit
else if (entry.Length < 2)
{
Console.WriteLine("The number is shorter than two-digit, please try again!");
}
// The length is correct, time to check the value
else if (!Regex.IsMatch(entry, "^[0-9]{2}$")) // <- just a static method
{
Console.WriteLine("The input is not 2 digit number, please try again!")
}
// The entry is valid, let's ptint the result out
else
{
// You don't have to parse and do arithmetic
// if you want to convert char to corresponding digit: '7' -> 7
int digit1 = entry[0] - '0';
int digit2 = entry[1] - '0';
// String interpolation is often more readable than formatting
Console.WriteLine(
$"The number has on the first place {digit1} and on the second place {digit2}");
}
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 6 years ago.
Improve this question
I want an solution to convert an input int say 010 to list of int {0,1,0}.
Below is code I tried, works until 0 is encountered.
Int num = 010;
List<int> listOfInt = new List<int>();
While(num > 0)
listOfInt.Add(num%10);
num / = 10;
I just want to split entered int and convert it to list of int. LINQ is fine if that could be efficient!
As others already mentioned 010 is identical to 10 when having parsed as int. However you could have your number as string coming from a console-input for example.
string myNumber = "010";
This can be split on every character quite easy using LINQ:
var intList = myNumber.Select(x => Convert.ToInt32(x.ToString())).ToList();
As every character is internally an int where '0' equals 49 you have to convert every single character to a string before which is done by using ToString.
Console.WriteLine("Enter a number:")
var input = Console.ReadLine();
List<int> result = input.Select(c => int.Parse(c.ToString())).ToList();
There is no difference between 010 and 10 either in computer arithmetic or real life. Zero is zero.
If you want to convert the number to a specific string format and extract the characters, perform the same steps as the statement:
10.ToString("000").Select(c=>c-48).ToList();
The result is a list with the numbers 0,1,0.
The expression c-48 takes advantage of the fact that characters are essentially ints, and digits start from 0 upwards. So 48 is 0, 1 is 49 etc.
If the input is a string, eg "10" you'll have to pad it with 0s up to the desired length:
"10".PadLeft(3,'0').Select(c=>c-48).ToList()
The result will be 0,1,0 again.
If, after all, you only want to retrieve characters from a paddes string, you only need padding, as a String is an IEnumerable. You can copy the characters to an array with String.ToCharArray() or to a List as before:
"10".PadLeft(3,'0').ToList()
string num = "010";
List<int> listOfInt = new List<int>();
foreach(char item in num)
{
listOfInt.Add(Convert.ToInt32(item.ToString()));
}
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 7 years ago.
Improve this question
I have an assignment that requires a lot conversions between different units of measure. I have all of the work done except the math part. My question is, and if anyone has a better solution im all ears, would it be best to do these calculations using a switch or an if statement? Here is a little background info about my program. I have a text file that contains 9 different units of measurement along with their lengths in terms of feet separated by a comma that looks like as follows:
inch,.083333
fathom,6
foot,1
furlong,660
kilometer,3281.5
meter,3.2815
mile,5280
rod,16.5
yard,3
So, i have successfully dumped all of the information into a string array. From there i split the string array twice. The first time i split the string array, i created a new string array that would hold only the names for each unit of measure. The second time i split the string array, i did it so i could create a double array to hold all of the numeric values for each unit of measurement. Now i need to do the math portion. My program is going to display the nine different units of measure, request the unit to convert from, requests the unit to convert to, request the quantity (or total measurement) to convert, and then display the converted quantity. SO far this is what i have:
private void SandC_Load(object sender, EventArgs e)
{
splitContainer1.Panel1Collapsed = false;
splitContainer1.Panel2Collapsed = true;
string[] lengths = File.ReadAllLines("Units.txt");
int count=0;
string[] unitName=new string[count];
while (!(count==10))
{
count++;
lbLengths.Items.Add(count+"."+" "+lengths[count-1].Split(new Char[]{','})[0]);
}
}
private void btnConvert_Click(object sender, EventArgs e)
{
string orginalunits = tborginalUnits.Text;
int orginalunits1;
string desiredunits = tbDesiredunits.Text;
int desiredunits1;
string lenghttoConvert = tbConvert.Text;
double lenghttoConvert1;
string[] lengths = File.ReadAllLines("Units.txt");
int count = lengths.Length;
double[] units = new double[lengths.Length];
for (int i = 0; i < lengths.Length;i++)
{
units[i] = Convert.ToDouble(lengths[i].Split(new Char[] { ',' })[1]);
}
if ((double.TryParse(lenghttoConvert, out lenghttoConvert1)) && (Int32.TryParse(orginalunits, out orginalunits1)) && (Int32.TryParse(desiredunits, out desiredunits1)))
{
if ((desiredunits1==3)&&(orginalunits1==1))
{
double answer;
answer = units[0] * lenghttoConvert1;
Math.Round(answer, 3);
mtbOutput.Text = Convert.ToString(answer);
lblConversion.Text = "Converted to foot length";
}
}
else
MessageBox.Show("In the'Orginal and Desired Units' boxes, please enter only the numbers 1 -9, and in the 'Length to Covert' Box, please enter only numbers");
}
So as you can see in the button click event, i am at the part where the conversions should take place. My question, once again, is what would be the best method i should use to handle all of these calculations? I already have 1 if statement, and if i am going to do if statements, i feel as if it will be very tedious and was wondering if there was a more efficient way of doing this. Thanks for your help guys, i really do appreciate it.
The best approach is to use a little math to avoid conditionals altogether.
No matter what's the original and target units are, you can do the conversion through by converting the original units to feet and then converting feet to the target unit.
Let's say you want to go from X units at index i to units at index j. All you need to do is dividing X by units[i], and multiplying by units[j]. No conditionals or switches are required.
How would the program know which unit to choose?
This depends on the organization of your program. This could be a very simple task if you use drop-down boxes for unit names in your UI, because the index of the selected item will be the same as the index of the conversion rate in the units[] array.
Given this specific example, if statements and switch statements are both redundant.
Another way to solve this would be to create a mapping table (two dimensional array) where you specify the conversion multiplier between both units especially that your code already uses digits to represent units instead of their actual names.
For example
C[1][1] = 1;
C[1][2] = 3.1;
C[1][3] = 5;
C[1][4] = 0.33;
C[2][1] = 1/C[1][2];
....
....
C[4][1] = 1/C[1][4];
After creating that array, you can simply plugin the numbers depending on the source and destination currencies to do the conversion.
You can further improve on the above by creating one or two if statement that check whether the first parameter for the array is less than the second or not. If yes, then take the value as it is, if not take the reciprocal of the value. Therefore, you dont have to fill the entire array with values such as:
C[2][1] = 1/C[1][2];
C[4][1] = 1/C[1][4];
Hope that helped.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am trying to write a program which will calculate the molecular weight of a given molecule based on its chemical formula.
This code can split a molecular formula like "CH3OH" to an array {C H 3 O H} but from here, what would be a good way to use the split text to calculate the molecular weight?
string input = MoleculeTextbox.text;
string pattern = #"([0-9]?\d*|[A-Z][a-z]{0,2}?\d*)";
string[] sunstrings = Regex.Split(input,pattern);
First of all, you'd need to parse the string and turn "H3" into "HHH", etc. That might look something like this:
var x = "CH3OH".replace(/([a-z])([2-9])/gi, function(_,c,n) { return new Array(1+parseInt(n)).join(c); });
First group being the matched character, and second group being the number of repetitions.
You now have a string that looks like "CHHHOH". You can split that line into an array with one character at each index, .split(''), and map each value to its molecular mass. For that you need to define some sort of lookup table. I'm using reduce to take care of the mapping and the addition in one go:
var mass = { C: 12.011, H: 1.008, O: 15.999 };
var weight = x.split('').reduce(function(sum,element) { return sum + mass[element]; }, 0);