c# array outputs 0 when it isnt specified - c#

I am trying to output the odd and even numbers of an array, i have got it all working but for some reason when i create a foreach loop and output each number that is odd/even it starts with a zero?
The way it is setup that the user inputs 10 numbers with a comma in between each letter (Starts as a string) and then it removes the comma and converts the numbers into an int and places it in an int array, to then be used in the other class. I input 1,2,3,4,5,6,7,8,9,1 to test it.
Odds(ai.Odds);
Evens(ai.Evens);
Console.ReadKey();
}
public static void Odds(int[] odds)
{
Console.WriteLine("\nOdds:");
foreach (var odd in odds)
{
Console.Write(odd + " ");
}
}
public static void Evens(int[] evens)
{
Console.WriteLine("\nEvens:");
foreach (var even in evens)
{
Console.Write(even + " ");
}
}
and in the separate class doing the magic:
public int[] Odds
{
get
{
int count = 0;
int[] odds = new int[NumArray.Length];
string[] oddNums = {"1", "3", "5", "7", "9"};
foreach (int num in NumArray)
{
foreach (string oddNum in oddNums)
{
if (num.ToString().EndsWith(oddNum))
{
odds[count++] = num;
}
}
}
Array.Sort(odds);
return RemoveDuplicates(odds);
}
}
public int[] Evens
{
get
{
int count = 0;
int[] evens = new int[NumArray.Length];
string[] evenNum = {"0", "2", "4", "6", "8"};
foreach (int num in NumArray)
{
foreach (string oddNum in evenNum)
{
if (num.ToString().EndsWith(oddNum))
{
evens[count++] = num;
}
}
}
Array.Sort(evens);
return RemoveDuplicates(evens);
}
}
Here is the RemoveDuplicates Method:
private int[] RemoveDuplicates(int[] numbers)
{
if (numbers.Length == 0)
{
return numbers;
}
int[] uniques = new int[numbers.Length];
int previousVal = numbers[0];
uniques[0] = numbers[0];
int count = 1;
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i] == previousVal) continue;
previousVal = numbers[i];
uniques[count++] = numbers[i];
}
Array.Resize(ref uniques, count);
return uniques;
}
as an output i get(vvv), but i don't want the 0's at the beginning of them both, i don't want a 0 at all

but i don't want the 0's at the beginning of them both, i don't want a 0 at all
Then you shouldn't create an array with 0s in, which is what you're doing.
Before you call Array.Sort(odds), your array will have all the odd numbers from NumArray, followed by a bunch of 0 values (as many as there are even values in NumArray), because when you construct an array, it is automatically filled with the default value of the element type for each element. You'll only have no 0 values if the whole of NumArray is odd.
You only want as many elements as you need, so it would be better to use List<int>, and just add to that when you need to. You can call ToArray() to create an array at the end, if you really need to.

When you're assigning values to the evens and odds arrays, you're using [count++] as the index. This means that it's never assigning index 0 and it'll have a default value of 0 from when the array was initialised.

Related

Join element from array if the array element length is less than 5

I am trying to join the next array element together to single element from array if the element of the array is less than length 4. It should add to the next element index.
Another logic is, if the next consecutive array length is also less then 4 char then it joins the next array element also up to 3 times in total. I want to implement this. It's getting complex for me I am not understand this logic.
This is the code, here it has array on titleList, now we have to use the above logic in this array list.
#foreach (var title in randomtitle)
{
</span>#titleList.ElementAt(title)</span>
}
#code {
[Parameter]
public string theTitle { get; set; }
private string[] titleList = Array.Empty<string>();
protected override void OnParametersSet()
{
if (!string.IsNullOrEmpty(theTitle))
{
titleList = theTitle.Split(" ");
}
}
private Random random = new();
private IEnumerable<int> randomtitle =>
Enumerable.Range(0, titleList.Count() - 1) // { 0, 1, 2, 3 } generate sequence
.OrderBy(x => random.Next()) // { 3, 1, 0, 2 } random shuffle
.Take(2) // { 3, 1 } pick two
.ToList();
}
I think you are looking for a method that does following:
take a collection of strings(like a string[])
iterate each string and check if it's length is greater than or equal 4
if so, everything is fine, take it as it is
if not, append the next to the current string and check their length afterwards
if they are still not greater than or equal 4 append the next one, but max 3 times
Then this should work (not tested well though):
Demo: https://dotnetfiddle.net/2uHREv
static string[] MergeItems(IList<string> all, int minLength, int maxGroupCount)
{
List<string> list = new List<string>(all.Count);
for(int i = 0; i < all.Count; i++)
{
string current = all[i];
if(i == all.Count - 1)
{
list.Add(current);
break;
}
if (current.Length < minLength)
{
for (int ii = 1; ii < maxGroupCount && i + ii < all.Count; ii++)
{
int nextIndex = i + ii;
string next = all[nextIndex];
current = current + next;
if (current.Length >= minLength || ii+1 == maxGroupCount)
{
list.Add(current);
i = nextIndex;
break;
}
}
}
else
{
list.Add(current);
}
}
return list.ToArray();
}

