Monday 11 September 2017

Rearrange the elements of an array of integers(positive) to form a maximum resulting number

Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the largest value



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test2
{
    class Program
    {
        static void Main(string[] args)
        {

            for (int y = 0; y< 1; y++)
            { 
            
            }

            string str = Console.ReadLine();
            string[] arr = str.Split(' ');
            
           //// int[] intarr = Array.ConvertAll(arr, x => int.Parse(x));
           // //int[] intArr = Array.ConvertAll(arr,int.Parse);
            int[] iArr = arr.Select(int.Parse).ToArray();

            for (int i = 0; i < iArr.Count(); i++)
            {
                for (int j = iArr.Count()-1; j >i; j--)
                {
                    for (int x = 0; x < iArr[j].ToString().Length; x++)
                    {
                        int counter = 0;
                        for (int k = 0; k < iArr[j - 1].ToString().Length; k++)
                        {
                            if (Convert.ToInt32(iArr[j].ToString().Substring(x, 1)) > Convert.ToInt32(iArr[j - 1].ToString().Substring(k, 1)))
                            {
                                Swap(ref iArr[j], ref iArr[j - 1]);
                                counter++;
                                break;
                            }
                            else if (Convert.ToInt32(iArr[j].ToString().Substring(x, 1)) == Convert.ToInt32(iArr[j - 1].ToString().Substring(k, 1)))
                            {
                                continue;
                            }
                            else
                            {
                                counter++;
                                break;
                            }
                        }
                        if (counter > 0)
                        {
                            counter = 0;
                            break;
                        }
                            
                    }
                       
                }
            }

            int a, b;
            a = 3; b = 4;
            Swap(ref a,ref b);

            Console.ReadLine();

            
        }

        public static void Swap(ref int a,ref int b)
        {
            a = a + b;
            b = a - b;
            a = a - b;
        }
    }
}

No comments:

Post a Comment