Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

John Edgar Congote Calle http://jcongote.blogspot.com

« Newer Snippets
Older Snippets »
Showing 11-20 of 22 total

Grafos en 3d

Implementacion con opengl de la visualizacion de grafos, donde los vertices son resortes uniendo los nodos, y los nodos se rechazan entre ellos, y existe una fuerza en el origen que los acerca a todos.

Makefile para compilarlo:


INCLUDE = -I/usr/include/
LIBDIR = -L/usr/X11R6/lib

CC = gcc
CCFLAGS = -g ${INCLUDE}
LIBRARY = -lX11 -lXi -lXmu -lglut -lGL -lGLU -lm

all :ejemplo1.o
${CC} ${CCFLAGS} -o ejemplo1 ejemplo1.o ${LIBDIR} ${LIBRARY}

clean :
rm -rf ejemplo1 ejemplo1.o



#include <GL/gl.h>
#include <GL/glut.h>

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define MAXNODOS 100

typedef struct _point{
	float x,y,z;
} point;

typedef struct _force{
	float fx,fy,fz;
} force;

typedef struct _sisi{
	point p;
	force f;
} sisi;

typedef struct _grafo{
	int nnodos;
	sisi nodos[100];
	int enlaces[100][100];
	point max,min;	
} grafo;

float angulo=0.0;
grafo grafo_global;

void calcularfuerzas(grafo *g){
	int i,j;
	float distancia;
	for (i=0;i<g->nnodos;i++){
		g->nodos[i].f.fx = 0.0f;
		g->nodos[i].f.fy = 0.0f;
		g->nodos[i].f.fz = 0.0f;
		
		for (j=0;j<g->nnodos;j++){
			if (i!=j && g->enlaces[i][j]==1){
				distancia = sqrt(powf(g->nodos[i].p.x - g->nodos[j].p.x,2.0f) + powf(g->nodos[i].p.y - g->nodos[j].p.y,2.0f) + powf(g->nodos[i].p.z - g->nodos[j].p.z,2.0f));
				if ( distancia > 0.001f ){
					g->nodos[i].f.fx += (g->nodos[i].p.x - g->nodos[j].p.x) / powf(distancia,3.0f);
					g->nodos[i].f.fy += (g->nodos[i].p.y - g->nodos[j].p.y) / powf(distancia,3.0f);
					g->nodos[i].f.fz += (g->nodos[i].p.z - g->nodos[j].p.z) / powf(distancia,3.0f);
				}
			}
		}
//		Nene

		distancia = sqrt(powf(g->nodos[i].p.x,2.0f)+powf(g->nodos[i].p.y,2.0f)+powf(g->nodos[i].p.z,2.0f));

		if (distancia>(float)g->nnodos){
			g->nodos[i].f.fx -= g->nnodos*g->nodos[i].p.x/powf(distancia,3.0f);
			g->nodos[i].f.fy -= g->nnodos*g->nodos[i].p.y/powf(distancia,3.0f);
			g->nodos[i].f.fz -= g->nnodos*g->nodos[i].p.z/powf(distancia,3.0f);				
		}

	}
	
	grafo_global.max.x=-1000;
	grafo_global.max.y=-1000;
	grafo_global.max.z=-1000;
	grafo_global.min.x=1000;
	grafo_global.min.y=1000;
	grafo_global.min.z=1000;		

	for (i=0;i<g->nnodos;i++){	
//		Movimiento
		g->nodos[i].p.x+=g->nodos[i].f.fx;
		g->nodos[i].p.y+=g->nodos[i].f.fy;
		g->nodos[i].p.z+=g->nodos[i].f.fz;		

		if (grafo_global.max.x<grafo_global.nodos[i].p.x)
			grafo_global.max.x=grafo_global.nodos[i].p.x;	

		if (grafo_global.max.y<grafo_global.nodos[i].p.y)
			grafo_global.max.y=grafo_global.nodos[i].p.y;	

		if (grafo_global.max.z<grafo_global.nodos[i].p.z)
			grafo_global.max.z=grafo_global.nodos[i].p.z;	

		if (grafo_global.min.x>grafo_global.nodos[i].p.x)
			grafo_global.min.x=grafo_global.nodos[i].p.x;	

		if (grafo_global.min.y>grafo_global.nodos[i].p.y)
			grafo_global.min.y=grafo_global.nodos[i].p.y;	

		if (grafo_global.min.z>grafo_global.nodos[i].p.z)
			grafo_global.min.z=grafo_global.nodos[i].p.z;	
	}
	
}