Is there a way to searchfor duplicate entries in an array in c#

I'm trying to code a Yahtzee game in C# with the .NET Framework in C#, but couldn't find a way for check if a fullhouse, three of a kind or four of a kind was generated. For all other possibilities I save the numbers in an Array and check with an if statement if an 1 or 2 is in it.
This is my code:
string[] numbers = { number1, number2, number3, number4, number5 };
if (numbers.Contains(1)) {
foreach (int i in numbers)
{
if (i == "1")
{
int num = num + 1;
}
}
}
If you need to count how many times a number repeats in your array you can use Linq GroupBy
The output of this code
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string[] numbers = new string[] { "1", "2", "1", "2", "1" };
var groups = numbers.GroupBy(n => n);
foreach (var g in groups) {
Console.WriteLine($"Number: {g.Key} Count: {g.Count()}");
}
}
}
is
Number: 1 Count: 3
Number: 2 Count: 2
You have an unnecessary check, 2 syntax errors, and a logical error (see comments in code):
string[] numbers = { "1", "1", "2", "3", "6" };
// Not needed because it will internally iterate the array, which you then
// do in your own code:
// if (numbers.Contains("1")) // Also, your code used an int rather than string
int numberOfOnes = 0;
foreach (var i in numbers) // Not type int
{
if (i == "1")
{
// Don't declare inside the loop since you get a fresh variable each time:
//int num = num + 1;
numberOfOnes++;
}
}
// Outputs 2 as expected:
Console.WriteLine($"Number of ones: {numberOfOnes}");
You can also accomplish this with a single line of Linq:
var numberOfOnes = numbers.Where(n => n == "1").Count();
There are quite a few syntax errors in the code you posted but you could use a method along these lines:
public static bool IsYahtzee(string[] numbers)
{
if(numbers.All(x => x == numbers[1]))
return true;
return false;
}
This obviously assumes all of these string values are valid numbers but it will return true if all the values in the array are equal to the first value in the array.

c# finding even or odd numbers

