(Coderbyte) Simple Mode - Solução

Using the Java language, have the function SimpleMode(arr) take the array of numbers stored in arr and return the number that appears most frequently (the mode). For example: if arr contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode return the one that appeared in the array first (ie. [5, 10, 10, 6, 5] should return 5 because it appeared first). If there is no mode return -1. The array will not be empty.


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

class Function { 
  int SimpleMode(int[] arr) { 

    int contador;
    int contadorMaisFrequente = -1;
    int maisFrequente = -1;
   
    for (int i = 0; i < arr.length; i++) {
      contador = 1;
      for (int j = i+1; j < arr.length; j++) {   
        if (arr[j] == arr[i]) {
          contador++;
        }
        if (contador > contadorMaisFrequente) {
          maisFrequente = arr[i];
          contadorMaisFrequente = contador;
        }
      }
    }
   
    if (contadorMaisFrequente == 1) {
      return -1;
    }
    return maisFrequente;
   
  }
 
  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.SimpleMode(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