'Sorce Bank'에 해당되는 글 16건

  1. 2010.06.01 JOGL로 한 그래픽스 실습 <Lighitng>
  2. 2010.05.15 B-Tree
  3. 2010.05.11 그래픽스 : Solar System
  4. 2010.05.08 Python BST + AVL
  5. 2010.05.06 Python HW 2번문제
  6. 2010.05.06 Python HW 1번문제
  7. 2010.04.27 그래픽스 실습 4.27
  8. 2010.04.15 파이썬 c API 하다 만거
  9. 2010.03.25 네트워크 홈워크 1
  10. 2010.03.18 GeneralTree to BinaryTree 2

JOGL로 한 그래픽스 실습 <Lighitng>


import java.awt.*;
import java.awt.event.*;

import com.sun.opengl.util.Animator;
import javax.media.opengl.GL;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;

public class Lighting extends Frame
        implements GLEventListener, KeyListener {

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            System.exit(0);
        }
    }
    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {
    }
    public Lighting() {
        super("Lighting and Shading");
        setLayout(new BorderLayout());
        setSize(400, 400);
        setLocation(40, 40);
        setVisible(true);
        setupJOGL();
    }

    /**
     * Called by the drawable immediately after the OpenGL context is
     * initialized; the GLContext has already been made current when
     * this method is called.
     *
     * @param drawable The display context to render to
     */
    public void init(GLAutoDrawable drawable) {
        GL gl = drawable.getGL();

        gl.glClearColor(1, 1, 1, 1);
        gl.glEnable(GL.GL_DEPTH_TEST);
        float light0_ambient[] = {0.0f, 0.0f, 0.0f, 1.0f};
        float light0_diffuse[] = {0.4f, 0.6f, 0.0f, 1.0f};
        float light0_specular[] = {1.0f, 1.0f, 1.0f, 1.0f};
        float light0_position[] = {1.0f, 1.0f, 1.0f, 0.0f};
        gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, light0_ambient, 0);
        gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, light0_diffuse, 0);
        gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, light0_specular, 0);
        gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light0_position, 0);
        gl.glEnable(GL.GL_LIGHTING);
        gl.glEnable(GL.GL_LIGHT0);

        float mat_ambient[] = {0.8f, 0.8f, 0.2f, 1.0f};
        float mat_diffuse[] = {0.1f, 0.5f, 0.8f, 1.0f};
        float mat_specular[] = {1.0f, 1.0f, 1.0f, 1.0f};
        float mat_emission[] = {0.0f, 0.0f, 0.0f, 1.0f};
        float mat_shininess = 50.0f;
        gl.glLightfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient, 0);
        gl.glLightfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse, 0);
        gl.glLightfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular, 0);
        gl.glLightfv(GL.GL_FRONT, GL.GL_EMISSION, mat_emission, 0);
        gl.glLightf(GL.GL_FRONT, GL.GL_SHININESS, mat_shininess);

        drawable.addKeyListener(this);
    }

    /**
     * Called by the drawable when the surface resizes itself. Used to
     * reset the viewport dimensions.
     *
     * @param drawable The display context to render to
     */
    public void reshape(GLAutoDrawable drawable,
            int x,
            int y,
            int width,
            int height) {
    }

    /**
     * Called by the drawable when the display mode or the display device
     * associated with the GLDrawable has changed
     */
    public void displayChanged(GLAutoDrawable drawable,
            boolean modeChanged,
            boolean deviceChanged) {
    }

    /**
     * Called by the drawable to perform rendering by the client.
     *
     * @param drawable The display context to render to
     */
    public void display(GLAutoDrawable drawable) {
        GL gl = drawable.getGL();
        GLU glu = new GLU();

        // clear the frame buffer and the depth buffer
        gl.glClear(GL.GL_COLOR_BUFFER_BIT);
        gl.glClear(GL.GL_DEPTH_BUFFER_BIT);
        // set intrinsic properties of the camera
        gl.glMatrixMode(GL.GL_PROJECTION);
        gl.glLoadIdentity();
        glu.gluPerspective(45.0f, 1.0f, 0.0001, 100000.0);

        // set extrinsic properties of the camera
        gl.glMatrixMode(GL.GL_MODELVIEW);
        gl.glLoadIdentity();
        glu.gluLookAt(3.0f, 3.0f, 3.0f,
                0.0f, 0.0f, 0.0f,
                0.0f, 1.0f, 0.0f);
        gl.glEnable(GL.GL_LIGHTING);
        gl.glEnable(GL.GL_LIGHT0);
        /// draw objects
        draw_cube(drawable);
        // swap buffers (double buffering)
        //glutSwapBuffers();
    }

    public void draw_cube(GLAutoDrawable drawable) {
        // TODO: set a proper normal for each face
        GL gl = drawable.getGL();

        gl.glBegin(GL.GL_QUADS);

        // front
        gl.glNormal3f(0.0f, 0.0f, 1.0f);
        gl.glVertex3f(1.0f, 1.0f, 1.0f);
        gl.glVertex3f(-1.0f, 1.0f, 1.0f);
        gl.glVertex3f(-1.0f, -1.0f, 1.0f);
        gl.glVertex3f(1.0f, -1.0f, 1.0f);

        // back
        gl.glNormal3f(0.0f, 0.0f, -1.0f);
        gl.glVertex3f(1.0f, -1.0f, -1.0f);
        gl.glVertex3f(-1.0f, -1.0f, -1.0f);
        gl.glVertex3f(-1.0f, 1.0f, -1.0f);
        gl.glVertex3f(1.0f, 1.0f, -1.0f);


        // right
        gl.glNormal3f(1.0f, 0.0f, 0.0f);
        gl.glVertex3f(1.0f, 1.0f, 1.0f);
        gl.glVertex3f(1.0f, -1.0f, 1.0f);
        gl.glVertex3f(1.0f, -1.0f, -1.0f);
        gl.glVertex3f(1.0f, 1.0f, -1.0f);

        // left
        gl.glNormal3f(-1.0f, 0.0f, 0.0f);
        gl.glVertex3f(-1.0f, 1.0f, -1.0f);
        gl.glVertex3f(-1.0f, -1.0f, -1.0f);
        gl.glVertex3f(-1.0f, -1.0f, 1.0f);
        gl.glVertex3f(-1.0f, 1.0f, 1.0f);


        // top
        gl.glNormal3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(1.0f, 1.0f, 1.0f);
        gl.glVertex3f(1.0f, 1.0f, -1.0f);
        gl.glVertex3f(-1.0f, 1.0f, -1.0f);
        gl.glVertex3f(-1.0f, 1.0f, 1.0f);

        // bottom
        gl.glNormal3f(0.0f, -1.0f, 0.0f);
        gl.glVertex3f(-1.0f, -1.0f, 1.0f);
        gl.glVertex3f(-1.0f, -1.0f, -1.0f);
        gl.glVertex3f(1.0f, -1.0f, -1.0f);
        gl.glVertex3f(1.0f, -1.0f, 1.0f);


        gl.glEnd();
    }

    private void setupJOGL() {
        GLCapabilities caps = new GLCapabilities();
        caps.setDoubleBuffered(true);
        caps.setHardwareAccelerated(true);

        GLCanvas canvas = new GLCanvas(caps);
        canvas.addGLEventListener(this);
        add(canvas, BorderLayout.CENTER);
        Animator anim = new Animator(canvas);
        anim.start();
    }

    public static void main(String[] args) {
        Lighting demo = new Lighting();
        demo.setVisible(true);
    }
}



