Cuente las ocurrencias del promedio de elementos de array con un número dado

Dada una array de  norte   enteros y un entero  X   . Para cada entero de la array a[i] , la tarea es calcular el recuento de números en la array con un valor igual al promedio del elemento a[i] y x . Es decir, el número de ocurrencias del ( promedio del elemento a[i] y x ) en la array.

Ejemplos: 

Entrada : arr[] = {2, 0, 4, 6, 2}, x = 2 
Salida : 2 0 0 1 2 
Para x = 2, los valores promedio para 2, 0, 4, 6, 2 serían 2, 1, 3, 4, 2 respectivamente. Entonces, la array de conteo daría como resultado 2, 0, 0, 1, 2. 

Entrada : arr[] = {9, 5, 2, 4, 0, 3}, x = 3 
Salida : 0 1 1 1 0 1 
Para x = 3, los valores promedio para 9, 5, 2, 4, 0, 3 sería 6, 4, 2, 3, 1, 2 respectivamente. Entonces, la array de conteo daría como resultado 0, 1, 1, 1, 0, 1. 

Acercarse:  

  1. Recorra la array y asigne cada elemento con su recuento de ocurrencias en la array.
  2. Ahora recorra la array nuevamente, tome el promedio del elemento de la array y  X   verifique su valor en el mapa.

A continuación se muestra la implementación del enfoque anterior:  

C++

// CPP program to find the count of
// occurrences of the average of array
// elements with a given number
#include<bits/stdc++.h>
 
using namespace std;
 
 
    // Function to find the count of
    // occurrences of the average of array
    // elements with a given number
    void getAverageCountArray(int a[], int x, int N)
    {
        // mp to store count of occurrence
        // of every array element in the array
        map<int,int> mp;
 
        // Array that stores the average
        // count for given array
        int avg[N] = {0};
        int val, av;
 
        for (int i = 0; i < N; i++)
        {
            // first occurrence of a[i]
            if (mp[a[i]] == 0)
                mp[a[i]] = 1;
             
            else
            mp[a[i]]++;
             
 
            // element has already occurred before
            // so increase its count
        }
 
        for (int i = 0; i < N; i++)
        {
            av = int((a[i] + x) / 2);
            if (mp.find(av) != mp.end())
            {
                val = mp[av];
                avg[i] = val;
            }
        }
 
        // Printing the average count array
        for (int i = 0; i < N; i++)
        {
            cout << avg[i] << " ";
        }
    }
 
    // Driver code
    int main()
    {
        int a[] = { 2, 0, 4, 6, 2 };
        int x = 2;
 
        int N = sizeof(a)/sizeof(a[0]);
        getAverageCountArray(a, x, N);
    }
 
// This code is contributed by
// Surendra_Gangwar

Java

// Java program to find the count of
// occurrences of the average of array
// elements with a given number
import java.io.*;
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to find the count of
    // occurrences of the average of array
    // elements with a given number
    static void getAverageCountArray(int[] a, int x, int N)
    {
        // Map to store count of occurrence
        // of every array element in the array
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 
        // Array that stores the average
        // count for given array
        int[] avg = new int[N];
        int val, av;
 
        for (int i = 0; i < N; i++) {
            // first occurrence of a[i]
            if (!map.containsKey(a[i])) {
                map.put(a[i], 1);
            }
 
            // element has already occurred before
            // so increase its count
            else {
                // gives current count of a[i]
                val = map.get(a[i]);
                val++;
                map.remove(a[i]);
                map.put(a[i], val);
            }
        }
 
        for (int i = 0; i < N; i++) {
            av = (a[i] + x) / 2;
            if (map.containsKey(av)) {
                val = map.get(av);
                avg[i] = val;
            }
        }
 
        // Printing the average count array
        for (int i = 0; i < N; i++) {
            System.out.print(avg[i] + " ");
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int[] a = { 2, 0, 4, 6, 2 };
        int x = 2;
 
        int N = a.length;
 
        getAverageCountArray(a, x, N);
    }
}

