Tema destacado: Grupo de acebook de elhacker.net
Autor
|
Tema: Algoritmia-Ejercicios introductorios. (Leído 6,431 veces)
|
|
ghastlyX
|
Para el 3, pongo varios algoritmos de ordenación en C++ que permiten ordenar un vector de reales: Ordenación por inserción (O(n 2)): #include <iostream> #include <vector> using namespace std; void ordena_por_insercion(vector<double>& v) { for (int i = 1; i < v.size(); ++i) { double x = v[i]; int j = i; while (j > 0 and v[j-1]>x) { v[j] = v[j-1]; --j; } v[j] = x; } } Ordenación por selección (O(n 2)): #include <iostream> #include <vector> using namespace std; int posicion_maximo(const vector<double>& v, int n) { int pos = 0; for (int i = 1; i <= n; ++i) if (v[i] > v[pos]) pos = i; return pos; } void ordena_por_seleccion(vector<double>& v, int n) { if (n > 0) { swap(v[posicion_maximo(v,n)],v[n]); ordena_por_seleccion(v,n-1); } } Ordenación por burbuja (O(n 2)): #include <iostream> #include <vector> using namespace std; void ordena_por_burbuja(vector<double>& v) { for (int i = 0; i < v.size(); ++i) { for (int j = v.size()-1; j >= i + 1; --j) { if (v[j] < v[j - 1] ) swap(v[j], v[j - 1]); } } } Y un par de algoritmos Divide&Conquer, primero Merge Sort (Ordenación por fusión, O(n log n)): #include <iostream> #include <vector> using namespace std; void fusiona(vector<double>& v, int e, int m, int d) { int n = d-e+1; vector<double> aux (n); int i = e; int j = m + 1; int k = 0; while (i <= m and j <= d) { if (v[i] <= v[j]) { aux[k] = v[i]; ++i; ++k; } else { aux[k] = v[j]; ++j; ++k; } } while (i <= m) { aux[k] = v[i]; ++k; ++i; } while (j <= d) { aux[k] = v[j]; ++j; ++k; } for (k = 0; k < n; ++k) v[k+e] = aux[k]; } void ordena_rec(vector<double>& v, int e, int d) { if (e < d) { int m = (e+d)/2; ordena_rec(v,e,m); ordena_rec(v,m+1,d); fusiona(v,e,m,d); } } void ordena_por_fusion(vector<double>& v) { ordena_rec(v, 0, v.size()-1); } Otro Divide&Conquer, Quicksort (O(n log n) en caso promedio, O(n 2) en el peor caso, aunque en general es más rápido que el Merge Sort): #include <iostream> #include <vector> using namespace std; int pivota(vector<double>& v, int ini, int fin) { double valor_pivote = v[ini]; int p1 = ini + 1, p2 = fin - 1; while (p1 <= p2) { if (v[p1] < valor_pivote) ++p1; else if (v[p2] >= valor_pivote) --p2; else { swap(v[p1], v[p2]); ++p1; --p2; } } swap(v[ini], v[p1 - 1]); return p1 - 1; } void quicksort_rec(vector<double>& v, int ini, int fin) { if (ini >= fin - 1) return; int pivote = pivota(v, ini, fin); quicksort_rec(v, ini, pivote); quicksort_rec(v, pivote + 1, fin); } void quicksort(vector<double>& v, int r) { quicksort_rec(v, 0, r); } Un saludo de ghastlyX 
|
|
|
|
|
En línea
|
|
|
|
h0oke
Desconectado
Mensajes: 2.058
Coder ~
|
ESRUCTURAS ESTATICAS BIDIMENSIONALES 1-Mostrar una matriz por filas. 2-Mostrar una mtriz por columnas. 3-Mostrar una matriz por recorrido en caracol. 4-Mostrar los elementos que se encuentran en el triangular inferior. ------------------------------------------------------------------------------, junto a su diagonal. 5-Sea una tabla NxM ordenada por filas ascendentemente y dada una lista tamaño M² insertar en la fila correspondiente utilizando el método de Búsqueda Binaria. 6- Se posee una tabla de A de M filas y N columnas, conformada por números naturales. Se deberá mostrar la posición del menor número repetido junto con su frecuencia de aparición. 7- De una tabla NxM informar la posición del primer elemento primo de cada fila y la posición del primer elemento primo de la tabla.
|
|
|
|
|
En línea
|
|
|
|
h0oke
Desconectado
Mensajes: 2.058
Coder ~
|
1-2 #include <stdio.h> #include <stdlib.h> int main() { int N,M,i,j; int a[100][100]; printf("Ingrese cantidad filas(M)\n"); scanf("%d",&M); printf("Ingrese cantidad columnas(N)\n"); scanf("%d",&N); for(i=0;i<M;i++) { for(j=0;j<N;j++) { printf("Elemento\n"); scanf("%d",&a[i][j]); } } for(i=0;i<M;i++) { for(j=0;j<N;j++) { printf("%d",a[i][j]); } } return 0; } #include <stdio.h> #include <stdlib.h> int main() { int N,M,i,j; int a[100][100]; printf("Ingrese cantidad filas(M)\n"); scanf("%d",&M); printf("Ingrese cantidad columnas(N)\n"); scanf("%d",&N); for(j=0;j<N;j++) { for(i=0;i<M;i++) { printf("Elemento\n"); scanf("%d",&a[i][j]); } } for(j=0;j<N;j++) { for(i=0;i<M;i++) { printf("%d",a[i][j]); } } return 0; }
|
|
|
|
« Última modificación: 24 Junio 2009, 03:22 por Emt.dev »
|
En línea
|
|
|
|
VonN
Desconectado
Mensajes: 151
Learnin' Python&C++
|
El algoritmo para recorrer y mostrar el triangulo superior: for(int i=0,i<n-1;i++) { for(int j=i+1;j<n;j++) { std::cout<<vec[i][j]<<std::endl; } } Triangulo superior y diagonal: for(int i=0,i<n;i++) { for(int j=i;j<n;j++) { std::cout<<vec[i][j]<<std::endl; } }
|
|
|
|
|
En línea
|
  Se toma por necios a aquellos que dicen lo que todos pesamos
