|
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. unsigned int naive(vec T, unsigned int i, unsigned int j) { unsigned int _max = 0; if (T.empty()) return 0; else { if (i < T.size() - 1 and T[i][j] == T[i + 1][j] + 1) _max = max(_max, naive(T, i + 1, j)); if (j < T.size() - 1 and T[i][j] == T[i][j + 1] + 1) _max = max(_max, naive(T, i, j + 1)); if (i > 0 and T[i][j] - 1 == T[i - 1][j]) _max = max(_max, naive(T, i - 1, j)); if (j > 0 and T[i][j] - 1 == T[i][j - 1]) _max = max(_max, naive(T, i, j - 1)); } return _max + 1; }
unsigned int memo(vec T, vec &M, unsigned int i, unsigned int j) { unsigned int _max = 0; if (T.empty()) return 0; if (M[i][j] != 0) return M[i][j]; else { if (i < T.size() - 1 and T[i][j] == T[i + 1][j] + 1) _max = max(_max, memo(T, M, i + 1, j)); if (j < T.size() - 1 and T[i][j] == T[i][j + 1] + 1) _max = max(_max, memo(T, M, i, j + 1)); if (i > 0 and T[i][j] - 1 == T[i - 1][j]) _max = max(_max, memo(T, M, i - 1, j)); if (j > 0 and T[i][j] - 1 == T[i][j - 1]) _max = max(_max, memo(T, M, i, j - 1)); M[i][j] = _max + 1; } return M[i][j]; }
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
|
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
Routinas void *routineRead(void *val) { pthread_mutex_lock(&mutex); int fg = 0, fd; void *buf = malloc(MAX_SIZE * 2); do { fd = open(val, O_RDONLY); if (fd == -1) { printf(" Se volvera a intentar despues\n"); sleep(5); } else fg = 1; } while (fg == 0); read(fd, buf, MAX_SIZE * 2); close(fd); pthread_mutex_unlock(&mutex); return buf; } void *routineWrite(void *val) { pthread_mutex_lock(&mutex1); int fg = 0, fd; do { fd = open(val, O_WRONLY); if (fd == -1) { printf(" Se volvera a intentar despues\n"); sleep(5); } else fg = 1; } while (fg == 0); write (fd , time, MAX_SIZE ); close(fd); pthread_mutex_unlock(&mutex1); }
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. pthread_t p_read, p_write, p_time; sem_init(&sem, 0, 1); sem_init(&sem1, 0, 1); clean_fifo(pipe); int seconds = atoi(argv [6]); pthread_create(&p_time, NULL, routineTime, &seconds); do { int cont = 0; //p_read get the agent name from the pipe pthread_create(&p_read, NULL, routineRead, pipe); pthread_join(p_read, (void **)&agent_name); printf("Agente:%s\t", agent_name ); clean_fifo(agent_name); //send current time pthread_create(&p_write, NULL, routineWrite, pipe); pthread_join(p_write, NULL); printf("pipe: %s\n", agent_name ); //Read all the requests by an agent do { pthread_create(&p_read, NULL, routineRead, agent_name); pthread_join(p_read, (void **)&data[cont].re); if (data[cont].re->amount_people != 0) answer_request(&tree, data[cont].re, &bh); else break; write_pipe(fd, (struct Reserva *)data[cont].re, sizeof(Reserva), agent_name, O_WRONLY); cont++; } while (1); } while (1);
|
|
|
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. #include <stdlib.h> #include <pthread.h> #include <stdio.h> #include <unistd.h> #include <semaphore.h> sem_t semaphore; void *routine(void *routine) { for (int i = 0; i < 3; i++) { sem_wait(&semaphore); printf("%s\n", (char *)routine ); sleep(1); sem_post(&semaphore); } } int main(void) { sem_init(&semaphore, 0, 1); pthread_t thread[3]; pthread_create(&thread[0], NULL, routine, "A"); pthread_create(&thread[1], NULL, routine, "B"); pthread_create(&thread[2], NULL, routine, "C"); for (int i = 0; i < 3; i++) { pthread_join(thread[i], NULL); sleep(1); } }
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
|
|
|
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 typedef struct node { void *data; struct node *next; } node, Node; typedef struct list { struct node *head; } list, List;
Estructura del arbol typedef struct NodeGeneral { void *data; list *dec; } GeneralNode; typedef struct GeneralTree { GeneralNode *root; } GeneralTree;
main En el siguiente código se encuentra el fragmento donde estoy realizando el cast(Linea 12). int main(void) { List *list; GeneralNode *proof; int x = 5; proof = init_GeneralNode((int *)&x); init_list(&list, &proof); Node *aux = list->head; while (aux != NULL) { GeneralNode *tmp =(GeneralNode *)aux->data; //Aqui estoy realizando el casteo printf("::%d\n", *((int *)tmp ->data )); aux = aux->next; } } //Las funciones init crean la memoria y establecen los datos
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) node *newNode(void *value) { node *newNode = (node *)malloc(sizeof(node )); newNode->data = value; newNode->next = NULL; return newNode; } void init_list(list **lista, void *value) { list *aux = *lista; aux = (list *)malloc(sizeof(list )); aux->head = newNode(value); *lista = aux; } //************************************ GeneralNode *init_GeneralNode(void *data) { GeneralNode *newNode = (GeneralNode *)malloc(sizeof(GeneralNode )); newNode->data = data; newNode->dec = NULL; return newNode; }
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. void write_pipe(int fd, void *buf, char *pipe) { int flag = 0, bytes; do { fd = open(pipe, O_WRONLY); if (fd == -1) { printf(" Se volvera a intentar despues\n"); sleep(5); } else flag = 1; } while (flag == 0); bytes = write(fd, buf, sizeof(buf)); printf("Sent it:%d\n", bytes ); close(fd); } void read_pipe(int fd, void *buf, char *pipe) { int flag = 0, bytes; do { fd = open(pipe, O_RDONLY); if (fd == -1) { printf(" Se volvera a intentar despues\n"); sleep(5); } else flag = 1; } while (flag == 0); bytes = read(fd, buf, sizeof(buf)); printf("Received it:%d\n", bytes ); close(fd); }
> Y asi llamo la función en el main struct data dt; write_pipe(fd[0],(struct data*)&dt, argv[8]);
|
|
|
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 #include <iostream> #include <sys/socket.h> #include <arpa/inet.h> //inet_addr #include <netdb.h> //Define hostent struct #include <unistd.h> //close socket #include <string.h> #define BUFFER 1024 using namespace std; int main(int argc, char **argv) { //Create socket int listening; listening = socket(AF_INET, SOCK_STREAM, 0); if (listening == -1) { cout << "Can't create socket" << endl; return 0; } //Set the server struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(atoi(argv[1])); server.sin_addr.s_addr = INADDR_ANY; //Assign to server a unique telephone number bind(listening, (struct sockaddr *)&server, sizeof(server)); //Listening ... cout << "Waiting for connections ... " << endl; listen(listening, SOMAXCONN); //Wait for connections struct sockaddr_in client; int sizeClient = sizeof(client); //Accept client int clientSocket = accept(listening, (struct sockaddr *)&client, (socklen_t *)&sizeClient); if (clientSocket == -1) { cout << "Can't connect with the client" << endl; return 0; } char welcome[BUFFER]; memset(welcome, 0, BUFFER); strcpy(welcome, "Welcome"); send(clientSocket, welcome, BUFFER, 0); cout << "Connected!" << endl; bool bandera = true; while (bandera) { cout << "(*)"; cin.getline(welcome, BUFFER); if (strcmp(welcome, "SHUTDOWN") == 0) { send(clientSocket, welcome, BUFFER, 0); bandera = false; } else { send(clientSocket, welcome, BUFFER, 0); } } close(listening); }
//CLIENTE #if defined _WIN32 #include <iostream> using namespace std; #include <WS2tcpip.h> #pragma comment(lib, "ws2_32.lib") int inet_pton(int af, const char *src, void *dst); #else #include <iostream> #include <sys/socket.h> #include <arpa/inet.h> //inet_addr #include <string.h> #include <unistd.h> //close socket #endif #define BUFFER 2048 using namespace std; int main() { #if defined(_WIN32) { WSADATA winsock; WORD word = MAKEWORD(2, 2); int winStatus = WSAStartup(word, &winsock); if (winStatus != 0) { cout << "Can't intialize Winsock on windows" << endl; return 0; } } #endif int socket_ = socket(AF_INET, SOCK_STREAM, 0); if (socket_ == -1) { cout << "Can't create the socket" << endl; return 0; } //Set socket sockaddr_in client; client.sin_port = htons(8080); client.sin_family = AF_INET; #if (_WIN32) string ipAdress="127.0.0.1"; inet_pton(AF_INET, ipAdress.c_str(), &client.sin_addr); #else client.sin_addr.s_addr = inet_addr("127.0.0.1"); #endif //Connect int connecting = connect(socket_, (struct sockaddr *)&client, sizeof(client)); if (connecting == -1) { cout << "You can't connect" << endl; return 0; } char rcvd[BUFFER]; memset(rcvd, 0, BUFFER); recv(socket_, rcvd, BUFFER, 0); cout << rcvd << endl; bool bandera = true; while (bandera) { memset(rcvd, 0, BUFFER); recv(socket_, rcvd, BUFFER, 0); if (strcmp(rcvd, "SHUTDOWN") == 0) { #if defined(_WIN32) WSACleanup(); #endif //close(socket_); bandera = false; cout << "The connection was closed" << endl; } else cout << "*) " << rcvd << endl; } } int inet_pton(int af, const char *src, void *dst) { #if (_WIN32) struct sockaddr_storage ss; int size = sizeof(ss); char src_copy[INET6_ADDRSTRLEN + 1]; ZeroMemory(&ss, sizeof(ss)); /* stupid non-const API */ strncpy(src_copy, src, INET6_ADDRSTRLEN + 1); src_copy[INET6_ADDRSTRLEN] = 0; if (WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0) { switch (af) { case AF_INET: *(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr; return 1; case AF_INET6: *(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr; return 1; } } #endif return 0; }
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?
|
|
|
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; } } } }
|
|
|
|
|
|
|