'Sorce Bank' 카테고리의 다른 글

B-Tree  (0) 2010.05.15
그래픽스 : Solar System  (0) 2010.05.11
Python BST + AVL  (0) 2010.05.08
Python HW 2번문제  (0) 2010.05.06
Python HW 1번문제  (0) 2010.05.06

B-Tree

Node.rb
class Node
  attr_accessor :keys, :parent

  def initialize (p, key)
    # keys = [P0, K1 ,P1, K2, ...., Pn ]
    if key.class == Array
      @keys = key
    else
    @keys = [nil,key,nil]
  end
    @parent = p
  end   # end of Constructor of Node class


  def addKey key
    for k in @keys
      if k == nil or k.class == Node
        next
      elsif key < k
        i =@keys.index(k)
        @keys.insert(i, nil)
        @keys.insert(i,key)
        return i
      end
    end
    @keys.push(key)
    @keys.push(nil)
    return @keys.index(key)
  end  # end of addKey

  def delKey key
    for k in @keys
      if k == nil or k.class == Node
              next
      elsif key == k
        i = @keys.index(k)
        @keys.delete_at(i)
        @keys.delete_at(i)
        return true
      end
    end
    return false
  end

  def size # return NUmber of Keys
    return @keys.size()/2
  end  # end of size

end   #end of Node class

B_Tree.rb
require 'Node'

class B_Tree
  attr_accessor :Root
  def initialize m
    @Root = nil
    @M_WAY = m
  end  # end of Constructor of B_Tree class

  def depth node
    keys = node.keys
    ps= []
    for p in keys
      next if p.class == keys[1].class
      ps.push(depth(p)) if p != nil
    end
    return 1 if ps == []
    return 1+ps.max

  end

  def isFull node
    if node.size() >= @M_WAY-1
      return true
    else
      return false
    end
  end  # end of isFull

  def isUnder node
    if node.size() <= @M_WAY/2-1
      return true
    else
      return false
    end # end of isUnder
  end

  def inorder node
    if node == nil
      return
    end
    for k in node.keys
      if k.class ==Node
        inorder(k)
      elsif k == nil
        next
      else
        print k,"(",depth(node),") "
      end
    end
  end  # end of inorder

  def left_merge neighbor, parent, node
    keys, n_keys, p_keys = node.keys, neighbor.keys, parent.keys
    n_index = p_keys.index(neighbor)
    neighbor.addKey(p_keys[n_index+1])
    n_keys.pop
    neighbor.keys = n_keys + keys
    2.times {p_keys.delete_at(n_index+1)}
    for k in neighbor.keys
      if k.class == Node
        k.parent = neighbor
      end
    end
  end

  def right_merge  neighbor, parent, node
    keys, n_keys, p_keys = node.keys, neighbor.keys, parent.keys
    n_index = p_keys.index(node)
    node.addKey(p_keys[n_index+1])
    keys.pop
    node.keys = keys + n_keys
    2.times {p_keys.delete_at(n_index+1)}
    for k in node.keys
      if k.class == Node
        k.parent = node
      end
    end
  end

  def left_loan neighbor, parent, node
    p_keys , n_keys,keys = parent.keys, neighbor.keys,node.keys
    n_index = p_keys.index(node)
    node.addKey(p_keys[n_index-1])
    keys[0],keys[2] = keys[2],keys[0]
    p_keys[n_index-1] = n_keys[n_keys.size-2]
    keys[0] = n_keys[n_keys.size-1]
    keys[0].parent = node if keys[0] != nil
    neighbor.keys = n_keys.slice(0,n_keys.size() -2)
  end

  def right_loan neighbor, parent, node
    p_keys , n_keys,keys = parent.keys, neighbor.keys, node.keys
    n_index = p_keys.index(node)
    node.addKey(p_keys[n_index+1])
    p_keys[n_index+1] = n_keys[1]
    keys[keys.size-1] = n_keys[0]
    n_keys[0].parent =node if n_keys[0] != nil
    neighbor.keys = n_keys.slice(2,n_keys.size()-2)
  end

  def search skey
    cur_node = @Root
    found = false
    begin
      s_node = cur_node
      keys = cur_node.keys
      for k in keys
        cur_node = k if k == keys[keys.size-1]
        next if k.class == Node or k == nil
        if skey == k
          found = true
          break
        elsif skey < k
          cur_node = keys[keys.index(k)-1]
          break
        end       # end of if
      end         # end of for

    end while !found and cur_node!=nil
    return found, s_node
  end             # end of search

  def insert nkey
    if @Root == nil
      @Root = Node.new(nil,nkey)
      return true
    else
      # Tree 가 비어있지 않을 때
      duplicate, node = search(nkey)
      if duplicate
        puts "중복되는 데이터를 삽입하였습니다 #{nkey}"
        return false
      end
      newNode = nil
      while true # 잘 들어갈때 까지.
        unless isFull(node)
          # Node에 여유가 있을 때
          i=node.addKey(nkey)
          keys = node.keys()
          keys[i+1] = newNode
          return true
        else
          i=node.addKey(nkey)
          keys = node.keys()
          keys[i+1] = newNode
          if node.size % 2 == 0 : center_index = keys.size/2+1
          else center_index = keys.size/2
          end
          leftkeys = keys.slice(0,center_index)
          rightkeys = keys.slice(center_index+1,keys.size - center_index)
          node.keys = leftkeys
          newNode = Node.new(node.parent,rightkeys)
          tmpkeys = newNode.keys
          for p in tmpkeys
            if p.class == Node
              p.parent = newNode
            end
          end
          if node.parent == nil
            # 부모 노드가 존재하지 않을 때
            @Root = Node.new(nil,keys[center_index])
            rkeys = @Root.keys
            rkeys[0],rkeys[2] = node, newNode
            node.parent = newNode.parent = @Root
            return true
          else
            # 부모 노드가 존재할 경우
            nkey = keys[center_index]
            node = node.parent
          end # end of 부모노드가 존재하지 않을 때
        end   # end of 노드에 여유가 있을 때

      end     # end of while
    end       # end of 트리가 비어있지 않을 때
  end         # end of insert

  def delete dkey
    if @Root == nil
      puts "비어있는 트리입니다. " 
    end
    found, node = search(dkey)
    if not found
      puts "없는 키에대한 삭제입니다 #{dkey}"
      return false
    end
    keys = node.keys
    if keys[0] == nil
      #leaf Node일때
      node.delKey(dkey)
      @Root = nil if @Root.size() <1 
      return true if (not isUnder node) or nil == @Root
      # Under flow 처리 루틴
      parent = node.parent
      # LEAF 노드 삭제 하는거
      until parent == nil

        p_keys = parent.keys
        n_index = p_keys.index(node)
        if n_index != p_keys.size() -1
          #오른쪽 집에서 빌리기
          neighbor = p_keys[n_index+2]
          if neighbor.size()-1 > @M_WAY/2-1
            # 옆집이 부자면
            right_loan(neighbor, parent, node)
            return true
          else
            # 옆집도 거지면
            right_merge(neighbor, parent,node)
            grandson,parent ,node =node, parent.parent,parent
            return true if not isUnder node
          end

        else
          #왼쪽 집에서 빌리기
          neighbor = p_keys[n_index-2]
          # 오른쪽 집 없어서 왼쪽집
          if neighbor.size()-1 > @M_WAY/2-1
            # 왼쪽집 부자면
            left_loan(neighbor, parent, node)
            return true
          else
            # 왼쪽집 거지면
            left_merge(neighbor, parent,node)
            grandson, parent ,node = neighbor, parent.parent,parent
            return true if not isUnder node
          end
        end

      end
      #Root까지 왔을때 처리 하는거
      if @Root.size <1
        @Root = grandson
        grandson.parent = nil
      end
      return true
    else
      # leaf node 가 아닐때
      i=keys.index(dkey)
      p = keys[i+1]
      ch_node = p
      until p == nil
        ch_node = p
        ch_keys = p.keys
        p=ch_keys[0]
      end
      ckeys = ch_node.keys
      c_key = ckeys[1]
      delete(c_key)
      found, node = search(dkey)
      keys = node.keys
      i=keys.index(dkey)
      keys[i] = c_key
      return true
    end
  end

end    # end of B_Tree class

'Sorce Bank' 카테고리의 다른 글

JOGL로 한 그래픽스 실습 <Lighitng>  (0) 2010.06.01
그래픽스 : Solar System  (0) 2010.05.11
Python BST + AVL  (0) 2010.05.08
Python HW 2번문제  (0) 2010.05.06
Python HW 1번문제  (0) 2010.05.06

그래픽스 : Solar System

// SolarSystem.cpp : Defines the entry point for the console application.
//

//self rotation 자전
//orbiting 공전

/*
* self rotation표현하기 위해 
* rotation axis : +y  (0,1,0)
* rotation angle : 얼마나 돌았나 
*/

#define _USE_MATH_DEFINES
#include 
#include 

void init();
void display();
void idle();
void draw_axes();
void draw_cube();

float moon_selfrot_angle;
float moon_radius,earth_radius ;
float moon_orbit_angle,earth_selfrot_angle;
float moon_orbit_raidus;
float   sun_radius,earth_orbit_raidus,earth_orbit_angle;

void main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);  
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(640, 640);
	glutCreateWindow("GLUT tutorial");
	glutDisplayFunc(display);
	glutIdleFunc(idle);
	init();
	glutMainLoop();
}


void init()
{
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glEnable(GL_DEPTH_TEST);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();  
	gluPerspective(45.0f, 1.0f, 0.001f, 10000.0f);    // don't care at this moment

	sun_radius=10.0f;
	earth_orbit_raidus=26.0f;
	earth_orbit_angle= 0.0f;
	moon_radius=0.7f;
	moon_selfrot_angle = 0.0f;
	moon_orbit_angle=0.0f;
	moon_orbit_raidus=3.5f;
	earth_radius=1.2f;
	earth_selfrot_angle=0.0f;
}


void display()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();  
	gluLookAt(50.0, 50.0, 50.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

	draw_axes();
	// DRAW the SUn

	glPushMatrix();

	glScalef(sun_radius,sun_radius,sun_radius);
	glColor3f(1.0f,0.0f,0.0f);
	draw_cube();
	glPopMatrix();



	glTranslatef(earth_orbit_raidus*cos(2*M_PI*earth_orbit_angle/360),0.0f,
		earth_orbit_raidus*sin(2*M_PI*earth_orbit_angle/360));


	glPushMatrix(); // 지구랑 달을 묶어서 위의 트렌스레이션을 하기위해
	// 중괄호 같이 묶는다는 느낌.
	//지구
	
	glPushMatrix();	/////////////////////////////////////
	//현재 MV메트릭스를 저장하고 POP때 불러온다 
	// 이게 계층척 그래픽스의 핵심. 모델간의 계층관계를 표현하기 위해.
	// 기존의 I 메트릭스를 PUSH 
	glRotatef(earth_selfrot_angle,0.5,0.5,0);
	glScalef(earth_radius,earth_radius,earth_radius);
	glColor3f(0.0f,1.0f,0.0f);
	draw_cube();
	glPopMatrix();	///////////////////////////////////
	// 기존의 pUSH 했던 I매트릭스를 pOP

	

	//dRAW THE MOON
	// 360 : 2*M_PI = Moon_orbit_angle : x ==> 2*M_PI*moon_orbit_angle/360 
	glTranslatef(moon_orbit_raidus*cos(2*M_PI*moon_orbit_angle/360),0.0f,
		moon_orbit_raidus*sin(2*M_PI*moon_orbit_angle/360));

	glScalef(moon_radius,moon_radius,moon_radius);
	glColor3f(0.5f, 0.5f, 0.5f);
	glRotatef(moon_selfrot_angle,0,-1,0);
	draw_cube();

	glPopMatrix();
	glutSwapBuffers();
}


void draw_axes()
{
	glBegin(GL_LINES);
	// x axis 
	glColor3f(0.2f, 0.2f, 0.2f);
	glVertex3f(-10.0f, 0.0f, 0.0f);
	glColor3f(1.0f, 0.0f, 0.0f);
	glVertex3f( 10.0f, 0.0f, 0.0f);
	// y axis 
	glColor3f(0.2f, 0.2f, 0.2f);
	glVertex3f(0.0f, -10.0f, 0.0f);
	glColor3f(0.0f, 1.0f, 0.0f);
	glVertex3f(0.0f,  10.0f, 0.0f);
	// z axis
	glColor3f(0.2f, 0.2f, 0.2f);
	glVertex3f(0.0f, 0.0f, -10.0f);
	glColor3f(0.0f, 0.0f, 1.0f);
	glVertex3f(0.0f, 0.0f,  10.0f);  
	glEnd();
}

void draw_cube()
{
	glBegin(GL_QUADS);
	// front
	glVertex3f( 0.5f,  0.5f,  0.5f);
	glVertex3f(-0.5f,  0.5f,  0.5f);
	glVertex3f(-0.5f, -0.5f,  0.5f);
	glVertex3f( 0.5f, -0.5f,  0.5f);
	// back
	glVertex3f( 0.5f,  0.5f, -0.5f);
	glVertex3f( 0.5f, -0.5f, -0.5f);
	glVertex3f(-0.5f, -0.5f, -0.5f);
	glVertex3f(-0.5f,  0.5f, -0.5f);
	// top
	glVertex3f( 0.5f,  0.5f,  0.5f);
	glVertex3f( 0.5f,  0.5f, -0.5f);
	glVertex3f(-0.5f,  0.5f, -0.5f);
	glVertex3f(-0.5f,  0.5f,  0.5f);
	// bottom
	glVertex3f( 0.5f, -0.5f,  0.5f);
	glVertex3f(-0.5f, -0.5f,  0.5f);
	glVertex3f(-0.5f, -0.5f, -0.5f);
	glVertex3f( 0.5f, -0.5f, -0.5f);
	// left
	glVertex3f(-0.5f,  0.5f,  0.5f);
	glVertex3f(-0.5f,  0.5f, -0.5f);
	glVertex3f(-0.5f, -0.5f, -0.5f);
	glVertex3f(-0.5f, -0.5f,  0.5f);
	// right
	glVertex3f( 0.5f,  0.5f,  0.5f);
	glVertex3f( 0.5f, -0.5f,  0.5f);
	glVertex3f( 0.5f, -0.5f, -0.5f);
	glVertex3f( 0.5f,  0.5f, -0.5f);
	glEnd();
}


void idle()
{
	// TODO: ...
	earth_orbit_angle+=0.01f;
	if(earth_orbit_angle > 360){
		earth_orbit_angle = 0.0f;
	}

	moon_selfrot_angle+=0.01;//degree (도)

	if(moon_selfrot_angle > 360){
		moon_selfrot_angle = 0.0f;
	}
	moon_orbit_angle+=0.04; //  
	if(moon_orbit_angle > 360){
		moon_orbit_angle= 0.0f;
	}
	earth_selfrot_angle+=0.06f;
	if(earth_selfrot_angle > 360)
		earth_selfrot_angle=0.0f;

	glutPostRedisplay();
}



'Sorce Bank' 카테고리의 다른 글

JOGL로 한 그래픽스 실습 <Lighitng>  (0) 2010.06.01
B-Tree  (0) 2010.05.15
Python BST + AVL  (0) 2010.05.08
Python HW 2번문제  (0) 2010.05.06
Python HW 1번문제  (0) 2010.05.06

Python BST + AVL

Tree.py
class Tree:

    def __init__(self):
        self.Root = None
 
Node.py
class Node:

    def __init__(self,key):
        self.key = key
        self.rightChild = self.leftChild = None
        
BST.py
# -*- coding : ms949 -*-
import Tree,Node
import sys

class BST:

    def search(self,tree,s_key):
        if (tree == None): return None,None
        parent, curr = None,tree.Root
        while(curr!=None):
            if(curr.key == s_key): break
            parent = curr
            if(curr.key > s_key): curr = curr.leftChild
            else: curr = curr.rightChild
        return parent,curr

    def inorder(self,node):
        if(node==None):
            return
        self.inorder(node.leftChild)
        sys.stdout.write(str(node.key))
        sys.stdout.write("("+str(self.depth(node))+")"+" ")
        self.inorder(node.rightChild)

    def depth(self,node):
        if(node==None): return 0;
        elif(node.rightChild!=None and node.leftChild != None):
            return 1+max(self.depth(node.rightChild),self.depth(node.leftChild))
        elif(node.leftChild==None): return 1+self.depth(node.rightChild)
        elif(node.rightChild==None): return 1+self.depth(node.leftChild)
        else: return 1

    def insert(self,tree,new_key):
        q, p = self.search(tree, new_key)
        if(p != None):
            print("Duplicate key error")
            return False
        newNode = Node.Node(new_key)
        if(tree.Root==None): tree.Root = newNode
        elif (new_key < q.key): q.leftChild=newNode
        else: q.rightChild = newNode
        return True

    def delete(self,tree, d_key):
        q, p = self.search(tree, d_key)
        if(p==None):
            print("There are no key to delete.")
            return False
        if(p.leftChild==None and p.rightChild==None):
            if(q == None):
                tree.Root = None
                return True
            if(q.leftChild == p): q.leftChild = None
            else: q.rightChild = None
        elif(p.leftChild!=None and p.rightChild!=None):
            if(self.depth(p.leftChild) > self.depth(p.rightChild)):
                # Depth of leftSubTree is larger than Right
                exchangeNode = p.leftChild
                while(exchangeNode.rightChild!=None):
                    exchangeNode = exchangeNode.rightChild
            else:
                # Depth of rightSubTree is larger than Left
                exchangeNode = p.rightChild
                while(exchangeNode.leftChild!=None):
                    exchangeNode = exchangeNode.leftChild

            self.delete(tree, exchangeNode.key)
            p.key,exchangeNode.key = exchangeNode.key,p.key


        elif(p.leftChild!=None):
            if(q.leftChild == p): q.leftChild = p.leftChild
            else: q.rightChild = p.leftChild
        else:
            if(q.leftChild == p): q.leftChild = p.rightChild
            else: q.rightChild = p.rightChild
        return True
AVL.py
# -*- coding: ms949 -*-
import BST
import sys

class AVL(BST.BST):
    def __init__(self):
        self.bf_stack=[]
        self.node_stack=[]

    def BFof(self,node):
        return self.depth(node.leftChild)-self.depth(node.rightChild)

    def insert(self,tree,key):
        if super(AVL,self).insert(tree,key) == False: return False
        if self.isAVL(tree,key) :
            del self.bf_stack[:]
            del self.node_stack[:]
        else: self.makeAVL(tree,key)
        return True

    def delete(self,tree,key):
        if super(AVL,self).delete(tree, key)==False: return False
        if self.isAVL(tree,key) :
            del self.bf_stack[:]
            del self.node_stack[:]
        else: self.makeAVL(tree,key)
        return True

    def isAVL(self,tree,key):
        parent,gabage = self.search(tree, key)
        if parent == None: return True
        if len(self.bf_stack)==3:
            self.bf_stack.remove(self.bf_stack[0])
            self.node_stack.remove(self.node_stack[0])
        bf=self.BFof(parent)
        self.bf_stack.append(bf)
        self.node_stack.append(parent)
        if(abs(bf)>1):
            return False
        return self.isAVL(tree,parent.key)

    def makeAVL(self,tree,key):
        if(len(self.bf_stack)==2):
            gabage,C = self.search(tree,key)
            self.node_stack.insert(0,C)
            self.bf_stack.insert(0,self.BFof(C))

        if len(self.bf_stack) == 3:

            if self.bf_stack[1] < 0 and self.bf_stack[2] > 0:
                print("insert",str(key),"=> LR")
                self.RL_LR(tree,self.node_stack[1],self.node_stack[2])

            elif self.bf_stack[1] > 0 and self.bf_stack[2] < 0:
                print("insert",str(key),"=> RL")
                self.RL_LR(tree,self.node_stack[2],self.node_stack[1])

            elif self.bf_stack[1] * self.bf_stack[2] > 0:
                sys.stdout.write("insert "+str(key))
                self.node_stack.remove(self.node_stack[0])
                self.LL_RR(tree)
        del self.bf_stack[:]
        del self.node_stack[:]


    def LL_RR(self,tree):
        A,B=self.node_stack[1],self.node_stack[0]
        parent,gabage = self.search(tree,A.key)
        if parent == None: tree.Root =B
        elif parent.leftChild == A: parent.leftChild = B
        else: parent.rightChild = B

        if self.bf_stack[1] > 0 and self.bf_stack[2] > 0:
            A.leftChild,B.rightChild = B.rightChild, A
            print(" => LL")
        elif self.bf_stack[1] < 0 and self.bf_stack[2] < 0:
            A.rightChild,B.leftChild = B.leftChild, A
            print(" => RR")

    def RL_LR(self,tree,left,right):
        parent,gabage = self.search(tree,self.node_stack[2].key)
        C = self.node_stack[0]
        if parent == None: tree.Root = C
        elif parent.leftChild == self.node_stack[2]: parent.leftChild = C
        else: parent.rightChild =C
        C.leftChild,C.rightChild,left.rightChild,right.leftChild 
              = left,right ,C.leftChild,C.rightChild
   

'Sorce Bank' 카테고리의 다른 글

B-Tree  (0) 2010.05.15
그래픽스 : Solar System  (0) 2010.05.11
Python HW 2번문제  (0) 2010.05.06
Python HW 1번문제  (0) 2010.05.06
그래픽스 실습 4.27  (0) 2010.04.27

Python HW 2번문제

import os.path

import glob
import sys
if(len(sys.argv)!=2):
    print("Usage : python <Script name> <Dir Name>")
    sys.exit(1)

class Du:
    def searchDir(self,dirName):
        fileList = glob.glob(dirName)
        size=0;
        for fullFile in fileList:
            if os.path.isdir(fullFile):
                size+=self.searchDir(fullFile+"/*")
            else:
                s = os.path.getsize(fullFile)
                size+=s
        print size/1024,dirName
        return size
  

test = Du()
test.searchDir(sys.argv[1]+"/*")

    

 

'Sorce Bank' 카테고리의 다른 글

그래픽스 : Solar System  (0) 2010.05.11
Python BST + AVL  (0) 2010.05.08
Python HW 1번문제  (0) 2010.05.06
그래픽스 실습 4.27  (0) 2010.04.27
파이썬 c API 하다 만거  (0) 2010.04.15

Python HW 1번문제

import os.path

import glob
import cStringIO
import os
import sys
if(len(sys.argv)!=2):
    print("Usage : python <Script name> <Dir Name>")
    sys.exit(1)

files={}
id=0

def countWord(filename):
    in_file = open(filename)
    text = in_file.read()
    in_file.close()
    strIO = cStringIO.StringIO(text)
    filelines = strIO.readlines()
    numOfWd=0
    numOfLn=0
    word=[]
    
    for line in filelines:
        word+=line.split()
        numOfLn+=1
    for w in word:
        numOfWd+=1  
        
    return numOfWd, numOfLn
    

def searchDir(dirName):
    fileList = glob.glob(dirName)
    for fullFile in fileList:
        if os.path.isdir(fullFile):
            searchDir(fullFile+"/*")
        else:
            d_name = os.path.dirname(fullFile)
            f_name = os.path.basename(fullFile)
            words,lines = countWord(fullFile)
            value=(d_name,f_name,lines,words)
            global id
            id+=1
            files[id]=value
  


searchDir(sys.argv[1]+"/*")
f_keys = files.keys()
for a in f_keys:
    print "id", a
    info = files[a]
    print "Path : ", info[0]
    print "File name : ", info[1]
    print "Number of lines :", info[2]
    print "Number of Words :",info[3]
    

 

'Sorce Bank' 카테고리의 다른 글

Python BST + AVL  (0) 2010.05.08
Python HW 2번문제  (0) 2010.05.06
그래픽스 실습 4.27  (0) 2010.04.27
파이썬 c API 하다 만거  (0) 2010.04.15
네트워크 홈워크 1  (0) 2010.03.25

그래픽스 실습 4.27



#include
#include 


void draw_axes();
void init();
void draw_drag();
void display(void);
void mouse(int button,int status,int x, int y);
void motion(int,int);

int last_x,last_y;			//last (x,y) position , where the left button pressed.
int current_x, current_y;   // current (x,y) position 
bool b_draw_dragbox = false;

int main()
{
	glutCreateWindow("TransFormation");
	glutDisplayFunc(display);
	glutMouseFunc(mouse);
	glutMotionFunc(motion);
	init();
	
	glutMainLoop();

	return 0;
}

void init()
{

	glClearColor(1.0f,1.0f,1.0f,1.0f);

}

void display()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	// set the current camera
	// f) extrinsic camera property, which can be specified by GL_MODELVIEW matirix
	// s) intrinsic camera property, which can be specified by GL_PROJECTION matrix

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1,1,- 1,1 ,-1, 1);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();														// M = I
	gluLookAt(0, 0, 1, 0, 0, 0, 0, 1 , 0);
	
	draw_axes();
	// Object를 조작함.
	//glRotatef(75.0f,0,0,1);											// R 메트릭스    M *=R   => M=R 
	//glScalef(2.0f,2.0f,2.0f);										// S 메트릭스		M *=S   => M=RS
	glTranslatef(0.3f,0.3f,0.0f);										// T 메트릭스		M *=T   => M=RST
																				// T ( S ( Rx))
	// Model Matrix Continue....																		M'  = RSTx    => T먼저 적용됨.

	// Draw DragBox
	if(b_draw_dragbox)
		draw_drag();

	

	//Drawing an object (a red box)
	// Object는 절대 건들이지 않는다. 메트릭스만 곱해서 조절 ->그리는건 조형대 애들이. 
	glColor3f(1.0f,0.0f,0.0f);
	glBegin(GL_QUADS);
	// -------------------------------
	glVertex2f(0.5f,0.5f);
	glVertex2f(-0.5f,0.5f);											// x메트릭스
	glVertex2f(-0.5f,-0.5f);
	glVertex2f(0.5f,-0.5f);
	// -------------------------------
	glEnd();
																				//  = > Tx
	glFlush();


}

void draw_drag()
{
	glColor3f(0.0f,1.0f,0.0f);
	glBegin(GL_LINE_LOOP);
	glVertex2f(last_x,last_y);
	glVertex2f(last_x,current_y);
	glVertex2f(current_x,current_y);
	glVertex2f(current_x,last_y);
	glEnd();
	printf("adfasd");

}
void draw_axes()
{
	glMatrixMode(GL_MODELVIEW);
	glBegin(GL_LINES);

	glColor3f(1.0f,0.0f,0.0f);
	glVertex2d(-5,0);
	glVertex2d(5,0);


	glColor3f(1.0f,1.0f,0.0f);
	glVertex2d(0,-5);
	glVertex2d(0,5);
	glEnd();
	glFlush();

}

void mouse(int button,int state,int x, int y)
{
	if( button == GLUT_LEFT_BUTTON&& state == GLUT_DOWN)
	{
		printf("left mouse button is pressed!\n");
		last_x = x;
		last_y = y;
		b_draw_dragbox=true;
		// 네모 그리고 
	} else if( button == GLUT_LEFT_BUTTON && state == GLUT_UP)
	{
		printf("left mouse button is Releassed!\n");
		b_draw_dragbox=false;
		// 네모지우고
	}
}


void motion(int x,int y)
{
	current_x =x;
	current_y = y;
	printf("mouse is dragging : x : %d   y: %d \n",x,y);

}

'Sorce Bank' 카테고리의 다른 글

Python HW 2번문제  (0) 2010.05.06
Python HW 1번문제  (0) 2010.05.06
파이썬 c API 하다 만거  (0) 2010.04.15
네트워크 홈워크 1  (0) 2010.03.25
GeneralTree to BinaryTree  (2) 2010.03.18

파이썬 c API 하다 만거

#include "Python.h"
//http://blog.redjini.com/94
//http://docs.python.org/c-api/list.html
//http://www.python.or.kr/pykug/C_20_c8_ae_c0_e5_b8_f0_b5_e2_20_b8_b8_b5_e9_b1_e2

static PyObject *ErrorObject;

 static PyObject* sample_dictest(PyObject *self, PyObject *args)
{
    PyObject* dic;
    int len;

    if (!PyArg_ParseTuple(args, "O", &dic)) /* 파이썬 객체를 dic로 전달 받는다 */
        return NULL;
    if (!PyDict_Check(dic)) { /* 사전인지 검사 */
        /* 사전이 아니면 예외 발생. 일단 건너뛰자 */
        PyErr_SetString(ErrorObject, "my exception");
        return NULL;
    }
    len = PyDict_Size(dic);     /* 사전의 길이를 얻는다 */
    printf("Yes, this is dictionary of len %d\n", len); /* 메시지 출력 */
    Py_INCREF(Py_None); /* 파이썬 None 객체 리턴 */
    return Py_None;
}


static PyObject* sample_system(PyObject *self, PyObject *args)
{
    char *command;
    int sts;
    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue("i", sts);
}

 static PyObject* my_sort(PyObject *self, PyObject *args)
{
    PyObject* list;
    int len;

    if (!PyArg_ParseTuple(args, "O", &list)) /* 파이썬 객체를 dic로 전달 받는다 */
        return NULL;
    if (!PyList_Check(list)) { /* 사전인지 검사 */
        /* 사전이 아니면 예외 발생. 일단 건너뛰자 */
        PyErr_SetString(ErrorObject, "my exception");
        return NULL;
    }
    len = PyList_Size(list);     /* 사전의 길이를 얻는다 */
    printf("Yes, this is List of len %d\n", len); /* 메시지 출력 */
    Py_INCREF(Py_None); /* 파이썬 None 객체 리턴 */
    return Py_None;
}



static struct PyMethodDef my_methods[] = {
 {"system",       sample_system,    METH_VARARGS}, /* name, address */
 {"dictest",      sample_dictest,   METH_VARARGS},
 {"sort",         my_sort,          METH_VARARGS},
 {NULL,         NULL}                              /* end, for initmodule */
};

void initsample()
{
    PyObject *m;
    /* 모듈을 생성하고 함수를 등록한다 */
    m = Py_InitModule("mylib", my_methods);        /* registration hook */
    /* 기타의 초기화 처리 */
    ErrorObject = Py_BuildValue("s", "sample error");
    /* ... */
}

'Sorce Bank' 카테고리의 다른 글

Python HW 1번문제  (0) 2010.05.06
그래픽스 실습 4.27  (0) 2010.04.27
네트워크 홈워크 1  (0) 2010.03.25
GeneralTree to BinaryTree  (2) 2010.03.18
Java Binary Tree  (0) 2010.03.14

네트워크 홈워크 1


