In this article we will look into the solution of Disks In a pile - a Level 1 coding challenge by Techgig
Introduction
Techgig is a global programming community and every month they conduct coding contest.This month they propose a challenge by the name Disks In a pile.It is a level-1 challenge. In this article we will see the my solution for the same.
The Problem Statement


Solution
using System;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[] number = { 3, 4, 2, 5, 1 };
int result = get_order(number);
Console.ReadKey();
}
public static int get_order(int[] input1)
{
var sortedArray = input1.OrderByDescending(o => o).ToArray();
var unsortedArray = input1;
int temp;
int swap = 0;
int arrayLength = sortedArray.Length;
for (int i = 0; i < arrayLength; i++)
{
if (sortedArray[i] != unsortedArray[i])
{
temp = unsortedArray[i];
unsortedArray[i] = sortedArray[i];
for (int j = i + 1; j < arrayLength; j++)
{
if (unsortedArray[j] == sortedArray[i])
{
unsortedArray[j] = temp;
swap++;
break;
}
}
}
}
return swap;
}
}
}
1) First, sort the array into descending order using the built in sorting function of C#.
2) Now, we can use this sorted array as a comparison - iterate through the array from left to right. Every time we find an element in the unsorted array that is != to the element in the same space in the sorted array, look deeper into the unsorted array for the value the sorted array has there and do one swap.
e.g.
3,4,2,5,1
Sort using Sort -> 5,4,3,2,1 is our sorted array
3 is != 5 - look in unsorted array for 5 - found it, swap them.
Unsorted is now 5,4,2,3,1
4 == 4
2 is != 3 - look in unsorted array for 3 - found it, swap them.
Unsorted is now 5,4,3,2,1
2 == 2
1 == 1
We're at the end of the unsorted array and we did two swaps.
Conclusion
I hope that this will be a good learning exercise for those whose are beginners in C#.Also participating in challenges helps us to hone our skills.Thanks for reading.
Disclaimer: This solution has been personally prepared by me and submitted for the knowledge sharing purpose.