|
|
|
Leo Gutiérrez.
. . .. ... ..... ........ ............. .....................
Colaborador
 
Desconectado
Mensajes: 2.968
/^$/
|
El 2 en Perl: #!/usr/bin/perl use strict; use warnings; print "Numero : "; my $numero = <stdin>; my $factorial = 1; for(my $i = 1; $i <= $numero; $i++) { $factorial *= $i; } print $factorial; exit;
|
|
|
|
|
En línea
|
|
|
|
VonN
Desconectado
Mensajes: 151
Learnin' Python&C++
|
Recien comenzando con python: Ejercicio 2: f=1 n=input("Ingresa n:") i=1 while(i<=n): f=f*i i=i+1 print "F:",f Ejercicio3 n=input("Ingresa Cantidad") x=input("Ingresa Numero") big=x i=1 while(i<n): x=input("Ingresa Numero") if x>big: big=x i=i+1 print "El mas grande: ",big
|
|
|
|
|
En línea
|
  Se toma por necios a aquellos que dicen lo que todos pesamos
|
|
|
VonN
Desconectado
Mensajes: 151
Learnin' Python&C++
|
Ejercicio 4: n=input("Ingrese cantidad") p=input("Ingrese primer numero") s=input("Ingrese segundo numero") if p<s: aux=p p=s s=aux i=1 while(i<=n-2): a=input("Ingrese numero") if p<a: s=p p=a elif s<a: s=a i=i+1 print "Segundo numero mas grande",sEjercicio 5 a=input("Ingrese numero") while(a!=0): d=a%10 a=a/10 print "Digito:",d
|
|
|
|
|
En línea
|
  Se toma por necios a aquellos que dicen lo que todos pesamos
|
|
|
VonN
Desconectado
Mensajes: 151
Learnin' Python&C++
|
Ejercicio 1. Variables indizadas: import math import random n=input("Ingresa cantidad") list=[0]*n for i in range(n): lista[i]=random.randint(0,100) menor=math.fabs(lista[0]-lista[1]) print "Mostrar lista obtenida:" i=0 tam=len(lista) while(i<tam): print lista[i] i=i+1 menor=math.fabs(lista[0]-lista[1]) pos1=0 pos2=1 i=0 j=0 while(i<tam): while(j<tam): if i<>j: vab=math.fabs(lista[i]-lista[j]) if vab<menor: menor=vab pos1=i pos2=j j=j+1 i=i+1 print "Menor distacia:",menor," POS1: ",pos1," POS": ",pos2
|
|
|
|
|
En línea
|
  Se toma por necios a aquellos que dicen lo que todos pesamos
|
|
|
VonN
Desconectado
Mensajes: 151
Learnin' Python&C++
|
Programa para buscar primos en una matriz NxM, parecido al ejercicio 5 de FSend. import random n=int(input("Ingresa las filas\n")) m=int(input("Ingresa las columnas\n")) matriz=[[0 for x in range(m)]for y in range(n)] i=0 j=0 while(i<n): while(j<m): matriz[i][j]=random.randint(0,100) j = j+1 i = i+1 j = 0 i=0 j=0 print(matriz) def buscaprimo(num): PD=2 while((PD<=num/2) and (num%PD<>0)): PD=PD+1 if((PD>num/2) and (num<>1)): return 1 else: return 0 i=0 j=0 while(i<n): while(j<m): z=matriz[i][j] if(buscaprimo(z)==1): print z j=j+1 j=0 i=i+1
|
|
|
|
|
En línea
|
  Se toma por necios a aquellos que dicen lo que todos pesamos
|
|
|
VonN
Desconectado
Mensajes: 151
Learnin' Python&C++
|
El 2 y el 4 en Pascal: program factorial; uses crt; var i,n,f:integer; begin clrscr; f:=1; readln(n); for i:=1 to n do begin f:=f*i; end; write(f); readln(n); end. program Untitled; uses crt; var n,p,s,i,a,aux:integer; begin clrscr; readln(n); readln(p); readln(s); if p<s then begin aux:=p; p:=s; s:=aux; end; for i:=1 to n-2 do begin readln(a); if p<a then begin s:=p; p:=a; end else begin if s<a then begin s:=a end; end; end; write(s); readln(n); end.
|
|
|
|
|
En línea
|
  Se toma por necios a aquellos que dicen lo que todos pesamos