/*
Student ID : 20052532
Name : Jea Young Park
*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

void display();
void exceptionHandler(char * msg);

int peertcpSocket = -1;	// peer socket

int main(int argc, char **argv)
{

  int tcpServ_sock;

  struct sockaddr_in tcpServer_addr;
  struct sockaddr_in tcpClient_addr;
  struct sockaddr_in newTcp_addr;

  int clnt_len;

  fd_set reads, temps;
  int fd_max;

  char command[1024];
  char comd[1024];


  char *tcpport = NULL;
  char *userid = NULL;
  int command_len;
  struct hostent *hostp;
  char* addr;
  char* port;
// NEED TO ADD SOME VARIABLES

  if(argc != 3){
    printf("Usage : %s  \n", argv[0]);
    exit(1);
  }


  display();
  tcpport = argv[1];
  userid = argv[2];


	// NEED TO CREATE A SOCKET FOR TCP SERVER
  peertcpSocket = socket(PF_INET, SOCK_STREAM, 0);
  tcpServ_sock = socket(PF_INET, SOCK_STREAM, 0);
  if (tcpServ_sock == -1||peertcpSocket==-1)
  {
      exceptionHandler("socket() error");
      exit(1);
  }

  memset(&tcpServer_addr,0,sizeof tcpServer_addr);
  tcpServer_addr.sin_family = AF_INET;
  tcpServer_addr.sin_addr.s_addr = INADDR_ANY;
  tcpServer_addr.sin_port = htons((u_short)atoi(tcpport));

	// NEED TO bind
  if(bind(tcpServ_sock,(struct sockaddr*)&tcpServer_addr,sizeof tcpServer_addr)==-1)
  {
      exceptionHandler("bind() error");
      exit(1);
  }


	// NEED TO listen
  if(listen(tcpServ_sock,SOMAXCONN)==-1)
  {
      exceptionHandler("listen() error");
      exit(1);
  }
	// initialize the select mask variables and set the
	// mask with stdin and the tcp server socket
  FD_ZERO(&reads);
  FD_SET(tcpServ_sock,&reads);
  FD_SET(peertcpSocket,&reads);
  FD_SET(fileno(stdin),&reads);

  printf("%s> \n", userid);

  while(1)
  {
    int nfound;
    temps = reads;

    nfound = select(fd_max+1, &temps, 0, 0, NULL);

	if(FD_ISSET(fileno(stdin), &temps)) {
		// Input from the keyboard
		fgets(command, sizeof (command), stdin);
  		FD_CLR(fileno(stdin), &temps);
                strcpy(comd,command);
                char* cmd = strtok(command," \n");
           


	// NEED TO IMPLEMENT for input from keybord
                if(strcmp(cmd,"@conn")==0){
                    addr = strtok (NULL, " \n");
                    port = strtok (NULL, " \n");

                    hostp = gethostbyname(addr);
                    
                    memset((void *) &newTcp_addr, 0, sizeof (newTcp_addr));
                    newTcp_addr.sin_family = AF_INET;
                    memcpy((void *) &newTcp_addr.sin_addr, hostp->h_addr, hostp->h_length);
                    newTcp_addr.sin_port = htons((u_short)atoi(port));
                    
                    if(connect(peertcpSocket,(struct sockaddr*)&newTcp_addr,sizeof newTcp_addr)==-1){
                        exceptionHandler("connect() error");
                        exit(1);
                    }

                } else if(strcmp(cmd,"@quit")==0)
                {
                    close(peertcpSocket);
                    fprintf(stdout,"Closed socket descriptor : %d\n",peertcpSocket);
                    peertcpSocket = socket(PF_INET, SOCK_STREAM, 0);
                }else if(strcmp(cmd,"@exit")==0)
                {
                    close(peertcpSocket);
                    close(tcpServ_sock);
                    exit(0);
                } else {
                    strcpy(command,comd);
                    strcpy(comd,userid);
                    strcat(comd , " ) ");
                    strcat(comd,command);
                    write(peertcpSocket,comd,strlen(comd));
                }

  		printf("%s> \n", userid);
	}
	else if(FD_ISSET(tcpServ_sock, &temps))
	{
		//connect request from a peer
           clnt_len = sizeof tcpClient_addr;
           close(peertcpSocket);
           peertcpSocket =accept(tcpServ_sock,(struct sockaddr*)&tcpClient_addr,&clnt_len);
           if(peertcpSocket == -1)
           {
                     exceptionHandler("accept() error");
                     exit(1);
           }
           fprintf(stdout,"New Talk : host %s, port %d, socket %d\n",inet_ntoa(tcpClient_addr.sin_addr),ntohs(tcpClient_addr.sin_port),peertcpSocket);

	}
	else if(FD_ISSET(peertcpSocket, &temps))
	{

            command_len=read(peertcpSocket,command,sizeof command);
            if(command_len == -1)
            {
                   exceptionHandler("read() error");
                   exit(1);
            }else if(command_len == 0)
            {
                close(peertcpSocket);
                peertcpSocket = socket(PF_INET, SOCK_STREAM, 0);
                fprintf(stdout,"Closed socket descriptor : %d\n",peertcpSocket);
            }else {
            command[command_len] = '\0';
            fputs(command,stdout);
            fputs("\n",stdout);
            }
	}

  }//while End
}//main End

void display()
{
	printf("Student ID : 20052532 \n");
	printf("Name : JeaYoung  \n");
}
void exceptionHandler(char * msg)
{
    fputs(msg,stderr);
    fputs("\n",stderr);
}




'Sorce Bank' 카테고리의 다른 글

그래픽스 실습 4.27  (0) 2010.04.27
파이썬 c API 하다 만거  (0) 2010.04.15
GeneralTree to BinaryTree  (2) 2010.03.18
Java Binary Tree  (0) 2010.03.14
Python Client  (0) 2010.03.14

GeneralTree to BinaryTree


main.cpp
/*
  Input File Command Manual

  1. insert  
	This Command Call insert Function.
	If  is Root,  will insert to Root Node.

  2. Gen2Bin
	This Command make General Tree Binary Tree.

  3. clearBinary
	This Command Clear data(link data : R_child, L_child) of Binary Tree.
	You Must call This command, When You insert Node after calling Gen2Bin command.

  4. inorder
	This Command is In-order Traversal.

  5. preorder
	This Command is Pre-order Traversal.

  6. postorder
	This Command is Post-order Traversal.

  7. end
	End of input File.

  #- all Commands are case-sensitive  -#
*/


//---------------------------------------------------------------------------

#pragma hdrstop
#include "GeneralTree.h"
#include 
#include 
#include 
//---------------------------------------------------------------------------

