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);
}
Related
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)
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 have a List<int[]> that I populated by splitting an integer array into 4 groups. Now I need to get the difference of the two highest numbers in the array. I tried Array.Sort but I am stuck on how to continue.
What I have done so far?
public static void solution(int[] T)
{
List<int[]> splitted = new List<int[]>();//This list will contain all the splitted arrays.
int lengthToSplit = T.Length / 4;
int arrayLength = T.Length;
for (int i = 0; i < arrayLength; i = i + lengthToSplit)
{
int[] val = new int[lengthToSplit];
if (arrayLength < i + lengthToSplit)
{
lengthToSplit = arrayLength - i;
}
Array.Copy(T, i, val, 0, lengthToSplit);
splitted.Add(val);
}
//this is the part where I must get the difference between the two highest numbers in an integer array and put into another list.
foreach (int[] integerarray in splitted)
{
//get the difference of the two highest numbers per integer array and place it on another List<int>
}
}
get the difference between the two highest numbers in an integer array
and put into another list
You can use LINQ and Math.Abs:
List<int> differenceList = splitted
.Select(list => list.OrderByDescending(i => i).Take(2).ToArray())
.Select(highestTwo => Math.Abs(highestTwo[0] - highestTwo[1]))
.ToList();
This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 5 years ago.
I stumbled across this challenge when I needed to calculate a check number/digit from the individual digits of the number itself.
E.g. I have the number (Int32) 423594340 and I want a collection of integers like 4,2,3,5,9,4,3,0.
I think it is better to not convert the given int into a String because of performance.
But how do you do that instead?
I came up with an individual puzzled out solution.
#1: Own created solution
public static IEnumerable<int> GetDigits(int source)
{
int individualFactor = 0;
int tennerFactor = Convert.ToInt32(Math.Pow(10, source.ToString().Length));
do
{
source -= tennerFactor * individualFactor;
tennerFactor /= 10;
individualFactor = source / tennerFactor;
yield return individualFactor;
} while (tennerFactor > 1);
}
#2: Modulo with Linq's .Reverse()
After that I explored the Internet for other solutions and I came across one from the Java folks: How to get the separate digits of an int number?
The downside is that the order of integers in the collection is reversed. Here comes Microsoft's Linq.
How to call the method with .Reverse().
...
GetDigits2(input).Reverse()
...
And the actual method.
public static IEnumerable<int> GetDigits2(int source)
{
while (source > 0)
{
var digit = source % 10;
source /= 10;
yield return digit;
}
}
#3: Modulo with Stack's LIFO
What else could I do when I do not want to think about calling .Revers() after the method (GetDigits2(int source))? So I use a variable inside the method, call .Reverse() on the variable and return its result instead.
Or something totally different: I remember the LIFO logic. In .NET you use the Stack class for that.
public static IEnumerable<int> GetDigits3(int source)
{
Stack<int> digits = new Stack<int>();
while (source > 0)
{
var digit = source % 10;
source /= 10;
digits.Push(digit);
}
return digits;
}
Testing
I tested each method 10 million times and measured the number of tickes between start and end of the test.
#1: Own Created method
1'549'084 ticks
#2: Modulo with Linq's .Reverse()
2'252'875 ticks
#3: Modulo with Stack's LIFO
23'626'839 ticks
tl;dr
Here comes the fiddle: Get Digits from int
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()));
}
I have a number like 601511616
If all number's length is multiple of 3, how can a split the number into an array without making a string
Also, how can I count numbers in the int without making a string?
Edit: Is there a way to simply split the number, knowing it's always in a multiple of 3... good output should look like this: {616,511,601}
You can use i % 10 in order to get the last digit of integer.
Then, you can use division by 10 for removing the last digit.
1234567 % 10 = 7
1234567 / 10 = 123456
Here is the code sample:
int value = 601511616;
List<int> digits = new List<int>();
while (value > 0)
{
digits.Add(value % 10);
value /= 10;
}
// digits is [6,1,6,1,1,5,1,0,6] now
digits.Reverse(); // Values has been inserted from least significant to the most
// digits is [6,0,1,5,1,1,6,1,6] now
Console.WriteLine("Count of digits: {0}", digits.Count); // Outputs "9"
for (int i = 0; i < digits.Count; i++) // Outputs "601,511,616"
{
Console.Write("{0}", digits[i]);
if (i > 0 && i % 3 == 0) Console.Write(","); // Insert comma after every 3 digits
}
IDEOne working demonstration of List and division approach.
Actually, if you don't need to split it up but only need to output in 3-digit groups, then there is a very convenient and proper way to do this with formatting.
It will work as well :)
int value = 601511616;
Console.WriteLine("{0:N0}", value); // 601,511,616
Console.WriteLine("{0:N2}", value); // 601,511,616.00
IDEOne working demonstration of formatting approach.
I can't understand your question regarding how to split a number into an array without making a string - sorry. But I can understand the question about getting the count of numbers in an int.
Here's your answer to that question.
Math.Floor(Math.Log10(601511616) + 1) = 9
Edit:
Here's the answer to your first question..
var n = 601511616;
var nArray = new int[3];
for (int i = 0, numMod = n; i < 3; numMod /= 1000, i++)
nArray[i] = numMod%1000;
Please keep in mind there's no safety in this operation.
Edit#3
Still not perfect, but a better example.
var n = 601511616;
var nLength = (int)Math.Floor(Math.Log10(n) + 1)/ 3;
var nArray = new int[nLength];
for (int i = 0, numMod = n; i < nLength; numMod /= 1000, i++)
nArray[i] = numMod%1000;
Edit#3:
IDEOne example http://ideone.com/SSz3Ni
the output is exactly as the edit approved by the poster suggested.
{ 616, 511, 601 }
Using Log10 to calculate the number of digits is easy, but it involves floating-point operations which is very slow and sometimes incorrect due to rounding errors. You can use this way without calculating the value size first. It doesn't care if the number of digits is a multiple of 3 or not.
int value = 601511616;
List<int> list = new List<int>();
while (value > 0) // main part to split the number
{
int t = value % 1000;
value /= 1000;
list.Add(t);
}
// Convert back to an array only if it's necessary, otherwise use List<T> directly
int[] splitted = list.ToArray();
This will store the splitted numbers in reverse order, i.e. 601511616 will become {616, 511, 601}. If you want the numbers in original order, simply iterate the array backwards. Alternatively use Array.Reverse or a Stack
Since you already know they are in multiples of 3, you can just use the extracting each digit method but use 1000 instead of 10. Here is the example
a = 601511616
b = []
while(a):
b.append(a%1000)
a = a//1000
print(b)
#[616, 511, 601]