Guest User

Untitled

a guest
Feb 17th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. public class ConjuntoTabla implements Conjunt {
  2. //Descripción general: Implementación en forma de tabla de enteros
  3.  
  4. //Tabla de enteros ordenada de forma creciente
  5. private int _tablaInt[];
  6.  
  7. public ConjuntoTabla() {
  8. this._tablaInt = new int [0];
  9. }
  10.  
  11. private void setElem(int i, int n) {
  12. _tablaInt[i] = n;
  13. }
  14.  
  15. private int getElem(int i) {
  16. return _tablaInt[i];
  17. }
  18.  
  19. //Cierto si n pertenece al conjunto
  20. public boolean pertenece(int n) {
  21. int medio, izq = 0, der = this.nelem()-1;
  22. boolean encontrado = false;
  23. while (!encontrado && izq <= der) {
  24. medio = (izq + der)/2;
  25. if (n < getElem(medio)) der = medio -1;
  26. else if (n > getElem(medio)) izq = medio + 1;
  27. else encontrado = true;
  28. }
  29. return encontrado;
  30. }
  31.  
  32. public int nelem() {
  33. return (_tablaInt.length);
  34. }
  35.  
  36. @Override
  37. public String toString() {
  38. String s = "";
  39. for (int i=0; i<nelem(); i++) {
  40. if (i==0) s = s+getElem(i);
  41. else s = s + "," + getElem(i);
  42. }
  43. return "[" + s + "]";
  44. }
  45. }
  46.  
  47. //Se ha añadido n al conjunto ordenadamente
  48. public void insertar(int n)
  49. {
  50. if (!this.pertenece(n)) {
  51. int i = this.nelem();
  52. int aux[] = new int[i+1];
  53. for (int j=0; j < i; j++) {
  54. aux[j] = getElem(j);
  55. }
  56. //Busca la posición donde se debe insertar n
  57. while (i > 0 && n < getElem(i-1)) {
  58. aux[i] = getElem(i-1);
  59. i--;
  60. }
  61. aux[i] = n;
  62. _tablaInt = aux;
  63. }
  64. }
  65.  
  66. import java.util.Scanner;
  67.  
  68. public class TestConjuntoTabla {
  69. //Lee dos secuencias consecutivas de enteros separadas con '#' y las
  70. //pone en dos conjuntos
  71.  
  72.  
  73. public static void main(String argv[]) throws Exception {
  74. Scanner s = new Scanner(System.in);
  75. Conjunto c1 = new ConjuntoTabla();
  76. Conjunto c2 = new ConjuntoTabla();
  77.  
  78. System.out.println("Introducir dos secuencias de enteros, separadas por el símbolo: #");
  79.  
  80. while (s.hasNextInt())
  81. c1.añadir(s.nextInt());
  82.  
  83. s.next(); // Salta '#'
  84.  
  85. while (s.hasNextInt())
  86. c2.añadir(s.nextInt());
  87.  
  88. System.out.println("nc1: " + c1);
  89. System.out.println("c2: " + c2);
  90. }
Add Comment
Please, Sign In to add comment