void init_grafo(void){
	int i,j;
	grafo_global.nnodos=30;

	for (i=0;i<grafo_global.nnodos;i++){
		for (j=0;j<grafo_global.nnodos;j++){
			grafo_global.enlaces[i][j]=1;
		}
		grafo_global.nodos[i].p.x=rand()%10;
		grafo_global.nodos[i].p.y=rand()%10;
		grafo_global.nodos[i].p.z=rand()%10;

	}

//	grafo_global.enlaces[0][1]=0;
//	grafo_global.enlaces[1][0]=0;

	grafo_global.nodos[0].p.x=5;
	grafo_global.nodos[0].p.y=1;
	grafo_global.nodos[0].p.z=5;		

	grafo_global.nodos[1].p.x=2;
	grafo_global.nodos[1].p.y=2;
	grafo_global.nodos[1].p.z=2;		

	grafo_global.nodos[2].p.x=2;
	grafo_global.nodos[2].p.y=2;
	grafo_global.nodos[2].p.z=3;		

	grafo_global.nodos[3].p.x=3;
	grafo_global.nodos[3].p.y=6;
	grafo_global.nodos[3].p.z=6;		


	grafo_global.nodos[4].p.x=5;
	grafo_global.nodos[4].p.y=-5;
	grafo_global.nodos[4].p.z=5;		

	grafo_global.nodos[5].p.x=-2;
	grafo_global.nodos[5].p.y=2;
	grafo_global.nodos[5].p.z=2;		

	grafo_global.nodos[6].p.x=2;
	grafo_global.nodos[6].p.y=2;
	grafo_global.nodos[6].p.z=-3;		

	grafo_global.nodos[7].p.x=3;
	grafo_global.nodos[7].p.y=8;
	grafo_global.nodos[7].p.z=6;		


	grafo_global.max.x=grafo_global.nodos[0].p.x;
	grafo_global.max.y=grafo_global.nodos[0].p.y;
	grafo_global.max.z=grafo_global.nodos[0].p.z;
	grafo_global.min.x=grafo_global.nodos[0].p.x;
	grafo_global.min.y=grafo_global.nodos[0].p.y;
	grafo_global.min.z=grafo_global.nodos[0].p.z;		


}

void init(void) 
{
   glClearColor (1.0, 1.0, 1.0, 0.0);
   glShadeModel (GL_FLAT);
}

void display(void)
{
   glClear (GL_COLOR_BUFFER_BIT);
   glColor3f (0, 0, 0);
   glLoadIdentity();
   gluLookAt (0.0, 0.0, 15.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
   glRotatef(angulo,0,1.0,0);

	float dx,dy,dz;
	
	dx = grafo_global.max.x - grafo_global.min.x;
	dy = grafo_global.max.y - grafo_global.min.y;
	dz = grafo_global.max.z - grafo_global.min.z;	
	
//   glutWireCube (1.0);
//   glScalef (10.0/dx, 10.0/dy, 10.0/dz);
	if (dx>dy && dx >dz){

		glScalef(10.0/dx,10.0/dx,10.0/dx);
		glutWireCube (dx);
//	glTranslatef(dx/2.0f,dx/2.0f,dx/2.0f);
	} else if (dy>dx && dy >dz){

		glScalef(10.0/dy,10.0/dy,10.0/dy);
		glutWireCube (dy);
//			glTranslatef(dy/2.0f,dy/2.0f,dy/2.0f);
	} else if (dz>dx && dz >dy){

		glScalef(10.0/dz,10.0/dz,10.0/dz);		
		glutWireCube (dz);
//			glTranslatef(dz/2.0f,dz/2.0f,dz/2.0f);
	}

	
	int cont,cont2;
	for (cont=0;cont<grafo_global.nnodos;cont++){
		glPushMatrix();
		glTranslatef(grafo_global.nodos[cont].p.x, grafo_global.nodos[cont].p.y, grafo_global.nodos[cont].p.z);
		glutSolidSphere(.2, 32, 32);
		glPopMatrix();
		for (cont2=cont;cont2<grafo_global.nnodos;cont2++){
			if (grafo_global.enlaces[cont][cont2]){
				glBegin(GL_LINES);
				glVertex3f(grafo_global.nodos[cont].p.x,grafo_global.nodos[cont].p.y,grafo_global.nodos[cont].p.z);
				glVertex3f(grafo_global.nodos[cont2].p.x,grafo_global.nodos[cont2].p.y,grafo_global.nodos[cont2].p.z);				
				glEnd();				
			}
		}
	}



   glFlush ();
   glutSwapBuffers();
}

void reshape(int w, int h)
{
   glViewport (0, 0, (GLsizei) w, (GLsizei) h); 
   glMatrixMode (GL_PROJECTION);
   glLoadIdentity ();
   glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 25.0);
   glMatrixMode (GL_MODELVIEW); 
}