|
|
|
VonN
Desconectado
Mensajes: 151
Learnin' Python&C++
|
Ejercicio inserión + búsqueda binaria. Tema: Variables indizadas unidimensionales: program Untitled; uses crt; var e,l,r,n,m,i,j:integer; a: array[1..100] of integer; begin clrscr; writeln('Ingrese cantidad elementos'); readln(n); writeln('Ingreso de elementos'); for i:=1 to n do begin readln(a[i]); end; writeln('Lista ingresada:'); for i:=1 to n do begin write(a[i],','); end; writeln('Ingrese e buscado'); readln(e); l:=1; r:=n+1; while l<r do begin m:=((l+r)div 2); if a[m]<e then begin l:=m+1; end else begin r:=m; end; end; if a[r]=E then begin writeln('Su posicion es:'); write(r); end else begin for j:=n downto r do begin a[j+1]:=a[j]; end; a[r]:=e; writeln('Se produjo una insercion'); end; readln(); end.
|
|
|
|
|
En línea
|
  Se toma por necios a aquellos que dicen lo que todos pesamos
|
|
|
h0oke
Desconectado
Mensajes: 2.058
Coder ~
|
Muy bien VonN, gracias por tu aporte!
Salu2!
|
|
|
|
|
En línea
|
|
|
|
Danther
Desconectado
Mensajes: 26
|
Las matematicas no son mi fuerte, pero espero no haberme equivocado con lo que se pedia: El primer ejercicio y el segundo juntos en Java: import java.io.*; public class Main{ private BufferedReader bf; public Main(){ bf = new BufferedReader(new InputStreamReader(System.in)); } private int PedirFilas() throws IOException{ int numFilas = 0; System.out.println("Introduce el numero de filas:"); String filas = bf.readLine(); try{ numFilas = Integer.parseInt(filas); if(numFilas < 0) numFilas = Math.abs(numFilas); }catch (Exception e){ System.out.println("El numero introducido no es valido"); System.exit(1); } return numFilas; } private int PedirColumnas() throws IOException{ int numColumnas = 0; System.out.println(); System.out.println("Introduce el numero de columnas:"); String columnas = bf.readLine(); try{ numColumnas = Integer.parseInt(columnas); if(numColumnas < 0) numColumnas = Math.abs(numColumnas); }catch (Exception e){ System.out.println("El numero introducido no es valido"); System.exit(1); } return numColumnas; } private void MostrarMatriz(int filas, int columnas) throws IOException{ int numLectura = 0; int [][] matriz = new int[filas][columnas]; System.out.println(); System.out.println("Indicame como quieres que se muestre."); System.out.println("-------------------------------------"); System.out.println("1 - Por filas"); System.out.println("2 - Por columnas"); String lectura = bf.readLine(); InicializarMatriz(matriz, filas, columnas); try{ numLectura = Integer.parseInt(lectura); if(numLectura != 1 && numLectura != 2){ System.out.println("El numero introducido no es valido"); System.exit(1); } }catch (Exception e){ System.out.println("El numero introducido no es valido"); System.exit(1); } System.out.println(); if(numLectura == 1){ for(int f = 0; f < filas; f++){ System.out.println("Fila "+(f+1)); for(int c = 0; c < columnas-1; c++){ System.out.print(matriz[f][c]); System.out.print(" -- "); } System.out.print(matriz[f][columnas-1]); System.out.println(); } }else{ for(int c = 0; c < columnas; c++){ System.out.println("Columna "+(c+1)); for(int f = 0; f < filas-1; f++){ System.out.print(matriz[f][c]); System.out.print(" -- "); } System.out.print(matriz[filas-1][c]); System.out.println(); } } } private void InicializarMatriz(int[][] matriz, int filas, int columnas) { for(int f = 0; f < filas; f++){ for(int c = 0; c < columnas; c++){ matriz[f][c] = (int)(Math.random()*100); } } } public static void main(String[] args) throws IOException { Main main = new Main(); main.MostrarMatriz(main.PedirFilas(), main.PedirColumnas()); } } Pd: O java usa mucho codigo, o yo soy muy torpe... T.T XD
|
|
|
|
« Última modificación: 29 Julio 2009, 16:58 por danther »
|
En línea
|
|
|
|
h0oke
Desconectado
Mensajes: 2.058
Coder ~
|
Nunca he estudiado Java, pero puedo apreciar que te esmeras más en la "interfaz" que en el algoritmo del problema. Espero que se de una pasada Amerik@no para chekar el problema.
Un saludo!
|
|
|
|
|
En línea
|
|
|
|
Shadowofvilla
Desconectado
Mensajes: 3
|
muchas gracias por el aporte saludos
|
|
|
|
|
En línea
|
|
|
|
|
|