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

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


  Mostrar Temas
Páginas: [1]
1  Programación / Programación C/C++ / Bottom up en: 26 Septiembre 2022, 03:09 am
Buenas noches, tengo un problema en el que basicamente se me pide encontrar la cadena mas larga de vecinos que esten ordenados en donde los elementos adyacentes de una matriz NXN tienen una diferencia de +1.

Ejemplo:  

10  16  15  12
9     8    7   13
2     5    6   14
3     4    1   11

Para la anterior matriz la solucion seria  S = <2,3,4,5,6,7,8,9,10>, se me pide basicamente desarrollar el backtracking pero para llegar al bactracking debo seguir una serie de pasos:
1) Sol recursiva ingenua
2) Memoizacion
3) Bottom-up
4) Backtracking


Mi problema es a la hora de implementar el bottom-up, se supone que debo quitar las recursiones por ciclos para que sea de forma iterativa, sin embargo, no he podido implementarlo de esa forma.

No se si porfa me puedan dar alguna idea para solucionarlo con Bottom-up.

Código
  1. unsigned int naive(vec T, unsigned int i, unsigned int j) {
  2.  unsigned int _max = 0;
  3.  if (T.empty())
  4.    return 0;
  5.  else {
  6.    if (i < T.size() - 1 and T[i][j] == T[i + 1][j] + 1)
  7.      _max = max(_max, naive(T, i + 1, j));
  8.    if (j < T.size() - 1 and T[i][j] == T[i][j + 1] + 1)
  9.      _max = max(_max, naive(T, i, j + 1));
  10.    if (i > 0 and T[i][j] - 1 == T[i - 1][j])
  11.      _max = max(_max, naive(T, i - 1, j));
  12.    if (j > 0 and T[i][j] - 1 == T[i][j - 1])
  13.      _max = max(_max, naive(T, i, j - 1));
  14.  }
  15.  return _max + 1;
  16. }
  17.  

Código
  1. unsigned int memo(vec T, vec &M, unsigned int i, unsigned int j) {
  2.  unsigned int _max = 0;
  3.  if (T.empty())
  4.    return 0;
  5.  if (M[i][j] != 0)
  6.    return M[i][j];
  7.  else {
  8.    if (i < T.size() - 1 and T[i][j] == T[i + 1][j] + 1)
  9.      _max = max(_max, memo(T, M, i + 1, j));
  10.    if (j < T.size() - 1 and T[i][j] == T[i][j + 1] + 1)
  11.      _max = max(_max, memo(T, M, i, j + 1));
  12.    if (i > 0 and T[i][j] - 1 == T[i - 1][j])
  13.      _max = max(_max, memo(T, M, i - 1, j));
  14.    if (j > 0 and T[i][j] - 1 == T[i][j - 1])
  15.      _max = max(_max, memo(T, M, i, j - 1));
  16.    M[i][j] = _max + 1;
  17.  }
  18.  
  19.  return M[i][j];
  20. }
  21.  
  22.  

Las dos implementaciones anteriores son las que hice ingenuamente y con memoizacion
2  Programación / Programación C/C++ / Sincronización de procesos en: 24 Mayo 2021, 04:11 am
Código
  1. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2. static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
  3.  

Routinas
Código
  1. void *routineRead(void *val)
  2. {
  3.    pthread_mutex_lock(&mutex);
  4.    int fg = 0, fd;
  5.    void *buf = malloc(MAX_SIZE * 2);
  6.    do
  7.    {
  8.        fd = open(val, O_RDONLY);
  9.        if (fd == -1)
  10.        {
  11.            perror("pipe");
  12.            printf(" Se volvera a intentar despues\n");
  13.            sleep(5);
  14.        }
  15.        else
  16.            fg = 1;
  17.    } while (fg == 0);
  18.    read(fd, buf, MAX_SIZE * 2);
  19.    close(fd);
  20.    pthread_mutex_unlock(&mutex);
  21.    return buf;
  22. }
  23. void *routineWrite(void *val)
  24. {
  25.    pthread_mutex_lock(&mutex1);
  26.    int fg = 0, fd;
  27.    int *time = malloc(sizeof(int));
  28.    *time = bh.current_time;
  29.    do
  30.    {
  31.        fd = open(val, O_WRONLY);
  32.        if (fd == -1)
  33.        {
  34.            perror("pipe");
  35.            printf(" Se volvera a intentar despues\n");
  36.            sleep(5);
  37.        }
  38.        else
  39.            fg = 1;
  40.    } while (fg == 0);
  41.    write(fd, time, MAX_SIZE);
  42.    close(fd);
  43.    pthread_mutex_unlock(&mutex1);
  44. }
  45.  

Mi proyecto consiste en conectar  dos procesos mediante pipes, un proceso es el controlador y el otro es agente. El controlador basicamente  se encarga de leer del pipe y enviar una respuesta, el punto es que estoy leyendo del pipe a través de un hilo, sin embargo,cada vez que se conecta un agente, el controlador lee el nombre del agente enviado por el agente y luego se crea un fifo que es el fd por donde se comunicaran ellos dos. Vale, el punto es que si llegan el agente1 y el agente2 al mismo tiempo no estoy seguro de lo que pasa pero creo que ambos entra a la sección critica y no me crea el fifo para cada agente sino  que la variable se concatena.

No supe montar la imagen aqui pero en el link pueden ver que es lo que pasa
https://ibb.co/JsgfTp5


Entonces no se  si me puedan ayudar a garantizar que si dos agente o mas se conectan a la vez atienda primero a uno y luego si siga con el otro.

Código
  1.    pthread_t p_read, p_write, p_time;
  2.    sem_init(&sem, 0, 1);
  3.    sem_init(&sem1, 0, 1);
  4.    clean_fifo(pipe);
  5.    int seconds = atoi(argv[6]);
  6.    pthread_create(&p_time, NULL, routineTime, &seconds);
  7.    do
  8.    {
  9.        int cont = 0;
  10.        //p_read get the agent name from the pipe
  11.        pthread_create(&p_read, NULL, routineRead, pipe);
  12.        pthread_join(p_read, (void **)&agent_name);
  13.        printf("Agente:%s\t", agent_name);
  14.        clean_fifo(agent_name);
  15.        //send current time
  16.        pthread_create(&p_write, NULL, routineWrite, pipe);
  17.        pthread_join(p_write, NULL);
  18.        printf("pipe: %s\n", agent_name);
  19.        //Read all the requests by an agent
  20.        do
  21.        {
  22.            pthread_create(&p_read, NULL, routineRead, agent_name);
  23.            pthread_join(p_read, (void **)&data[cont].re);
  24.            if (data[cont].re->amount_people != 0)
  25.                answer_request(&tree, data[cont].re, &bh);
  26.            else
  27.                break;
  28.            write_pipe(fd, (struct Reserva *)data[cont].re, sizeof(Reserva), agent_name, O_WRONLY);
  29.            cont++;
  30.        } while (1);
  31.  
  32.    } while (1);
  33.  

3  Programación / Programación C/C++ / Semaforos en c en: 16 Mayo 2021, 02:03 am
Hola buenas noches a todos, estoy empezando en el tema de sincronización de procesos a través de semaforos basicamente lo que me piden hacer es que apartir de tres procesos A,B y C tenga como salida ABC ABC ABC utilizando semaforos.

Código
  1. #include <stdlib.h>
  2. #include <pthread.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <semaphore.h>
  6. sem_t semaphore;
  7. void *routine(void *routine)
  8. {
  9.     for (int i = 0; i < 3; i++)
  10.     {
  11.          sem_wait(&semaphore);
  12.          printf("%s\n", (char *)routine);
  13.          sleep(1);
  14.          sem_post(&semaphore);
  15.     }
  16. }
  17. int main(void)
  18. {
  19.     sem_init(&semaphore, 0, 1);
  20.     pthread_t thread[3];
  21.     pthread_create(&thread[0], NULL, routine, "A");
  22.     pthread_create(&thread[1], NULL, routine, "B");
  23.     pthread_create(&thread[2], NULL, routine, "C");
  24.     for (int i = 0; i < 3; i++)
  25.     {
  26.          pthread_join(thread[i], NULL);
  27.          sleep(1);
  28.     }
  29. }
  30.  

Esa es la implementación que llevo hasta el momento, sin embargo,la salida me es erronea

Esta es mi salida:
AAA BBB CCC

Les agredezco si me pueden ayudar  ;D
4  Programación / Programación C/C++ / cast Void pointer en c en: 19 Abril 2021, 06:56 am
Buenas noches comunidad, estoy realizando un arbol general en c que cuenta con una lista génerica para guardar los descendientes(hijos) que hice  en c de forma génerica usando void pointer pero estoy teniendo problemas  :-(.

El problema que me surge ya lo tengo identificado, sin embargo, no se como solucionarlo, lo que pasa es que cuando quiero imprimir un dato del nodo general que se encuentra dentro de la lista me esta saliendo basura, el problema debe ser que estoy realizando mal el cast pero ya intente de varias formas y sigue sin funcionar.

Estructura de la lista
Código
  1. typedef struct node
  2. {
  3.    void *data;
  4.    struct node *next;
  5. } node, Node;
  6. typedef struct list
  7. {
  8.    struct node *head;
  9.  
  10. } list, List;
  11.  
  12.  

Estructura del arbol
Código
  1. typedef struct NodeGeneral
  2. {
  3.    void *data;
  4.    list *dec;
  5. } GeneralNode;
  6. typedef struct GeneralTree
  7. {
  8.    GeneralNode *root;
  9. } GeneralTree;
  10.  



main
En el siguiente código se encuentra el fragmento donde estoy realizando el cast(Linea 12).
Código
  1. int main(void)
  2. {
  3.  
  4.  List *list;
  5.  GeneralNode *proof;
  6.  int x = 5;
  7.  proof = init_GeneralNode((int *)&x);
  8.  init_list(&list, &proof);
  9.  Node *aux = list->head;
  10.  while (aux != NULL)
  11.  {
  12.    GeneralNode *tmp =(GeneralNode *)aux->data; //Aqui estoy realizando el casteo
  13.    printf("::%d\n", *((int *)tmp->data));
  14.    aux = aux->next;
  15.  
  16.  }
  17.  
  18. }
  19. //Las funciones init crean la memoria y establecen los datos
  20.  
Anexó las funciones con las que inicialice la lista y establezco la cabeza(Ya la he probado con diferentes tipos de datos(int,float... datos nativos) y funciona bien la lista)
Código
  1. node *newNode(void *value)
  2. {
  3.    node *newNode = (node *)malloc(sizeof(node));
  4.    newNode->data = value;
  5.    newNode->next = NULL;
  6.    return newNode;
  7. }
  8. void init_list(list **lista, void *value)
  9. {
  10.    list *aux = *lista;
  11.    aux = (list *)malloc(sizeof(list));
  12.    aux->head = newNode(value);
  13.    *lista = aux;
  14. }
  15. //************************************
  16. GeneralNode *init_GeneralNode(void *data)
  17. {
  18.    GeneralNode *newNode = (GeneralNode *)malloc(sizeof(GeneralNode));
  19.    newNode->data = data;
  20.    newNode->dec = NULL;
  21.    return newNode;
  22. }
  23.  

En el NodoGeneral que tengo,en el caso de la lista de descendiente cada dato de la lista representa un NodoGeneral.El next, el puntero al siguiente hijo.

Les agradezco si me pueden ayudar.
5  Programación / Programación C/C++ / Genericos en c pipes (void*) en: 10 Abril 2021, 18:14 pm
Buenos dias , soy nuevo en el lenguaje de c y estoy teniendo problemas a la hora de crear un función génerico para escribir o enviar el pipe.La función  funciona perfectamente sin el génerico pero con el genérico me esta pasando basura y me salta un error Segmentation Fault.
Código
  1. void write_pipe(int fd, void *buf, char *pipe)
  2. {
  3.    int flag = 0, bytes;
  4.    do
  5.    {
  6.        fd = open(pipe, O_WRONLY);
  7.        if (fd == -1)
  8.        {
  9.            perror("pipe");
  10.            printf(" Se volvera a intentar despues\n");
  11.            sleep(5);
  12.        }
  13.        else
  14.            flag = 1;
  15.    } while (flag == 0);
  16.    bytes = write(fd, buf, sizeof(buf));
  17.    printf("Sent it:%d\n", bytes);
  18.    close(fd);
  19. }
  20. void read_pipe(int fd, void *buf, char *pipe)
  21. {
  22.    int flag = 0, bytes;
  23.    do
  24.    {
  25.        fd = open(pipe, O_RDONLY);
  26.        if (fd == -1)
  27.        {
  28.            perror("pipe");
  29.            printf(" Se volvera a intentar despues\n");
  30.            sleep(5);
  31.        }
  32.        else
  33.            flag = 1;
  34.    } while (flag == 0);
  35.    bytes = read(fd, buf, sizeof(buf));
  36.    printf("Received it:%d\n", bytes);
  37.    close(fd);
  38. }
  39.  
>

Y asi llamo la función en el main
Código
  1. struct data dt;
  2. write_pipe(fd[0],(struct data*)&dt, argv[8]);
  3.  

6  Programación / Programación C/C++ / Socket c++ en: 12 Enero 2021, 06:42 am
Hola que tal , estoy desarrollando un código como pasatiempo en el que creo un servidor  local y cliente.El servidor unicaménte lo tengo codificado para correr en linux mientras el cliente lo tengo tanto para win y linux, sin embargo, cuando ejecuto el cliente dentro de  un SO linux si es posible conectarse caso contrario al de Win en el que me dice que no es posible conectarse. ¿Alguno sabe si es un problema de compatiblidad o simplemente un problema en mi código ?

//SERVIDOR
Código
  1. #include <iostream>
  2. #include <sys/socket.h>
  3. #include <arpa/inet.h> //inet_addr
  4. #include <netdb.h>     //Define hostent struct
  5. #include <unistd.h>    //close socket
  6. #include <string.h>
  7. #define BUFFER 1024
  8. using namespace std;
  9. int main(int argc, char **argv)
  10. {
  11.    //Create socket
  12.    int listening;
  13.    listening = socket(AF_INET, SOCK_STREAM, 0);
  14.    if (listening == -1)
  15.    {
  16.        cout << "Can't create socket" << endl;
  17.        return 0;
  18.    }
  19.    //Set the server
  20.    struct sockaddr_in server;
  21.    server.sin_family = AF_INET;
  22.    server.sin_port = htons(atoi(argv[1]));
  23.    server.sin_addr.s_addr = INADDR_ANY;
  24.    //Assign to server a unique telephone number
  25.    bind(listening, (struct sockaddr *)&server, sizeof(server));
  26.    //Listening ...
  27.    cout << "Waiting for connections ... " << endl;
  28.    listen(listening, SOMAXCONN);
  29.    //Wait for connections
  30.    struct sockaddr_in client;
  31.    int sizeClient = sizeof(client);
  32.    //Accept client
  33.    int clientSocket = accept(listening, (struct sockaddr *)&client, (socklen_t *)&sizeClient);
  34.    if (clientSocket == -1)
  35.    {
  36.        cout << "Can't connect with the client" << endl;
  37.        return 0;
  38.    }
  39.    char welcome[BUFFER];
  40.    memset(welcome, 0, BUFFER);
  41.    strcpy(welcome, "Welcome");
  42.    send(clientSocket, welcome, BUFFER, 0);
  43.    cout << "Connected!" << endl;
  44.    bool bandera = true;
  45.    while (bandera)
  46.    {
  47.        cout << "(*)";
  48.        cin.getline(welcome, BUFFER);
  49.        if (strcmp(welcome, "SHUTDOWN") == 0)
  50.        {
  51.            send(clientSocket, welcome, BUFFER, 0);
  52.            bandera = false;
  53.        }
  54.        else
  55.        {
  56.            send(clientSocket, welcome, BUFFER, 0);
  57.        }
  58.    }
  59.    close(listening);
  60. }
  61.  
  62.  



//CLIENTE
Código
  1. #if defined _WIN32
  2. #include <iostream>
  3. using namespace std;
  4. #include <WS2tcpip.h>
  5. #pragma comment(lib, "ws2_32.lib")
  6. int inet_pton(int af, const char *src, void *dst);
  7. #else
  8. #include <iostream>
  9. #include <sys/socket.h>
  10. #include <arpa/inet.h> //inet_addr
  11. #include <string.h>
  12. #include <unistd.h> //close socket
  13. #endif
  14. #define BUFFER 2048
  15. using namespace std;
  16. int main()
  17. {
  18. #if defined(_WIN32)
  19.    {
  20.        WSADATA winsock;
  21.        WORD word = MAKEWORD(2, 2);
  22.        int winStatus = WSAStartup(word, &winsock);
  23.        if (winStatus != 0)
  24.        {
  25.            cout << "Can't intialize Winsock on windows" << endl;
  26.            return 0;
  27.        }
  28.    }
  29. #endif
  30.    int socket_ = socket(AF_INET, SOCK_STREAM, 0);
  31.    if (socket_ == -1)
  32.    {
  33.        cout << "Can't create the socket" << endl;
  34.        return 0;
  35.    }
  36.    //Set socket
  37.    sockaddr_in client;
  38.    client.sin_port = htons(8080);
  39.    client.sin_family = AF_INET;
  40. #if (_WIN32)
  41.    string ipAdress="127.0.0.1";
  42.    inet_pton(AF_INET, ipAdress.c_str(), &client.sin_addr);
  43. #else
  44.    client.sin_addr.s_addr = inet_addr("127.0.0.1");
  45. #endif
  46.    //Connect
  47.    int connecting = connect(socket_, (struct sockaddr *)&client, sizeof(client));
  48.    if (connecting == -1)
  49.    {
  50.        cout << "You can't connect" << endl;
  51.        return 0;
  52.    }
  53.    char rcvd[BUFFER];
  54.    memset(rcvd, 0, BUFFER);
  55.    recv(socket_, rcvd, BUFFER, 0);
  56.    cout << rcvd << endl;
  57.    bool bandera = true;
  58.    while (bandera)
  59.    {
  60.        memset(rcvd, 0, BUFFER);
  61.        recv(socket_, rcvd, BUFFER, 0);
  62.        if (strcmp(rcvd, "SHUTDOWN") == 0)
  63.        {
  64.  
  65. #if defined(_WIN32)
  66.            WSACleanup();
  67. #endif
  68.            //close(socket_);
  69.            bandera = false;
  70.            cout << "The connection was closed" << endl;
  71.        }
  72.        else
  73.            cout << "*) " << rcvd << endl;
  74.    }
  75. }
  76. int inet_pton(int af, const char *src, void *dst)
  77. {
  78. #if (_WIN32)
  79.    struct sockaddr_storage ss;
  80.    int size = sizeof(ss);
  81.    char src_copy[INET6_ADDRSTRLEN + 1];
  82.  
  83.    ZeroMemory(&ss, sizeof(ss));
  84.    /* stupid non-const API */
  85.    strncpy(src_copy, src, INET6_ADDRSTRLEN + 1);
  86.    src_copy[INET6_ADDRSTRLEN] = 0;
  87.  
  88.    if (WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0)
  89.    {
  90.        switch (af)
  91.        {
  92.        case AF_INET:
  93.            *(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
  94.            return 1;
  95.        case AF_INET6:
  96.            *(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
  97.            return 1;
  98.        }
  99.    }
  100. #endif
  101.    return 0;
  102. }
  103.  


MOD: Modificadas las etiquetas de Código GeSHi para el lenguaje C++
7  Sistemas Operativos / GNU/Linux / Que version de Kernel es la mas estable? en: 17 Marzo 2020, 18:20 pm
Hace unos meses estaba en ubuntu y me iba de maravilla ,sin embargo, luego cambie a LInux mint y note que la ultima versión de Kernel me iba fatal. Asi que reinstale ubuntu de nuevo y tengo el kernel 5.3.0 -42 pero igualmente me va mal.

Intel core i5 8250u
4 ram
3.4 Ghz

Tengo dual boot con Windows pero anteriormente no me daba problema con el dual boot. Asi que descarte esa posibilidad.¿Cual kernel me recomiendan?
8  Seguridad Informática / Hacking / Libros de aprendizaje para linux en: 17 Marzo 2020, 05:04 am
Buenas noches, quisiera saber sin tiene material de Seguridad informatica desde linux que puedan compartir , foros o cursos gratuitos para aprender desde cero
9  Programación / Programación C/C++ / Ayuda imprimir solo una vez la repeticiones de un arreglo en: 16 Marzo 2020, 18:37 pm
Buenas tardes, tengo que hacer un codigo para determinar las ocurrencias,sin embargo, ya tengo el arreglo de ocurrencias y palabras pero no se como hacer para que cuando vaya imprimir me imprima solo una vez la palabra que este repetida. Cree una estructura para solucionar eso pero no he podido hacer la impresion de forma correcta (el codigo que anexo esta sin la impresión, puesto que no supe hacerla para solo imprimirla una vez). Agradeceria si me ayudan.



#include <iostream>
#include <string.h>
#include<ctype.h>
using namespace std;
struct ocu
{
    string word;
    int ocurrencias=0;
};
void ocurrencia(char Parrafo[],string *Palabras,int *ocurrencias,int &arra_y,struct ocu *ocurren);
int main()
{
    struct ocu *ocurren=new ocu[50];
    int *ocurrencias=new int[50],tamano,arra_y=0,cant=0;
    char Parrafo[500];
    string *Palabras = new string[50];
    cin.getline(Parrafo, sizeof(Parrafo));
    tamano=strlen(Parrafo);
    for(int i=0; i<tamano; i++)
        Parrafo=tolower(Parrafo);
    ocurrencia(Parrafo,Palabras,ocurrencias,arra_y,ocurren);
}

void ocurrencia(char Parrafo[],string *Palabras,int *ocurrencias,int &arra_y,struct ocu *ocurren)
{
    char *ptro,cant=0;
    ptro = strtok(Parrafo, " .,;");
    while (ptro != NULL)
    {
        *(Palabras+arra_y)=ptro;
        ptro = strtok(NULL, " .,;");
        arra_y++;
    }
    for(int i=0; i<arra_y; i++)
        *(ocurrencias+i)=1;

    for(int i=0; i<arra_y; i++)
    {
        for(int j=0; j<arra_y; j++)
        {
            if(*(Palabras+i)==*(Palabras+j))
            {
                if(i==j)
                {}
                else
                    *(ocurrencias+i)= *(ocurrencias+i)+1;
            }
        }
    }
}

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