void keyboard(unsigned char key, int x, int y)
{
   switch (key) {
      case 27:
         exit(0);
         break;
   }
}

void idle(void){

	static int timelast=0;
	int time;
	time = glutGet(GLUT_ELAPSED_TIME);
	if (time-timelast>10){
		timelast=time;
	if (angulo<360){
		angulo+=0.1;
	} else {
		angulo=0.0;
	}
	
	}
	calcularfuerzas(&grafo_global);

	
	glutPostRedisplay();	
}

int main(int argc, char** argv)
{
	
	/*
	 * Inicializando OpenGL
	 * */
   glutInit(&argc, argv);
   glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
   glutInitWindowSize (500, 500); 
   glutInitWindowPosition (100, 100);
   glutCreateWindow (argv[0]);
   init ();
   glutDisplayFunc(display); 
   glutReshapeFunc(reshape);
   glutKeyboardFunc(keyboard);
   glutIdleFunc(idle);

   /*
    * Inicializando Entrada del Grafo
    * */
   init_grafo();

	/*
	 * Entrando en el ciclo
	 * */

   glutMainLoop();
   
   return 0;
}

Emulacion de Objetos en C

Esta es una forma de estender el uso de las estructuras para simular el modelo objetual en c


struct _Object;
typedef struct _Object Object;

void Object_init(Object *this);

struct _Object{
       unsigned int id;
       void (*init)(Object*);
} obj ={0,&Object_init};

void Object_init(Object *this){
     
}

int main(int argc, char *argv[])
{
    
    Object Obj;
    Obj.id=1;
  return 0;
}

Calcular el epsilon de la libreria gmp

Este codio calcula el epsilon de la libreria gmp, variando en cada ciclo la presicion del numero.

#include <iostream>
#include <limits.h>
#include <gmpxx.h>

using namespace std;


int main(int argc, char **argv){
	unsigned long int i,j;
//	4294967295

	for (i=1;i<4294967295UL;i*=2){
		j=0;
		mpf_class epsilon(0.5,i);

		while(epsilon+1 != 1){
		//cout.precision(200000);
		//cout<<"Epsilon: "<<epsilon<<endl;
			epsilon /= 2;
			j++;
		};
		cout.precision(20);	
//	cout<<"Precision: "<<ULONG_MAX<<endl;
		cout<<"Epsilon Final: "<<epsilon<<" Numero de ciclos: "<<j<<" Precision: "<<i<<endl;
	}

	return 0;
}

Conteo de caracteres

Este pedazo de codigo cuenta los caracteres de un archivo

this code count the chars of a file.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int cont[257];
    int t;
    FILE *ent;
    
    for (t=0;t<257;t++)
        cont[t]=0;
      
    ent=fopen("input.txt","r");
//    printf("Se abrio el archivo :P\n");
    do {
        t = fgetc(ent);
        cont[t]++;
    } while (!feof(ent));
    fclose(ent);

    for (t=0;t<257;t++){
        printf("Caracter %i se repitio %i veces\n", t, cont[t]);
    }

    
//  system("PAUSE");	
  return 0;
}

Camino mas corto

Ejemplo en java del algoritmo para hallar el camino mas corto de un grafo. se implementa el algoritmo de floyd

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public final class Grafo {

	private int nnodos;

	private int nodos[][][];

	private char nombres[];

	Grafo(int n) {
		this.nnodos = n;
		this.nodos = new int[nnodos][nnodos][2];
		this.nombres = new char[nnodos];
	}

	public void ingresarArco(int n1, int n2, int peso) {
		this.nodos[n1][n2][0] = peso;
		this.nodos[n2][n1][0] = peso;
		this.nodos[n1][n2][1] = n1;
		this.nodos[n2][n1][1] = n2;
	}

	public void ingresarNombre(int nodo, char letra) {
		this.nombres[nodo] = letra;
	}

	public void calcular() {
		int i, j, k;
		for (i = 0; i < this.nnodos; i++) {
			for (j = 0; j < this.nnodos; j++) {
				for (k = 0; k < this.nnodos; k++) {
					if (this.nodos[i][k][0] + this.nodos[k][j][0] < this.nodos[i][j][0]) {
						this.nodos[i][j][0] = this.nodos[i][k][0]
								+ this.nodos[k][j][0];
						this.nodos[i][j][1] = k;
					}
				}
			}
		}
	}

	public int pesominimo(int org, int des) {
		return this.nodos[org][des][0];
	}

	public String caminocorto(int org, int des) {
		String cam;
		if (org == des) {
			cam = "->" + nombres[org];
		} else {
			cam = caminocorto(org, this.nodos[org][des][1]) + "->"
					+ nombres[des];
		}
		return cam;
	}

	public char getNombre(int nodo) {
		return this.nombres[nodo];
	}

	public static void main(String args[]) throws IOException {
		Grafo g;

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String temp;
		int res;

		System.out.println("Entre el numero de nodos del grafo:\n");
		temp = br.readLine();
		res = Integer.parseInt(temp);

		g = new Grafo(res);

		for (int i = 0; i < res; i++) {
			System.out.println("Cual es el nombre del nodo [" + (i + 1)
					+ "]:\n");
			temp = br.readLine();
			g.ingresarNombre(i, temp.charAt(0));
		}
		for (int i = 0; i < res; i++) {
			for (int j = 0; j < res; j++) {
				if (i < j) {
					System.out.println("El nodo " + g.getNombre(i)
							+ " esta conectado con el nodo " + g.getNombre(j)
							+ " (s/n)\n");
					temp = br.readLine();
					if (temp.charAt(0) == 's') {
						int peso;
						System.out.println("Cual es el peso del arco:\n");
						temp = br.readLine();
						peso = Integer.parseInt(temp);
						g.ingresarArco(i, j, peso);
					} else {
						g.ingresarArco(i, j, 10000);
					}
				}
			}
		}

		g.calcular();
		for (int i = 0; i < res; i++) {
			for (int j = 0; j < res; j++) {
				if (i > j) {
					System.out.println("El camino mas corto entre los nodos:"
							+ g.getNombre(i) + "-" + g.getNombre(j) + " es: \n"
							+ g.caminocorto(i, j) + " y su peso es: "
							+ g.pesominimo(i, j));
				}
			}
		}
	}
}

