(Coderbyte) Mean Mode - Solução

Using the Java language, have the function MeanMode(arr) take the array of numbers stored in arr and return 1 if the mode equals the mean, 0 if they don't equal each other (ie. [5, 3, 3, 3, 1] should return 1 because the mode (3) equals the mean (3)). The array will not be empty, will only contain positive integers, and will not contain more than one mode.

Solução:

import java.util.*;
import java.io.*;

class Function { 
  int MeanMode(int[] arr) {
    Arrays.sort(arr);
   
    int[] vetor = new int[arr[arr.length-1]+1];
   
    // calcula a média
    int soma = 0;
    for (int i = 0; i < arr.length; i++) {
      soma += arr[i];
      vetor[arr[i]]++;
    }
    int media = soma/arr.length;

    // verificar o valor que mais se repete
    int maior = 1;
    int valorQueRepeteMais = -1;
    for (int i = 0; i < vetor.length; i++) {
      if (vetor[i] > maior) {
        maior = vetor[i]; // maior repetição
        valorQueRepeteMais = i; // valor que mais se repete
      }
    }
   
    // se o valor que mais se repete é igual a média
    if (valorQueRepeteMais == media) {
         return 1;
    }
    else {
        return 0;
    }
  }
 
  public static void main (String[] args) { 
    // keep this function call here    
    Scanner  s = new Scanner(System.in);
    Function c = new Function();
    System.out.print(c.MeanMode(s.nextLine()));
  }  
 
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução