OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
I need help creating a parametized JUnit test case for the following.pdffonecomp
I need help creating a parametized JUnit test case for the following class.
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static java.lang.Integer.valueOf;
public class IntegerSet {
/**
* The only instance variable in the class. No other variables allowed.
*/
private List list;
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
/**
* Initializes the empty set.
*/
public IntegerSet() {
list = new LinkedList();
}
/**
* Initializes a set with the numbers in the argument.
*/
public IntegerSet(Integer[] integers) {
this();
if (integers == null) {
throw new NullPointerException(\"The argument cannot be null\");
} else {
for (Integer i : integers) {
if (!exists(i)) {
this.insertElement(i);
}
}
}
Collections.sort(list);
}
/**
* Inserts an integer to the set if the integer does not exist in the set
*/
public void insertElement(int i) {
if (!list.contains(i)) {
list.add(i);
}
}
/**
* Inserts to the set all the integers in the argument which do not exist in
* the set.
*/
public void insertAll(Integer[] data) {
if (data == null) {
throw new NullPointerException(\"The argument cannot be null\");
// throw new
// IllegalArgumentException(\"The argument cannot be null\");
} else {
Arrays.sort(data);
for (Integer num : data) {
if (!exists(num)) {
insertElement(num);
}
}
}
}
/**
* Deletes an integer from the set if it exists in the set.
*/
public void deleteElement(int i) {
list.remove(i);
}
/**
* Deletes all the elements in the set.
*/
public void deleteAll() {
list.clear();
}
/**
* Returns true if the argument exists in the set, false otherwise.
*/
public boolean exists(int i) {
return list.contains(i);
}
public String toString() {
char delimiter = \' \';
String str = \"[\";
for (Integer i : list) {
str += i;
str += delimiter;
}
return str + \"]\";
}
/**
* Finds the union of two sets. A null pointer is considered an empty set.
*
* Return \"new IntegerSet()\" when the result is an empty set.
*/
public static IntegerSet union(IntegerSet set1, IntegerSet set2) {
IntegerSet union = new IntegerSet();
if (set1.isEmpty() && set2.isEmpty()) {
return union;
}
if (!set1.list.isEmpty()) {
for (Integer num : set1.list) {
if (!union.list.contains(num)) {
union.list.add(num);
}
}
}
if (!set2.isEmpty()) {
for (Integer num : set2.list) {
if (!union.list.contains(num)) {
union.list.add(num);
}
}
}
return union;
}
/**
* Finds the intersection of two sets. A null pointer is considered an empty
* set.
*
* Return \"new IntegerSet()\" when the result is an empty set.
*/
public static IntegerSet intersection(IntegerSet set1, IntegerSet set2) {
IntegerSet intersection = new IntegerSet();
// check for null pointers
if (set1.list.isEmpty() || set2.list.isEmpty()) {
return intersection;
}
for (Integer num : set1.list) {
if ((!intersection.list.contains(num)) && set2.list.contains(num)) {
intersection.list.add(num);
}
}
return intersection;
}
/**
* Builds an array with the ele.
The document provides an index and descriptions of various topics related to web development including:
1. The modulus operator and examples of using it to check for divisibility.
2. Relational and logical operators like greater than, less than, equal to and examples of using them in code.
3. Descriptions of do-while and for loops with examples.
4. An example using a parameterized constructor to initialize cube dimensions.
5. Examples of string methods like startsWith, length, and trim.
6. Descriptions and examples of overloading methods and constructors.
7. An example of inheritance with overriding methods.
8. An interface example with animal classes
META-INF/MANIFEST.MF
Manifest-Version: 1.0
.classpath
PriorityQueue.classpublicsynchronizedclass PriorityQueue {
Heap q;
public void PriorityQueue(int, java.util.Comparator);
public Object peek();
public Object remove();
void add(Object);
boolean isEmpty();
public int size();
}
PriorityQueue.javaPriorityQueue.javaimport java.util.Comparator;
publicclassPriorityQueue<E>{
Heap q;
/**
*PriorityQueue initializes the queue.
*
* @param initialCapacity an int that is the heaps initial size.
* @param comparator the priority of various imputs.
*/
publicPriorityQueue(int initialCapacity,Comparator<?super E> comparator){
q=newHeap(initialCapacity,comparator);
}
/**
* Peek, returns the next item in the queue without removing it.
*
* If it is empty then null is returned.
* @return the next item in the queue.
*/
public E peek(){
if(q.size()==0){
returnnull;
}
return(E) q.findMax();
}
/**
* This removes the first item from the queue.
*
* It returns null if the queue is empty.
* @return the first item in the queue.
*/
public E remove(){
if(q.size()==0){
returnnull;
}
return(E) q.removeMax();
}
/**
* This adds item to the queue
* @param item that is added to the queue.
*/
void add(E item){
q.insert(item);
}
/**
* isEmpty returns if the queue is empty or not.
*
* @return boolean if the queue is empty or not.
*/
boolean isEmpty(){
if(q.size()!=0){
returnfalse;
}
returntrue;
}
/**
* size returns the size of the queue.
*
* @return int the size of the queue.
*/
publicint size(){
return q.size();
}
}
ArithmeticExpression.classpublicsynchronizedclass ArithmeticExpression {
BinaryTree t;
java.util.ArrayList list;
String equation;
void ArithmeticExpression(String) throws java.text.ParseException;
public String toString(BinaryTree);
public String toPostfixString(BinaryTree);
void setVariable(String, int) throws java.rmi.NotBoundException;
public int evaluate(BinaryTree);
}
ArithmeticExpression.javaArithmeticExpression.javaimport java.rmi.NotBoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Stack;
/**
* ArithmeticExpression takes equations in the form of strings creates a binary
* tree, and can return either the regular or postfix equation. It also allows
* them to be calculated.
*
*
* Extra Credit:
* ** it can handle spaces or no spaces in the string inputted. ** it can return
* regular or postfix notation
*
* @author tai-lanhirabayashi
*
*/
publicclassArithmeticExpression{
BinaryTree t;
ArrayList list;
String equation;
/**
* ArithmeticExpression is the construction which takes in a space
* delimitated equation containing "*,/,+,-" symbols and converts it into a
* binary tree.
*
* If the expression is not valid it will throw a ParseException. This is ...
The document contains code snippets for several Java programs including:
1. An Armstrong number checker that uses recursion to check if a number is an Armstrong number.
2. A binary search program that searches an integer array using a binary search algorithm.
3. A binary search on a float array using the Arrays binarySearch method.
The document then continues with additional code examples for recursive binary search, bubble sort, constructors, converting between object and primitive types, data input/output streams, encapsulation, enumerating a vector, exception handling, and creating threads by extending the Thread class.
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
Basic java, java collection Framework and Date Time APIjagriti srivastava
This document provides an overview of basic Java concepts including classes, objects, methods, inheritance, and polymorphism. It also discusses Java tools, OOP concepts, and how to create classes, objects, and methods. Additionally, it covers Java control structures like if/else and for loops, arrays, and different collection classes like ArrayList, LinkedList, and HashMap. Finally, it presents Java date/time API classes and examples of parsing, comparing, and performing calculations on dates.
public class TrequeT extends AbstractListT { .pdfinfo30292
/**
*/
public class Treque extends AbstractList {
/**
* You decide on the instance variables you need.
*/
public Treque(Class t) {
// Put your own code here
throw new UnsupportedOperationException(\"Constructor not yet implemented\");
}
public T get(int i) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here instead of throwing this exception
throw new UnsupportedOperationException(\"get(i) not yet implemented\");
}
public T set(int i, T x) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here instead of throwing this exception
throw new UnsupportedOperationException(\"set(i,x) not yet implemented\");
}
public void add(int i, T x) {
if (i < 0 || i > size()) throw new IndexOutOfBoundsException();
// Put your own code here
throw new UnsupportedOperationException(\"add(i,x) not yet implemented\");
}
public T remove(int i) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here
throw new UnsupportedOperationException(\"remove(i) not yet implemented\");
}
public int size() {
// Put your own code here
throw new UnsupportedOperationException(\"size() not yet implemented\");
}
public static void main(String[] args) {
//List tr = new ArrayDeque(Integer.class);
List tr = new Treque(Integer.class);
int K = 1000000;
Stopwatch s = new Stopwatch();
System.out.print(\"Appending \" + K + \" items...\");
System.out.flush();
s.start();
for (int i = 0; i < K; i++) {
tr.add(i);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Prepending \" + K + \" items...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.add(0, i);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Midpending(?!) \" + K + \" items...\");
System.out.flush();
s.start();
for (int i = 0; i < K; i++) {
tr.add(tr.size()/2);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the back...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(tr.size()-1);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the front...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(0);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the middle...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(tr.size()/2);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
}
}
-------------------------------------------------------------------
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements the List interface using a collection of arrays of
* sizes 1, 2, 3, 4, and so on. The main advantages of this over an
* implementation like ArrayList is that there is never more than O(sqr.
I need help creating a parametized JUnit test case for the following.pdffonecomp
I need help creating a parametized JUnit test case for the following class.
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static java.lang.Integer.valueOf;
public class IntegerSet {
/**
* The only instance variable in the class. No other variables allowed.
*/
private List list;
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
/**
* Initializes the empty set.
*/
public IntegerSet() {
list = new LinkedList();
}
/**
* Initializes a set with the numbers in the argument.
*/
public IntegerSet(Integer[] integers) {
this();
if (integers == null) {
throw new NullPointerException(\"The argument cannot be null\");
} else {
for (Integer i : integers) {
if (!exists(i)) {
this.insertElement(i);
}
}
}
Collections.sort(list);
}
/**
* Inserts an integer to the set if the integer does not exist in the set
*/
public void insertElement(int i) {
if (!list.contains(i)) {
list.add(i);
}
}
/**
* Inserts to the set all the integers in the argument which do not exist in
* the set.
*/
public void insertAll(Integer[] data) {
if (data == null) {
throw new NullPointerException(\"The argument cannot be null\");
// throw new
// IllegalArgumentException(\"The argument cannot be null\");
} else {
Arrays.sort(data);
for (Integer num : data) {
if (!exists(num)) {
insertElement(num);
}
}
}
}
/**
* Deletes an integer from the set if it exists in the set.
*/
public void deleteElement(int i) {
list.remove(i);
}
/**
* Deletes all the elements in the set.
*/
public void deleteAll() {
list.clear();
}
/**
* Returns true if the argument exists in the set, false otherwise.
*/
public boolean exists(int i) {
return list.contains(i);
}
public String toString() {
char delimiter = \' \';
String str = \"[\";
for (Integer i : list) {
str += i;
str += delimiter;
}
return str + \"]\";
}
/**
* Finds the union of two sets. A null pointer is considered an empty set.
*
* Return \"new IntegerSet()\" when the result is an empty set.
*/
public static IntegerSet union(IntegerSet set1, IntegerSet set2) {
IntegerSet union = new IntegerSet();
if (set1.isEmpty() && set2.isEmpty()) {
return union;
}
if (!set1.list.isEmpty()) {
for (Integer num : set1.list) {
if (!union.list.contains(num)) {
union.list.add(num);
}
}
}
if (!set2.isEmpty()) {
for (Integer num : set2.list) {
if (!union.list.contains(num)) {
union.list.add(num);
}
}
}
return union;
}
/**
* Finds the intersection of two sets. A null pointer is considered an empty
* set.
*
* Return \"new IntegerSet()\" when the result is an empty set.
*/
public static IntegerSet intersection(IntegerSet set1, IntegerSet set2) {
IntegerSet intersection = new IntegerSet();
// check for null pointers
if (set1.list.isEmpty() || set2.list.isEmpty()) {
return intersection;
}
for (Integer num : set1.list) {
if ((!intersection.list.contains(num)) && set2.list.contains(num)) {
intersection.list.add(num);
}
}
return intersection;
}
/**
* Builds an array with the ele.
The document provides an index and descriptions of various topics related to web development including:
1. The modulus operator and examples of using it to check for divisibility.
2. Relational and logical operators like greater than, less than, equal to and examples of using them in code.
3. Descriptions of do-while and for loops with examples.
4. An example using a parameterized constructor to initialize cube dimensions.
5. Examples of string methods like startsWith, length, and trim.
6. Descriptions and examples of overloading methods and constructors.
7. An example of inheritance with overriding methods.
8. An interface example with animal classes
META-INF/MANIFEST.MF
Manifest-Version: 1.0
.classpath
PriorityQueue.classpublicsynchronizedclass PriorityQueue {
Heap q;
public void PriorityQueue(int, java.util.Comparator);
public Object peek();
public Object remove();
void add(Object);
boolean isEmpty();
public int size();
}
PriorityQueue.javaPriorityQueue.javaimport java.util.Comparator;
publicclassPriorityQueue<E>{
Heap q;
/**
*PriorityQueue initializes the queue.
*
* @param initialCapacity an int that is the heaps initial size.
* @param comparator the priority of various imputs.
*/
publicPriorityQueue(int initialCapacity,Comparator<?super E> comparator){
q=newHeap(initialCapacity,comparator);
}
/**
* Peek, returns the next item in the queue without removing it.
*
* If it is empty then null is returned.
* @return the next item in the queue.
*/
public E peek(){
if(q.size()==0){
returnnull;
}
return(E) q.findMax();
}
/**
* This removes the first item from the queue.
*
* It returns null if the queue is empty.
* @return the first item in the queue.
*/
public E remove(){
if(q.size()==0){
returnnull;
}
return(E) q.removeMax();
}
/**
* This adds item to the queue
* @param item that is added to the queue.
*/
void add(E item){
q.insert(item);
}
/**
* isEmpty returns if the queue is empty or not.
*
* @return boolean if the queue is empty or not.
*/
boolean isEmpty(){
if(q.size()!=0){
returnfalse;
}
returntrue;
}
/**
* size returns the size of the queue.
*
* @return int the size of the queue.
*/
publicint size(){
return q.size();
}
}
ArithmeticExpression.classpublicsynchronizedclass ArithmeticExpression {
BinaryTree t;
java.util.ArrayList list;
String equation;
void ArithmeticExpression(String) throws java.text.ParseException;
public String toString(BinaryTree);
public String toPostfixString(BinaryTree);
void setVariable(String, int) throws java.rmi.NotBoundException;
public int evaluate(BinaryTree);
}
ArithmeticExpression.javaArithmeticExpression.javaimport java.rmi.NotBoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Stack;
/**
* ArithmeticExpression takes equations in the form of strings creates a binary
* tree, and can return either the regular or postfix equation. It also allows
* them to be calculated.
*
*
* Extra Credit:
* ** it can handle spaces or no spaces in the string inputted. ** it can return
* regular or postfix notation
*
* @author tai-lanhirabayashi
*
*/
publicclassArithmeticExpression{
BinaryTree t;
ArrayList list;
String equation;
/**
* ArithmeticExpression is the construction which takes in a space
* delimitated equation containing "*,/,+,-" symbols and converts it into a
* binary tree.
*
* If the expression is not valid it will throw a ParseException. This is ...
The document contains code snippets for several Java programs including:
1. An Armstrong number checker that uses recursion to check if a number is an Armstrong number.
2. A binary search program that searches an integer array using a binary search algorithm.
3. A binary search on a float array using the Arrays binarySearch method.
The document then continues with additional code examples for recursive binary search, bubble sort, constructors, converting between object and primitive types, data input/output streams, encapsulation, enumerating a vector, exception handling, and creating threads by extending the Thread class.
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
Basic java, java collection Framework and Date Time APIjagriti srivastava
This document provides an overview of basic Java concepts including classes, objects, methods, inheritance, and polymorphism. It also discusses Java tools, OOP concepts, and how to create classes, objects, and methods. Additionally, it covers Java control structures like if/else and for loops, arrays, and different collection classes like ArrayList, LinkedList, and HashMap. Finally, it presents Java date/time API classes and examples of parsing, comparing, and performing calculations on dates.
public class TrequeT extends AbstractListT { .pdfinfo30292
/**
*/
public class Treque extends AbstractList {
/**
* You decide on the instance variables you need.
*/
public Treque(Class t) {
// Put your own code here
throw new UnsupportedOperationException(\"Constructor not yet implemented\");
}
public T get(int i) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here instead of throwing this exception
throw new UnsupportedOperationException(\"get(i) not yet implemented\");
}
public T set(int i, T x) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here instead of throwing this exception
throw new UnsupportedOperationException(\"set(i,x) not yet implemented\");
}
public void add(int i, T x) {
if (i < 0 || i > size()) throw new IndexOutOfBoundsException();
// Put your own code here
throw new UnsupportedOperationException(\"add(i,x) not yet implemented\");
}
public T remove(int i) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here
throw new UnsupportedOperationException(\"remove(i) not yet implemented\");
}
public int size() {
// Put your own code here
throw new UnsupportedOperationException(\"size() not yet implemented\");
}
public static void main(String[] args) {
//List tr = new ArrayDeque(Integer.class);
List tr = new Treque(Integer.class);
int K = 1000000;
Stopwatch s = new Stopwatch();
System.out.print(\"Appending \" + K + \" items...\");
System.out.flush();
s.start();
for (int i = 0; i < K; i++) {
tr.add(i);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Prepending \" + K + \" items...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.add(0, i);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Midpending(?!) \" + K + \" items...\");
System.out.flush();
s.start();
for (int i = 0; i < K; i++) {
tr.add(tr.size()/2);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the back...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(tr.size()-1);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the front...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(0);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the middle...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(tr.size()/2);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
}
}
-------------------------------------------------------------------
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements the List interface using a collection of arrays of
* sizes 1, 2, 3, 4, and so on. The main advantages of this over an
* implementation like ArrayList is that there is never more than O(sqr.
The next document shows a Try-Catch block to handle an ArithmeticException from dividing by zero. It prints the exception message. The following document creates two threads, a main thread and a new child thread, running loops that print
This document provides an overview of key concepts in Java and Python including:
- Programming paradigms like functional and object-oriented programming
- The compilation process in Java vs interpretation in Python
- Basic syntax for variables, data types, arithmetic and comparison operators, conditional statements, loops, classes and objects in both languages
- Examples of built-in functions for strings and numbers
- Concepts like aggregation, inheritance and polymorphism demonstrated through classes
This document provides information on arrays in Java. It begins by defining an array as a collection of similar data types that can store values of a homogeneous type. Arrays must specify their size at declaration and use zero-based indexing. The document then discusses single dimensional arrays, how to declare and initialize them, and how to set and access array elements. It also covers multi-dimensional arrays, providing syntax for declaration and initialization. Examples are given for creating, initializing, accessing, and printing array elements. The document concludes with examples of searching arrays and performing operations on two-dimensional arrays like matrix addition and multiplication.
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
package singlylinkedlist;
public class Node {
public String value;
public Node next;
public Node(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
SingleyLinkedList.java :
package singlylinkedlist;
import java.io.*;
import java.util.*;
/**
* Defines the interface for a singly-linked list.
*
*/
public interface SinglyLinkedList {
/**
* @return Reference to the first node. If the list is empty, this method
* returns null.
*/
public Node getFirst();
/**
* @return Reference to the last node . If the list is empty, this method
* returns null.
*/
public Node getLast();
/**
* @return Number of nodes in the list
*/
public int size();
/**
* @return true if the list has no nodes; false otherwise
*/
public boolean isEmpty();
/**
* Removes all nodes in the list.
*/
public void clear();
/**
* Inserts a new node with the given value after cursor.
*
* @param cursor
* The node to insert after. Set this to null to insert value as
the
* new first Node.
* @param value
* The value to insert
* @return a reference to the newly inserted Node
*/
public Node insert(Node cursor, String value);
/**
* Inserts a new node with the given value at the "end" of the list.
*
* @param value
* @return a reference to the newly inserted Node
*/
public Node append(String value);
/**
* Removes the node after the specified Node (cursor) from the list.
*
* @param cursor
* A reference to the Node to remove.
*/
public void removeAfter(Node cursor);
/**
* Returns a reference to the first Node containing the key, starting from
the
* given Node.
*
* @param start
* @param key
* @return a reference to the first Node containing the key
*/
public Node find(Node start, String key);
/**
* Prints the values of all the items in a list
*/
public void printWholeList();
}
SinglyLinkedTester.java:
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import static sbcc.Core.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import org.w3c.dom.ranges.*;
import sbcc.*;
import singlylinkedlist.*;
/**
* 09/16/2021
*
* @author sstrenn
*
*/
public class SinglyLinkedListTester {
public static String newline = System.getProperty("line.separator");
public static int totalScore = 0;
public static int extraCredit = 0;
public static boolean isZeroScore = false;
public static String scorePreamble = "";
@BeforeClass
public static void beforeTesting() {
totalScore = 0;
extraCredit = 0;
}
@AfterClass
public static void afterTesting() {
if (isZeroScore) {
totalScore = 0;
extraCredit = 0;
}
println(scorePreamble + "Estimated score (w/o late penalties, etc.) is:
" + totalScore + " out of 25.");
// If the project follows the naming convention, save the results in a
folder on
// the desktop. (Alex Kohanim)
try {
String directory =
substri.
This document discusses object initialization in Java. It explains that in Java, constructors allow objects to be initialized when they are created. Constructors ensure that class member variables and objects have initial values before an object is used. The document provides examples of how to write constructors, how to overload constructors, and how to use the this keyword in constructors. It also discusses static initialization and the use of toString() methods.
This document discusses object initialization in Java. It explains that in Java, constructors allow objects to be initialized when they are created. Constructors ensure that class member variables and objects are properly initialized before use. The document provides examples of how to write classes with constructors and use constructor overloading. It also discusses static initialization, the this keyword, and recursion.
The document provides examples of Java code using try, catch, throw, and exceptions to handle errors and exceptions. Program 36 introduces a try-catch block to handle potential InputMismatchExceptions from user input. Program 37 uses try-catch-finally to handle an ArithmeticException from division by zero and ensure the finally block always executes. Program 38 demonstrates multiple catch blocks to handle different exception types.
The document discusses how to define an interface in Java that specifies methods for generating different types of number series. An interface named Series is defined with three methods - getNext() to return the next number, reset() to restart the series, and setStart() to set the starting value. Classes can then implement the Series interface and provide implementations of these three methods to generate specific types of number series, like one that returns even numbers starting from 2.
JAVA OOP project; desperately need help asap im begging.Been stuck.pdffantasiatheoutofthef
JAVA OOP project; desperately need help asap im begging.
Been stuck on this for a week since my OOP skills are not good at all. Due in a couple hours so
im desperate. Codes needed will be provided at the end, thank you.
Codes:
DotChaser.java:
import java.util.*;
public class DotChaser {
public static Random rand = new Random(System.currentTimeMillis());
/**
* A "Thing" moves in a grid world. A TypeA Thing randomly
* decides to turn left or right (or not turn) every "round",
* and, afterward, takes a step forward. A TypeB Thing
* only considers making a random turn every 10th round.
*
* A STATIC CLASS? OH NO! GET IT OUT OF HERE!
*/
public static class Thing {
// dir: 0=North, 1=East, 2=South, 3=West.
// timeSinceLast: this is only important for "TypeB" Things.
public int row, col, dir, timeSinceLast;
public char lab = 'r';
public boolean isTypeB;
}
/**
* YOU'LL NEED TO PUT THIS SOMEWHERE ELSE
* HINT: WOULDN'T IT BE NICE TO HAVE A LIST OR QUEUE SO THAT
* WE DON'T HAVE TO USE NODES HERE?
* This class is for linked lists of Thing's
*/
public static class Node {
public Thing data;
public Node next;
}
// EEEEEK! STATIC METHODS!!! PLEASE FIND THEM A BETTER HOME.
public static void rightTurn(Thing t) {
t.dir = (t.dir + 1) % 4;
}
public static void leftTurn(Thing t) {
t.dir = (t.dir + 3) % 4;
}
public static void maybeTurn(Thing t) {
int i = rand.nextInt(3);
if (t.isTypeB) {
t.timeSinceLast++;
if (t.timeSinceLast == 10) {
t.timeSinceLast = 0;
if (i == 1) {
rightTurn(t);
}
if (i == 2) {
leftTurn(t);
}
}
} else {
if (i == 1) {
rightTurn(t);
}
if (i == 2) {
leftTurn(t);
}
}
}
public static void step(Thing t) {
final int[] dc = {
0, 1, 0, -1
}, dr = {
1, 0, -1, 0
};
t.row += dr[t.dir];
t.col += dc[t.dir];
}
/**
* This static method is ok :)
*/
public static void main(String[] args) {
int N = 200;
if( args.length != 0 )
N = Integer.parseInt(args[0]);
// INSTEAD OF A NODE, CREATE SOMETHING MORE USER-FRIENDLY.
Node L = null;
int count = 0;
while( true ) {
// Every N rounds, add another typeA and typeB Thing.
if( count % N == 0 ) {
// Add a typeA thing to the list.
// (GEE, THAT'S A LOT OF CODE FOR JUST CREATING ONE THING)
Thing tA = new Thing();
tA.row = 45;
tA.col = 50;
Node nA = new Node();
nA.data = tA;
nA.next = L;
L = nA;
// Add a typeB thing to the list
Thing tB = new Thing();
tB.row = 55;
tB.col = 50;
tB.lab = 'b';
tB.isTypeB = true;
Node nB = new Node();
nB.data = tB;
nB.next = L;
L = nB;
}
// Print out each thing.
// (SEEMS LIKE A NICE PRINTALL() METHOD CALL WOULD WORK HERE)
// (SEEMS LIKE A toString() METHOD IN THE CLASS WOULD ALSO BE NICE)
for( Node T = L; T != null; T = T.next )
System.out.println(T.data.row + " " + T.data.col + " " + T.data.lab);
System.out.println("done");
System.out.flush();
// Move each thing.
// (SEEMS LIKE A NICE MOVEALL() METHOD CALL WOULD WORK HERE)
for( Node T = L; T != null; T = T.next ) {
maybeTurn(T.data);
step(T.data);
}
count++;
}
}
}
Lab2_Tester.java
import org.junit.Test;
import static org.junit.Assert.assertEqual.
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
Implement a queue using a linkedlist (java)
Solution
LinkedQueueImplement.java
import java.util.*;
class Node
{
protected int data;
protected Node link;
public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedQueue
{
protected Node front, rear;
public int size;
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
return front == null;
}
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 :
try
{
System.out.println(\"Peek Element = \"+ lq.peek());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 4 :
System.out.println(\"Empty status = \"+ lq.isEmpty());
break;
case 5 :
System.out.println(\"Size = \"+ lq.getSize());
break;
default :
System.out.println(\"Wrong Entry \ \");
break;
}
/* display queue */
lq.display();
System.out.println(\"\ Do you want to continue (Type y or n) \ \");
ch = scan.next().charAt(0);
} while (ch == \'Y\'|| ch == \'y\');
}
}
Output :
Linked Queue Test
Queue Operations
1. inse.
The document discusses various String methods in Java:
- The charAt() method returns the character at a given index in the String.
- The compareTo() method compares two Strings lexicographically and returns an integer indicating their relative ordering.
- The indexOf() method returns the index of the first occurrence of a character or substring in the given String. It has overloads to specify a starting index for the search.
Programing with java for begniers .pptxadityaraj7711
Java is a high-level, object-oriented programming language developed by Sun Microsystems in the mid-1990s (now owned by Oracle Corporation). It is widely used for building a variety of applications, including desktop, web, mobile, and enterprise software. Java's design emphasizes portability, simplicity, and security, making it one of the most popular programming languages in the world.
### Importance of Java:
1. **Platform Independence**:
- Java programs can run on any device or operating system that supports the Java Virtual Machine (JVM).
- This "write once, run anywhere" (WORA) capability makes Java applications highly portable.
2. **Object-Oriented Programming (OOP)**:
- Java supports key OOP principles such as inheritance, encapsulation, polymorphism, and abstraction.
- These principles enable developers to create modular and reusable code.
3. **Rich Ecosystem and Libraries**:
- Java has a vast ecosystem of libraries, frameworks, and tools that facilitate development across various domains.
- Popular frameworks like Spring, Hibernate, and Apache Struts streamline development in enterprise environments.
4. **Robustness and Reliability**:
- Java has strong exception handling and type-checking mechanisms that contribute to the robustness and reliability of applications.
5. **Community and Support**:
- Java has a large and active developer community, providing support and resources for learning and troubleshooting.
- Java's extensive documentation and community forums are valuable resources for developers.
6. **Performance**:
- Java's just-in-time (JIT) compilation allows for optimized execution, improving performance.
- Java can handle large-scale applications and complex computations efficiently.
7. **Security**:
- Java's architecture includes features such as runtime security checks and a security manager for safe execution.
- This makes it a preferred choice for developing secure applications.
8. **Enterprise Applications**:
- Java is a dominant language in enterprise development due to its scalability, stability, and compatibility with existing systems.
- Many businesses rely on Java for mission-critical applications.
9. **Career Opportunities**:
- Proficiency in Java opens up many career opportunities, particularly in enterprise development, finance, healthcare, and telecommunications.
10. **Future-Proofing**:
- Java's continuous updates and compatibility with emerging technologies ensure that it remains relevant and future-proof.
Overall, Java's versatility, reliability, and widespread adoption make it an essential language for developers across various industries
Frequency .java Word frequency counter package frequ.pdfarshiartpalace
Frequency .java
/**
* Word frequency counter
*/
package frequency;
import java.util.Iterator;
/**
*
* @author UMD CS
*/
public class Frequency implements Iterable{
private Node first;
private int N;
Frequency(){
N = 0;
first = null;
}
@Override
public Iterator iterator() {
return new ListIterator();
}
/**
*
* List iterator
*
*/
private class ListIterator implements Iterator{
private Node current;
private int index ;
ListIterator(){
current = first;
index = 0;
}
@Override
public boolean hasNext() {
return current != null;
}
public String next() {
if(!hasNext()){
return null;
}
String word = current.key;
int count = current.count;
String r = \"(\"+word + \",\" + Integer.toString(count)+\")\";
current = current.next;
return r;
}
@Override
public void remove() {
}
}
/**
*
* Node class
*
*/
private class Node {
private String key;
private int count;
private Node next;
Node(String item){
key = item;
count = 1;
next = null;
}
@Override
public String toString(){
return \"(\"+key +\",\"+count+\")\";
}
}
/*
* Inserts a word into the linked list. If the word exists, increment the
* count by q.
*/
public void insert(String word){
if(word.equals(\"\")){
return;
}
//TODO
/*
* implement here
*/
}
/**
*
* @param str input string
* This method splits a string into words and pass the words to insert method
*
*/
public void insertWords(String str){
String delims = \"[ .,?!\'\\\"()}{;/<>&=#-:\\\\ _]+\";
String[] words = str.split(delims);
for(String s: words){
s = s.toLowerCase();
insert(s);
}
}
/**
* prints the word frequency list
*/
public void print(){
Node c = first;
while(c != null){
System.out.print(\"(\"+c.key + \",\" + c.count+\")\");
c = c.next;
}
System.out.print(\"\ \");
}
}
--------------------------------------------------------------------------------------------------------------------
------------------------------------------------------
WordFrequency.java
package frequency;
import utils.In;
import utils.Stopwatch;
/**
*
* @author UMD CS
*/
public class WordFrequency {
/**
* @param input source
* @param
* This method receives input resource and return the word frequency string
* DO NOT CHANGE THIS METHOD.
*/
public static String freq(String inputSource, int maxLines){
In in;
// Frequency class can only count the frequency of strings. DO NOT CHANGE THIS.
Frequency freq = new Frequency();
int MAX = 100;
String inputSourceName = inputSource;
try {
in = new In(inputSourceName);
while (!in.isEmpty()) {
String s = in.readLine();
//System.out.println(s);
freq.insertWords(s);
}
}
catch (Exception e) {
e.printStackTrace();
}
StringBuilder strFrequency = new StringBuilder();
int cnt = 0;
for(String s: freq){
strFrequency.append(s);
strFrequency.append(\",\");
cnt++;
if(cnt >= maxLines){break;}
}
return strFrequency.toString();
}
/**
*
*/
public static void main(String[] args) {
In in;
Frequency freq = new Frequency();
int MAX = 100;
// String inputSourceName =
\"http://www.cs.umd.edu/class/summer2015/cmsc132/projects/P3_WordFrequency/test1.html\";
String .
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
Creat Shape classes from scratch DETAILS You will create 3 shape classes (Circle, Rectangle,
Triangle) that all inherit from a single abstract class called AbstractShape which implements
Shape (also created by you). You are also responsible for creating the driver class
\"Assignment7.java\" (program that tests your classes and described on page 3) which does the
following reads input data from a file instantiates various objects of the three shapes based on the
input data stores each in a LinkedList outputs this list to an output file sorts a \"copy\" of this
LinkedList of objects outputs the sorted version of the list to the output file outputs the original
list to the output file This driver program also needs to \"ignore errors in the input file that breach
the specified input format as described in the Assianment7,java details (see page 3 1. Shape.java
This is an interface that has 2 abstract methods, and passes the responsibility of implementing the
compareTo method to the class that implements Shape (you may note, nomally Comparable is
\"implemented\" by a class. However, an interface cannot implement because interfaces can only
contain abstract methods. That said, an interface can only extend other interfaces and the
responsibility of actually \"implementing\" the abstract method(s) of the super class interface is
passed on to the sub-classes) public interface Shape extends Comparable public double
calculateAreal) Il This abstract method is implemented at the concrete level public Shape
copyShape); Il also implemented at the concrete level 2. AbstractShape.java public abstract class
AbstractShape implements Shape This class should contain an instance field to store the name of
each obiect. The constructor which sets this field should receive the name and a number to be
concatenated to the name and then stored in the name field Recall, when the super class has a
parameterized constructor, the sub-classes will need to call it AND the sub- classes will need to
also provide a constructor without parameters This abstract class will implement the compareTo
method passed on from the Shape interface and will pass on the responsibility of implementing
calculateArea to the extending sub-classes (compare To will use the calculateArea method when
comparing 2 Shape objects). Along with compare To, one more concrete method should be
included. The following will be used by the sub-classes\' toString method: public String
getName) II Simply returns the name field data
Solution
in7.txt
4.4
2.5 3
8.1 3.0 5.0
2.5 3 4
2.5
tuesday
-7
1.0
3 three
3 -9
3 5
1.0
Assignment7.java
import java.io.*;
import java.util.*;
public class Assignment7 {
/**
* This is the test driver class that will include main.
* This program MUST read a file named in7.txt and
* generate an output file named out7.txt. The in7.txt
* file must be created by you based on formatting
* described shortly.
*
* @param theArgs
*/
public static void main(String[] theArgs) {
List myList = new Arra.
JAVA - Design a data structure IntSet that can hold a set of integers-.docxolsenlinnea427
JAVA - Design a data structure IntSet that can hold a set of integers. Hide the private implementation: a Binary Search Tree of Integer objects. Provide the following public methods only.
• Constructor to make an empty set,
• Constructor to create a set by initializing the root,
• void add(int x) to add x if it is not present,
• void remove(int x) to remove x if it is present,
• void print() to print all the elements currently in the set,
• boolean contains(int x) to test whether x is present,
• IntSet copy() to create a new BTS as a copy of the current one.
Note that the root of the BST is a private data member and there is no need to define getRoot(), and setRoot() functions. All the above functions should be defined public and should call recursive private functions to do the task. e.g.
// remove
private Node recRemove(Node loc, int x) { // To do }
public void remove(int x) { root= recRemove(root, x) ; }
// contains
private boolean recContains(Node loc, int x) { // to do }
public boolean contains(int x) { return recContains(root, x) ; }
Complete the class IntSet by supplying the intersection and union functions. Use the same format as above i.e. each public function calls a private recursive function to do the task:
public IntSet union(IntSet other)
public IntSet intersection(IntSet other)
Solution
import java.util.Scanner; class BinarySearchExample { public static void main(String args[]) { int counter, num, item, array[], first, last, middle; //To capture user input Scanner input = new Scanner(System.in); System.out.println(\"Enter number of elements:\"); num = input.nextInt(); //Creating array to store the all the numbers array = new int[num]; System.out.println(\"Enter \" + num + \" integers\"); //Loop to store each numbers in array for (counter = 0; counter < num; counter++) array[counter] = input.nextInt(); System.out.println(\"Enter the search value:\"); item = input.nextInt(); first = 0; last = num - 1; middle = (first + last)/2; while( first <= last ) { if ( array[middle] < item ) first = middle + 1; else if ( array[middle] == item ) { System.out.println(item + \" found at location \" + (middle + 1) + \".\"); break; } else { last = middle - 1; } middle = (first + last)/2; } if ( first > last ) System.out.println(item + \" is not found.\ \"); } }
.
The document contains code snippets in Java for getting different types of information. This includes code to get the hostname, month from a date, IP address, memory size and usage, and more. The code uses various Java classes and methods like InetAddress, DateFormat, Runtime etc. to retrieve the desired information and print/return the output.
The document contains 11 Java programming assignments involving arrays and strings:
1. Sorting an integer array using bubble sort
2. Printing only odd numbers from an integer array
3. Moving all even numbers to the beginning of an integer array
4. Finding unique numbers and occurrences of duplicates in an array
5. Checking if an integer array matches the Fibonacci series
6. Checking if an integer array is a palindrome
7. Finding unique words in a string
8. Reversing a string
9. Reversing each word in a string separately
10. Reversing the lines when writing a file
11. Creating a Java program with APIs for database SELECT and UPDATE operations
This document contains code for finding the path of most resistance in an acyclic digraph. It defines classes for nodes, a node collection, and methods for loading a file representing the digraph as a list of nodes, setting relationships between nodes, and finding the highest value path from bottom to top. Node objects store attributes like name and accumulated totals. The node collection class manages the nodes and provides methods for accessing, adding, and finding nodes.
1.Cexplanation; Cloud consumers that use cloud-based IT resources .pdfakkhan101
1.C
explanation; Cloud consumers that use cloud-based IT resources can generally lease them with a
pay-for-use model. With this model, cloud consumers pay a usage fee for only the amount of the
IT resource actually used, resulting in directly proportional costs. This gives an organization
access to IT resources without having to purchase its own, resulting in reduced investment
requirements
2.B
explanation
The availability of an IT resource is the probability that it will be accessible. The probability
value is generally expressed with a percentage representing the amount of time that the IT
resource is accessible during a given period. The percentage is calculated as follows: 1. Divide
the amount of hours the IT resource was unavailable (within a measured period) by the total
amount of hours within the measured period. 2. Multiply the value by 100. 3. Deduct the value
from 100
3.D
explanation;
Horizontal scaling refers to the allocation or releasing of resources of the same type. The
horizontal allocation of resources is referred to as scaling out and the horizontal releasing of
resources is referred to as scaling in. Horizontal scaling is a common form of scaling within
cloud environments
4.C
explanation;
Cloud-based IT resources that are used by a cloud consumer reside outside of the cloud
consumer’s organizational boundary. To use the IT resources, the cloud consumer will generally
need to trust them. As a result, the cloud consumer’s trust boundary is expanded beyond its
organizational boundary to encompass the cloud.
5.C
explanation;
An organization will often have existing IT resources that are already paid for and operational.
The prior investment that has been made in these on-premise IT resources is referred to as sunk
costs. When comparing cloud-based IT resources to on-premise IT resources with sunk costs,
the up-front costs for on-premise IT resources is significantly lower. It can therefore be more
difficult to justify the leasing of cloud- based IT resources as an alternative
6.D
explanation
the fact that trust boundaries overlap can lead to opportunities for an attacker to attack IT
resources shared by multiple cloud consumers
7.D
explanation
all r correct
8.B
explanation
Cloud A provides Cloud Service A as part of a failover system that encompasses a redundant
implementation of Cloud Service A on Cloud B. If Cloud Service A on Cloud A fails, then
Cloud Service A on Cloud B is automatically provisioned transparently to Cloud Service
Consumer A. Each cloud has a specific level of reliability and availability that it guarantees for
Cloud Service A. By spanning the failover system across both clouds, the overall reliability and
availability will be higher than the maximum reliability and availability of either cloud
9.C
explanation
Different physical and virtual IT resources are dynamically assigned and reassigned according to
cloud consumer demand, typically followed by execution through statistical multiplexing.
Resource poolin.
1) WBC count is high and this level indicates that the person has le.pdfakkhan101
1) WBC count is high and this level indicates that the person has leucocytosis. This may be due
to some infections or stress etc.
2)the pH level is alkalotic and this is caused by the respiratory alkalosis. As the pH is less than
the normal level.
Solution
1) WBC count is high and this level indicates that the person has leucocytosis. This may be due
to some infections or stress etc.
2)the pH level is alkalotic and this is caused by the respiratory alkalosis. As the pH is less than
the normal level..
More Related Content
Similar to OrderTest.javapublic class OrderTest { Get an arra.pdf
The next document shows a Try-Catch block to handle an ArithmeticException from dividing by zero. It prints the exception message. The following document creates two threads, a main thread and a new child thread, running loops that print
This document provides an overview of key concepts in Java and Python including:
- Programming paradigms like functional and object-oriented programming
- The compilation process in Java vs interpretation in Python
- Basic syntax for variables, data types, arithmetic and comparison operators, conditional statements, loops, classes and objects in both languages
- Examples of built-in functions for strings and numbers
- Concepts like aggregation, inheritance and polymorphism demonstrated through classes
This document provides information on arrays in Java. It begins by defining an array as a collection of similar data types that can store values of a homogeneous type. Arrays must specify their size at declaration and use zero-based indexing. The document then discusses single dimensional arrays, how to declare and initialize them, and how to set and access array elements. It also covers multi-dimensional arrays, providing syntax for declaration and initialization. Examples are given for creating, initializing, accessing, and printing array elements. The document concludes with examples of searching arrays and performing operations on two-dimensional arrays like matrix addition and multiplication.
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
package singlylinkedlist;
public class Node {
public String value;
public Node next;
public Node(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
SingleyLinkedList.java :
package singlylinkedlist;
import java.io.*;
import java.util.*;
/**
* Defines the interface for a singly-linked list.
*
*/
public interface SinglyLinkedList {
/**
* @return Reference to the first node. If the list is empty, this method
* returns null.
*/
public Node getFirst();
/**
* @return Reference to the last node . If the list is empty, this method
* returns null.
*/
public Node getLast();
/**
* @return Number of nodes in the list
*/
public int size();
/**
* @return true if the list has no nodes; false otherwise
*/
public boolean isEmpty();
/**
* Removes all nodes in the list.
*/
public void clear();
/**
* Inserts a new node with the given value after cursor.
*
* @param cursor
* The node to insert after. Set this to null to insert value as
the
* new first Node.
* @param value
* The value to insert
* @return a reference to the newly inserted Node
*/
public Node insert(Node cursor, String value);
/**
* Inserts a new node with the given value at the "end" of the list.
*
* @param value
* @return a reference to the newly inserted Node
*/
public Node append(String value);
/**
* Removes the node after the specified Node (cursor) from the list.
*
* @param cursor
* A reference to the Node to remove.
*/
public void removeAfter(Node cursor);
/**
* Returns a reference to the first Node containing the key, starting from
the
* given Node.
*
* @param start
* @param key
* @return a reference to the first Node containing the key
*/
public Node find(Node start, String key);
/**
* Prints the values of all the items in a list
*/
public void printWholeList();
}
SinglyLinkedTester.java:
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import static sbcc.Core.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import org.w3c.dom.ranges.*;
import sbcc.*;
import singlylinkedlist.*;
/**
* 09/16/2021
*
* @author sstrenn
*
*/
public class SinglyLinkedListTester {
public static String newline = System.getProperty("line.separator");
public static int totalScore = 0;
public static int extraCredit = 0;
public static boolean isZeroScore = false;
public static String scorePreamble = "";
@BeforeClass
public static void beforeTesting() {
totalScore = 0;
extraCredit = 0;
}
@AfterClass
public static void afterTesting() {
if (isZeroScore) {
totalScore = 0;
extraCredit = 0;
}
println(scorePreamble + "Estimated score (w/o late penalties, etc.) is:
" + totalScore + " out of 25.");
// If the project follows the naming convention, save the results in a
folder on
// the desktop. (Alex Kohanim)
try {
String directory =
substri.
This document discusses object initialization in Java. It explains that in Java, constructors allow objects to be initialized when they are created. Constructors ensure that class member variables and objects have initial values before an object is used. The document provides examples of how to write constructors, how to overload constructors, and how to use the this keyword in constructors. It also discusses static initialization and the use of toString() methods.
This document discusses object initialization in Java. It explains that in Java, constructors allow objects to be initialized when they are created. Constructors ensure that class member variables and objects are properly initialized before use. The document provides examples of how to write classes with constructors and use constructor overloading. It also discusses static initialization, the this keyword, and recursion.
The document provides examples of Java code using try, catch, throw, and exceptions to handle errors and exceptions. Program 36 introduces a try-catch block to handle potential InputMismatchExceptions from user input. Program 37 uses try-catch-finally to handle an ArithmeticException from division by zero and ensure the finally block always executes. Program 38 demonstrates multiple catch blocks to handle different exception types.
The document discusses how to define an interface in Java that specifies methods for generating different types of number series. An interface named Series is defined with three methods - getNext() to return the next number, reset() to restart the series, and setStart() to set the starting value. Classes can then implement the Series interface and provide implementations of these three methods to generate specific types of number series, like one that returns even numbers starting from 2.
JAVA OOP project; desperately need help asap im begging.Been stuck.pdffantasiatheoutofthef
JAVA OOP project; desperately need help asap im begging.
Been stuck on this for a week since my OOP skills are not good at all. Due in a couple hours so
im desperate. Codes needed will be provided at the end, thank you.
Codes:
DotChaser.java:
import java.util.*;
public class DotChaser {
public static Random rand = new Random(System.currentTimeMillis());
/**
* A "Thing" moves in a grid world. A TypeA Thing randomly
* decides to turn left or right (or not turn) every "round",
* and, afterward, takes a step forward. A TypeB Thing
* only considers making a random turn every 10th round.
*
* A STATIC CLASS? OH NO! GET IT OUT OF HERE!
*/
public static class Thing {
// dir: 0=North, 1=East, 2=South, 3=West.
// timeSinceLast: this is only important for "TypeB" Things.
public int row, col, dir, timeSinceLast;
public char lab = 'r';
public boolean isTypeB;
}
/**
* YOU'LL NEED TO PUT THIS SOMEWHERE ELSE
* HINT: WOULDN'T IT BE NICE TO HAVE A LIST OR QUEUE SO THAT
* WE DON'T HAVE TO USE NODES HERE?
* This class is for linked lists of Thing's
*/
public static class Node {
public Thing data;
public Node next;
}
// EEEEEK! STATIC METHODS!!! PLEASE FIND THEM A BETTER HOME.
public static void rightTurn(Thing t) {
t.dir = (t.dir + 1) % 4;
}
public static void leftTurn(Thing t) {
t.dir = (t.dir + 3) % 4;
}
public static void maybeTurn(Thing t) {
int i = rand.nextInt(3);
if (t.isTypeB) {
t.timeSinceLast++;
if (t.timeSinceLast == 10) {
t.timeSinceLast = 0;
if (i == 1) {
rightTurn(t);
}
if (i == 2) {
leftTurn(t);
}
}
} else {
if (i == 1) {
rightTurn(t);
}
if (i == 2) {
leftTurn(t);
}
}
}
public static void step(Thing t) {
final int[] dc = {
0, 1, 0, -1
}, dr = {
1, 0, -1, 0
};
t.row += dr[t.dir];
t.col += dc[t.dir];
}
/**
* This static method is ok :)
*/
public static void main(String[] args) {
int N = 200;
if( args.length != 0 )
N = Integer.parseInt(args[0]);
// INSTEAD OF A NODE, CREATE SOMETHING MORE USER-FRIENDLY.
Node L = null;
int count = 0;
while( true ) {
// Every N rounds, add another typeA and typeB Thing.
if( count % N == 0 ) {
// Add a typeA thing to the list.
// (GEE, THAT'S A LOT OF CODE FOR JUST CREATING ONE THING)
Thing tA = new Thing();
tA.row = 45;
tA.col = 50;
Node nA = new Node();
nA.data = tA;
nA.next = L;
L = nA;
// Add a typeB thing to the list
Thing tB = new Thing();
tB.row = 55;
tB.col = 50;
tB.lab = 'b';
tB.isTypeB = true;
Node nB = new Node();
nB.data = tB;
nB.next = L;
L = nB;
}
// Print out each thing.
// (SEEMS LIKE A NICE PRINTALL() METHOD CALL WOULD WORK HERE)
// (SEEMS LIKE A toString() METHOD IN THE CLASS WOULD ALSO BE NICE)
for( Node T = L; T != null; T = T.next )
System.out.println(T.data.row + " " + T.data.col + " " + T.data.lab);
System.out.println("done");
System.out.flush();
// Move each thing.
// (SEEMS LIKE A NICE MOVEALL() METHOD CALL WOULD WORK HERE)
for( Node T = L; T != null; T = T.next ) {
maybeTurn(T.data);
step(T.data);
}
count++;
}
}
}
Lab2_Tester.java
import org.junit.Test;
import static org.junit.Assert.assertEqual.
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
Implement a queue using a linkedlist (java)
Solution
LinkedQueueImplement.java
import java.util.*;
class Node
{
protected int data;
protected Node link;
public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedQueue
{
protected Node front, rear;
public int size;
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
return front == null;
}
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 :
try
{
System.out.println(\"Peek Element = \"+ lq.peek());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 4 :
System.out.println(\"Empty status = \"+ lq.isEmpty());
break;
case 5 :
System.out.println(\"Size = \"+ lq.getSize());
break;
default :
System.out.println(\"Wrong Entry \ \");
break;
}
/* display queue */
lq.display();
System.out.println(\"\ Do you want to continue (Type y or n) \ \");
ch = scan.next().charAt(0);
} while (ch == \'Y\'|| ch == \'y\');
}
}
Output :
Linked Queue Test
Queue Operations
1. inse.
The document discusses various String methods in Java:
- The charAt() method returns the character at a given index in the String.
- The compareTo() method compares two Strings lexicographically and returns an integer indicating their relative ordering.
- The indexOf() method returns the index of the first occurrence of a character or substring in the given String. It has overloads to specify a starting index for the search.
Programing with java for begniers .pptxadityaraj7711
Java is a high-level, object-oriented programming language developed by Sun Microsystems in the mid-1990s (now owned by Oracle Corporation). It is widely used for building a variety of applications, including desktop, web, mobile, and enterprise software. Java's design emphasizes portability, simplicity, and security, making it one of the most popular programming languages in the world.
### Importance of Java:
1. **Platform Independence**:
- Java programs can run on any device or operating system that supports the Java Virtual Machine (JVM).
- This "write once, run anywhere" (WORA) capability makes Java applications highly portable.
2. **Object-Oriented Programming (OOP)**:
- Java supports key OOP principles such as inheritance, encapsulation, polymorphism, and abstraction.
- These principles enable developers to create modular and reusable code.
3. **Rich Ecosystem and Libraries**:
- Java has a vast ecosystem of libraries, frameworks, and tools that facilitate development across various domains.
- Popular frameworks like Spring, Hibernate, and Apache Struts streamline development in enterprise environments.
4. **Robustness and Reliability**:
- Java has strong exception handling and type-checking mechanisms that contribute to the robustness and reliability of applications.
5. **Community and Support**:
- Java has a large and active developer community, providing support and resources for learning and troubleshooting.
- Java's extensive documentation and community forums are valuable resources for developers.
6. **Performance**:
- Java's just-in-time (JIT) compilation allows for optimized execution, improving performance.
- Java can handle large-scale applications and complex computations efficiently.
7. **Security**:
- Java's architecture includes features such as runtime security checks and a security manager for safe execution.
- This makes it a preferred choice for developing secure applications.
8. **Enterprise Applications**:
- Java is a dominant language in enterprise development due to its scalability, stability, and compatibility with existing systems.
- Many businesses rely on Java for mission-critical applications.
9. **Career Opportunities**:
- Proficiency in Java opens up many career opportunities, particularly in enterprise development, finance, healthcare, and telecommunications.
10. **Future-Proofing**:
- Java's continuous updates and compatibility with emerging technologies ensure that it remains relevant and future-proof.
Overall, Java's versatility, reliability, and widespread adoption make it an essential language for developers across various industries
Frequency .java Word frequency counter package frequ.pdfarshiartpalace
Frequency .java
/**
* Word frequency counter
*/
package frequency;
import java.util.Iterator;
/**
*
* @author UMD CS
*/
public class Frequency implements Iterable{
private Node first;
private int N;
Frequency(){
N = 0;
first = null;
}
@Override
public Iterator iterator() {
return new ListIterator();
}
/**
*
* List iterator
*
*/
private class ListIterator implements Iterator{
private Node current;
private int index ;
ListIterator(){
current = first;
index = 0;
}
@Override
public boolean hasNext() {
return current != null;
}
public String next() {
if(!hasNext()){
return null;
}
String word = current.key;
int count = current.count;
String r = \"(\"+word + \",\" + Integer.toString(count)+\")\";
current = current.next;
return r;
}
@Override
public void remove() {
}
}
/**
*
* Node class
*
*/
private class Node {
private String key;
private int count;
private Node next;
Node(String item){
key = item;
count = 1;
next = null;
}
@Override
public String toString(){
return \"(\"+key +\",\"+count+\")\";
}
}
/*
* Inserts a word into the linked list. If the word exists, increment the
* count by q.
*/
public void insert(String word){
if(word.equals(\"\")){
return;
}
//TODO
/*
* implement here
*/
}
/**
*
* @param str input string
* This method splits a string into words and pass the words to insert method
*
*/
public void insertWords(String str){
String delims = \"[ .,?!\'\\\"()}{;/<>&=#-:\\\\ _]+\";
String[] words = str.split(delims);
for(String s: words){
s = s.toLowerCase();
insert(s);
}
}
/**
* prints the word frequency list
*/
public void print(){
Node c = first;
while(c != null){
System.out.print(\"(\"+c.key + \",\" + c.count+\")\");
c = c.next;
}
System.out.print(\"\ \");
}
}
--------------------------------------------------------------------------------------------------------------------
------------------------------------------------------
WordFrequency.java
package frequency;
import utils.In;
import utils.Stopwatch;
/**
*
* @author UMD CS
*/
public class WordFrequency {
/**
* @param input source
* @param
* This method receives input resource and return the word frequency string
* DO NOT CHANGE THIS METHOD.
*/
public static String freq(String inputSource, int maxLines){
In in;
// Frequency class can only count the frequency of strings. DO NOT CHANGE THIS.
Frequency freq = new Frequency();
int MAX = 100;
String inputSourceName = inputSource;
try {
in = new In(inputSourceName);
while (!in.isEmpty()) {
String s = in.readLine();
//System.out.println(s);
freq.insertWords(s);
}
}
catch (Exception e) {
e.printStackTrace();
}
StringBuilder strFrequency = new StringBuilder();
int cnt = 0;
for(String s: freq){
strFrequency.append(s);
strFrequency.append(\",\");
cnt++;
if(cnt >= maxLines){break;}
}
return strFrequency.toString();
}
/**
*
*/
public static void main(String[] args) {
In in;
Frequency freq = new Frequency();
int MAX = 100;
// String inputSourceName =
\"http://www.cs.umd.edu/class/summer2015/cmsc132/projects/P3_WordFrequency/test1.html\";
String .
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
Creat Shape classes from scratch DETAILS You will create 3 shape classes (Circle, Rectangle,
Triangle) that all inherit from a single abstract class called AbstractShape which implements
Shape (also created by you). You are also responsible for creating the driver class
\"Assignment7.java\" (program that tests your classes and described on page 3) which does the
following reads input data from a file instantiates various objects of the three shapes based on the
input data stores each in a LinkedList outputs this list to an output file sorts a \"copy\" of this
LinkedList of objects outputs the sorted version of the list to the output file outputs the original
list to the output file This driver program also needs to \"ignore errors in the input file that breach
the specified input format as described in the Assianment7,java details (see page 3 1. Shape.java
This is an interface that has 2 abstract methods, and passes the responsibility of implementing the
compareTo method to the class that implements Shape (you may note, nomally Comparable is
\"implemented\" by a class. However, an interface cannot implement because interfaces can only
contain abstract methods. That said, an interface can only extend other interfaces and the
responsibility of actually \"implementing\" the abstract method(s) of the super class interface is
passed on to the sub-classes) public interface Shape extends Comparable public double
calculateAreal) Il This abstract method is implemented at the concrete level public Shape
copyShape); Il also implemented at the concrete level 2. AbstractShape.java public abstract class
AbstractShape implements Shape This class should contain an instance field to store the name of
each obiect. The constructor which sets this field should receive the name and a number to be
concatenated to the name and then stored in the name field Recall, when the super class has a
parameterized constructor, the sub-classes will need to call it AND the sub- classes will need to
also provide a constructor without parameters This abstract class will implement the compareTo
method passed on from the Shape interface and will pass on the responsibility of implementing
calculateArea to the extending sub-classes (compare To will use the calculateArea method when
comparing 2 Shape objects). Along with compare To, one more concrete method should be
included. The following will be used by the sub-classes\' toString method: public String
getName) II Simply returns the name field data
Solution
in7.txt
4.4
2.5 3
8.1 3.0 5.0
2.5 3 4
2.5
tuesday
-7
1.0
3 three
3 -9
3 5
1.0
Assignment7.java
import java.io.*;
import java.util.*;
public class Assignment7 {
/**
* This is the test driver class that will include main.
* This program MUST read a file named in7.txt and
* generate an output file named out7.txt. The in7.txt
* file must be created by you based on formatting
* described shortly.
*
* @param theArgs
*/
public static void main(String[] theArgs) {
List myList = new Arra.
JAVA - Design a data structure IntSet that can hold a set of integers-.docxolsenlinnea427
JAVA - Design a data structure IntSet that can hold a set of integers. Hide the private implementation: a Binary Search Tree of Integer objects. Provide the following public methods only.
• Constructor to make an empty set,
• Constructor to create a set by initializing the root,
• void add(int x) to add x if it is not present,
• void remove(int x) to remove x if it is present,
• void print() to print all the elements currently in the set,
• boolean contains(int x) to test whether x is present,
• IntSet copy() to create a new BTS as a copy of the current one.
Note that the root of the BST is a private data member and there is no need to define getRoot(), and setRoot() functions. All the above functions should be defined public and should call recursive private functions to do the task. e.g.
// remove
private Node recRemove(Node loc, int x) { // To do }
public void remove(int x) { root= recRemove(root, x) ; }
// contains
private boolean recContains(Node loc, int x) { // to do }
public boolean contains(int x) { return recContains(root, x) ; }
Complete the class IntSet by supplying the intersection and union functions. Use the same format as above i.e. each public function calls a private recursive function to do the task:
public IntSet union(IntSet other)
public IntSet intersection(IntSet other)
Solution
import java.util.Scanner; class BinarySearchExample { public static void main(String args[]) { int counter, num, item, array[], first, last, middle; //To capture user input Scanner input = new Scanner(System.in); System.out.println(\"Enter number of elements:\"); num = input.nextInt(); //Creating array to store the all the numbers array = new int[num]; System.out.println(\"Enter \" + num + \" integers\"); //Loop to store each numbers in array for (counter = 0; counter < num; counter++) array[counter] = input.nextInt(); System.out.println(\"Enter the search value:\"); item = input.nextInt(); first = 0; last = num - 1; middle = (first + last)/2; while( first <= last ) { if ( array[middle] < item ) first = middle + 1; else if ( array[middle] == item ) { System.out.println(item + \" found at location \" + (middle + 1) + \".\"); break; } else { last = middle - 1; } middle = (first + last)/2; } if ( first > last ) System.out.println(item + \" is not found.\ \"); } }
.
The document contains code snippets in Java for getting different types of information. This includes code to get the hostname, month from a date, IP address, memory size and usage, and more. The code uses various Java classes and methods like InetAddress, DateFormat, Runtime etc. to retrieve the desired information and print/return the output.
The document contains 11 Java programming assignments involving arrays and strings:
1. Sorting an integer array using bubble sort
2. Printing only odd numbers from an integer array
3. Moving all even numbers to the beginning of an integer array
4. Finding unique numbers and occurrences of duplicates in an array
5. Checking if an integer array matches the Fibonacci series
6. Checking if an integer array is a palindrome
7. Finding unique words in a string
8. Reversing a string
9. Reversing each word in a string separately
10. Reversing the lines when writing a file
11. Creating a Java program with APIs for database SELECT and UPDATE operations
This document contains code for finding the path of most resistance in an acyclic digraph. It defines classes for nodes, a node collection, and methods for loading a file representing the digraph as a list of nodes, setting relationships between nodes, and finding the highest value path from bottom to top. Node objects store attributes like name and accumulated totals. The node collection class manages the nodes and provides methods for accessing, adding, and finding nodes.
Similar to OrderTest.javapublic class OrderTest { Get an arra.pdf (20)
1.Cexplanation; Cloud consumers that use cloud-based IT resources .pdfakkhan101
1.C
explanation; Cloud consumers that use cloud-based IT resources can generally lease them with a
pay-for-use model. With this model, cloud consumers pay a usage fee for only the amount of the
IT resource actually used, resulting in directly proportional costs. This gives an organization
access to IT resources without having to purchase its own, resulting in reduced investment
requirements
2.B
explanation
The availability of an IT resource is the probability that it will be accessible. The probability
value is generally expressed with a percentage representing the amount of time that the IT
resource is accessible during a given period. The percentage is calculated as follows: 1. Divide
the amount of hours the IT resource was unavailable (within a measured period) by the total
amount of hours within the measured period. 2. Multiply the value by 100. 3. Deduct the value
from 100
3.D
explanation;
Horizontal scaling refers to the allocation or releasing of resources of the same type. The
horizontal allocation of resources is referred to as scaling out and the horizontal releasing of
resources is referred to as scaling in. Horizontal scaling is a common form of scaling within
cloud environments
4.C
explanation;
Cloud-based IT resources that are used by a cloud consumer reside outside of the cloud
consumer’s organizational boundary. To use the IT resources, the cloud consumer will generally
need to trust them. As a result, the cloud consumer’s trust boundary is expanded beyond its
organizational boundary to encompass the cloud.
5.C
explanation;
An organization will often have existing IT resources that are already paid for and operational.
The prior investment that has been made in these on-premise IT resources is referred to as sunk
costs. When comparing cloud-based IT resources to on-premise IT resources with sunk costs,
the up-front costs for on-premise IT resources is significantly lower. It can therefore be more
difficult to justify the leasing of cloud- based IT resources as an alternative
6.D
explanation
the fact that trust boundaries overlap can lead to opportunities for an attacker to attack IT
resources shared by multiple cloud consumers
7.D
explanation
all r correct
8.B
explanation
Cloud A provides Cloud Service A as part of a failover system that encompasses a redundant
implementation of Cloud Service A on Cloud B. If Cloud Service A on Cloud A fails, then
Cloud Service A on Cloud B is automatically provisioned transparently to Cloud Service
Consumer A. Each cloud has a specific level of reliability and availability that it guarantees for
Cloud Service A. By spanning the failover system across both clouds, the overall reliability and
availability will be higher than the maximum reliability and availability of either cloud
9.C
explanation
Different physical and virtual IT resources are dynamically assigned and reassigned according to
cloud consumer demand, typically followed by execution through statistical multiplexing.
Resource poolin.
1) WBC count is high and this level indicates that the person has le.pdfakkhan101
1) WBC count is high and this level indicates that the person has leucocytosis. This may be due
to some infections or stress etc.
2)the pH level is alkalotic and this is caused by the respiratory alkalosis. As the pH is less than
the normal level.
Solution
1) WBC count is high and this level indicates that the person has leucocytosis. This may be due
to some infections or stress etc.
2)the pH level is alkalotic and this is caused by the respiratory alkalosis. As the pH is less than
the normal level..
What are the four steps of a process involving a heterogeneous catal.pdfakkhan101
What are the four steps of a process involving a heterogeneous catalyst?
Stage 1:Diffusion of Reactant(s) to the Surface
The rate at which reactants will diffuse to the surface will be influenced by their bulk
concentration and by the thickness of the boundary layer.
Stage 2:Adsorption of reactants
Bonds are formed as the reactant(s) are adsorbed onto the surface of the catalyst.
The ability for an atom or molecule to stick to the surface is known, brilliantly, as the Sticking
Co-efficient. This is just the ratio or percentage of molecules that end up sticking on the surface.
Stage 3:Reaction
Bonds form between the atoms and molecules on the surface
Stage 4:Desorption of products
Bonds are broken as the product(s) desorb from the surface.
Stage 5:Diffusion of Product(s) away from the Surface
The products are then desorbed from the surface of the catalyst.
Solution
What are the four steps of a process involving a heterogeneous catalyst?
Stage 1:Diffusion of Reactant(s) to the Surface
The rate at which reactants will diffuse to the surface will be influenced by their bulk
concentration and by the thickness of the boundary layer.
Stage 2:Adsorption of reactants
Bonds are formed as the reactant(s) are adsorbed onto the surface of the catalyst.
The ability for an atom or molecule to stick to the surface is known, brilliantly, as the Sticking
Co-efficient. This is just the ratio or percentage of molecules that end up sticking on the surface.
Stage 3:Reaction
Bonds form between the atoms and molecules on the surface
Stage 4:Desorption of products
Bonds are broken as the product(s) desorb from the surface.
Stage 5:Diffusion of Product(s) away from the Surface
The products are then desorbed from the surface of the catalyst..
The given function is-Strictly increasing from 2 to infinityHen.pdfakkhan101
The given function is:-
Strictly increasing from 2 to infinity
Hence, Strictly increasing:- (2,inf)Option 2
Strictly decreasing :- (-inf , 2) Option 4
Hence, Option- 2,4 are correct.
Solution
The given function is:-
Strictly increasing from 2 to infinity
Hence, Strictly increasing:- (2,inf)Option 2
Strictly decreasing :- (-inf , 2) Option 4
Hence, Option- 2,4 are correct..
In the span of several decades, the Kingdom Protista has been disass.pdfakkhan101
In the span of several decades, the Kingdom Protista has been disassembled because sequence
analyses have revealed new genetic (and therefore evolutionary) relationships among these
eukaryotes. Moreover, protists that exhibit similar morphological features may have evolved
analogous structures because of similar selective pressures—rather than because of recent
common ancestry. This phenomenon, called convergent evolution, is one reason why protist
classification is so challenging. The emerging classification scheme groups the entire domain
Eukaryota into six “supergroups” that contain all of the protists as well as animals, plants, and
fungi that evolved from a common ancestor. The supergroups are believed to be monophyletic,
meaning that all organisms within each supergroup are believed to have evolved from a single
common ancestor, and thus all members are most closely related to each other than to organisms
outside that group. There is still evidence lacking for the monophyly of some groups.
Many of the protist species classified into the supergroup Excavata are asymmetrical, single-
celled organisms with a feeding groove “excavated” from one side. This supergroup includes
heterotrophic predators, photosynthetic species, and parasites. Its subgroups are the diplomonads,
parabasalids, and euglenozoans.
Diplomonads
Among the Excavata are the diplomonads, which include the intestinal parasite, Giardia lamblia.
Until recently, these protists were believed to lack mitochondria. Mitochondrial remnant
organelles, called mitosomes, have since been identified in diplomonads, but these mitosomes
are essentially nonfunctional. Diplomonads exist in anaerobic environments and use alternative
pathways, such as glycolysis, to generate energy. Each diplomonad cell has two identical nuclei
and uses several flagella for locomotion.
Parabasalids
A second Excavata subgroup, the parabasalids, also exhibits semi-functional mitochondria. In
parabasalids, these structures function anaerobically and are called hydrogenosomes because
they produce hydrogen gas as a byproduct. Parabasalids move with flagella and membrane
rippling. Trichomonas vaginalis, a parabasalid that causes a sexually transmitted disease in
humans.
Euglenozoans
Euglenozoans includes parasites, heterotrophs, autotrophs, and mixotrophs, ranging in size from
10 to 500 µm. Euglenoids move through their aquatic habitats using two long flagella that guide
them toward light sources sensed by a primitive ocular organ called an eyespot. The familiar
genus, Euglena, encompasses some mixotrophic species that display a photosynthetic capability
only when light is present. In the dark, the chloroplasts of Euglena shrink up and temporarily
cease functioning, and the cells instead take up organic nutrients from their environment.
The human parasite, Trypanosoma brucei, belongs to a different subgroup of Euglenozoa, the
kinetoplastids. The kinetoplastid subgroup is named after the kinetoplast, a DNA mass carri.
Information privacy It refers to the collection of data and disse.pdfakkhan101
Information privacy :
It refers to the collection of data and dissemination of the data.
It includes following issues those are
1. Data collection
2. Extract data from affected subjects
3. Controlled disclosureI
Option A is correct choice.
Solution
Information privacy :
It refers to the collection of data and dissemination of the data.
It includes following issues those are
1. Data collection
2. Extract data from affected subjects
3. Controlled disclosureI
Option A is correct choice..
H2SO4 --- 2H+ + SO42-1 mole of H2SO4 produces 2 moles of H+ ions.pdfakkhan101
H2SO4 ---> 2H+ + SO42-
1 mole of H2SO4 produces 2 moles of H+ ions
So [H+ ] = 2* molarity of H2SO4 = 2 * 6M = 12 M
HNO3 ---> H+ + NO3-
1 mole of HNO3 produces 1 mole of H+ ion
So [H+ ] = 1* Molarity of HNO3 = 1*6M = 6M
So there is difference in the [H+ ] ion concentration by taking HNO3 instead of H2SO4
Solution
H2SO4 ---> 2H+ + SO42-
1 mole of H2SO4 produces 2 moles of H+ ions
So [H+ ] = 2* molarity of H2SO4 = 2 * 6M = 12 M
HNO3 ---> H+ + NO3-
1 mole of HNO3 produces 1 mole of H+ ion
So [H+ ] = 1* Molarity of HNO3 = 1*6M = 6M
So there is difference in the [H+ ] ion concentration by taking HNO3 instead of H2SO4.
Gene editing of somatic cellsThere are grave concerns regarding th.pdfakkhan101
Gene editing of somatic cells
There are grave concerns regarding the ethical and safety implications of this research. There is
also fear of the negative impact it could have on important work involving the use of genome-
editing techniques in somatic (non-reproductive) cells.
Genome-editing technologies may offer a powerful approach to treat many human diseases,
including HIV/AIDS, haemophilia, sickle-cell anaemia and several forms of cancer
genome editing in human embryos using current technologies could have unpredictable effects
on future generations. This makes it dangerous and ethically unacceptable. Such research could
be exploited for non-therapeutic modifications. We are concerned that a public outcry about such
an ethical breach could hinder a promising area of therapeutic development, namely making
genetic changes that cannot be inherited.
prospect of manipulating the genome of human embryos has raised debates and discussions
amongst scientists, regulators, and the public. It is a crucial conversation that we need to
participate in as we have done for other scientific advancements in the past from embryonic stem
cells research to ‘in vitro’ fertilization and, recently in the UK, mitochondrial replacement.
Gene editing of somatic cells is currently in clinical development for a variety of conditions. The
editing of genomes in human somatic cells certainly raises ethical questions, but is distinct from
germline gene modification, in that changes in the gene(s) do not persist beyond a single
generation. As to human germline editing, the EGE is of the view that there should be a
moratorium on gene editing of human embryos or gametes which would result in the
modification of the human genome.
Solution
Gene editing of somatic cells
There are grave concerns regarding the ethical and safety implications of this research. There is
also fear of the negative impact it could have on important work involving the use of genome-
editing techniques in somatic (non-reproductive) cells.
Genome-editing technologies may offer a powerful approach to treat many human diseases,
including HIV/AIDS, haemophilia, sickle-cell anaemia and several forms of cancer
genome editing in human embryos using current technologies could have unpredictable effects
on future generations. This makes it dangerous and ethically unacceptable. Such research could
be exploited for non-therapeutic modifications. We are concerned that a public outcry about such
an ethical breach could hinder a promising area of therapeutic development, namely making
genetic changes that cannot be inherited.
prospect of manipulating the genome of human embryos has raised debates and discussions
amongst scientists, regulators, and the public. It is a crucial conversation that we need to
participate in as we have done for other scientific advancements in the past from embryonic stem
cells research to ‘in vitro’ fertilization and, recently in the UK, mitochondrial replacement.
Gene editing of somatic.
Four parts of compare and contrastSolutionFour parts of compar.pdfakkhan101
Comparing and contrasting involves four parts: the topics being compared, their similarities, their differences, and the significance of analyzing their similarities and differences.
Each Restriction enzymes has a unique restriction site and therefore.pdfakkhan101
Each Restriction enzymes has a unique restriction site and therefore in a GFP-HindIII clone no
restriction patterns will be observed with EcoRI digestion until and unless one has prior
knowledge of all restriction sites present on the clone.
Solution
Each Restriction enzymes has a unique restriction site and therefore in a GFP-HindIII clone no
restriction patterns will be observed with EcoRI digestion until and unless one has prior
knowledge of all restriction sites present on the clone..
This short document discusses a solution but provides no details about the problem or solution. It states that the solution is correct but does not explain what is being solved or how the solution works. The document on its own does not provide enough contextual information to generate an informative summary.
Code of main classpublic class LBmain { public static void m.pdfakkhan101
Code of main class:
public class LBmain {
public static void main(String[]args)
{
LinkedStack list = new LinkedStack<>();
System.out.println(\"Let\'s make a List!\");
System.out.println(\"Push 3 times.\");
System.out.println(\"Check the size.\");
System.out.println(\"Peek the top element.\");
System.out.println(\"Pop three times.\");
System.out.println (\"The size now should be zero!\" + \"\ \");
list.Push(1);
list.Push(2);
list.Push(3);
System.out.println(list.toString());
list.Size();
list.Peek();
list.Pop();
list.Pop();
list.Pop();
list.Size();
}
public class LinkedStack implements Stack {
private int count;
private LinearNode top;
//-----------------------------------------------------------------
// Creates an empty stack using the default capacity.
//-----------------------------------------------------------------
public LinkedStack()
{
count = 0;
top = null;
}
@Override
public boolean IsEmpty()
{
if(top == null)
{
System.out.println(\"Stack is empty\");
}
return top == null;
}
@Override
public void Push(T element)
{
LinearNode current = new LinearNode<>(element);
current.setNext(top);
top = current;
count++;}
@Override
public T Pop()
{
T result;
System.out.println(\"Lets pop the top element!\");
if (count == 0)
{
System.out.println(\"Pop operation failed. \"+ \"The stack is empty.\");
}
result = top.getElement();
top = top.getNext();
count--;
System.out.println(\"The element that we have poped is :\" + result);
return result;
}
Override
public String toString()
{
String result = \"\ \";
LinearNode current = top;
while (current != null)
{
result += current.getElement() + \"\ \";
current = current.getNext();
}
return result + \"\";
}
@Override
public T Peek() {
System.out.println(\"Lets peek the top element!\");
if(count == 0)
{
System.out.println(\"Peek failed stack is empty\");
}
System.out.println(\"The element that we have peeked is: \" + top.getElement());
return top.getElement();
}
@Override
public int Size() {
System.out.println(\"The size of the list now is: \" + count);
return count;
}
}
main.Peek();
main.Pop();
main.Pop();
main.Size();
main.toString();
}
}
@Override
public void Push(T element)
{
LinearNode current = new LinearNode<>(element);
current.setNext(top);
top = current;
count++;
}
}
public class LinearNode {
private LinearNode next; //se guarda la referencia del Nodo
private T element; //Lista vacia
public LinearNode()
{
next = null;
element = null;
}
//-----------------------------------------------------------------
// Creates a node storing the specified element.
//-----------------------------------------------------------------
public LinearNode (T elem)
{
next = null;
element = elem;
}
//-----------------------------------------------------------------
// Returns the node that follows this one.
//-----------------------------------------------------------------
public LinearNode getNext()
{
return next;
}
//-----------------------------------------------------------------
// Sets the node that follows this one.
.
BibliographyHall, J. E. (2015). Guyton and Hall textbook of medic.pdfakkhan101
Bibliography:
Hall, J. E. (2015). Guyton and Hall textbook of medical physiology. Elsevier Health Sciences.
De Luca Jr, L. A., Menani, J. V., & Johnson, A. K. (2014). Circumventricular Organs:
Integrators of Circulating Signals Controlling Hydration, Energy Balance, and Immune
Function--Neurobiology of Body Fluid Homeostasis: Transduction and Integration.
Sherwood, L. (2015). Human physiology: from cells to systems. Cengage learning.
Homeostatic Regulation of the Vascular System | Anatomy and Physiology II. (2016).
Courses.lumenlearning.com. Retrieved 25 November 2016, from
https://courses.lumenlearning.com/ap2/chapter/homeostatic-regulation-of-the-vascular-system
De Luca Jr, L. A., Menani, J. V., & Johnson, A. K. (2014). Preoptic–Periventricular Integrative
Mechanisms Involved in Behavior, Fluid–Electrolyte Balance, and Pressor Responses--
Neurobiology of Body Fluid Homeostasis: Transduction and Integration.
Keeping in mind the end goal to keep up homeostasis in the cardiovascular framework and give
sufficient blood to the tissues, blood stream must be diverted constantly to the tissues as they
turn out to be more dynamic. Undeniably, the cardiovascular framework takes part in asset
assignment, in light of the fact that there is insufficient blood stream to disseminate blood
similarly to all tissues at the same time. For instance, when an individual is working out, more
blood will be coordinated to skeletal muscles, the heart, and the lungs. Taking after a dinner,
more blood is coordinated to the stomach related framework. Just the mind gets a pretty much
steady supply of blood whether you are dynamic, resting, considering, or occupied with some
other activity.The sensory system assumes a basic part in the direction of vascular homeostasis.
The essential administrative destinations incorporate the cardiovascular focuses in the mind that
control both heart and vascular capacities. Also, more summed up neural reactions from the
limbic framework and the autonomic sensory system are variables.
The Cardiovascular Centers in the Brain
Neurological control of circulatory strain and stream relies on upon the cardiovascular focuses
situated in the medulla oblongata. This group of neurons reacts to changes in pulse and in
addition blood convergences of oxygen, carbon dioxide, and hydrogen particles. The
cardiovascular focus contains three particular combined segments:
The cardioaccelerator focuses empower cardiovascular capacity by controlling heart rate and
stroke volume by means of thoughtful incitement from the cardiovascular quickening agent
nerve.
The cardioinhibitor focuses moderate cardiovascular capacity by diminishing heart rate and
stroke volume through parasympathetic incitement from the vagus nerve.
The vasomotor focuses control vessel tone or withdrawal of the smooth muscle in the tunica
media. Changes in width influence fringe resistance, weight, and stream, which influence
cardiovascular yield. The lion\'s share of these neurons demonst.
This very short document appears to be discussing the topic of synthesis or solution synthesis but provides no other context or details in just three words: "synthesis", "Solution", "synthesis". It is not possible to provide a meaningful summary in 3 sentences or less given the extremely limited information provided.
LiOH is a strong base so we assume it dissociates.pdfakkhan101
LiOH is a strong base so we assume it dissociates completely. So there will be 8.82
x 10^-3 M of OH- pOH = -log[OH-] = -log(8.82 x 10^-3) = 2.05 pH = 14 - pOH = 14 - 2.05 =
11.95
Solution
LiOH is a strong base so we assume it dissociates completely. So there will be 8.82
x 10^-3 M of OH- pOH = -log[OH-] = -log(8.82 x 10^-3) = 2.05 pH = 14 - pOH = 14 - 2.05 =
11.95.
With Sp3d hybridization, a seesaw or linear shape.pdfakkhan101
With Sp3d hybridization, a seesaw or linear shape is possible. The seesaw shape
occurs when the molecule has the form AB4E, where A is the central atom, B represents the
atoms attached to the central atom and E is a nonbonding pair of electrons attached to the central
atom. Linear is in the form AB2E3. So A is the central atom and should be by itself and the only
choice that fits that criteria is answer A (BrFs)
Solution
With Sp3d hybridization, a seesaw or linear shape is possible. The seesaw shape
occurs when the molecule has the form AB4E, where A is the central atom, B represents the
atoms attached to the central atom and E is a nonbonding pair of electrons attached to the central
atom. Linear is in the form AB2E3. So A is the central atom and should be by itself and the only
choice that fits that criteria is answer A (BrFs).
The document discusses two-photon transition probability. It involves the probability of an atom making a transition between two energy levels by absorbing or emitting two photons simultaneously. This is a higher-order optical process that is much weaker than single-photon transitions.
this is because Nitrogen has a lone pair and and .pdfakkhan101
this is because Nitrogen has a lone pair and and the Carbon with chlorine is
electrophilic in nature and therefore, the lone pair attracted towards that lone pair.
Solution
this is because Nitrogen has a lone pair and and the Carbon with chlorine is
electrophilic in nature and therefore, the lone pair attracted towards that lone pair..
There is no easy way to remember the ionization l.pdfakkhan101
There is no easy way to remember the ionization levels on periodic table. Elements
in a certain group share similar properties. That could be one way to predict the ionization levels
but its not 100% accurate at all times.
Solution
There is no easy way to remember the ionization levels on periodic table. Elements
in a certain group share similar properties. That could be one way to predict the ionization levels
but its not 100% accurate at all times..
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
Physiology and chemistry of skin and pigmentation, hairs, scalp, lips and nail, Cleansing cream, Lotions, Face powders, Face packs, Lipsticks, Bath products, soaps and baby product,
Preparation and standardization of the following : Tonic, Bleaches, Dentifrices and Mouth washes & Tooth Pastes, Cosmetics for Nails.
Assessment and Planning in Educational technology.pptxKavitha Krishnan
In an education system, it is understood that assessment is only for the students, but on the other hand, the Assessment of teachers is also an important aspect of the education system that ensures teachers are providing high-quality instruction to students. The assessment process can be used to provide feedback and support for professional development, to inform decisions about teacher retention or promotion, or to evaluate teacher effectiveness for accountability purposes.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
OrderTest.javapublic class OrderTest { Get an arra.pdf
1. OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println("Usage: java OrderTest sizeOfArray "
+ "tor tjava OrderTest arrayFile");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println("unable to read array from " + args[0]);
System.exit(1);//14
}
}
System.out.println("before:");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
2. System.out.println(" after:");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
3. */
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + " ");
}
outFile.close();
} catch (IOException e) {
System.err.println("Could not write to " + outfile + " " + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
4. InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) {
int myNum = 0;
for (int next = 1; next < array.length; next++) {//2
//n
myNum++;
int val = array[next];
int index = next;
while (index > 0 && val < array[index - 1]) {//3
array[index] = array[index - 1];//n
index--;
myNum++;
}
array[index] = val;
}
return myNum;
5. }
}
BieberSortTest.java
public class BieberSortTest {
public static void main(String[] args){
if (args.length != 1) {
System.out.println("Usage: java BieberSortTest numberOfBiebz");
System.exit(1);
}
try {
int n = Integer.parseInt(args[0]);
BieberSort bs = new BieberSort(n);
bs.printBiebers();
System.out.println("---------");
bs.sort(); // this is the method to measure
bs.printBiebers();
System.out.println(bs.getLoop1()+" <==Loop1");
System.out.println(bs.getLoop2()+" <==Loop");
} catch (NumberFormatException nfe) {
System.out.println("number of Biebz must be a positive integer");
nfe.printStackTrace();
}
}
}
BiberSort.java
import java.util.Random;
public class BieberSort {
private Biebz[] theBiebz;
6. int counterLoop1=0,counterLoop2=0;
/**
* Inner class for the BieberSort
*/
public class Biebz implements Comparable{
private int b;
public Biebz(int b){
this.b = b;
}
public int compareTo(Biebz o) {
return this.b - o.b;
}
public String toString() {
return String.valueOf(this.b);
}
}
/**
* Construct a new BieberSort class with n fans
*/
public BieberSort(int n) {
this.theBiebz = new Biebz[n];
Random rdm = new Random(System.currentTimeMillis());
for(int i = 0; i< n;i++){
theBiebz[i] = new Biebz(rdm.nextInt(n));
}
}
public int getLoop1(){
return counterLoop1;
}
public int getLoop2(){
return counterLoop2;
}
/**
* Prints all the Biebers that we have ...
7. */
public void printBiebers(){
for(Biebz bz:theBiebz){
System.out.println(bz);
}
}
/**
* Sorts a collection of Bieber objects
*/
public void sort(){
for(int i =0;ii;j--){
counterLoop2++;
if(theBiebz[i].compareTo(theBiebz[j]) > 0 ){
swap(i,j);
}
}
}
}
private void swap(int i, int j){
Biebz b =theBiebz[i];
theBiebz[i] = theBiebz[j];
theBiebz[j]=b;
}
}
FindTest.java
public class FindTest {
/**
* Get an array of specified size and find the indexes of all elements
* in the array using Find.find().
*/
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FindTest sizeOfArray "
+ "tor tjava FindTest arrayFile");
8. System.exit(1);
}
// create or read the int[]
int size = 0;
int counter = 0;
int[] array = new int[0];
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println("unable to read array from " + args[0]);
System.exit(1);
}
}
// find the index of every element
double average=0;
for (int i = 1; i <= array.length; i++) {
//this is the method of interest, but you'll need to average
//the number of statements needed to find each element for
//meaningful results
int index = Find.find(array, i);
average = Find.getAverage(array);
System.out.printf("%d found at index %d ", i, index);
}
System.out.println("The average is: "+average);
System.out.println(size);
}
}
9. Find.java
public class Find {
/**
* Return index where value is found in array or -1 if not found.
*/
public static int find(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
public static double getAverage(int[] myArray){
int sum=0;
double average=0;
for (int i = 0; i < myArray.length; i++) {
sum=sum+myArray[i];
}
average=sum/myArray.length;
return average;
}
}
ConsecutivePairs.java
public class ConsecutivePairs {
private int n;
private long pairsCount;
private long numStatements = 0; //looking for the dominant section as n gets large
10. /**
* Generates all combinations of numberOfBits and counts all matched bit pairs.
*/
public ConsecutivePairs(int numberOfBits) throws IllegalArgumentException {
if (numberOfBits < 1) {
throw new IllegalArgumentException("number of bits must be positive");
}
n = numberOfBits;
pairsCount = 0;
int[] bit = new int[n];
for (int i = 0; i < bit.length; i++) {
bit[i] = 0;
}
//generate all combinations of n "bits" by mimicking a binary counter
while(positivesCount(bit) < n) {
numStatements++; //are these the most important statements?
//count "bits" that match their neighbor
for(int i = 0; i < bit.length - 1; i++) {
//numStatements++; //are these the most important statements?
if(bit[i] == bit[i+1]) {
pairsCount++;
}
}
//add 1
int b = 0;
while (b < bit.length && bit[b] == 1) {
bit[b] = 0;
b++;
11. //numStatements++; //are these the most important statements?
}
if (b < bit.length) {
bit[b] = 1;
}
}
//still need to count last state where all bits are 1s
//count "bits" that match their neighbor
for(int i = 0; i < bit.length - 1; i++) {
//numStatements++; //are these the most important statements?
if(bit[i] == bit[i+1]) {
pairsCount++;
}
}
}
private int positivesCount(int[] intsArray) {
int positives = 0;
for(int i = 0; i < intsArray.length; i++) {
//numStatements++; //are these the most important statements?
if(intsArray[i] > 0) {
positives++;
}
}
return positives;
}
public long getPairsCount() {
return pairsCount;
}
12. public int getNumberOfBits() {
return n;
}
public long getNumStatements() {
return numStatements;
}
}
ConsecutivePairsTest.java
public class ConsecutivePairsTest {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java ConsecutivePairsTest numberOfBits");
System.exit(1);
}
try {
int n = Integer.parseInt(args[0]);
ConsecutivePairs pairs = new ConsecutivePairs(n); //this is the call to measure
System.out.printf("for n = %d, there are %d matched bit pairs ",
n, pairs.getPairsCount());
System.out.printf("approximately %d statements were executed to calculate this
answer",
pairs.getNumStatements());
} catch (Exception nfe) {
System.out.println("number of bits must be a positive integer");
nfe.printStackTrace();
System.exit(1);
}
}
}
analysis.odt
Haseeb Nain
13. Computer Science 221
Mason Vail
FindSort:
Part 1 Section 1
Because this sort relies on finding a specific value at the within the array. And in doing so finds
multiple values at multiple points within the array it must be at least O(n). This is simply because
the amount of recursion is directly related to the size of the array.
Part 1 Section 2
Table 1 FindSort Data
FindSort
Input Average NumStatements
1000 500 500000
10000 5000 50000000
20000 10000 200000000
30000 15000 450000000
40000 20000 800000000
50000 25000 1250000000
Figure 1: FindSort Average
Figure 2: FindSort Statments
Part 1 Section 3
This outcome did not support my hypothesis, I believed that the array simply relied on the
length of the array, n, this is not the case. While the average was constant, the actual amount of
time the statements were run followed more closely to a O(n2).
Order Sort:
Part 2 Section 1
Because this sort relies on the value of a point in an array, and then compares the two arrays,
and then switches the position of the array based on its size in comparison, this sort will be
greater in magnitude than the previous FindSort. The order.java class seems to make the
comparison, so it must always run twice for each loop, the loop is the size of the array, so it will
repeat n times. When putting these together I arrive at a O(n2).
Part 2 Section 2
Table 2: OrderSort Data
OrderSort
Input NumStatements
14. 1000 247753
10000 25256933
20000 1.00E+08
30000 2.24E+08
40000 3.98E+08
50000 6.23E+08
Figure 3: OrderSort Statements
Part 2 Section 3
After plotting the number of statements in relation to the number of inputs, I noticed that the
graph looked similar to the quadratic of the second power. This confirms my hypothesis of
O(n2).
BeiberSort:
Part 3 Section 1
BeiberSort is similar to Consecutive Sort, as it compares two values and then orders them from
lowest to greatest. Because it also follows though with two for loops, I believe this will also be
O(n2).
Part 3 Section 2
Table 3: BeiberSort Data
BeiberSort
Input Count
1000 499500
10000 49995000
20000 199990000
30000 449985000
40000 799980000
50000 1249975000
Figure 4: BeiberSort Statements
Part 3 Section 3
The information exracted from the amount of statements and the amount of inputs provides a
graph with a plot equivalent to a quadratic of power 2. This further confirms my hypothesis that
O(n2)
ConsecutiveSort:
Part 4 Section 1
Because the consecutive sort merges concepts from the previous sorting methods, I believe its
number of statements run must be larger then anything before. The consecutive sort will find
15. values, then compare the values and report values where two values are equivalent and
consecutive. The use of a while loop will also contribute to the amount of statements run,
because it directly relates to the size of “n”. In the end I believe this to be an exponential
increase, so O(2n).
Part 4 Section 2
Table 4: ConsecutiveSort Data
ConsecutiveSort
Input NumStatements
5 31
10 1023
15 32767
20 1048575
25 33554431
Figure 5: ConsecutiveSort Statements
Part 4 Section 3
The information provided by the input and the number of statements further confirms my
hypothesis. The slope was minimal at first by begins to ramp up significantly after 20. On my
excel sheet the data went negative for the value between 15 and 20, I believe this is simply an
error on the behalf of Excel.
Solution
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println("Usage: java OrderTest sizeOfArray "
+ "tor tjava OrderTest arrayFile");
System.exit(1);
}
16. // create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println("unable to read array from " + args[0]);
System.exit(1);//14
}
}
System.out.println("before:");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(" after:");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
17. import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
18. /**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + " ");
}
outFile.close();
} catch (IOException e) {
System.err.println("Could not write to " + outfile + " " + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
19. }
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) {
int myNum = 0;
for (int next = 1; next < array.length; next++) {//2
//n
myNum++;
int val = array[next];
int index = next;
while (index > 0 && val < array[index - 1]) {//3
array[index] = array[index - 1];//n
index--;
myNum++;
}
array[index] = val;
}
return myNum;
}
}
BieberSortTest.java
public class BieberSortTest {
public static void main(String[] args){
if (args.length != 1) {
System.out.println("Usage: java BieberSortTest numberOfBiebz");
System.exit(1);
}
20. try {
int n = Integer.parseInt(args[0]);
BieberSort bs = new BieberSort(n);
bs.printBiebers();
System.out.println("---------");
bs.sort(); // this is the method to measure
bs.printBiebers();
System.out.println(bs.getLoop1()+" <==Loop1");
System.out.println(bs.getLoop2()+" <==Loop");
} catch (NumberFormatException nfe) {
System.out.println("number of Biebz must be a positive integer");
nfe.printStackTrace();
}
}
}
BiberSort.java
import java.util.Random;
public class BieberSort {
private Biebz[] theBiebz;
int counterLoop1=0,counterLoop2=0;
/**
* Inner class for the BieberSort
*/
public class Biebz implements Comparable{
private int b;
public Biebz(int b){
this.b = b;
}
public int compareTo(Biebz o) {
return this.b - o.b;
}
21. public String toString() {
return String.valueOf(this.b);
}
}
/**
* Construct a new BieberSort class with n fans
*/
public BieberSort(int n) {
this.theBiebz = new Biebz[n];
Random rdm = new Random(System.currentTimeMillis());
for(int i = 0; i< n;i++){
theBiebz[i] = new Biebz(rdm.nextInt(n));
}
}
public int getLoop1(){
return counterLoop1;
}
public int getLoop2(){
return counterLoop2;
}
/**
* Prints all the Biebers that we have ...
*/
public void printBiebers(){
for(Biebz bz:theBiebz){
System.out.println(bz);
}
}
/**
* Sorts a collection of Bieber objects
*/
public void sort(){
for(int i =0;ii;j--){
counterLoop2++;
if(theBiebz[i].compareTo(theBiebz[j]) > 0 ){
22. swap(i,j);
}
}
}
}
private void swap(int i, int j){
Biebz b =theBiebz[i];
theBiebz[i] = theBiebz[j];
theBiebz[j]=b;
}
}
FindTest.java
public class FindTest {
/**
* Get an array of specified size and find the indexes of all elements
* in the array using Find.find().
*/
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FindTest sizeOfArray "
+ "tor tjava FindTest arrayFile");
System.exit(1);
}
// create or read the int[]
int size = 0;
int counter = 0;
int[] array = new int[0];
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {
try {
23. array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println("unable to read array from " + args[0]);
System.exit(1);
}
}
// find the index of every element
double average=0;
for (int i = 1; i <= array.length; i++) {
//this is the method of interest, but you'll need to average
//the number of statements needed to find each element for
//meaningful results
int index = Find.find(array, i);
average = Find.getAverage(array);
System.out.printf("%d found at index %d ", i, index);
}
System.out.println("The average is: "+average);
System.out.println(size);
}
}
Find.java
public class Find {
/**
* Return index where value is found in array or -1 if not found.
*/
public static int find(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
24. }
public static double getAverage(int[] myArray){
int sum=0;
double average=0;
for (int i = 0; i < myArray.length; i++) {
sum=sum+myArray[i];
}
average=sum/myArray.length;
return average;
}
}
ConsecutivePairs.java
public class ConsecutivePairs {
private int n;
private long pairsCount;
private long numStatements = 0; //looking for the dominant section as n gets large
/**
* Generates all combinations of numberOfBits and counts all matched bit pairs.
*/
public ConsecutivePairs(int numberOfBits) throws IllegalArgumentException {
if (numberOfBits < 1) {
throw new IllegalArgumentException("number of bits must be positive");
}
n = numberOfBits;
pairsCount = 0;
int[] bit = new int[n];
for (int i = 0; i < bit.length; i++) {
bit[i] = 0;
25. }
//generate all combinations of n "bits" by mimicking a binary counter
while(positivesCount(bit) < n) {
numStatements++; //are these the most important statements?
//count "bits" that match their neighbor
for(int i = 0; i < bit.length - 1; i++) {
//numStatements++; //are these the most important statements?
if(bit[i] == bit[i+1]) {
pairsCount++;
}
}
//add 1
int b = 0;
while (b < bit.length && bit[b] == 1) {
bit[b] = 0;
b++;
//numStatements++; //are these the most important statements?
}
if (b < bit.length) {
bit[b] = 1;
}
}
//still need to count last state where all bits are 1s
//count "bits" that match their neighbor
for(int i = 0; i < bit.length - 1; i++) {
//numStatements++; //are these the most important statements?
26. if(bit[i] == bit[i+1]) {
pairsCount++;
}
}
}
private int positivesCount(int[] intsArray) {
int positives = 0;
for(int i = 0; i < intsArray.length; i++) {
//numStatements++; //are these the most important statements?
if(intsArray[i] > 0) {
positives++;
}
}
return positives;
}
public long getPairsCount() {
return pairsCount;
}
public int getNumberOfBits() {
return n;
}
public long getNumStatements() {
return numStatements;
}
}
ConsecutivePairsTest.java
public class ConsecutivePairsTest {
public static void main(String[] args) {
if (args.length != 1) {
27. System.out.println("Usage: java ConsecutivePairsTest numberOfBits");
System.exit(1);
}
try {
int n = Integer.parseInt(args[0]);
ConsecutivePairs pairs = new ConsecutivePairs(n); //this is the call to measure
System.out.printf("for n = %d, there are %d matched bit pairs ",
n, pairs.getPairsCount());
System.out.printf("approximately %d statements were executed to calculate this
answer",
pairs.getNumStatements());
} catch (Exception nfe) {
System.out.println("number of bits must be a positive integer");
nfe.printStackTrace();
System.exit(1);
}
}
}
analysis.odt
Haseeb Nain
Computer Science 221
Mason Vail
FindSort:
Part 1 Section 1
Because this sort relies on finding a specific value at the within the array. And in doing so finds
multiple values at multiple points within the array it must be at least O(n). This is simply because
the amount of recursion is directly related to the size of the array.
Part 1 Section 2
Table 1 FindSort Data
FindSort
Input Average NumStatements
1000 500 500000
28. 10000 5000 50000000
20000 10000 200000000
30000 15000 450000000
40000 20000 800000000
50000 25000 1250000000
Figure 1: FindSort Average
Figure 2: FindSort Statments
Part 1 Section 3
This outcome did not support my hypothesis, I believed that the array simply relied on the
length of the array, n, this is not the case. While the average was constant, the actual amount of
time the statements were run followed more closely to a O(n2).
Order Sort:
Part 2 Section 1
Because this sort relies on the value of a point in an array, and then compares the two arrays,
and then switches the position of the array based on its size in comparison, this sort will be
greater in magnitude than the previous FindSort. The order.java class seems to make the
comparison, so it must always run twice for each loop, the loop is the size of the array, so it will
repeat n times. When putting these together I arrive at a O(n2).
Part 2 Section 2
Table 2: OrderSort Data
OrderSort
Input NumStatements
1000 247753
10000 25256933
20000 1.00E+08
30000 2.24E+08
40000 3.98E+08
50000 6.23E+08
Figure 3: OrderSort Statements
Part 2 Section 3
After plotting the number of statements in relation to the number of inputs, I noticed that the
graph looked similar to the quadratic of the second power. This confirms my hypothesis of
O(n2).
BeiberSort:
Part 3 Section 1
29. BeiberSort is similar to Consecutive Sort, as it compares two values and then orders them from
lowest to greatest. Because it also follows though with two for loops, I believe this will also be
O(n2).
Part 3 Section 2
Table 3: BeiberSort Data
BeiberSort
Input Count
1000 499500
10000 49995000
20000 199990000
30000 449985000
40000 799980000
50000 1249975000
Figure 4: BeiberSort Statements
Part 3 Section 3
The information exracted from the amount of statements and the amount of inputs provides a
graph with a plot equivalent to a quadratic of power 2. This further confirms my hypothesis that
O(n2)
ConsecutiveSort:
Part 4 Section 1
Because the consecutive sort merges concepts from the previous sorting methods, I believe its
number of statements run must be larger then anything before. The consecutive sort will find
values, then compare the values and report values where two values are equivalent and
consecutive. The use of a while loop will also contribute to the amount of statements run,
because it directly relates to the size of “n”. In the end I believe this to be an exponential
increase, so O(2n).
Part 4 Section 2
Table 4: ConsecutiveSort Data
ConsecutiveSort
Input NumStatements
5 31
10 1023
15 32767
20 1048575
30. 25 33554431
Figure 5: ConsecutiveSort Statements
Part 4 Section 3
The information provided by the input and the number of statements further confirms my
hypothesis. The slope was minimal at first by begins to ramp up significantly after 20. On my
excel sheet the data went negative for the value between 15 and 20, I believe this is simply an
error on the behalf of Excel.