• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

AlgorithmPartI:ProgrammingAssignment(2)

mysql 搞代码 4年前 (2022-01-09) 16次浏览 已收录 0个评论
文章目录[隐藏]

问题描述: 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 int

问题描述:

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:

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

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:

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

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 ≤ kN, where N is the number of string on standard input.

% <strong>echo A B C D E F G H I | java Subset 3</strong>       % <strong>echo AA BB BB BB BB BB CC CC | java Subset 8</strong>C                                              BBG                                              AAA                                              BB                                               CC% <strong>echo A B C D E F G H I | java Subset 3</strong>       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.

<strong>public class Subset {   public static void main(String[] args)}</strong>

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 implements Iterable {	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 = nul<em>本文来源[email protected]搞@^&代*@码2网</em>l;			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		}	@Override	public Iterator iterator() {		// TODO Auto-generated method stub		return new ListIterator();	}	private class Node {		private Node left;		private Node right;		private Item i;	}	private class ListIterator implements Iterator {				private Node ptr;		private Item i;				public ListIterator()		{			ptr = first;		}		@Override		public boolean hasNext() {			// TODO Auto-generated method stub			if (ptr == null)				return false;			else				return true;		}		@Override		public Item next() {			// TODO Auto-generated method stub			if (!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 implements Iterable {	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;	}	@Override	public Iterator iterator() {		// TODO Auto-generated method stub		return new ListIterator();	}	private class ListIterator implements Iterator {				int index;		public ListIterator() {			index = 0;		}		@Override		public boolean hasNext() {			// TODO Auto-generated method stub			return index <= length - 1;		}		@Override		public Object next() {			// TODO Auto-generated method stub			if (!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 stub		RandomizedQueue 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());	}}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:AlgorithmPartI:ProgrammingAssignment(2)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址