Alguns Exemplos em Java Fernando Silva & Luís Lopes DCC-FCUP Estruturas de Dados
Problema 1: Dígito mais frequente Exemplo: o número 3435667323 contém: 1 (2), 4 (3), 1 (4), 1 (5), 2 (6) e 1 (7) digitomaisfrequente(3435667323) retorna 3 se existir um empate, deve mostrar o menor dígito. Sugestão: usar um contador por cada dígito (vector com 10 contadores) d=n%10 dá o dígito das unidades; n=n/10 retira dígito das unidades Exemplo 669260267
Problema 1: Dígito mais frequente p u b l i c c l a s s DigitCounterTest { p u b l i c s t a t i c v o i d main ( String [] args ) { i n t most_freq = highestfrequencydigit (669260267); System. out. print (" most frequent -> " + most_freq ); System. out. println (); s t a t i c i n t highestfrequencydigit ( i n t n) { i n t [] counters = new i n t [10]; w h i l e ( n > 0 ) { i n t d = n % 10; counters [d ]++; n /= 10; i n t max = 0; f o r ( i n t i = 1 ; i < counters. length ; i++ ) i f ( counters [i] > counters [ max ] ) max = i; r e t u r n max ;
Problema 2: Histogramas Escrever um método void histograma(int notas[]) que, recebendo como parâmetro um vector de classificações, dados como valores inteiros, produza um histograma de estrelas (*) que indique o número de alunos que obtiveram uma determinada classificação (supor apenas os registos de 0 a 20). Exemplo: dados 12 13 12 17 14 14 18 15 13 15 12 15 deve produzir: 12: *** 13: ** 14: ** 15: *** 17: * 18: * Sugestão: solução parecida com anterior, mas com 21 contadores!
Problema 2: Histogramas c l a s s HistogramTest { p u b l i c s t a t i c v o i d main ( String [] args ) { i n t [] notas = {12,13,12,17,14,14,18,15,13,15,12,15; histogram ( notas ); s t a t i c v o i d histogram ( i n t [] notas ) { i n t [] counters = new i n t [21]; f o r ( i n t i = 0 ; i < notas. length ; i++ ) counters [ notas [i ]]++; f o r ( i n t i = 0 ; i < counters. length ; i++ ) i f ( counters [i] > 0 ) { System. out. print (i + ": "); f o r ( i n t j = 0 ; j < counters [i] ; j++ ) System. out. print ("*"); System. out. println ();
Problema 3: Pontos no plano xy p u b l i c c l a s s Point { p r i v a t e i n t x, y; p u b l i c Point () { x = 0; y = 0; p u b l i c Point ( i n t x0, i n t y0 ) { x = x0; y = y0; p u b l i c double distance ( Point q) { Point p = t h i s ; r e t u r n Math. sqrt ( (p.x - q.x )^2 + (p.y - q.y )^2 ); p u b l i c String tostring () { r e t u r n "( " + x + ", " + y + " )"; Suponhamos que pretendemos ler n pontos no plano e determinar qual deles está mais próximo da origem. Como fazer?
Problema 3: Pontos no plano xy import java. util.*; p u b l i c c l a s s PointTest { p u b l i c s t a t i c v o i d main ( String [] args ) { Scanner stdin = new Scanner ( System. in ); i n t np = stdin. nextint (); Point [] ap = new Point [ np ]; f o r ( i n t i = 0 ; i < np ; i++ ) { i n t x = stdin. nextint (); i n t y = stdin. nextint (); ap[ i] = new Point (x, y); Point q = closesttoorigin ( ap ); System. out. println (" closest to origin -> " + q);
Problema 3: Pontos no plano xy p u b l i c s t a t i c Point closesttoorigin ( Point [] ap) { Point closest = ap [0]; Point origin = new Point (0,0); double minimum = closest. distance ( origin ); f o r ( i n t i = 1 ; i < ap. length ; i++ ) { double dist = ap[ i]. distance ( origin ); i f ( dist < minimum ) { closest = ap[ i]; minimum = dist ; r e t u r n closest ;
Problema 4: Vectores multidimensionais p u b l i c c l a s s Vector { p r i v a t e i n t dim ; // dimension of the vector p r i v a t e double [] data ; // array of vector s components p u b l i c Vector ( i n t d) { dim = d; data = new double [ d]; p u b l i c Vector ( double a) { dim = a. length ; data = new double [ dim ]; f o r ( i n t i = 0; i < dim ; i ++) data [i] = a[i]; p u b l i c i n t dimension () { r e t u r n dim ;
Problema 4: Vectores multidimensionais p u b l i c double dot ( Vector v) { Vector u = t h i s ; double sum = 0.0; f o r ( i n t i = 0; i < dim ; i ++) sum = sum + (u. data [i] * v. data [i ]); r e t u r n sum ; p u b l i c double norm () { Vector u = t h i s ; r e t u r n Math. sqrt (u. dot (u )); p u b l i c Vector plus ( Vector v) { Vector u = t h i s ; Vector w = new Vector ( dim ); f o r ( i n t i = 0; i < dim ; i ++) w. data [i] = u. data [i] + v. data [i]; r e t u r n w;
Problema 4: Vectores multidimensionais p u b l i c s t a t i c v o i d main ( String [] args ) { double [] xdata = { 1.0, 2.0, 3.0, 4.0 ; double [] ydata = { 5.0, 2.0, 4.0, 1.0 ; Vector x = new Vector ( xdata ); Vector y = new Vector ( ydata ); StdOut. println (" x = " + x); StdOut. println (" y = " + y); Vector z = x. plus ( y); StdOut. println (" x = " + x. norm ()); StdOut. println (" <x, y> = " + x. dot (y ));
Problema 5: Números complexos p u b l i c f i n a l c l a s s Complex { p r i v a t e f i n a l double re; // real p r i v a t e f i n a l double im; // imaginary // constructor that takes in rectangular coordinates p u b l i c Complex ( double re, double im) { t h i s.re = re; t h i s.im = im; // accessor methods p u b l i c double re () { r e t u r n re; p u b l i c double im () { r e t u r n im;
Problema 5: Números complexos // return this Complex number plus b p u b l i c Complex plus ( Complex b) { Complex a = t h i s ; r e t u r n new Complex (a.re () + b.re (), a.im () + b.im ()); // return this Complex number minus b p u b l i c Complex minus ( Complex b) { Complex a = t h i s ; r e t u r n new Complex (a.re () - b.re (), a.im () - b.im ()); // return this Complex number times b p u b l i c Complex times ( Complex b) { Complex a = t h i s ; r e t u r n new Complex (a.re () * b.re () - a.im () * b.im (), a.re () * b.im () + a.im () * b.re () );
Problema 5: Números complexos p u b l i c c l a s s TestComplex { p u b l i c s t a t i c v o i d main ( String [] args ) { Complex a = new Complex (5.0, 6.0); System. out. println ("a = " + a); Complex b = new Complex ( -2.0, 3.0); System. out. println ("b = " + b); Complex c = b. times ( a); System. out. println ("c = " + c); Complex d = new Complex (0.0, 0.0); System. out. println ("d = " + d); Complex e = c. divide ( d); System. out. println ("e = " + e);
Problema 5: Números complexos (alternativa) p u b l i c f i n a l c l a s s Complex { p r i v a t e f i n a l double re; // real p r i v a t e f i n a l double im; // imaginary // constructor that takes in rectangular coordinates p u b l i c Complex ( double re, double im) { t h i s.re = re; t h i s.im = im; // accessor methods p u b l i c double re () { r e t u r n re; p u b l i c double im () { r e t u r n im; // string representation p u b l i c String tostring () { r e t u r n re () + " + " + im () + "i";
Problema 5: Números complexos p u b l i c c l a s s ComplexMath { // return this Complex number plus b p u b l i c s t a t i c Complex plus ( Complex a, Complex b) { r e t u r n new Complex (a.re () + b.re (), a.im () + b.im ()); // return this Complex number minus b p u b l i c s t a t i c Complex minus ( Complex a, Complex b) { r e t u r n new Complex (a.re () - b.re (), a.im () - b.im ()); // return this Complex number times b p u b l i c s t a t i c Complex times ( Complex a, Complex b) { r e t u r n new Complex (a.re () * b.re () - a.im () * b.im (), a.re () * b.im () + a.im () * b.re () );
Problema 5: Números complexos p u b l i c c l a s s TestComplex { p u b l i c s t a t i c v o i d main ( String [] args ) { Complex a = new Complex (5.0, 6.0); System. out. println ("a = " + a); Complex b = new Complex ( -2.0, 3.0); System. out. println ("b = " + b); Complex c = ComplexMath. times (a, b); System. out. println ("c = " + c); Complex d = new Complex (0.0,0.0); System. out. println ("d = " + d); Complex e = ComplexMath. divide (c, d); System. out. println ("e = " + e);
Problema 6: Média, variância, desvio padrão p u b l i c c l a s s OnePass { p r i v a t e i n t N = 0; p r i v a t e double sum = 0.0; p r i v a t e double sum2 = 0.0; p u b l i c v o i d add ( double value ) { sum = sum + value ; sum2 = sum2 + value * value ; N ++; p u b l i c double mean () { r e t u r n sum / N; p u b l i c double variance () { r e t u r n (N* sum2 - sum * sum ) / (N*(N -1)); p u b l i c double stddev () { r e t u r n Math. sqrt ( variance ());
Problema 6: Média, variância, desvio padrão // test client p u b l i c s t a t i c v o i d main ( String [] args ) { Scanner stdin = new Scanner ( System. in ); OnePass dataset = new OnePass (); w h i l e (! stdin. hasnextdouble ()) dataset. add ( stdin. nextdouble ()); double mean = dataset. mean (); double stddev = dataset. stddev (); double lo = mean - 1.96 * stddev ; double hi = mean + 1.96 * stddev ; // print results System. out. println (" mean = " + mean ); System. out. println (" sample stddev = " + stddev ); System. out. print (" 95% confidence interval = "); System. out. println ("[ " + lo + ", " + hi + " ]");
Problema 6: Multiplicação de matriz por vector Multiplicação de uma vector a[n][m] por um vector u[m] para dar v[n]: i.e. v i = M 1 j=0 a ij u j (0 i < N)
Problema 6: Multiplicação de matriz por vector c l a s s MatrixVectorProductTest { p u b l i c s t a t i c v o i d main ( String [] args ) { i n t [][] a = {{1,2,3,{4,5,6; i n t [] u = {1,2,3; i n t [] v = matrixvectormult (a,u); f o r ( i n t i = 0 ; i < v. length ; i++ ) System. out. print (v[i] + " "); System. out. println (); s t a t i c i n t [] matrixvectormult ( i n t [][] a, i n t [] u) { i n t [] v = new i n t [a. length ]; f o r ( i n t i = 0 ; i < v. length ; i++ ) { v[ i] = 0; f o r ( i n t j = 0 ; j < u. length ; j++ ) v[i] += a[i][j] * u[j]; r e t u r n v;
Problema 7: Triângulo de Pascal O triângulo de Pascal pode ser visto como uma matriz triangular inferior: 1 ou 1 <-- lin 0 1 1 1 1 <-- lin 1 1 2 1 1 2 1 <-- lin 2 1 3 3 1 1 3 3 1 <-- lin 3 1 4 6 4 1 1 4 6 4 1 <-- lin 4 1 5 10 10 5 1 1 5 10 10 5 1 <-- lin 5 Cada valor é a soma dos dois valores mais próximos da linha anterior. A representação corresponde a uma matriz triangular inferior.
Problema 7: Triângulo de Pascal Método para calcular as linhas do Triângulo de Pascal, usando uma matriz apenas dimensionada triangularmente: p u b l i c c l a s s PascalTriangleTest { i n t [][] triangulopascal ( i n t n) { i n t [][] tp = new i n t [n ][]; f o r ( i n t i = 0 ; i < n ; i++ ) tp[i] = new i n t [i +1]; f o r ( i n t i = 0 ; i < n ; i++ ) { tp[ i ][0] = 1; f o r ( i n t j = 1 ; j < i ; j++ ) tp[i][j] = tp[i -1][j -1] + tp[i -1][ j]; tp[ i][ i] = 1; r e t u r n tp;
Problema 7: Triângulo de Pascal Método para calcular as linhas do Triângulo de Pascal, usando uma matriz apenas dimensionada triangularmente: import java. util.*; p u b l i c c l a s s PascalTriangleTest { p u b l i c s t a t i c v o i d main ( String [] args ) { Scanner arg = new Scanner ( args [0]); i n t n = arg. nextint (); i n t [][] tp = computepascaltriangle (n); f o r ( i n t i = 0 ; i < tp. length ; i++ ) { f o r ( i n t j = 0 ; j <= i ; j++ ) System. out. print (tp[i][j] + " "); System. out. println ();
Problema 7: Dimensionamento matriz triangular inferior Ilustração da matriz triangular inferior que representa o triângulo de Pascal (só estamos a reservar memória para o número correcto de elementos na linha):
Problema 8: Escrita de Números por Extenso Dado um número n : 0 n < 1000000, escreva um programa que traduza n para texto. Exemplos: 100 = cem 105 = cento e cinco 1000 = mil 12345 = doze mil trezentos e quarenta e cinco 10045 = dez mil e quarenta e cinco 10000 = dez mil 10020 = dez mil e vinte
Problema 8: Sugestões Como lidar com números menores que 100, i.e. números com dois dígitos N = d 1 d 2? Se d 1 for 0? números de 0 a 9 i.e. temos strings de zero a nove String unidades[]={"zero",,"nove"; indexamos o vector com o valor de d2 Se d 1 for 1? números de 10 a 19 i.e. temos strings de dez a dezanove String dez_dezanove[]={"dez",,"dezanove"; Se d 2 for 0? temos números números 20, 30,, 90. String dezenas[]={"","","vinte",,"noventa"; Caso geral com os dois dígitos temos números números como 25, 33, dezenas[d1] + " e " + unidades[d2]
Problema 8: método converte2() import java. util.*; c l a s s Number2TextTest { s t a t i c String unidades []={ " zero ", "um", " dois ", " tres ", " quatro ", " cinco ", " seis ", " sete ", " oito ", " nove " ; s t a t i c String dez_dezanove []={ " dez "," onze "," doze "," treze ", " catorze "," quinze "," dezasseis "," dezassete ", " dezoito ", " dezanove " ; s t a t i c String converte2 ( i n t n) { i n t d1= n /10; i n t d2= n %10; i f (d1 ==0) // 0X r e t u r n unidades [d2 ]; i f (d1 ==1) // 1X r e t u r n dez_dezanove [d2 ]; i f (d2 ==0) // X0 r e t u r n dezenas [d1 ]; // XY r e t u r n dezenas [d1] + " e " + unidades [d2 ];
Problema 8: método converte3() Como converter números menores que 1000? s t a t i c String centenas []={ ""," cento ", " duzentos ", " trezentos ", " quatrocentos ", " quinhentos ", " seiscentos ", " setecentos ", " oitocentos ", " novecentos " ; s t a t i c String converte3 ( i n t n) { i n t d1= n /100; i n t d2= n %100; i f (d1 ==0) // se menor que 100 r e t u r n converte2 (d2 ); i f (d1 ==1 && d2 ==0) // se 100 r e t u r n " cem "; i f ( d2 ==0) // se múltiplo de 100 r e t u r n centenas [d1 ]; r e t u r n centenas [d1] + " e " + converte2 (d2 );
Problema 8: método converte6() Como converter números menores que 1000000? s t a t i c String ligar ( i n t n) { // adiciona "e" se for menor que 100 ou multiplo de 100 r e t u r n (n <100 n %100==0)? " e " : " "; s t a t i c String converte6 ( i n t n) { i n t d1=n /1000; i n t d2=n %1000; i f (d1 ==0) // se menor que 1000 r e t u r n converte3 (d2 ); i f (d1 ==1 && d2 ==0) // 1000 r e t u r n " mil "; i f (d1 ==1) // "mil e 0xx" "mil xxx" r e t u r n " mil " + ligar (d2) + converte3 (d2 ); i f (d2 ==0) // 10000 ou 600000 r e t u r n converte3 (d1) + " mil "; r e t u r n converte3 (d1) + " mil " + ligar (d2) + converte3 (d2 );
Problema 8: método main() Leitura do input e escrita: p u b l i c s t a t i c v o i d main ( String args []) { Scanner stdin = new Scanner ( System. in ); w h i l e ( stdin. hasnextint ()) { i n t number = stdin. nextint (); System. out. printf ("%s\n", converte6 ( number ));