Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmGenerate an array B from the given array A which satisfies the...

Generate an array B[] from the given array A[] which satisfies the given conditions

Given an array A[] of N integers such that A[0] + A[1] + A[2] + … A[N – 1] = 0. The task is to generate an array B[] such that B[i] is either ?A[i] / 2? or ?A[i] / 2? for all valid i and B[0] + B[1] + B[2] + … + B[N – 1] = 0.
 

Examples: 

Input: A[] = {1, 2, -5, 3, -1} 
Output: 0 1 -2 1 0
Input: A[] = {3, -5, -7, 9, 2, -2} 
Output: 1 -2 -4 5 1 -1  

Approach: For even integers, it is safe to assume that B[i] will be A[i] / 2 but for odd integers, to maintain the sum equal to zero, take the ceil of exactly half of odd integers and floor of exactly other half odd integers. Since Odd – Odd = Even and Even – Even = Even and 0 is also Even, it can be said that A[] will always contain an even number of odd integers so that the sum can be 0. So for valid input, there will always be an answer.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to print
// the array elements
void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
 
// Function to generate and print
// the required array
void generateArr(int arr[], int n)
{
 
    // To switch the ceil and floor
    // function alternatively
    bool flip = true;
 
    // For every element of the array
    for (int i = 0; i < n; i++) {
 
        // If the number is odd then print the ceil
        // or floor value after division by 2
        if (arr[i] & 1) {
 
            // Use the ceil and floor alternatively
            if (flip ^= true)
                cout << ceil((float)(arr[i]) / 2.0) << " ";
            else
                cout << floor((float)(arr[i]) / 2.0) << " ";
        }
 
        // If arr[i] is even then it will
        // be completely divisible by 2
        else {
            cout << arr[i] / 2 << " ";
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 3, -5, -7, 9, 2, -2 };
    int n = sizeof(arr) / sizeof(int);
 
    generateArr(arr, n);
 
    return 0;
}


Java




// Java implementation of the approach
// Utility function to print
// the array elements
import java.util.*;
import java.lang.*;
 
class GFG
{
 
static void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        System.out.print(arr[i] + " ");
}
 
// Function to generate and print
// the required array
static void generateArr(int arr[], int n)
{
 
    // To switch the ceil and floor
    // function alternatively
    boolean flip = true;
 
    // For every element of the array
    for (int i = 0; i < n; i++)
    {
 
        // If the number is odd then print the ceil
        // or floor value after division by 2
        if ((arr[i] & 1) != 0)
        {
 
            // Use the ceil and floor alternatively
            if (flip ^= true)
                System.out.print((int)(Math.ceil(arr[i] /
                                            2.0)) + " ");
            else
                System.out.print((int)(Math.floor(arr[i] /
                                            2.0)) + " ");
        }
 
        // If arr[i] is even then it will
        // be completely divisible by 2
        else
        {
            System.out.print(arr[i] / 2 +" ");
        }
    }
}
 
// Driver code
public static void main(String []args)
{
    int arr[] = { 3, -5, -7, 9, 2, -2 };
    int n = arr.length;
 
    generateArr(arr, n);
}
}
 
// This code is contributed by Surendra_Gangwar


Python3




# Python3 implementation of the approach
from math import ceil, floor
 
# Utility function to print
# the array elements
def printArr(arr, n):
    for i in range(n):
        print(arr[i], end = " ")
 
# Function to generate and print
# the required array
def generateArr(arr, n):
 
    # To switch the ceil and floor
    # function alternatively
    flip = True
 
    # For every element of the array
    for i in range(n):
 
        # If the number is odd then print the ceil
        # or floor value after division by 2
        if (arr[i] & 1):
 
            # Use the ceil and floor alternatively
            flip ^= True
            if (flip):
                print(int(ceil((arr[i]) / 2)),
                                   end = " ")
            else:
                print(int(floor((arr[i]) / 2)),
                                    end = " ")
 
        # If arr[i] is even then it will
        # be completely divisible by 2
        else:
            print(int(arr[i] / 2), end = " ")
 
# Driver code
arr = [3, -5, -7, 9, 2, -2]
n = len(arr)
 
generateArr(arr, n)
 
# This code is contributed by Mohit Kumar


C#




// C# implementation of the approach
// Utility function to print
// the array elements
using System;
using System.Collections.Generic;
 
class GFG
{
 
static void printArr(int []arr, int n)
{
    for (int i = 0; i < n; i++)
        Console.Write(arr[i] + " ");
}
 
// Function to generate and print
// the required array
static void generateArr(int []arr, int n)
{
 
    // To switch the ceil and floor
    // function alternatively
    bool flip = true;
 
    // For every element of the array
    for (int i = 0; i < n; i++)
    {
 
        // If the number is odd then print the ceil
        // or floor value after division by 2
        if ((arr[i] & 1) != 0)
        {
 
            // Use the ceil and floor alternatively
            if (flip ^= true)
                Console.Write((int)(Math.Ceiling(arr[i] /
                                            2.0)) + " ");
            else
                Console.Write((int)(Math.Floor(arr[i] /
                                            2.0)) + " ");
        }
 
        // If arr[i] is even then it will
        // be completely divisible by 2
        else
        {
            Console.Write(arr[i] / 2 +" ");
        }
    }
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 3, -5, -7, 9, 2, -2 };
    int n = arr.Length;
 
    generateArr(arr, n);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// javascript implementation of the approach
// Utility function to print
// the array elements   
function printArr(arr , n) {
        for (i = 0; i < n; i++)
            document.write(arr[i] + " ");
    }
 
    // Function to generate and print
    // the required array
    function generateArr(arr , n) {
 
        // To switch the ceil and floor
        // function alternatively
        var flip = true;
 
        // For every element of the array
        for (i = 0; i < n; i++) {
 
            // If the number is odd then print the ceil
            // or floor value after division by 2
            if ((arr[i] & 1) != 0) {
 
                // Use the ceil and floor alternatively
                if (flip ^= true)
                    document.write(parseInt( (Math.ceil(arr[i] / 2.0))) + " ");
                else
                    document.write(parseInt( (Math.floor(arr[i] / 2.0))) + " ");
            }
 
            // If arr[i] is even then it will
            // be completely divisible by 2
            else {
                document.write(arr[i] / 2 + " ");
            }
        }
    }
 
    // Driver code
     
        var arr = [ 3, -5, -7, 9, 2, -2 ];
        var n = arr.length;
 
        generateArr(arr, n);
 
// This code is contributed by todaysgaurav
</script>


Output: 

1 -2 -4 5 1 -1

 

Time Complexity: O(n)

Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments