Title: according to the queue knowledge of data structure, an algorithm is compiled to output Yanghui triangle with queue
Solutions:
1. Build a self built queue and put the data of Yanghui triangle at the end of the queue;
2. When printing, take out the queue head for printing and delete it from the queue;
The code is as follows:
Queue code
package queue; /** * Define a queue */ public class Queue<T> { private Object[] data; //Data stored in the queue private int maxSize ; //Size of the queue private int front ;//Pointer to the head of the queue private int rear ; //Pointer to the end of the queue public Queue(int size){ if (size < 0) throw new IllegalArgumentException("data is invalid: "+ size); this.maxSize = size; this.data = new Object[maxSize]; front = -1; rear = -1; } /** * Determine whether the queue is full * @return */ public boolean isFull(){ return rear == maxSize -1 ; } /** * Judge whether the queue is empty * @return */ public boolean isEmpty(){ return rear == front; } /** * Add data to queue * @param n */ public void add(T t){ if(isFull()){ System.out.println("The queue is full and cannot be added"); return; } data[++rear] = t; } /** * Display header data * @return */ public Object head(){ if(isEmpty()){ throw new RuntimeException("Queue is empty"); } Object obj=data[front+1]; return obj; //System.out.println(data[front+1]); } /** * Take out the header data * @return */ public Object pop(){ if(isEmpty()){ throw new RuntimeException("Queue is empty"); } Object obj = data[++front]; data[front] = null; return obj; } /** * Print all data */ public void print(){ if(isEmpty()){ System.out.println("Queue is empty"); return; } for(int i=0;i<data.length;i++){ System.out.printf("array["+i+"]=%d\n",data[i]); } } }
Print Yanghui triangle Code:
import queue.Queue; import java.util.Scanner; public class YhTrianQueue { public static void main(String[] args) { System.out.println("How many lines do you want?:"); Scanner input = new Scanner(System.in); //Enter the number of lines in Yang Hui triangle int lines = input.nextInt(); //Create a 2D array to hold data int[][] array=new int[lines][lines]; //The length of queue created is the total number of data in Yanghui triangle (n*(n+1))/2 Queue<Integer> queueI = new Queue((lines*(lines+1))/2); //Loop data in queue for (int i=0;i<lines;i++){ //Printing value for (int j=0;j<i+1;j++){ if ((i >= 2) && (j >= 1)&&(j < i)){ array[i][j] = array[i-1][j-1] + array[i-1][j]; //Add data to queue queueI.add(array[i][j]); } else { array[i][j] = 1; //Add data to queue queueI.add(array[i][j]); }; } } //Print Yanghui triangle for (int i=0;i<=lines-1;i++) { //Print space for (int j=0;j<=lines-i-1;j++){ System.out.print(" "); } //Print value, the number of each line is the number of lines for (int m=0; m <= i; m++) { System.out.print(queueI.head() + " "); //Out of line queueI.pop(); } System.out.println(); } } }