using namespace std;
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
	string command;
	cout << "Enter Input File name : ";
	cin >> command;
	fstream i_file(command.c_str(), ios_base::in);
	cout << "Enter Output File name : ";
	cin >> command;
	fstream o_file(command.c_str(), ios_base::out);

	GeneralTree* tree = new GeneralTree(o_file);

	while(!i_file.eof()){
	i_file >> command ;
	if (strcmp(command.c_str(),"insert")==0) {
		string p;
		char a;
		i_file >>p >> a;
		if(strcmp(p.c_str(),"Root")==0)
		{
			tree->Insert(NULL,a);
		} else {
			tree->Insert(p[0],a);
		}
	} else if (strcmp(command.c_str(),"Gen2Bin")==0) {
			tree->General2Binary(tree->getRoot());
		   }
	else if (strcmp(command.c_str(),"clearBinary")==0) {
			tree->ClearBinary(tree->getRoot());
		 }

	 else if (strcmp(command.c_str(),"inorder")==0) {
			 tree->inOrder(tree->getRoot());
			 o_file << "\n";

	 }
	  else if (strcmp(command.c_str(),"preorder")==0) {
			tree->preOrder(tree->getRoot());
			 o_file << "\n";
	 }
	  else if (strcmp(command.c_str(),"postorder")==0) {
			tree->postOrder(tree->getRoot());
			o_file << "\n";
	 }
	 else if (strcmp(command.c_str(),"end")==0) {
				cout <<"[Finished]\n";
				tree->~GeneralTree();
				i_file.close();
				o_file.close();
				return 0;
	 }
	 else {
				cout <<"Unknown Command Error!! : "<< command<<"\n";
				tree->~GeneralTree();
				i_file.close();
				o_file.close();
				return 1;
			}
	}
 }
//---------------------------------------------------------------------------
Node.h
#include 

#ifndef NODE_H
#define NODE_H
template 
class Node
{
public:

	Node(Ty d)
	{
		data=d;
		//children.reserve(10);
	}
	inline void setRight(Node* node){ R_child = node;}
	inline void setLeft(Node* node) { L_child = node;}

	inline Node* getRight(){return R_child;}
	inline Node* getLeft() {return L_child;}

	inline Ty getData()const { return data; }
	std::vector* > children;
private:
	Node *R_child;
	Node *L_child;
	Ty data;
};

#endif
GeneralTree.h
#ifndef GENERALTREE_H
#define GENERALTREE_h
#include 
#include 

#include 

#include "Node.h"
using namespace std;


template 
class GeneralTree
{
public:
	GeneralTree(ostream o_stream)
	{
		root = new Node(NULL);
		NullNode = new Node(NULL);
		os = o_stream;
	}

	~GeneralTree()
	{
		delete root;
		delete NullNode;
	}

	Node* findNode(Node* node,Ty data);
	bool Insert(Ty Dop,Ty data);
	Node* makeNode(Ty data);
	void General2Binary(Node* CurrentNode);
	void inOrder(Node *node);
	void preOrder(Node *node);
	void postOrder(Node *node);
	void showData(Node *node);
	void ClearBinary( Node *node);

	inline Node* getRoot() const {return root; }



private:
	Node* root;
	Node* NullNode;
	ostream os;

};

template 
void GeneralTree::General2Binary(Node* CurrentNode)
{
	typedef vector< Node* >::iterator Child_t;
	if(!(CurrentNode->children.empty()))
	{
		for(Child_t it= CurrentNode->children.begin();it != CurrentNode->children.end()-1 ; it++)
		{
			if(it == CurrentNode->children.begin())
			{
				CurrentNode->setLeft(*it);
				(*it)->setRight(*(it+1));
				General2Binary(*it);
			} else {
				(*it)->setRight(*(it+1));
				General2Binary(*it);
			}
		}
	}
}

/*
 * Dop : Data of Parent
 *       if Dop is NULL , data Will be Inserted to Root.
 *       if Dop could not find, data Will Not be inserted.
 *       if Dop was Found , data will be Inserted to Child of Dop.
 * data : A data to insert
 */
template 
bool GeneralTree::Insert(Ty Dop, Ty data)
{
	if(root->getData() == NULL)
	{
		root = makeNode(data);
		return true;
	} else {
		Node* parent;
		parent = findNode(root,Dop);
		if(parent == NullNode)
		{
			std::cerr << " 원하는 부모의 값이 없습니다. \n";
			return false;
		} else {
			parent->children.push_back(makeNode(data));
			return true;
		}
	}

}

template 
Node* GeneralTree::findNode(Node* node,Ty data)
{
	typedef vector< Node* >::iterator Child_t;
	Node* temp;
	if(node->getData() == data)
		return node;
	else {
		Node* Parent=node;
		Child_t begin = Parent->children.begin();
		for(Child_t it = begin; it != Parent->children.end(); it++)
		{
			temp = findNode((*it),data);
			if(temp != NullNode )
				return temp;
		}
		return NullNode;
	}

}
template 
Node* GeneralTree::makeNode(Ty data)
{
	Node* new_node = new Node(data);
	new_node->setLeft(NullNode);
	new_node->setRight(NullNode);
	return new_node;
}

template 
void GeneralTree::showData(Node *node)
{
	os << node->getData() <<" ";
}


template 
void GeneralTree::preOrder(Node * node)
{
	if(node == NullNode ) return ;
	if(node == root) os << "PreOrder : ";

	showData(node);
	preOrder(node->getLeft());
	preOrder(node->getRight());
}

template 
void GeneralTree::inOrder(Node * node)
{
	if(node == NullNode ) return ;
	if(node == root) os << "InOrder : ";

	inOrder(node->getLeft());
	showData(node);
	inOrder(node->getRight());
}

template 
void GeneralTree::postOrder(Node * node)
{
	if(node == NullNode ) return ;
	if(node == root) os << "PostOrder : ";

	postOrder(node->getLeft());
	postOrder(node->getRight());
	showData(node);
}

template 
void GeneralTree::ClearBinary(Node *node)
{
	if(node == NullNode ) return ;
	ClearBinary(node->getLeft());
	ClearBinary(node->getRight());
	node->setLeft(NullNode);
	node->setRight(NullNode);
}

#endif

'Sorce Bank' 카테고리의 다른 글

파이썬 c API 하다 만거  (0) 2010.04.15
네트워크 홈워크 1  (0) 2010.03.25
Java Binary Tree  (0) 2010.03.14
Python Client  (0) 2010.03.14
Python Server  (0) 2010.03.14
prev 1 2 next