Algorithm Part I:Programming Assignment(2),assignment2.2

來源:互聯網
上載者:User

Algorithm Part I:Programming Assignment(2),assignment2.2

問題描述:

Programming Assignment 2: Randomized Queues and Deques

Write a generic data type for a deque and a randomized queue. The goal of this assignment is to implement elementary data structures using arrays and linked lists, and to introduce you to generics and iterators.

Dequeue. A double-ended queue or deque (pronounced "deck") is a generalization of a stack and a queue that supports inserting and removing items from either the front or the back of the data structure. Create a generic data type Deque that implements the following API:

public class Deque<Item> implements Iterable<Item> {   public Deque()                           // construct an empty deque   public boolean isEmpty()                 // is the deque empty?   public int size()                        // return the number of items on the deque   public void addFirst(Item item)          // insert the item at the front   public void addLast(Item item)           // insert the item at the end   public Item removeFirst()                // delete and return the item at the front   public Item removeLast()                 // delete and return the item at the end   public Iterator<Item> iterator()         // return an iterator over items in order from front to end   public static void main(String[] args)   // unit testing}

Throw a NullPointerException if the client attempts to add a null item; throw a java.util.NoSuchElementException if the client attempts to remove an item from an empty deque; throw an UnsupportedOperationException if the client calls the remove() method in the iterator; throw a java.util.NoSuchElementException if the client calls the next() method in the iterator and there are no more items to return.

Your deque implementation must support each deque operation in constant worst-case time and use space proportional to the number of items currently in the deque. Additionally, your iterator implementation must support the operations next() and hasNext() (plus construction) in constant worst-case time and use a constant amount of extra space per iterator.

Randomized queue. A randomized queue is similar to a stack or queue, except that the item removed is chosen uniformly at random from items in the data structure. Create a generic data type RandomizedQueue that implements the following API:

public class RandomizedQueue<Item> implements Iterable<Item> {   public RandomizedQueue()                 // construct an empty randomized queue   public boolean isEmpty()                 // is the queue empty?   public int size()                        // return the number of items on the queue   public void enqueue(Item item)           // add the item   public Item dequeue()                    // delete and return a random item   public Item sample()                     // return (but do not delete) a random item   public Iterator<Item> iterator()         // return an independent iterator over items in random order   public static void main(String[] args)   // unit testing}

Throw a NullPointerException if the client attempts to add a null item; throw a java.util.NoSuchElementException if the client attempts to sample or dequeue an item from an empty randomized queue; throw anUnsupportedOperationException if the client calls the remove() method in the iterator; throw a java.util.NoSuchElementException if the client calls the next() method in the iterator and there are no more items to return.

Your randomized queue implementation must support each randomized queue operation (besides creating an iterator) in constant amortized time and use space proportional to the number of items currently in the queue. That is, any sequence of M randomized queue operations (starting from an empty queue) should take at most cM steps in the worst case, for some constant c. Additionally, your iterator implementation must support construction in time linear in the number of items and it must support the operations next() and hasNext() in constant worst-case time; you may use a linear amount of extra memory per iterator. The order of two or more iterators to the same randomized queue should be mutually independent; each iterator must maintain its own random order.

Subset client. Write a client program Subset.java that takes a command-line integer k; reads in a sequence of N strings from standard input using StdIn.readString(); and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that 0 ≤ k ≤ N, where N is the number of string on standard input.

% echo A B C D E F G H I | java Subset 3       % echo AA BB BB BB BB BB CC CC | java Subset 8C                                              BBG                                              AAA                                              BB                                               CC% echo A B C D E F G H I | java Subset 3       BBE                                              BBF                                              CCG                                              BB
The running time of Subset must be linear in the size of the input. You may use only a constant amount of memory plus either one Deque or RandomizedQueue object of maximum size at most N, where N is the number of strings on standard input. (For an extra challenge, use only one Deque or RandomizedQueue object of maximum size at most k.) It should have the following API.
public class Subset {   public static void main(String[] args)}

Deliverables. Submit only Deque.java, RandomizedQueue.java, and Subset.java. We will supply stdlib.jar. You may not use any libraries other than those in stdlib.jar, java.lang, java.util.Iterator, and java.util.NoSuchElementException.

代碼:

Deque.java

import java.util.Iterator;;public class Deque<Item> implements Iterable<Item> {private Node first;private Node last;private int length;public Deque() {first = null;last = null;length = 0;}public boolean isEmpty() {return length == 0;}public int size() {return length;}public void addFirst(Item item) {if (item == null)throw new NullPointerException();if (length == 0) {Node newNode = new Node();newNode.i = item;newNode.left = null;newNode.right = null;first = newNode;last = newNode;length++;} else {Node newNode = new Node();newNode.i = item;newNode.right = null;newNode.left = first;first.right = newNode;first = newNode;length++;}}public void addLast(Item item) {if (item == null)throw new NullPointerException();if (length == 0) {Node newNode = new Node();newNode.i = item;newNode.left = null;newNode.right = null;first = newNode;last = newNode;length++;} else {Node newNode = new Node();newNode.i = item;newNode.right = last;newNode.left = null;last.left = newNode;last = newNode;length++;}}public Item removeFirst() {if (isEmpty())throw new java.util.NoSuchElementException();if (length == 1) {Item item = first.i;first = null;last = null;length--;return item;} else {Item item = first.i;Node temp = first.left;first.left.right = null;first.left = null;first = temp;length--;return item;}}public Item removeLast() {if (isEmpty())throw new java.util.NoSuchElementException();if (length == 1) {Item item = first.i;first = null;last = null;length--;return item;} else {Item item = last.i;Node temp = last.right;last.right.left = null;last.right = null;last = temp;length--;return item;}}public static void main(String[] args) {// TODO Auto-generated method stub}@Overridepublic Iterator<Item> iterator() {// TODO Auto-generated method stubreturn new ListIterator();}private class Node {private Node left;private Node right;private Item i;}private class ListIterator implements Iterator<Item> {private Node ptr;private Item i;public ListIterator(){ptr = first;}@Overridepublic boolean hasNext() {// TODO Auto-generated method stubif (ptr == null)return false;elsereturn true;}@Overridepublic Item next() {// TODO Auto-generated method stubif (!hasNext())throw new java.util.NoSuchElementException();else {i = ptr.i;ptr = ptr.left;return i;}}public void remove() {throw new UnsupportedOperationException();}}}


RandomizedQueue.java

import java.util.Iterator;public class RandomizedQueue<Item> implements Iterable<Item> {private Item items[];private int length;public RandomizedQueue() {items = (Item[]) new Object[2];length = 0;}public boolean isEmpty() {return length == 0;}public int size() {return length;}public void enqueue(Item item) {if (item == null)throw new NullPointerException();if (length == items.length)resize(items.length * 2);items[length] = item;length++;}public Item dequeue() {if (isEmpty())throw new java.util.NoSuchElementException();int n = (int) (Math.random() * length);Item i = items[n];if (n != length - 1)items[n] = items[length - 1];length--;if (length > 0 && length == items.length / 4)resize(items.length / 2);return i;}private void resize(int n) {Item newItem[] = (Item[]) new Object[n];for (int i = 0; i < length; i++)newItem[i] = items[i];items = newItem;}public Item sample() {if (isEmpty())throw new java.util.NoSuchElementException();int n = (int) (Math.random() * length);Item i = items[n];return i;}@Overridepublic Iterator<Item> iterator() {// TODO Auto-generated method stubreturn new ListIterator();}private class ListIterator<Item> implements Iterator {int index;public ListIterator() {index = 0;}@Overridepublic boolean hasNext() {// TODO Auto-generated method stubreturn index <= length - 1;}@Overridepublic Object next() {// TODO Auto-generated method stubif (!hasNext())throw new java.util.NoSuchElementException();int n = (int) (Math.random()*(length-index));Object item = items[n];if(n != length-index-1)items[n] = items[length-index-1];index++;return item;}public void remove() {throw new UnsupportedOperationException();}}public static void main(String[] args) {// TODO Auto-generated method stub}}

Subset.java

public class Subset {public static void main(String[] args) {// TODO Auto-generated method stubRandomizedQueue rq = new RandomizedQueue();int k = Integer.parseInt(args[0]);while (!StdIn.isEmpty())rq.enqueue(StdIn.readString());for (int i = 0; i < k; i++)StdOut.println(rq.dequeue());}}



很急:幫忙翻譯一下這段中文(鐵定追加分)

The material is as follows:
the distributional stock and the transportation dispatching system integration optimization question from systematized, the integrated thought embarks, the physical distribution two big functions, the inventory control and transports the dispatch, takes a whole to carry on the optimization. the LGP group is facing the pressure of competition which raw material and the service cost rise and the globalization bring, simultaneously the huge reserve and the freight volume have consumed the massive transport business cost, experiences only carries on the transportation dispatch plan, as soon as comes in the management process to have the work chaotic situation frequently, two do not have the scientific target to make the improvement comparison, will grow strong to the future enterprise brings the bottleneck. This group hoped that can make the reasonable adjustment through the scientific technique to own stock assignment transportation system, the main purpose is must reduce the cost transport business cost. this topic in view of the distributional stock and the transportation dispatching system integration optimization question, produces in the manufacturing industry the actual case to make the actor's opening words, proposes several simple and the actual optimization plan. The manufacture network chart can unfold this enterprise's basic condition, then through the model computation, in the network chart most short-path design and in the pure l......餘下全文>>
 
Data Structures and Algorithm Analysis in C++書後的習題答案

下面是我根據別人的提示和自己的參考總結出的幾個階段的書籍,希望對你有協助!!

第一階段:
1::H.M.Deitel和P.J.Deitel的《 C++ How to Program 》(C++大學教程)
2:: 錢能的《C++程式設計教程》
3::Stanley B.lippman著 侯捷 譯的《essential c++》
4::Stanley B.Lippman,Josee LaJoie,Barbara E.Moo的《c++ primer》
5::Bjarne Stroustrup的《the c++ programming language》

第二階段:
1::Scott Meyers的《effective c++》
2::Herb Sutter的《exceptional c++》
3::Scott Meyers的《more effective c++》
4::Herb Sutter的《more exceptional c++》

第三階段:
1::Stanley B.lippman的《insied the c++ object model》(深度探索C++ 物件模型)
2::Bjarne Stroustrup的《The design and evolution of c++》(C++的設 計與演化)
3::tephen C. Dewhurst的《C++ Gotchas: Avoiding Common Problems in Coding and Design》(C++程式設計陷阱)

第四階段:
1:: Nicolai M.Josuttis的《the c++ standard library》(C++標準程式庫 —自修教程與參考手冊)
2::Scott Meyers的《effective stl》
3::Matthew H. Austern的《generic programming and the stl》(泛型編 程與STL)
4::侯捷的 《stl源碼剖析》

第五階段:
1::Herb Sutter的《exeptional c++ style》
2::《c++ template》
3::Andrei Alexandrescu的《modern c++ design》

第六階段
1::《C++ 輸入輸出資料流及本地化》《C++ Network Programming》《大規模C++程式設計》
2::Barbara E.Moo和Andrew Koenig的《Ruminations On C++》(C++ 沉思錄)

其他的:
Stanley B. Lippman,《Inside The C++ Object Model》影印版、中文版《深度探索C++物件模型》
Elements of Reusable Object-Oriented software》影印版、中文版《設計模式:可複用物件導向軟體的基礎》
John Lakos的著作《Large-Scale C++ Software Design》(《大規模C++程式設計》
Andrew Koenig和Barbara Moo在《Accelerated C++: Practical Programming by Example》《Ruminations on C++》
Bruce Eckel,《C++編程思想》

windows編程系列:

Charles Petzold 的 《Programming Windows》(Windows程式設計)
Je......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.