2014년 7월 27일 일요일

(java queue fibonacci, 자바수열)자바 큐를 이용한 피보나치 수열, 자바알고리즘, 자바자료구조

(java queue fibonacci, 자바수열)자바 큐를 이용한 피보나치 수열, 자바알고리즘, 자바자료구조

자바 큐를 이용한 피보나치 수열, 자바알고리즘, 자바자료구조
 
import java.io.*;
interface Queue  {  
           public boolean isEmpty();
     public boolean isFull();
           public Object getFrontElement();
           public Object getRearElement();
           public void put(Object theObject);
           public Object remove();
}
public class ArrayQueue implements Queue
     {
           // data members
          int front;          // one counterclockwise from first element
          int rear;           // position of rear element of queue
          Object [] queue;    // element array
         
          public ArrayQueue(int initialCapacity)
         {
               if (initialCapacity < 1)
                    throw new IllegalArgumentException
                      ("initialCapacity must be >= 1");
               queue = new Object [initialCapacity + 1];
               // default front = rear = 0
         }   
   
       public boolean isEmpty() {
      return front == rear;
       }
   
       public boolean isFull() {
      return (rear+1) % queue.length == front;
       }
      
       public Object getFrontElement() {
           if (isEmpty())  return null;
           else return queue[(front + 1) % queue.length];
      }
     
      public Object getRearElement() {
          if (isEmpty())  return null;
          else return queue[rear];
     }
   
     public void put(Object theElement)  {
          // increase array length if necessary
          if ((rear + 1) % queue.length == front) {
            // double array size
            // code to double array size comes here
         }
         // put theElement at the rear of the queue
         rear = (rear + 1) % queue.length;
         queue[rear] = theElement;
     }   


      public Object remove()  {
           if (isEmpty())
               return null;
           front = (front + 1) % queue.length;
          Object frontElement = queue[front];
          queue[front] = null;  // enable garbage collection
          return frontElement;
      }
  }
 
 
class FiboWithQueue {
 void fibo(int n) {
  int[] fib = new int[n];
  int a, b;
  ArrayQueue queue = new ArrayQueue(2);
  fib[0] = fib[1] = 1;
  queue.put(new Integer(1));  // fib(0)
  queue.put(new Integer(1));   //fib(1)
  for(int i=2; i<n; i++) {
   a = ((Integer)queue.getFrontElement()).intValue();
   b = ((Integer)queue.getRearElement()).intValue();
   fib[i] = a + b;
   queue.remove();
   queue.put(new Integer(fib[i]));
  }
  //------------ 수열 출력
  for(int i=0; i<fib.length; i++) {
   System.out.println(fib[i] + " ");
  }
 }
 public static void main(String[] args) {
  if (args.length < 1) {
   System.out.println("Usage : java FiboWithQueue number");
   System.exit(1);
  }
  int n = Integer.parseInt(args[0]);
  FiboWithQueue f = new FiboWithQueue();
  f.fibo(n);
 }
}
 

댓글 없음:

댓글 쓰기