How to convert int to List<int> [closed] - c#

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()));
}

Related

Fill in numbers in order between two numbers [closed]

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 3 months ago.
Improve this question
Let's say you have two numbers, 4 and 9. The numbers can't be less than 0 or more than 9.
I want to fill the gap between 4 and 9 with numbers in correct order like so:
456789
How does one exactly do so? I've been stuck on this problem for the past 2 hours.
Thank you.
I have tried putting the numbers into an array and using the array's length as a way to fill in the numbers.
I've tried numerous other things that I don't know how to explain.
Just create a loop and loop thru all the integers between your numbers and add each number to a string if that is your desired output:
string CreateNumberSequence(int start, int end){
var sb = new StringBuilder();
for(int i = start; i <= end; i++){
sb.Add(i.ToString());
}
return sb.ToString();
}
Note that 10-12 would produce 101112, so you might want to add some separator between numbers, or just create a list of numbers and do the formatting separatly. You could also use Enumerable.Range, but if you are new to programming it is useful to know how to use plain loops.
If you want a list of numbers, change StringBuilder to List<int>, remove all the .ToString() and change the return-type. Or just use the previously mentioned Enumerable.Range.
You can use Enumerable.Range
int start = 4, end = 10;
int[] range = Enumerable.Range(start, end - start + 1).ToArray();
// range: 4 5 6 7 8 9 10
You can use the range method. since you know the start and end of the sequence you can put the start as 4 and the difference to the end from counting all the way from start will be 6.
and for 10-12 it will be like
var number = Enumerable.Range(10, 3);
var number = Enumerable.Range(4, 6);
var result = string.Join("", number.Select(x => x.ToString()).ToArray());
With extension methods :
public static class Ext
{
public static bool ToIntValue(this IEnumerable<int> source, out int output)
{
string joinedSource = string.Join(string.Empty, source);
return int.TryParse(joinedSource, out output);
}
public static IEnumerable<int> NumbersBetween(this int start, int end)
{
if (start > 0 && end <= 9 && start <= end)
{
for (int i = start; i <= end; i++)
yield return i;
}
else
{
throw new ArgumentException("Start and end must be beetween 1 and 9 and end must be bigger than start.");
}
}
}
use case :
if (1.NumbersBetween(9).ToIntValue(out int result))
{
Console.WriteLine(result);
}

Is there a function that swaps two variables in a string? [closed]

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 3 years ago.
Improve this question
So we have to have code that swaps the integers in a two-digit number, such as "43" being "34". The user inputs a random two digit number and that number must be swapped.
I am not sure how to separate or mess with the two digit number that the user inputs into the console, so I have not had much luck in doing this.
static void Main(string[] args)
{
Console.WriteLine("Please enter a two-digit integer");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
Console.ReadKey();
}
You can also just reverse the string before you parse it:
string input = string.Concat(Console.ReadLine().Reverse());
// If the user entered "34", 'input' will equal "43"
You can try modulo arithmetics:
number = number % 10 * 10 + number / 10;
you could do:
Console.WriteLine("Enter a No. to reverse");
int Number = int.Parse(Console.ReadLine());
int Reverse = 0;
while(Number>0)
{
int remainder = Number % 10;
Reverse = (Reverse * 10) + remainder;
Number = Number / 10;
}
Console.WriteLine("Reverse No. is {0}",Reverse);
Console.ReadLine();
this will give you 34 if you entered 43.
You can checkout this https://www.c-sharpcorner.com/blogs/reverse-a-number-and-string-in-c-sharp1 for more info.

How to multiple all digits of x number? [closed]

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.

