Fill two instances of all numbers from 1 to n in a specific way

Given a number n, create an array of size 2n such that the array contains 2 instances of every number from 1 to n, and the number of elements between two instances of a number i is equal to i. If such a configuration is not possible, then print the same.
Examples:
Input: n = 3
Output: res[] = {3, 1, 2, 1, 3, 2}

Input: n = 2
Output: Not Possible

Input: n = 4
Output: res[] = {4, 1, 3, 1, 2, 4, 3, 2}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApplication1
{
    class Program
    {
        public static int flag = 0;
        static void Main(string[] args)
        {
            int n = 15;
            int[] numArray = new int[2 * n];
            for (int i = 0; i < 2* n; i++)
            {
                numArray[i] = 0;
            }
            Arrange(numArray, n);
            if (flag == 0)
            {
                Console.WriteLine("No solution found...");
            }
            else
            {
                Console.WriteLine("Solution found!!!");
                for (int i = 0; i < numArray.Length; i++)
                {
                    Console.Write(numArray[i] + " ");
                }
                Console.WriteLine();
            }
        }
        public static void Arrange(int[] numArray, int num)
        {
            if (num == 0) //Solution found
            {
                flag = 1;
            }
            else
            {
                for (int i = 0; (i + num + 1) < numArray.Length && flag == 0; i++)
                {
                    if (numArray[i] == 0 && numArray[i + num + 1] == 0)
                    {
                        numArray[i] = num;
                        numArray[i + num + 1] = num;
                        Arrange(numArray, num - 1);
                        if (flag == 0)
                        {
                            numArray[i] = 0;
                            numArray[i + num + 1] = 0;
                        }
                    }
                }
            }
        }
    }
}

Output
=======
Solution found!!!
15 13 14 8 5 12 7 11 4 10 5 9 8 4 7 13 15 14 12 11 10 9 6 3 1 2 1 3 2 6
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s