Calendar Loops

this program is very usefull when you need to know the list of dates of a repetitive task in the week.

I create this program to fill the records of my teaches in a school.

#include <stdio.h>


int meses[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int dias[365][3];
/*
0 Lunes
1 Martes
2 Miercoles
3 Jueves
4 Viernes
5 Sabado
6 Domingo
*/

int cursos[7][4]={{0,0,0,0},{2,2,0,0},{1,0,1,1},{0,1,0,0},{0,0,2,2},{0,0,0,0},{0,0,0,0}};

int main(){
    int i,j,k;
    dias[0][0]=5;
    for (i=1;i<365;i++){
        dias[i][0]=(dias[i-1][0]+1)%7;                       
    }    
    k=0;
    for (i=0;i<12;i++){
        for (j=1;j<=meses[i];j++){
            dias[k][1]=i;    
            dias[k][2]=j;
            k++;
        }
    }
    
    for (i=0;i<365;i++){
       // bool salto=false;
        for (j=0;j<4;j++){

            for (k=0;k<cursos[dias[i][0]][j];k++){
                printf("6-%c \t %i - %i \n",'A'+j,dias[i][2]+1,dias[i][1]+1);
//                salto=true;
            }               
        }    
       // if (salto)
       //    printf("\n");
    }
    
    return 0;
}

Allegro Dibujos de posicion relativa

Dibujos en allegro dependiendo de la posicion del mouse

#include <allegro.h>


void  dibujo(int x,int y){
      circle (screen, x+100,y+100,100,makecol(128,0,0));
      circlefill (screen,x+50,y+50,20,makecol(0,255,0));
      circlefill (screen,x+150,y+50,20,makecol(0,255,0));
      rect (screen,x+80,y+100,x+120,y+150,makecol(0,0,128));
      line (screen,x+50,y+180,x+150,y+180,makecol(128,128,0));
}

void init();
void deinit();


int main() {
	init();
	show_mouse(screen);
	while (!key[KEY_ESC]) {  
          clear_to_color(screen,0);
          dibujo(mouse_x,mouse_y);
	}

	deinit();
	return 0;
}
END_OF_MAIN();

void init() {
	int depth, res;
	allegro_init();
	depth = desktop_color_depth();
	if (depth == 0) depth = 32;
	set_color_depth(depth);
	res = set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
	if (res != 0) {
		allegro_message(allegro_error);
		exit(-1);
	}

	install_timer();
	install_keyboard();
	install_mouse();
	/* add other initializations here */
}

void deinit() {
	clear_keybuf();
	/* add other deinitializations here */
}

Allegro Patron

Patron para la creacion de programas en allegro iniciando algunas de sus rutinas basicas.

#include <allegro.h>

void init();
void deinit();

int main() {
	init();

	while (!key[KEY_ESC]) {
		/* put your code here */
	}

	deinit();
	return 0;
}
END_OF_MAIN();

void init() {
	int depth, res;
	allegro_init();
	depth = desktop_color_depth();
	if (depth == 0) depth = 32;
	set_color_depth(depth);
	res = set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
	if (res != 0) {
		allegro_message(allegro_error);
		exit(-1