How to write a toString method without using other class libraries [closed]

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 want to write my own toString method since I am not allowed to use any class libraries.
So I took a look into the source code of the toString method, but it uses a lot of other libraries. I want to convert an Integer into a String, but I am not sure how i can address the numbers one by one.
If I could do that, I could continue by casting the Integers into a Char and in the end add up all the Chars for a String.
Can someone help?
Here's a similar approach to the other answers.
The important points:
We calculate the last digit of a number by finding its remainder when it's divided by 10 (i.e. lastDigit = number % 10;)
To throw away the last digit of a number, simply divide it by 10.
When finding digits that way, they will of course be returned in reverse order (least significant digit first) so you have to reverse the digits to get the correct answer. One way to do this is to store from the end to the beginning of a char array.
Negative numbers have to be handled specially. The easiest way is to note that the number is negative so that a - sign can be added when appropriate; then, negate the number to make it positive. However, note that you can't negate int.MinValue, so that has to be handled specially.
You can convert from a numeric digit to its char equivalent by adding it to the char '0' and casting the result back to char.
Here's an approach that uses those points:
public static string MyToString(int number)
{
if (number == int.MinValue)
return "-2147483648"; // Special case.
char[] digits = new char[64]; // Support at most 64 digits.
int last = digits.Length;
bool isNegative = number < 0;
if (isNegative)
number = -number;
do
{
digits[--last] = (char) ('0' + number % 10);
number /= 10;
}
while (number != 0);
if (isNegative)
digits[--last] = '-';
return new string(digits, last, digits.Length-last);
}
I think the main part you were asking about is how to get the digits of a number one-by-one, which is answered by the do/while loop above.
[EDIT] Addressed the points raised in the comments below.
I don't understand why you're not allowed to use any libraries. But if you need to do the conversion entirely by hand, you could do it something like this
private static string IntToString(int i)
{
string[] digits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
string sign = (i < 0 ? "-" : "");
var absI = (i < 0 ? -i : i);
string result = "";
while (absI != 0)
{
int digit = absI % 10;
result = digits[digit] + result;
absI = (absI - digit) / 10;
}
return sign + result;
}
The code above doesn't work properly for zero. If you need that, it's very simple to add.
For example you can split your number into individual characters:
// Note that this is just for example and for positive numbers only.
IEnumerable<char> ToChar(int num)
{
while (num > 0)
{
// adding '0' to number will return char for that number
char ch = (char)(num % 10 + '0');
num /= 10;
yield return ch;
}
}
then create new string based on that:
string ToString(int num)
{
// ToChar will return char collection in reverse order,
// so you will need to reverse collection before using.
// Well in your situation you will be probably needed to
// to write Reverse method by yourself, so this is just for
// working example
var chArray = ToChar(num).Reverse().ToArray();
string str = new string(chArray);
return str;
}
and usage:
int i = 554;
string str = ToString(i);
References: DotNetFiddle Example (with simplified ToChar() method)

Short Id generation and maximum number of combinations

Okay this is probably more a maths question but since its related to programming and my web application i'll ask here first:
I'm trying to create short id's that are 8 characters long . The "pool" to draw the id from is a combination of numbers, upper and lower case letters.
string charPool = "ABCDEFGOPQRSTUVWXY1234567890ZabcdefghijklmHIJKLMNnopqrstuvwxyz"
And if you're interested here's the method:
private string GenerateRandomCode(int length)
{
string charPool = "ABCDEFGOPQRSTUVWXY1234567890ZabcdefghijklmHIJKLMNnopqrstuvwxyz";
StringBuilder rs = new StringBuilder();
for (int i = 0; i < length; i++)
{
rs.Append(charPool[(int)(_random.NextDouble() * charPool.Length)]);
}
return rs.ToString();
}
How many possible combinations are there for 8 character id's? Grateful if you can post the equation as well :)
Thanks
options per slot ^ number of slots = number of combinations
a-z is 26, times 2 (for uppers as well) is 52, plus 10 (0-9) is 62. Each ID is 8 chars long, so the result is 62^8, which is pretty big:
218,340,105,584,896 possible unique ID's
I would suggest doing:
_random.Next(charPool.Length - 1)
(and saving charPool.Length - 1 in a variable outside of the loop), instead of:
_random.NextDouble() * charPool.Length
Because you might get an exact 1.0 with .nextDouble(), which means you will be accessing the array at an index that equals the length, and you will get IndexOutOfRangeException.

Categories