Python3

# Python3 program to find the count of
# occurrences of the average of array
# elements with a given number
 
# Function to find the count of
# occurrences of the average of array
# elements with a given number
def getAverageCountArray(a, x, N):
      
    # Dictionary to store count of occurrence
    # of every array element in the array
    map = {}
     
    # Array that stores the average
    # count for given array
    avg = [0] * N
   
    for i in range(N): 
        # first occurrence of a[i]
        if a[i] not in map: 
            map[a[i]] =  1
              
        # element has already occurred before
        # so increase its count
        else:
            # gives current count of a[i]
            map[a[i]] += 1
             
    for i in range(N): 
        av = (a[i] + x) // 2
         
        if av in map:
            val = map[av]
            avg[i] = val
              
    # Printing the average count array
    for i in range(N):
        print(avg[i], end = " ")
          
      
if __name__ == "__main__":
      
    a = [2, 0, 4, 6, 2] 
    x = 2
   
    N = len(a)
    getAverageCountArray(a, x, N)
     
# This code is contributed by Rituraj Jain

C#

// C# program to find the count of
// occurrences of the average of array
// elements with a given number
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to find the count of
// occurrences of the average of array
// elements with a given number
static void getAverageCountArray(int[] a, int x,
                                          int N)
{
    // Map to store count of occurrence
    // of every array element in the array
    Dictionary<int,
               int> map = new Dictionary<int,
                                         int>();
 
    // Array that stores the average
    // count for given array
    int[] avg = new int[N];
    int val, av;
 
    for (int i = 0; i < N; i++)
    {
        // first occurrence of a[i]
        if (!map.ContainsKey(a[i]))
        {
            map.Add(a[i], 1);
        }
 
        // element has already occurred before
        // so increase its count
        else
        {
            // gives current count of a[i]
            val = map[a[i]];
            val++;
            map.Remove(a[i]);
            map.Add(a[i], val);
        }
    }
 
    for (int i = 0; i < N; i++)
    {
        av = (a[i] + x) / 2;
        if (map.ContainsKey(av))
        {
            val = map[av];
            avg[i] = val;
        }
    }
 
    // Printing the average count array
    for (int i = 0; i < N; i++)
    {
        Console.Write(avg[i] + " ");
    }
}
 
// Driver code
public static void Main()
{
    int[] a = { 2, 0, 4, 6, 2 };
    int x = 2;
 
    int N = a.Length;
 
    getAverageCountArray(a, x, N);
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// JavaScript program to find the count of
// occurrences of the average of array
// elements with a given number
 
    // Function to find the count of
    // occurrences of the average of array
    // elements with a given number
    function getAverageCountArray(a, x, N)
    {
        // Map to store count of occurrence
        // of every array element in the array
        let map = new Map();
 
        // Array that stores the average
        // count for given array
        let avg = Array.from({length: N}, (_, i) => 0);
        let val, av;
 
        for (let i = 0; i < N; i++) {
            // first occurrence of a[i]
            if (!map.has(a[i])) {
                map.set(a[i], 1);
            }
 
            // element has already occurred before
            // so increase its count
            else {
                // gives current count of a[i]
                val = map.get(a[i]);
                val++;
                map.delete(a[i]);
                map.set(a[i], val);
            }
        }
 
        for (let i = 0; i < N; i++) {
            av = (a[i] + x) / 2;
            if (map.has(av)) {
                val = map.get(av);
                avg[i] = val;
            }
        }
 
        // Printing the average count array
        for (let i = 0; i < N; i++) {
            document.write(avg[i] + " ");
        }
    }
     
// Driver Code
 
           let a = [ 2, 0, 4, 6, 2 ];
        let x = 2;
 
        let N = a.length;
 
        getAverageCountArray(a, x, N);
         
</script>
Producción: 

2 0 0 1 2

 

Publicación traducida automáticamente

Artículo escrito por rachana soma y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *