elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


  Mostrar Temas
Páginas: [1] 2
1  Programación / PHP / Problema con conexion de Yii Framework a SQLServer en: 29 Enero 2016, 15:16 pm
Estoy intentando conectar Yii con SQLSERVER y me sale este error.

Código
  1. CDbException
  2.  
  3. CDbConnection failed to open the DB connection.

Esto es lo que tengo en el COMMON/Config/main.php

Código
  1. <?php
  2.  
  3. return array(
  4.    'preload' => array('log', 'bootstrap'),
  5.    'aliases' => array(
  6.        'frontend' => dirname(__FILE__) . '/../..' . '/frontend',
  7.        'common' => dirname(__FILE__) . '/../..' . '/common',
  8.        'backend' => dirname(__FILE__) . '/../..' . '/backend',
  9.        'vendor' => dirname(__FILE__) . '/../..' . '/common/lib/vendor',
  10.        'bootstrap' => dirname(__FILE__) . '/../..' . '/common/lib/vendor/clevertech/yii-booster/src',
  11.        'auth' => dirname(__FILE__) . '/../..' . '/backend/modules/auth'
  12.    ),
  13.    'import' => array(
  14.        'common.extensions.components.*',
  15.        'common.components.*',
  16.        'common.helpers.*',
  17.        'common.models.*',
  18.        'application.controllers.*',
  19.        'application.extensions.*',
  20.        'application.helpers.*',
  21.        'application.models.*',
  22.        'common.gii.*'
  23.    ),
  24.    'language' => 'es',
  25.    //'behaviors' => array('LanguageBehavior'),
  26.    'components' => array(
  27.        'db' => array(
  28.            //'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
  29.            //'connectionString' => 'mysql:host=192.168.0.117;dbname=yiiBase',
  30.            'connectionString' => 'sqlsrv:server=SOPORTE03\SQLEXPRESS;database=seguimiento',
  31.            //'emulatePrepare' => true,
  32.            'username' => 'sa',
  33.            'password' => 'jean1234',
  34.            //'charset' => 'utf8',
  35.            'tablePrefix' => 'dbo.',
  36.        ),
  37.        'errorHandler' => array(
  38.            'errorAction' => 'site/error',
  39.        ),
  40.        'bootstrap' => array(
  41.            'class' => 'common.lib.vendor.clevertech.yii-booster.src.components.Bootstrap',
  42.        ),
  43.        'log' => array(
  44.            'class' => 'CLogRouter',
  45.            'routes' => array(
  46.                array(
  47.                    'class' => 'CDbLogRoute',
  48.                    'connectionID' => 'db',
  49.                    'levels' => 'error, warning',
  50.                ),
  51.            ),
  52.        ),
  53.    ),
  54.    'params' => array(
  55.        // php configuration
  56.        'php.defaultCharset' => 'utf-8',
  57.        'php.timezone' => 'UTC',
  58.    )
  59. );
2  Programación / Java / error en consulta sql en java! en: 21 Octubre 2015, 19:51 pm
Alguien sabe porque me sale este error? He tratado de solucionarlo pero de momento no he podido !!! Saludos!!!


java.sql.SQLException: Operation not allowed after ResultSet closed



Código:
  public  int GenerarIDInfante(){
    int IDGenerado=0;
    
    try {
            operaciones consulta=new operaciones(); //crea un objeto de la clase consulta
            ResultSet resultado=consulta.ConsultaBase("select count(*) as id from documentos"); //
            
              resultado.next();
              IDGenerado=resultado.getInt("id");
              
//          
            consulta.getStmt().close();
            
        } catch (SQLException ex) {
             System.out.println(ex);
        }
    
    return IDGenerado+1;
   }




Mod: No escribir en maýuculas
3  Programación / Programación C/C++ / Lectura de archivo log, error al eliminar IPs duplicadas! en: 8 Junio 2015, 04:31 am
Tengo un problema al eliminar las direcciones IP que se repiten!

Código
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <fstream>
  4. #include <ctime>
  5. #include <string>
  6. #include<cstdio>
  7.  
  8. using namespace std;
  9.  
  10. /*
  11.  *Leer el log y extraer la primera dirección IP  (nnn.nnn.nnn.nnn).
  12.  *Guardar la dirección ip en una lista -evitar que se repite la dirección ip.
  13.  *Resumir cuantas veces se repite cada ip y visualizar en un SVG el resumen.
  14.  */
  15.  
  16. struct miDataStruct {
  17.    string direccionIP;
  18.    int id;
  19. };
  20.  
  21. struct nodo {
  22.    miDataStruct datoDelNodo;
  23.    nodo *ant;
  24.    nodo *next;
  25. };
  26.  
  27.  
  28. //PROTOTIPOS
  29.  
  30. void archivos_lectura(nodo * list);
  31. int getPosition(string linea,int opcion,int ini);
  32. //FUNCIONES DE MI LISTA DOBLE
  33. nodo * new_list();
  34. nodo * insert_right(nodo *list, nodo data);
  35. void printListAsc(nodo *head);
  36. void printListDesc(nodo *head);
  37. void printList(  nodo* list);
  38.  
  39. void borrarNodo(nodo **head, nodo *node);
  40. void removerDuplicado(nodo **head);
  41.  
  42.  
  43.  
  44. int main () {
  45.  
  46. nodo *head = new_list();
  47.     nodo *current = head;
  48.      archivos_lectura(current);
  49.  
  50.      printList( current);
  51.     removerDuplicado(&head);
  52.  
  53.  
  54.  
  55.  return 0;
  56. }
  57.  
  58. nodo * new_list(){
  59.  
  60.    nodo *newelement= new nodo;
  61.    newelement->datoDelNodo.direccionIP = - 1 ;
  62.    newelement->next = newelement;
  63.    newelement->ant = newelement;
  64.    return newelement;
  65.  
  66. }
  67.  
  68. void addList(  nodo *list , string number){    
  69.        nodo *newelement = new nodo;
  70.        newelement->datoDelNodo.direccionIP = number;      
  71.        newelement->next = list;
  72.        newelement->ant = list->ant;
  73.        list->ant = newelement;
  74.        newelement->ant->next = newelement;
  75. }
  76.  
  77.  
  78. void printListAsc(nodo *head) {
  79.    nodo *current = head;
  80.    while (current->next != head) {
  81.        current = current->next;        
  82.        printList(current);      
  83.    }
  84. }
  85.  
  86.  
  87. void printListDesc(nodo *head) {
  88.    nodo *current = head;
  89.    //printNode(current);
  90.    while (current->ant != head) {
  91.        current = current->ant;
  92.        printList(current);
  93.  
  94.    }
  95. }
  96.  
  97. void printList(  nodo* list){
  98. nodo *head = list;
  99. nodo *current = list;
  100. int i=1;
  101. char caracter;
  102. while (current != head->ant){
  103.            current=current->next;
  104.            cout<<"LINEA --------> "<<i++<<endl<<endl;
  105.       cout<<"Numero de IP: "<<current->datoDelNodo.direccionIP<<endl;
  106.       cout<<"__________________________________"<<endl<<endl;
  107.      // caracter = getchar();
  108.       //getch();
  109.        }
  110. cout<< endl ;
  111.  
  112. }
  113.  
  114. // Proceso de los ficheros...
  115.  
  116. //Obteniendo la posicion de los datos del .log        
  117. int getPosition(string linea,int opcion,int ini){
  118.  
  119. int r;
  120.  
  121. switch(opcion) {
  122.    case 1:
  123.        r = linea.find("UDP") + 4;break;
  124.    case 2:
  125.        r=linea.find(" ",ini);break;
  126. }
  127. // -----> En caso de mas parametros a obtener, mas case; <-
  128. return r;
  129. }
  130.  
  131.  
  132. void archivos_lectura(nodo * list) {
  133.  nodo *current=list;  
  134.  
  135.  string line;
  136.  ifstream myfile ("firewall_1.log");
  137.  int p1,p2;
  138.  string numero;
  139.  
  140.  nodo myDataIP;
  141.  
  142.  if (myfile.is_open())
  143.  {
  144.    while ( getline (myfile,line) )
  145.    {
  146.        p1 =getPosition(line,1,0); // p1=29
  147.        p2=getPosition(line,2,p1);
  148.        numero=line.substr(p1,p2-p1);    
  149.        addList(current,numero);
  150.  
  151.        //cout << line << '\n';
  152.    }
  153.  
  154.    myfile.close();
  155.  }
  156.  
  157.  else cout << "Unable to open file";
  158. }
  159.  
  160.  
  161. // FUNCIONES PARA ELIMINAR LOS DUPLICADOS
  162.  
  163. void removerDuplicado(nodo **head)
  164. {
  165. if((*head)->next == NULL) return;
  166. nodo *current = *head;
  167. nodo *aux;
  168. while(current) {
  169. aux = current->next;
  170. while(aux) {
  171. if(current->datoDelNodo.direccionIP == aux->datoDelNodo.direccionIP) {
  172. borrarNodo(head, aux);
  173. }
  174. aux = aux->next;
  175. }
  176. current = current->next;
  177. }
  178. return;
  179. }
  180.  
  181.  
  182.  
  183. void borrarNodo(nodo **head, nodo *node)
  184. {
  185. nodo *current = *head;
  186. nodo *ant = *head;
  187. if(node == *head) {
  188. if((*head)->next != NULL) {
  189. *head = (*head)->next;
  190. }
  191. return;
  192. }
  193. while(current) {
  194. if(current == node) {
  195. ant->next = current->next;
  196. return;
  197. }
  198. ant = current;
  199. current = current->next;
  200. }
  201. }
  202.  
  203.  

//aqui les adjunto el codigo completo con el archivo log para que lo abran como proyecto!
https://mega.co.nz/#F!L8NSyIxZ!RZX98C_HXUVnnwaW30UYFw

Mod: No escribir en mayúsculas
4  Programación / Scripting / Error en busqueda en amplitud con python en: 3 Junio 2015, 18:43 pm
He estado tratando de corregir el error pero no lo encuentro ... Me sale: while nodo.get_padre() != None:
AttributeError: 'NoneType' object has no attribute 'get_padre'


Código
  1. from arbol import Nodo
  2.  
  3. def buscar_solucion_BFS(estado_inicial, solucion):
  4.    solucionado = False
  5.    nodos_visitados = []
  6.    nodos_frontera = []
  7.    nodoInicial = Nodo(estado_inicial)
  8.    nodos_frontera.append(nodoInicial)
  9.    while(not solucionado) and len(nodos_frontera) != 0:
  10.        nodo = nodos_frontera.pop(0)
  11.        #extraer nodo y anadirlo a visitados
  12.        nodos_visitados.append(nodo)
  13.        if nodo.get_datos() == solucion:
  14.            #solucion encontrada
  15.            solucionado = True
  16.            return nodo
  17.        else:
  18.            #expandir nodos hijos
  19.            dato_nodo = nodo.get_datos()
  20.  
  21.            #operador izquierdo
  22.            hijo = [dato_nodo[1], dato_nodo[0], dato_nodo[2], dato_nodo[3]]
  23.            hijo_izquierdo = Nodo(hijo)
  24.            if not hijo_izquierdo.en_lista(nodos_visitados) and not hijo_izquierdo.en_lista(nodos_frontera):
  25.                nodos_frontera.append(hijo_izquierdo)
  26.                #operador central
  27.                hijo = [dato_nodo[0], dato_nodo[2], dato_nodo[1], dato_nodo[3]]
  28.                hijo_central = Nodo(hijo)
  29.                if not hijo_central.en_lista(nodos_visitados) and not hijo_central.en_lista(nodos_frontera):
  30.                    nodos_frontera.append(hijo_central)
  31.                    #operador derecho
  32.                    hijo = [dato_nodo[0], dato_nodo[1], dato_nodo[3], dato_nodo[2]]
  33.                    hijo_derecho = Nodo(hijo)
  34.                    if not hijo_derecho.en_lista(nodos_visitados) and not hijo_derecho.en_lista(nodos_frontera):
  35.                        nodos_frontera.append(hijo_derecho)
  36.  
  37.                        nodo.set_hijos([hijo_izquierdo, hijo_central, hijo_derecho])
  38.  
  39.  
  40. if __name__ == "__main__":
  41.    estado_inicial = [4, 2, 3, 1]
  42.    solucion = [1, 2, 3, 4]
  43.    nodo_solucion = buscar_solucion_BFS(estado_inicial, solucion)
  44.        #mostrar resultado
  45.    resultado = []
  46.    nodo = nodo_solucion
  47.    while nodo.get_padre() != None:
  48.        resultado.append(nodo.get_datos())
  49.        nodo = nodo.get_padre()
  50.    resultado.append(estado_inicial)
  51.    resultado.reverse()
  52.  
  53.    print resultado
  54.  
5  Programación / Java / ayuda sencilla de applet en: 13 Mayo 2015, 06:21 am
Mod: lee las reglas del foro, no debes escribir en mayúsculas, los codigos ven en etiquetas GeSHi, las cosas van en su respuesctivo subforo... tema corregido y movido

saludos, tengo un error en mi ejercicio y me gustaria que me ayuden a encontrar el problema; es sobre la resolucion de una ecuacion cuadratica con applets...


Código
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6.  
  7. import java.applet.Applet;
  8. import java.awt.*;
  9. import java.applet.*;
  10. import java.awt.event.*;
  11. import java.lang.Math;
  12.  
  13. /**
  14.  *
  15.  * @author
  16.  */
  17. public class EcuacionApplet extends Applet implements ActionListener {
  18.  
  19.    /**
  20.      * Initialization method that will be called after the applet is loaded into
  21.      * the browser.
  22.      */
  23.    Label l1, l2, l3, l4, l5;
  24.    TextField t1, t2, t3, t4, t5,t6,t7;
  25.    Button b;
  26.  
  27.    public void init() {
  28.        // TODO start asynchronous download of heavy resources
  29.  
  30.        // --> DECLARANDO MIS ETIQUETAS Y CAJAS DE TEXTO
  31.        l1 = new Label("a");
  32.        t1 = new TextField();
  33.  
  34.        l2 = new Label("b");
  35.  
  36.        t2 = new TextField();
  37.  
  38.        l3 = new Label("c");
  39.        t3 = new TextField();
  40.  
  41.        l4 = new Label("Raiz 1");
  42.        t4 = new TextField("  ");
  43.  
  44.        l5 = new Label("Raiz 2");
  45.  
  46.        t5 = new TextField("  ");
  47.  
  48.        b = new Button("CALCULAR");
  49.        t6= new TextField("  ");
  50.        t7= new TextField("  ");
  51.  
  52.     // --> AÑADIENDO BOTONES Y LABELS
  53.        add(l1);
  54.        add(t1);
  55.        add(l2);
  56.        add(t2);
  57.        add(l3);
  58.        add(t3);
  59.        add(b); //-->BOTON
  60.        add(l4);
  61.        add(t4);
  62.        add(l5);
  63.        add(t5);
  64.        add(t6);
  65.        add(t7);
  66.    b.addActionListener(this);
  67.    // TODO overwrite start(), stop() and destroy() methods
  68.    }
  69.  
  70.    //-->OPERACIONES LOGICAS DEL BOTON CALCULAR
  71.    public void actionPerformed(ActionEvent ae) {
  72.  
  73.        // var a=num,b=num2,c=num3
  74. double num=Double.parseDouble(t1.getText());
  75. double num2=Double.parseDouble(t2.getText());
  76. double num3=Double.parseDouble(t3.getText());
  77. // descarga en la variable d el valor de b^2-4ac
  78. double d=(Math.pow(num2,2.0)-(4*num*num3));
  79. // calcula las raices de la ecuación
  80.        double raiz1=((-num2)+Math.sqrt(d))/(2*num);
  81.        double raiz2=((-num2)-Math.sqrt(d))/(2*num);
  82. // compara la variable d
  83. if (d==0)
  84. {
  85. // las raices son igulaes
  86. t6.setText(""+raiz1);
  87. t7.setText(""+raiz2);
  88. }
  89. if (d>0)
  90. {
  91. // tiene 2 raices diferentes
  92. t6.setText(""+raiz1);
  93. t7.setText(""+raiz2);
  94. }
  95.  
  96. if (d<0) //--> CONDICION DE VALORES IMAGINARIOS
  97. {
  98. t6.setText("IMAGINARIA");
  99. t7.setText("IMAGINARIA");
  100. }
  101.  
  102.    }
  103.  
  104.   //---> POSICIONANDO ENCABEZADO
  105.    public void paint(Graphics g) {
  106.        g.drawString("Resolucion Ecuación Cuadratica  aX^2+bx+c=0", 10, 110);
  107.        g.drawString("Lenguaje de Programacion", 11, 130);
  108.  
  109.    }
  110.  
  111. }
6  Programación / Programación C/C++ / Problema al ordenar una Lista Doble(Lectura de XML) en: 23 Febrero 2015, 03:21 am
Alguien podría ayudarme a corregir mi error; lo que pasa es que estoy intentando ordenar mi lista Doble que la hice a partir de la lectura de un archivo xml.(La lectura funciona correctamente). Todo funciona hasta que ejecuta la funcion de ordenar y ahi deja de funcionar!

Les agradecería infinitamente si me ayudan a resolver este problema! Igual si encuentro la solución les aviso! Muchas Gracias de antemano!



Código:
#include <iostream>
#include <cstring>
#include <fstream>
#include <cstdlib>


using namespace std;

struct datos {
    string TITLE;
    string ARTIST;
    string COUNTRY;
    string COMPANY;
    float PRICE;
    int YEAR;
};

struct node {
    datos data;
    node *left;
    node *right;
};

string getTagName(string str);
string getTagContent(string str);
node * newList();
node * insert_right(node *list, datos nuevo_nodeo);
void printList(node* list);
void readXML(node *head);
void sortList(node **lista, int rule, bool dsc) ;


int main() {

    node *head = newList();
    node *current = head;

    //LEYENDO MI ARCHIVO XML
    readXML(head);


    cout << "IMPRIMIENDO LISTA" << endl << endl;
    printList(head);
     // Todo funciona hasta que le incorpora la parte para ordenar y la aplicacion deja de funcionar en ese momento!!
    
    
     sortList( &head, 1, true );  // Ordenando por precio, pero no me funciona y no encuentro el error!
    
     return 0;
}

node * newList() {
    node *nuevo;
    nuevo = new node;
    nuevo->data.ARTIST=-1;
     nuevo->data.COMPANY=-1;
      nuevo->data.COUNTRY=-1;
       nuevo->data.PRICE=-1;
        nuevo->data.TITLE=-1;
         nuevo->data.YEAR=-1;
    nuevo->right = nuevo;
    nuevo->left = nuevo;
    return nuevo;
}


string getTagName(string str) {
    int posInit, posFin;
    int delta;
    posInit = str.find("<");
    posFin = str.find(">");
    delta = posFin - posInit;
    return str.substr(posInit + 1, delta - 1);
}

string getTagContent(string str) {

    int posInit, posFin;
    int delta;
    posInit = str.find(">");
    posFin = str.find("</");
    delta = posFin - posInit;

    return str.substr(posInit + 1, delta - 1);
}

node * insert_right(node *list, datos nuevo_nodeo) {
    node *nuevo;
    nuevo = new node;

    nuevo->data.TITLE = nuevo_nodeo.TITLE;
    nuevo->data.ARTIST = nuevo_nodeo.ARTIST;
    nuevo->data.COUNTRY = nuevo_nodeo.COUNTRY;
    nuevo->data.COMPANY = nuevo_nodeo.COMPANY;
    nuevo->data.PRICE = nuevo_nodeo.PRICE;
    nuevo->data.YEAR = nuevo_nodeo.YEAR;

    nuevo->left = list;
    nuevo->right = list->right;
    list->right = nuevo;
    nuevo->right->left = nuevo;
    return nuevo;
}

void printList(node* list) {
    node *head = list;
    node *current = list;

    while (head != (current = current->right)) {
        cout << "------------------------" << endl;
        cout << current->data.TITLE << endl;
        cout << current->data.ARTIST << endl;
        cout << current->data.COUNTRY << endl;
        cout << current->data.COMPANY << endl;
        cout << current->data.PRICE << endl;
        cout << current->data.YEAR << endl;
    }

}

void readXML(node *current) {

    datos nuevo;
    string fileName = "cd_catalog.XML";
    string line;
    string tagName;
    int posInit, posFin;
    int delta;
    int ban = 0;
    cout << "-----archivo XML->" << fileName << "--------" << endl << endl << endl;
    ifstream myFile((char*) fileName.c_str());

    while (getline(myFile, line, '\n')) {
        tagName = getTagName(line);

        if (ban == 0) {
            datos nuevo; //Para acceder a mi estructura facilmente!
        }

        if (tagName.compare("TITLE") == 0) {
            nuevo.TITLE = getTagContent(line);
            ban++;
        } else if (tagName.compare("ARTIST") == 0) {
            nuevo.ARTIST = getTagContent(line);
            ban++;
        } else if (tagName.compare("COUNTRY") == 0) {
            nuevo.COUNTRY = getTagContent(line);
            ban++;
        } else if (tagName.compare("COMPANY") == 0) {
            nuevo.COMPANY = getTagContent(line);
            ban++;
        } else if (tagName.compare("PRICE") == 0) {
            nuevo.PRICE = atof(getTagContent(line).c_str());
            ban++;
        } else if (tagName.compare("YEAR") == 0) {
            nuevo.YEAR = atoi(getTagContent(line).c_str());
            ban++;
        }

        if (ban == 6) {
            current = insert_right(current, nuevo);
            ban = 0;
        }

    }

    myFile.close();
        
}



void sortList(node **lista, int rule, bool dsc) {

    // rule { 1 --> Price, 2 --> year, 3 --> Artis, 4 --> title }

    node *lst = *lista;

    node *sig;

    datos temp;

    //-- Boolean para validar situación de cambio ---//
    bool valid;

    do {

        sig = lst->right;

        while (sig->right != NULL) {

            switch (rule) {

                case 1:


                    valid = dsc ? (lst->data.PRICE > sig->data.PRICE) : (lst->data.PRICE < sig->data.PRICE);

                    break;

                case 2:


                    valid = dsc ? (lst->data.YEAR > sig->data.YEAR) : (lst->data.YEAR < sig->data.YEAR);

                    break;

                case 3:

                    valid = dsc ? (lst->data.ARTIST > sig->data.ARTIST) : (lst->data.ARTIST < sig->data.ARTIST);

                    break;

                case 4:

                    valid = dsc ? (lst->data.TITLE > sig->data.TITLE) : (lst->data.TITLE < sig->data.TITLE);

                    break;

            }

            if (valid) {

                temp = lst->data;

                lst->data = sig->data;

                sig->data = temp;

            }

            sig = sig->right;

        }

        lst = lst->right;

    } while (lst->right != NULL);

}


7  Programación / Programación C/C++ / BUSCAR EL VALOR MAXIMO Y MINIMO DEL ARBOL BINARIO en: 27 Julio 2014, 00:09 am
/*
 * File:   firstTree.cpp
 * Author: Estudiantes
 *
 * Created on 17 de julio de 2014, 06:49 PM
 *
 *
 */

//Necesito saber como sacar el valor máximo y mínimo del árbol binario que esta a //continuación graficado. El problema es que mi función solo toma los valores //extremos del arbol( izquierda y derecha) que son hojas!


#include <cstdlib>
#include <iostream>


using namespace std;

/*
 *
 *
 *
 *
 *
 */

struct misDatos{
    string nombre;
    int edad;
    int num;
};

struct node{
    misDatos datos;
    node *left;
    node *right;
};



node * newTree();
node * insert(int data, string name);


int printPreOrden(node* ptr);
int printRoot(node* head);
int printPostOrden(node *ptr);
int printInOrden(node *ptr);
int findMinimumValueLEFT(node* node);
int findMinimumValueRIGHT(node* node);


int size(node *node); //MAXIMO DE NODOS
int maxALTURA(node *node); //ALTURA


node * insert_right( int data);
node * insert_left( int data);
 int contar_hojas(node *p) ;
int nodosInteriores(node *raiz );

node *max(node *n);
node *min(node *n);


int MAXIMOprintPreOrden(node* ptr);



int main() {
   
   //ARBOL 1
   node *raiz = newTree();
   node *current = raiz;
   node *arbol=raiz;
   
   /*
   
 ----> GRAFICO DEL ARBOL BINARIO
   
        A
     /    \
    B      C
  / \    /  \
  D  E  F    G

*/
   
   
        //A=10
        //B=14
        //C=16
        //D=18
        //E=20
        //F=24
        //G=30
   
        arbol->left = insert(14,"B");
        arbol->right = insert(16,"C");

        current=arbol->left;
 
        current->left = insert(50,"D");
        current->right = insert(60,"E");

        current=arbol->right;
       
       
        current->left = insert(24,"F");
        current->right = insert(30,"G");
   
     
   
            cout << "\tR E C O R R I D O  P R E - O R D E N\n";
            printPreOrden(raiz);
   



    //cout<<endl<<endl;
   // cout << "\tR E C O R R I D O  P O S T - O R D E N\n";
    //printPostOrden(raiz);
   
     //cout<<endl<<endl;
    //cout << "\tR E C O R R I D O  I N - O R D E N\n";
   // printInOrden(raiz);
            cout<<endl<<endl<<endl<<endl;
           
 
           
            cout<<"NUMERO DE NODOS: "<<size(raiz)<<endl;
           
            cout<<"ALTURA :  "<<maxALTURA(raiz)<<endl;
           cout<<"NUMERO DE HOJAS: "<<contar_hojas(raiz)<<endl;
           
           cout<<"NODOS INTERIORES: "<<nodosInteriores(raiz)<<endl;
     
           
           
    return 0;
}

//---------------> NEW TREE
node * newTree() {
    node *nuevo;
    nuevo = new node; 
   
    nuevo->datos.nombre= "A";
    nuevo->datos.edad = 10; // 
    nuevo->right = nuevo;
    nuevo->left = nuevo;

    return nuevo;
}

// -------------> INSERTANDO
node* insert(int data, string name) {
   
    node *nuevo;
    nuevo = new node;
    nuevo->datos.edad=data;
    nuevo->datos.nombre=name;
    nuevo->left=NULL; 
    nuevo->right=NULL;

    return nuevo;
}




// -------------> O R D E N A M I E N T O S

// -----> PREORDEN

int printPreOrden(node* ptr) {
   
    node *current = ptr;
   
   
      printRoot(current);     //RAIZ
 
   
      if(current->left!=NULL){
         printPreOrden(current->left);    //IZQUIERDA     
       }
   
    if(current->right!=NULL){
       printPreOrden(current->right);    //DERECHA
    }
    return current->datos.edad;
}





int printPostOrden(node *ptr){
    node *current= ptr;
   
     if(current->left!=NULL){
         printPostOrden(current->left);    //IZQUIERDA     
       }

     if(current->right!=NULL){
       printPostOrden(current->right);    //DERECHA
    }
   
    printRoot(current);   
   
   
}

int printInOrden(node *ptr){
    node *current= ptr;
   
     if(current->left!=NULL){
         printInOrden(current->left);    //IZQUIERDA     
       }
   
      printRoot(current);
   
      if(current->right!=NULL){
       printInOrden(current->right);    //DERECHA
    }
   
 
   
}


//numero de nodos
int size(node *node){
    if(node==NULL)
        return 0;
    else
        return (size(node->left)+1+size(node->right));
}
//altura del arbol
int maxALTURA(node *node){
    if(node==NULL)
        return 0;
    else{
        int s=maxALTURA(node->left);
     int m=maxALTURA(node->right);
     if (s>m)
         return (m+1);
     else
         return (s+1);
    }return (size(node->left)+1+size(node->right));
}



//IMPRIMIENDO RAIZ

int printRoot(node* head)
{
    cout<<"Nombre: "<<head->datos.nombre<<"    Edad: "<< head->datos.edad<<"\n"<<endl;
   
}


//VALORES MAXIMOS Y MINIMOS ERRONEOS
    node *min(node *n) {
        if (n == NULL || n->left == NULL)
            return n;
        else
            return min(n->left);
    }

    node *max(node *n) {
        if (n == NULL || n->left == NULL)
            return n;
        else
            return max(n->left);
    }
   


//-----> CONTAR HOJAS   
int contar_hojas(node *p){
   if (p == NULL)
      return 0;
   else if (p->left == NULL && p->right == NULL)
      return 1;
   else
      return contar_hojas(p->left) + contar_hojas(p->right);
}

//NODOS INTERIORES
   int nodosInteriores(node *raiz ){
      return size(raiz)-contar_hojas(raiz);
}
8  Programación / Programación C/C++ / Ordenar strings de analisis de fechas en lista doblemente enlazada. en: 13 Junio 2014, 21:05 pm
/*
 *

 * Analizar los elementos en la lista por:
 *

 * ------>precio ( los 5 libors mas caros, mlas baratos, imprimir del libro mas caro al mas barato) ---> Casi completada

 * ------>fecha de publicacion (el libro mas viejo, lista del libro mas "joven" al mas viejo) ---> como ordenar strings?

 * ------>Libros por autor (lista ordenado por autor, y libro) --> como ordenar strings?
 *  
 *
 * Created on 9 de junio de 2014, 18:11
 * Como puedo ordenar los strings de fechas? ... y tambien que esta mal en mi
 * mostrarLista. PD. Estoy trabajando con PUGIXML para leer xml.
 * pero hacer enfasis sobre todo en estas 2 funciones.
 */

// LIBRERIAS.
#include <iostream>
#include <string>
#include "pugixml.hpp"
#include "pugixml.cpp"



// ESPACIO DE NOMBRES.
using namespace std;


#define ASCENDENTE 1
#define DESCENDENTE 0

// ESTRUCTURAS.
struct datos {
    string id; //id
    string autor; //author
    string titulo; //tittle
    string genero; //genre
    float precio; //price
    string  fechaPublic; //public date
    string descripcion; //descrip
    
    int number;
};

//struct c_date {
//    int USA;
//    int UK;
//    int EU;
//    int Norway;
//};

struct node {
    datos data;
    datos dataMoment;
    node *left;
    node *right;
};


// PROTOTIPOS.
// Función para crear una lista.
node *newList();
// Función para insertar en una lista por la derecha.
node *insertRight(node *list, node data);
// Función para imprimir un nodo en la lista.
void printNode(node *current);
// Función para imprimir la lista.
void printList(node *current);
// Función para retornar el tamaño de la lista.
int size(node * list);
node *analisisFecha(node *head);
// Función para leer el archivo XML.
void read(node *list);
node *Insertar(node *list, node data);
void ordenarLista(node *lista);
// Función para determinar libros mas caros y mas baratos
//void country(node *head);
node  *LibrosCaros(node *head);
node *LibrosBaratos(node *head);

//void analisisFecha(node *head);
void MostrarLista(node *head, int orden);


// FUNCIÓN PRINCIPAL.
int main() {
    node *head = newList();
    node *current = head;
    
    cout << "Lista\n";
    
    read(head);
    
    cout << "----------------------------------" << endl;
    printList(head);
    
   // MostrarLista(head,ASCENDENTE);
    
    cout << endl << "TAMAÑO DE LISTA TOTAL: " << size(head) << endl << endl << endl;
    
    cout << "______________________________________________________" << endl;
 
    
    
    cout<<"LIBROS BARATOS:"<<endl<<endl;
    LibrosBaratos(head);
    //printList(LibrosCaros(head)); //Imprimir lista de libros BARATOS detalladamente
    
    cout << "______________________________________________________" << endl;
    cout<<"LIBROS CAROS:"<<endl<<endl;
    LibrosCaros(head);
    //printList(LibrosCaros(head)); //Imprimir lista de libros CAROS detalladamente
    
    analisisFecha(head);
    
    return 0;
}



// DESARROLLO DE LOS PROTOTIPOS.
node *newList() {
    node *element = new node;
    element->data.precio = -1;
    element->right = element;
    element->left = element;
    
    return element;
}


node *insertRight(node *list, node data) {
    node *element = new node;
    element->data = data.data;
    element->left = list;
    element->right = list->right;
    list->right = element;
    element->right->left = element;
    
    return element;
}


void printNode(node *current) {
    int number = 1;
    
    cout << "[" << current->data.number << "]" << endl << endl;
    cout << "Book ID  : " << current->data.id << endl;
    cout << "Autor : " << current->data.autor << endl;
    cout << "Titulo: " << current->data.titulo << endl;
    cout << "Genero: " << current->data.genero << endl;
    cout << "Precio  : " << current->data.precio << endl;
    cout << "Fecha de Publicacion   : " << current->data.fechaPublic << endl;
    cout << "Descripcion   : " << current->data.descripcion << endl;
    cout << "----------------------------------" << endl;
    
    number++;
}

void printList(node *head) {
    node *current = head;
    while (head != current->left) {
        current = current->left;
        printNode(current);
    }
    
    cout << endl;
}

int size(node * list) {
    node *head = list;
    node *current = list;
    
    int cont = 0;
    
    while (head != (current = current->right)) {
        cont = cont + 1;
    }

    return cont;
}

void read(node *list) {
    node date;
    
    string moment;
    
    pugi::xml_document book;
    book.load_file("books.xml");    
    pugi::xml_node catalog = book.first_child().first_child();
    int n = 1;
  
  
    do {
        
        date.data.id = catalog.attribute("id").as_string();
        
        date.data.autor = catalog.child("author").text().get();
        date.data.titulo = catalog.child("title").text().get();
        date.data.genero = catalog.child("genre").text().get();
      
        //convirtiendo precio
        moment = catalog.child("price").text().get();
        date.data.precio = atof(moment.c_str());
        date.data.fechaPublic= catalog.child("publish_date").text().get();
        
        date.data.number = n;
        date.data.descripcion = catalog.child("description").text().get();
        
        
        insertRight(list, date);
        
        n++;
    }
    while(catalog = catalog.next_sibling());
}

node *LibrosCaros(node *head){
    node *current =head;
    node *librosCaros= newList(); //Creando lista libros caros para realizar el analisis
    node data;
        
    while (head != (current=current->right)){
        if (current->data.precio>15){
            data.data=current->data;        
            cout<<current->data.titulo<<"-->"<<current->data.precio<<endl;
            insertRight(librosCaros, data); //Insertando en una segunda lista de libros caros, ojo si imprimo lista se imprimen todos los detalles de cada librp
                 }
        }
       return librosCaros;
          
}


