Addi
Addi

Reputation: 33

how to get result my code show me wrong result

Write a function which accepts two arrays and inserts the first n elements of the second array into position x of the first array and adds the remaining elements of the second array to the end.

InsertElements(arr1 = [1,2,3,9], arr2 = [4,7,2], pos = 3, count = 2) should return [1,2,4,7,3,9,2]

static void getresult(int []a, int []b, 
                            int n, int m)
    {
        for (int i = 0; i < n; i++)
        {
            int j;

            for (j = 0; j < m; j++)
                if (a[i] == b[j])
                    break;

            if (j == m)
                Console.Write(a[i] + " ");
        }
    }

    // Driver code
    public static void Main()
    {
        int []a = {1, 2, 3, 9};
        int []b = {4,7,2};

        int n = a.Length;
        int m = b.Length;

        getresult(a, b, n, m);
    }

Upvotes: 1

Views: 103

Answers (2)

Mik
Mik

Reputation: 151

One of the solutions might be this one:

static void Main(string[] args)
    {
        int[] a = { 1, 2, 3, 9 };
        int[] b = { 4, 7, 2 };

        InsertElements(a, b, 3, 2);
    }

    private static void InsertElements(int[] arr1, int[] arr2, int x, int n)
    {
        var listOfArr1 = arr1.ToList();
        var itemsToInsert = arr2.Take(n);
        var itemsToAdd = arr2.Skip(n);

        var pos = x - 1;

        foreach (var item in itemsToInsert)
        {
            listOfArr1.Insert(pos, item);
            pos++;
        }

        listOfArr1.AddRange(itemsToAdd);

        var result = listOfArr1.ToArray();
    }

Upvotes: 1

yash
yash

Reputation: 812

i am not sure about position of 3 according to your Example but here is code which produces desired output:-

        static void Main(string[] args)
    {
        int[] a = { 1, 2, 3, 9 };
        int[] b = { 4, 7, 2 };

        int position = 3;
        int count = 2;

        getresult(a, b, position, count);

        Console.ReadLine();
    }

            static void getresult(int[] a, int[] b,
                        int n, int m)
    {
        int firstArrayCount = 0;

        for(int i=0; i < n-1 ; i++)
        {
            Console.WriteLine(a[i]);

            firstArrayCount++;
        }

        for(int i=0; i < m ; i++)
        {
            Console.WriteLine(b[i]);
        }

        for(int i=firstArrayCount;i<a.Length;i++)
        {
            Console.WriteLine(a[i]);
        }

        for(int i=m;i<b.Length;i++)
        {
            Console.WriteLine(b[i]);
        }
    }

Upvotes: 0

Related Questions