DEV Community

loading...

Discussion on: Daily Challenge #12 - Next Larger Number

Collapse
praneetnadkar profile image
Praneet Nadkar

I know I am late.
This what I did in C#

static void Main()
{
     Console.WriteLine("Enter any integer: ");
     var read = Console.ReadLine();
     var referrer = new string(read.ToCharArray().OrderBy(i => i).ToArray());
     var input = read.ToCharArray().Select(x => int.Parse(x.ToString())).ToList();
     var first = int.Parse(read);
     var last = int.Parse(string.Join("", input.OrderByDescending(i => i).ToArray()));
     var permutations = Enumerable.Range(first, last).ToList();
     var container = new List<int>();
     foreach (var item in permutations)
     {
       var reference = new string(item.ToString().ToCharArray().OrderBy(i => i).ToArray());

       int c = string.Compare(referrer, reference);
       if (c != 0) continue;        
        container.Add(int.Parse(item.ToString()));
     }

     var inputNumberIndex = container.IndexOf(int.Parse(read));
     if (inputNumberIndex >= 0)
     {
        if (container.Count == 0) Console.WriteLine(container.FirstOrDefault());

        var findIndex = inputNumberIndex + 1;
        Console.WriteLine(container[findIndex]);
     }
     else
     {
       Console.WriteLine("-1");
     }


   Console.ReadKey();
 }