Posts

Showing posts from June, 2015

(Coderbyte) Dash Insert II - Solução

Have the function DashInsertII( str ) insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers in str . For example: if str is 4546793 the output should be 454*67-9-3 . Don't count zero as an odd or even number. import java.util.*; import java.io.*; class Function {    String DashInsertII(String num) {     int anterior = Integer.parseInt(String.valueOf(num.charAt(0)));     String resultado = String.valueOf(num.charAt(0));         for (int i = 1; i < num.length(); i++) {       int atual = Integer.parseInt(String.valueOf(num.charAt(i)));       if (anterior%2 == 0 && atual%2 == 0 && anterior != 0 && atual != 0) {         resultado += "*";       }       else if (anterior%2 == 1 && atual%2 == 1) {         resultado += "-";       }       resultado += String.valueOf(num.charAt(i));       anterior = atual;     }            return resultado;       }     public sta

(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 ==

(Coderbyte) Run Length - Solução

Using the Java language, have the function RunLength( str ) take the str parameter being passed and return a compressed version of the string using the Run-length encoding algorithm. This algorithm works by taking the occurrence of each repeating character and outputting that number along with a single character of the repeating sequence. For example: "wwwggopp" would return 3w2g1o2p . The string will not contain any numbers, punctuation, or symbols. import java.util.*; import java.io.*; class Function {    String RunLength(String str) {     String resposta = "";         int contador = 1;     char c = str.charAt(0);     for (int i = 1; i < str.length(); i++) {       if (str.charAt(i) == c) {         contador++;       }       else {         resposta += contador+""+c;         c = str.charAt(i);         contador = 1;       }     }     resposta += contador+""+c;         return resposta;       }     public static void main (String[]

(Coderbyte) Formatted Division - Solução

Have the function FormattedDivision( num1 , num2 ) take both parameters being passed, divide num1 by num2 , and return the result as a string with properly formatted commas and 4 significant digits after the decimal place. For example: if num1 is 123456789 and num2 is 10000 the output should be "12,345.6789" . The output must contain a number in the one's place even if it is a zero. import java.util.*; import java.io.*; import java.text.*; class Function {    String FormattedDivision(int num1, int num2) {     DecimalFormat df = new DecimalFormat("#,##0.0000");     return df.format((double)num1/num2);       }     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.FormattedDivision(s.nextLine()));   }     }

Merge Sort

É um algoritmo de ordenação que usa o princípio de dividir e conquistar. Na implementação abaixo, inicialmente dividimos um vetor com N elementos em vários vetores menores. Realizadas estas divisões, teremos então vetores unitários que serão fundidos através da operação merge, formando assim vetores maiores ordenados. Isso ocorre sucessivamente até termos o vetor inteiro ordenado. import java.io.*; import java.util.*; import java.lang.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         int qteElementos = leitor(br);         int[] vetor = new int[qteElementos];                 for (int i = 0; i < qteElementos; i++) {             vetor[i] = leitor(br);         }         if (qteElementos > 1) {             vetor = juntaVetores(vetor, 0, qteElementos);         }                     imprimeVetor(vetor, qteElementos);                 System.e

(Coderbyte) Division - Solução

Have the function Division( num1 , num2 ) take both parameters being passed and return the Greatest Common Factor . That is, return the greatest number that evenly goes into both numbers with no remainder. For example: 12 and 16 both are divisible by 1, 2, and 4 so the output should be 4. The range for both parameters will be from 1 to 10^3. * Esta é uma solução alternativa à solução que seria comum. Não funciona para números negativos, mas resolve o problema proposto. Este problema também poderia ter sido resolvido usando outros algoritmos mais eficientes para calcular o Máximo Divisor Comum (MDC). import java.util.*; import java.io.*; class Function {    int Division(int num1, int num2) {     int menor;         if (num1 < num2) {       menor = num1;     }     else {       menor = num2;     }         for (int i = menor; i >= 1; i--) {       if (num1%i == 0 && num2%i == 0) {         return i;        }     }            return 1;       }     public static void

(URI) Soma Natural - Solução

Tendo em vista que no enunciado as entradas A e B podem variar de 1 a 10 9 , então uma entrada possível é: 1 1000000000 O que nos daria como resposta o valor 500000000500000000, que não é comportado por um int . Por este motivo, a resposta é um tipo long . import java.io.*; import java.util.*; import java.lang.*; class Main {     public static void main(String[] args) throws NumberFormatException, IOException {         Main processando = new Main();         processando.processa();                System.exit(0);     }        static int leitor(BufferedReader br) throws NumberFormatException, IOException {         int n;         int resp = 0;         int sinal = 1;         while (true) {             n = br.read();             if (n >= '0' && n <= '9') break;             if (n == '-') sinal = -1;             if (n == '+') sinal = 1;         }         while (true) {             resp = resp*10 + n-'0';             n = br.read(

(URI) Soma Natural

Image
Um número natural é um inteiro não-negativo (0, 1, 2, 3, 4, 5,...). A sua tarefa neste problema é calcular a soma dos números naturais que estão presentes em um determinado intervalo [ A , B ] inclusive. Por exemplo, a soma dos números naturais no intervalo [2, 5] é 14 = (2+3+4+5). Entrada Cada caso de teste contém dois inteiros A e B (1 ≤ A ≤ B ≤ 10 9 ), representando o limite inferior e o superior respectivamente. Saída Para cada caso de teste, a saída consiste de uma linha contendo a soma dos números naturais do intervalo.

(URI) Economia Brasileira - Solução

import java.io.*; import java.util.*; class Main {     public static void main(String[] args) throws NumberFormatException, IOException {         Main processando = new Main();         processando.processa();                 System.exit(0);     }         static int leitor(BufferedReader br) throws NumberFormatException, IOException {         int n;         int resp = 0;         while (true) {             n = br.read();             if (n >= '0' && n <= '9') break;         }         while (true) {             resp = resp*10 + n-'0';             n = br.read();             if (n < '0' || n > '9') break;         }         return resp;     }         void processa() throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                 int qteEntrevistados = leitor(br);                 int satisfacao = 0;         for (int i = 0; i < qteEntrevistados; i++) {