Question: You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.
Examples
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)
[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)
Problem: I can find the target number. It is "6" in this instance. But when i try to write it, it is written 3 times. I did not understand why it is not written once.
namespace sayitoplamları
{
class Program
{
static void Main(string[] args)
{
int[] integers;
integers = new int[] {1,3,5,6};
int even = 0;
int odd = 0;
foreach (var num in integers)
{
if (num%2==0)
{
even += 1;
}
else
{
odd += 1;
}
if (even>1)
{
foreach (var item in integers)
{
if (item%2!=0)
{
Console.WriteLine(item);
}
}
}
else if (odd>1)
{
foreach (var item in integers)
{
if (item%2==0)
{
Console.WriteLine(item);
}
}
}
}
}
}
}```
Since we are doing this assignment for a good grade :)
We really don't need to count both odd and even elements and can just count odd once as it more convenient - just add up all remainders ( odd % 2 = 1, even % 2 = 0). If we would need number of even elements it would be array.Length - countOdd.
int countOdd = 0;
for (int i = 0; i < array.Length; i++) // or foreach
{
countOdd += array[i] % 2;
}
If you feel that trick with counting is too complicated and only needed for A+ mark on the assignment than variant of your original code is fine:
int countOdd = 0;
foreach (int element in array)
{
if (element % 2 == 1)
countOdd ++; // which is exactly countOdd += 1, just shorter.
}
Now for the second part - finding the outlier. We don't even need to know if it is Odd or Even but rather just reminder from "% 2". We now know how many odd element - which could be either 1 (than desired remainder is 1 - we are looking for odd element) or more than one (then desired remainder is 0 as we are looking for even one).
int desiredRemainder = countOdd == 1 ? 1 : 0;
Now all its left is to check which element has desired remainder and return from our method:
foreach (int element in array)
{
if (element % 2 == desiredRemainder)
{
return element;
}
}
Please note that assignment asks for "return" and not "print". Printing the value does not allow it to be used by the caller of the method unlike returning it. Using early return also saves some time to iterate the rest of array.
Complete code:
int FindOutlier(int[] array)
{
int desiredReminder = array.Sum(x => x % 2) == 1 ? 1 : 0;
return array.First(x => x % 2 == desiredReminder);
}
Alternative solution would be to iterate array only once - since we need to return first odd or first even number as soon as we figure out which one repeats similar how your tried with nested foreach. Notes since we are guaranteed that outlier present and is only one we don't need to try to remember first number - just current is ok.
int FindOutlier(int[] array)
{
int? odd = null; // you can use separate int + bool instead
int? even = null;
int countOdd = 0;
int countEven = 0;
foreach (int element in array)
{
bool isEven = element % 2 == 0;
if (isEven)
{
countEven++;
even = element;
}
else
{
countOdd++;
odd = element;
}
if (countEven > 1 && odd.HasValue)
return odd.Value;
if (countOdd > 1 && even.HasValue)
return even.Value;
}
throw new Exception("Value must be found before");
}
And if you ok to always iterate whole list code will be simple as again we'd need to only keep track of count of odd numbers (or even, just one kind) and return would not need to check if we found the value yet as we know that both type of numbers are present in the list:
int FindOutlier(int[] array)
{
int odd = 0;
int even = 0;
int countEven = 0;
foreach (int element in array)
{
if (element % 2 == 0)
{
countEven++;
even= element;
}
else
{
odd = element;
}
}
return countEven > 1 ? odd : even;
}
You are mixing everything into a single algorithm. In most cases it's a better idea to have separate steps. In your case, the steps could be:
Count odds and evens
Find the outlier
Print the result
That way you can make sure that the output does not interfere with the loops.
class Program
{
static void Main(string[] args)
{
int[] integers;
integers = new int[] {1,3,5,6};
int even = 0;
int odd = 0;
// Count odds and evens
foreach (var num in integers)
{
if (num%2==0)
{
even += 1;
}
else
{
odd += 1;
}
}
// Find the outlier
var outlier = 0;
foreach (var item in integers)
{
if (even == 1 && item%2==0)
{
outlier = item;
break;
}
if (odd == 1 && item%2!=0)
{
outlier = item;
break;
}
}
// Print the result
Console.WriteLine(outlier);
}
}
You could even make this separate methods. It also makes sense due to SoC (separation of concerns) and if you want to achieve testability (unit tests).
You want a method anyway and use the return statement, as mentioned in the assignment
Write a method that takes the array as an argument and returns this "outlier" N.
Maybe you want to check the following code, which uses separate methods:
class Program
{
static void Main(string[] args)
{
int[] integers;
integers = new int[] { 1, 3, 5, 6 };
var outlier = FindOutlier(integers);
Console.WriteLine(outlier);
}
private static int FindOutlier(int[] integers)
{
if (integers.Length < 3) throw new ArgumentException("Need at least 3 elements.");
bool isEvenOutlier = IsEvenOutlier(integers);
var outlier = FindOutlier(integers, isEvenOutlier ? 0:1);
return outlier;
}
static bool IsEvenOutlier(int[] integers)
{
// Count odds and evens
int even = 0;
int odd = 0;
foreach (var num in integers)
{
if (num % 2 == 0)
{
even += 1;
}
else
{
odd += 1;
}
}
// Check which one occurs only once
if (even == 1) return true;
if (odd == 1) return false;
throw new ArgumentException("No outlier in data.", nameof(integers));
}
private static int FindOutlier(int[] integers, int remainder)
{
foreach (var item in integers)
{
if (item % 2 == remainder)
{
return item;
}
}
throw new ArgumentException("No outlier in argument.", nameof(integers));
}
}
The reason it is printing '6' 3 times is because you iterate over the inetegers inside a loop where you iterate over the integers. Once with num and again with item.
Consider what happens when you run it against [1,3,5,6].
num=1, you get odd=1 and even=0. Neither of the if conditions are true so we move to the next iteration.
num=3, you get odd=2 and even=0. odd > 1 so we iterate over the integers (with item) again and print '6' when item=6.
num=5, you get odd=3 and even=0. Again, this will print '6' when item=6.
num=6, you get odd=3 and even=1. Even though we incremented the even count, we still have odd > 3 so will print '6' when item=6.
It is best to iterate over the values once and store the last even and last odd numbers along with the count (it is more performant as well).
You can then print the last odd number if even > 0 (as there will only be one odd number, which will be the last one) or the last even number if odd > 0.
I.e.
namespace sayitoplamları
{
class Program
{
static void Main(string[] args)
{
int[] integers;
integers = new int[] { 1, 3, 5, 6 };
int even = 0;
int? lastEven = null;
int odd = 0;
int? lastOdd = null;
foreach (var num in integers)
{
if (num % 2 == 0)
{
even += 1;
lastEven = num;
}
else
{
odd += 1;
lastOdd = num;
}
}
if (even > 1)
{
Console.WriteLine(lastOdd);
}
else if (odd > 1)
{
Console.WriteLine(lastEven);
}
}
}
}
because you didn't close the the first foreach loop before printing...
namespace sayitoplamları
{
class Program
{
static void Main(string[] args)
{
int[] integers;
integers = new int[] {1,3,5,6};
int even = 0;
int odd = 0;
foreach (var num in integers)
{
if (num%2==0)
{
even += 1;
}
else
{
odd += 1;
}//you need to close it here
if (even>1)
{
foreach (var item in integers)
{
if (item%2!=0)
{
Console.WriteLine(item);
}
}
}
else if (odd>1)
{
foreach (var item in integers)
{
if (item%2==0)
{
Console.WriteLine(item);
}
}
}
}
}//not here
}
}

Parse a single array to array 2D from index with greater than 5 characters

I'm new to c# and want to process strings according to the following pattern:
var data = new List<object> { "ABCDEFGHIJKLMNO", 80, "TestMain", "PQRSTUVWXY" };
/*
- if string contains > 5 characters --> Split
- check, which is the longest array from the split
- use the longest split to be an array 2D
*/
// expected result
var new_data = new List<object[]> {
new object[] { "ABCDE", 80, "TestM", "PQRST" },
new object[] { "FGHIJ", " ", "ain", "UVWXY" },
new object[] { "KLMNO", " ", " ", " " }
}
You will have to constrain your List<object> to a List<string>, since you cannot assure a valid conversion back to the original type, once you split it.
var data = new List<object> { "ABCDEFGHIJKLMNO", 80, "TestMain", "PQRSTUVWXY" };
List<string> stringData = data.Select(o => o.ToString()).ToList();
const int maxCharacters = 5;
int nrOfEntries = data.Count;
List<string[]> result = new List<string[]>();
while (true)
{
bool finished = true;
string[] newRow = new string[nrOfEntries];
for (int i = 0; i < nrOfEntries; i++)
{
string currentString = stringData[i];
if (string.IsNullOrEmpty(currentString))
{
newRow[i] = " ";
continue;
}
int length = currentString.Length;
int charactersToTake = Math.Min(length, maxCharacters);
int charactersRemaining = length - charactersToTake;
newRow[i] = currentString.Substring(0, charactersToTake);
switch (charactersRemaining)
{
case 0:
stringData[i] = null;
break;
default:
stringData[i] = currentString.Substring(charactersToTake, charactersRemaining);
finished = false;
break;
}
}
result.Add(newRow);
if(finished)
break;
}
You could use List<object[]> result, but that list will only contain strings (and will only be useful as such) since there is no way you can convert back arbitrary objects, as stated before.
I would use Linq to solve the problem. (Be sure you have using System.Linq; at the top of your code file!)
First of all, we define a function to break down an object into several strings with length 5 or less or the object itself, if it is not a string.
object[] BreakDownObject(object o)
=> BreakDownObjectToEnumerable(o).ToArray();
IEnmuerable<object> BreakDownObjectToEnumerable(object o)
{
// If object is string, thant yield return every part
// with 5 characters (or less than 5, if necessary,
// for the last one)
if(o is string s)
{
for(int i = 0; i < s.Length; i += maxStringLength)
{
yield return s.Substring(i, Math.Min(s.Length - i, maxStringLength));
}
}
// object is not a string, don't break it up
else
{
yield return o;
}
}
Wie use Substring in Combination with Math.Min. If length - index is smaller than 5, than we use this instead for the substring.
If we use this function on all items of the list we get an array of arrays of object. This array could be interpreted as "columns", because the first index gives us the columns, and the second index the subsequent broken down strings.
var data = new List<object> { "ABCDEFGHIJKLMNO", 80, "TestMain", "PQRSTUVWXY" };
object[][] columns = data.Select(BreakDownObject).ToArray();
Now we want to transpose the array, so rows first. We write a function, that takes an index and our array of arrays and returns the row with that index. (Again I use Linq-IEnumerable for easier creation of the array):
object[] GetRowAtIndex(int index, object[][] columns)
=> GetRowAtIndexAsEnumerable(index, columns).ToArray();
IEnumerable<object> GetRowAtIndexAsEnumerable(int index, object[][] columns)
{
foreach(var column in columns)
{
// Each column has different length,
// if index is less than length, we
// return the item at that index
if(index < column.Length)
{
yield return column[index];
}
// If index is greater or equal length
// we return a string with a single space
// instead.
else
{
yield return " ";
}
}
}
This function also fills up missing items in the columns with a one-space string.
Last but not least, we iterate through the rows, until no column has items left:
List<object[]> GetAllRows(object[][] columns)
=> GetAllRowsAsEnumerable(columns);
Enumerable<object[]> GetAllRowsAsEnumerable(object[][] columns)
{
int index = 0;
while(true)
{
// Check if any column has items left
if(!columns.Any(column => index < column.Length))
{
// No column with items left, left the loop!
yield break;
}
// return the row at index
yield return GetRowAtIndex(index, columns);
// Increase index
++index;
}
}
Put it together as one function:
List<object[]> BreakDownData(List<object> data)
{
object[][] columns = data.Select(BreakDownObject).ToArray();
return GetAllRows(columns);
}
After that, your code would be:
var data = new List<object> { "ABCDEFGHIJKLMNO", 80, "TestMain", "PQRSTUVWXY" };
var new_data = BreakDownData(data);

How to sort large numbers stored in a string array?

I need to sort the large numbers stored as string in string array but my algorithm and .net built Array sort method doesn't work.
I tried to convert the number into long or ulong but that throw exception of overflow.
Here is the code that I tried:
string[] unsorted = { "1","2","100","12303479849857341718340192371",
"3084193741082937","3084193741082938","111","200" };
for (int index = 0; index < unsorted.Length - 1; index++)
{
for (int count = 0; count < unsorted.Length - index - 1; count++)
{
if (string.Compare(unsorted[count], unsorted[count + 1]) == 1)
{
string temp = unsorted[count];
unsorted[count] = unsorted[count + 1];
unsorted[count + 1] = temp;
}
}
}
Also used the following method:
Array.Sort(unsorted);
The array should be sorted correctly.
You could use BigInteger.Parse and use Linq's OrderBy on it. For example:
var sorted = unsorted.Select(BigInteger.Parse).OrderBy(e => e).ToArray();
If you need it back as string:
var sorted = unsorted.Select(BigInteger.Parse).OrderBy(e => e).Select(e => e.ToString()).ToArray();
This has a drawback in converting it first to a BigInteger, but probably you need it anyway. However compared to IO and Database access, this nothing adds to a typical application performance.
Pro: Readable
Contra: Probably not the most efficient solution.
Try following :
string[] unsorted = { "1","2","100","12303479849857341718340192371",
"3084193741082937","3084193741082938","111","200" };
var groups = unsorted.OrderBy(x => x.Length).GroupBy(x => x.Length).ToArray();
List<string> results = new List<string>();
foreach (var group in groups)
{
string[] numbers = group.ToArray();
for(int i = 0; i < numbers.Count() - 1; i++)
{
for(int j = i + 1; j < numbers.Count(); j++)
{
if(numbers[i].CompareTo(numbers[j]) == 1)
{
string temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
results.AddRange(numbers);
}
You don't have an array of numbers, you have an array of strings. So they're being sorted alpha-numerically.
One option would be to use the BigInteger class to store them as numbers:
BigInteger[] unsorted = {
BigInteger.Parse("1"),
BigInteger.Parse("2"),
BigInteger.Parse("100"),
BigInteger.Parse("12303479849857341718340192371"),
BigInteger.Parse("3084193741082937"),
BigInteger.Parse("3084193741082938"),
BigInteger.Parse("111"),
BigInteger.Parse("200")
};
Failing that, if you want to keep them as strings then you can left-pad them with zeros to make the lengths consistent so the alphanumeric sorting would work:
string[] unsorted = {
"00000000000000000000000000001",
"00000000000000000000000000002",
"00000000000000000000000000100",
"12303479849857341718340192371",
"00000000000003084193741082937",
"00000000000003084193741082938",
"00000000000000000000000000111",
"00000000000000000000000000200"
};
If you choose the former, just change the types in your if block to also be BigInteger as well.
If we want to sort very big numbers stored as strings, without changing string to BigInteger, it's better sort them according to it's length at first and then according to lexicographic order. We can see the sample code below:
using System;
using System.Linq;
public class Test
{
public static void Main()
{
string[] unsorted = { "1","2", "100","12303479849857341718340192371",
"3084193741082937","3084193741082938","111","200" };
unsorted.OrderBy(s => s.Length).ThenBy(s => s);
Console.WriteLine("Sorted numbers are:");
foreach (var x in unsorted) {
Console.WriteLine(x);
}
}
}
Note: In order to use OrderBy and ThenBy functionality , we have to include using System.Linq to our program.
For an elegant solution you can use linq, you will have a minimum of code with good performance.
var result = unsorted.Select(e => decimal.Parse(e)).OrderBy(e => e);
The system must be like following. You can transfer values in the array to an arraylist then you can parse them all to BigInteger by for loop. And finally you can sort the list :
BigInteger[] unsorted;
var bigIntegers = new List<System.Numerics.BigInteger>();
for (int index = 0; index < unsorted.Length - 1; index++)
{
bigIntegers[i] = BigInteger.Parse[i]
}
bigIntegers.sort();
Another variation:
static void Main(string[] args)
{
List<string> unsorted = new List<string>(new string[] {"1","2","100","12303479849857341718340192371",
"3084193741082938","3084193741082937", "111","200" });
unsorted.Sort((x, y) => (x.Length != y.Length ? x.Length.CompareTo(y.Length) : x.CompareTo(y)));
foreach(string number in unsorted)
{
Console.WriteLine(number);
}
Console.Write("Press Enter to quit");
Console.ReadLine();
}
Building upon #jdweng's answer, but further reducing it by eliminating the 'manual' bubble sort:
string[] result =
unsorted.OrderBy(x => x.Length)
.GroupBy(x => x.Length)
.SelectMany(x => x.OrderBy(y => y))
.ToArray();
Or some other variation of the same theme:
using System.Collections.Generic;
using System.Linq;
...
string[] result =
unsorted.OrderBy(x => x, Comparer<string>.Create((a, b) => a.Length == b.Length ? a.CompareTo(b) : a.Length - b.Length))
.GroupBy(x => x.Length)
.SelectMany(x => x)
.ToArray();
(As noted by #fester's comment underneath #jdweng's answer, this approach will not work reliably if some of the strings are numbers with prepended zeros, such as "00123" for example.)
package com.solution.sorting;
import java.util.Arrays;
import java.util.Comparator;
public class ArraySort {
public static void main(String[] args) {
String[] number = { "3", "2", "4", "10", "11", "6", "5", "8", "9", "7" };
String[] unsorted = { "8", "1", "2", "100", "12303479849857341718340192371", "3084193741082937",
"3084193741082938", "111", "200" };
Arrays.sort(number);
for (String s : number)
System.out.println("number="+s);
//
Arrays.sort(unsorted, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return compareStrings(o1,o2);//Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
});
for (String s : unsorted)
System.out.println("number1=" + s);
}
private static int compareStrings(String s1, String s2) {
//
if (s1.length() < s2.length()) {
return -1;
} else if (s1.length() > s2.length()) {
return 1;
}
for (int i = 0; i < s1.length(); i++) {
if ((int) s1.charAt(i) < (int) s2.charAt(i))
return -1;
if ((int) s1.charAt(i) > (int) s2.charAt(i))
return 1;
}
return 0;
}
}
For extremely large numbers where Primitive Data Types might fail, create a Comparator that first sorts the String by length and then sorts the String by the value of the same length.
Arrays.sort(array, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
/** Sort by Length */
if (o1.length() < o2.length()) {
return -1;
}
if (o1.length() > o2.length()) {
return 1;
}
/** Sort by the value of the same Length */
return o1.compareTo(o2);
}
});

Categories

Resources