node *LibrosBaratos(node *head){
    node *current =head;
    node *librosBaratos= newList(); //Creando lista libros caros para realizar el analisis
    node data;
        
    while (head != (current=current->right)){
        if (current->data.precio<15){
            data.data=current->data;        
            cout<<current->data.titulo<<"-->"<<current->data.precio<<endl;
            insertRight(librosBaratos, data); //Insertando en una segunda lista de libros caros
                 }
        }
          
       return librosBaratos;
          
}

//ANALIZAR FECHAS Y ORDENAR PERO TAMPOCO TRABAJA CORRECTAMENTE
node *analisisFecha(node *head){
    node *current =head;
    node *list3= newList(); //Creando lista 2 para realizar el analisis
    node data;
    string date = "2014-06-12";
    int temp;
    cout<<"_______________________________"<<endl<<endl;
    while (head != (current=current->right)){
        //if (current->data.fechaPublic<date)
          //  cout<<current->data.number<<"--->"<<current->data.fechaPublic<<endl;
  
    }
    
}

//FUNCION NO TRABAJA CORRECTAMENTE ...
void MostrarLista(node *head, int orden) {
  
   if(!head) cout<<"Lista Vacia";
   node *current = head;
  
   if(orden == ASCENDENTE) {
      
      while(current->left ) current = current->right;
      cout<<"Orden ascendente: "<<endl;
      while(current) {
         cout<<current->data.precio<<endl;  
         current = current->right;
      }
   }
   else {
      while(current->right) current = current->right;
      cout<<"Orden descendente: "<<endl;
      while(current) {
         cout<<current->data.precio<<endl;
         current = current->left;
      }
   }
   cout<<endl;
}


9  Programación / Programación C/C++ / Listas dobles, comparacion de un elemento con el siguiente en: 24 Enero 2014, 05:18 am
Saludos, mi duda es acerca de como puedo comparar un elemento con el siguiente hasta el final de la lista doble! El problema radica en que por ejemplo tengo que contar cuantas materias diferentes tengo en mi lista. Necesito ir comparando elemento a elemento hasta el final de la lista.
PDTA. Materia es tipo string.


      int i=0; //Contador de nodos
       int j=1; //Contador de materias diferentes

while (current != head->left){
            current=current->right;
      
       cout<<"NODO --------> "<<j++<<endl<<endl;
       cout<<"MATERIA : "<<current->data.materia<<endl;
       cout<<"__________________________________"<<endl<<endl;
       if (current->data.materia==current->right->data.materia) //PROBLEMA
           cout<<i++<<endl;
      
getch();
        
}
10  Programación / Programación C/C++ / Ayuda con creacion de archivo txt en una lista doble en: 18 Enero 2014, 02:25 am
Saludos colegas, tengo un problema con el siguiente codigo .. Al parecer no inserta de forma correcta en una lista doble; el problema tambien es que al generar el archivo.txt sale vacio.

//EJERCICIO DE ARCHIVO CON LISTA DOBLEMENTE ENLAZADA
//Generar numeros aleatorio y descomponer cada uno sumando el resultado de
//cada numero. Realizar todo en una lista doblemente enlazada.

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <cstdlib>
     
    using namespace std;
     
    struct datos {
        int num;
    };
     
    struct node {
        datos data;
        node *left;
        node *right;
    };
     
     
    node * newList();
    node * insert_right(node *list, node data);
    void printListAsc(node *current);
    void printNode(node *current);
     int llenar_archivo(char path[]) ;
     int rand_number(int min, int max);
   
     
    int main(void) {
       
        node *head = newList();
        node *current = head;
     
        srand((unsigned int) time(0));
        char name[] = "numerosAleatorio.log";
        llenar_archivo(name);
               
            return 0;
    }
     
     
    node * newList() {
        node *nuevo;
        nuevo = new node;
     
        nuevo->data.num = -1;
        nuevo->right = nuevo;
        nuevo->left = nuevo;
     
        return nuevo;
    }
     
   
    void printNode(node *current) {
        cout << current->data.num << endl;
    }
   
   
    void printListAsc(node *head) {
        node *current = head;
        while (current->right != head) {
            current = current->right;
            printNode(current);
        }
    }
   
   
    node * insert_right(node *list, node data) {
     
        node *nuevo;
        nuevo = new node;
     
        nuevo->data = data.data;
     
        nuevo->left = list;
        nuevo->right = list->right;
        list->right = nuevo;
        nuevo->right->left = nuevo;
     
        return nuevo;
    }


     
     int llenar_archivo(char path[]) {
         node *current;
ofstream myFile;
node myData;
myFile.open(path);

if(myFile.is_open())
{
    int Digito,num,Valor;
   
 
for(int i=0; i < 500;i++){
   
int s=0;   
myData.data.num=rand_number(1,1000);

while (Valor > 0){
   
Digito = Valor % 10;
Valor /= 10;
cout<<Digito<<" ";
s=s+Digito;
Valor=myData.data.num;
current = insert_right(current, myData);
}

cout<<endl<<"SUMA: "<< s<<endl;       
}
   
myFile.close();
return 1;
}

return 0;
}


int rand_number(int min, int max) {   
return rand() % (max - min + 1) + min;
}


Páginas: [1] 2
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines