public class Stopwatch {
private double startTime;
private double endTime;
public static void main(String[]args) {
}
public void stopWatch() {
startTime = System.currentTimeMillis();
}
public void start() {
startTime = System.currentTimeMillis();
}
public void stop() {
endTime = System.currentTimeMillis();
}
public long getStartTime()
{
return (long) startTime;
}
public long getEndTime()
{
return (long) endTime;
}
public long getElapsedTime()
{
return (long) (System.currentTimeMillis() - startTime);
}
public short getMilliSeconds()
{
return (short)((System.currentTimeMillis() - startTime) % 1000);
}
}
I need to run this testSearch with the StopWatch Class above
When I input the array size I get the Linear Search result but the Binary Search stays at 0 nano seconds
import java.util.*;
public class testSearch {
public static void main(String[] args){
// input array size from user
Scanner input = new Scanner(System.in);
System.out.print("Enter array size: ");
int size = input.nextInt();
System.out.println();
// create the array (the numbers do not really matter)
int[] numbers = new int[size];
for(int i=0; i<numbers.length; i++){
// we want the numbers sorted for binary search
// so why not just the numbers 0,1,...,size-1
numbers[i]=i;
}
// store the time now
long startTime = System.nanoTime();
// linear search for size (which is not in the array)
linearSearch(numbers,size);
// display the time elapsed
System.out.println("The time taken by Linear Search is " + (System.nanoTime() - startTime) + "nanoseconds.");
// prepare to measure the time elapsed again
startTime = System.nanoTime();
// binary search for size
binarySearch(numbers,size);
// display the time elapsed
System.out.println("The time taken by Binary Search is " + (System.nanoTime() - startTime) + "nanoseconds.");
}
public static boolean linearSearch(int[] a, int key) {
for(int i=0; i<a.length; i++){
if(a[i]==key) return true;
}
return false;
}
public static boolean binarySearch(int[] a, int key) {
int low = 0;
int high = a.length -1;
int mid;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid]>key) {
high = mid - 1;
} else if (a[mid]<key) {
low = mid + 1;
} else {
return true;
}
}
return false;
}
}
Here is the output that I get
Enter array size:
2
The time taken by Linear Search is 1456959922854 milliseconds.
The time taken by Binary Search is 0 milliseconds.
Related
I'm doing a Java programming assignment which involves bubble sorting a .dat file BetelgeuseNames.dat with strings in it alphabetically. My AP Computer Science A teacher told me my code is correct, but it still gives the wrong output.
There are three classes called BubbleSort, BubbleSortTimer, and StopWatch. The program runs from BubbleSortTimer.
BubbleSort:
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.io.FileWriter;
import java.io.IOException;
public class BubbleSort {
// Private instance variables:
private ArrayList<String> list;
private int number;
public BubbleSort(ArrayList<String> a_list) {
list = a_list;
}
public void swap(int first, int second) {
String temp1 = list.get(first);
String temp2 = list.get(second);
list.set(first, temp2);
list.set(second, temp1);
}
public int getNumber() {
String numStr;
numStr = JOptionPane.showInputDialog("How many names do you want to sort?");
number = Integer.parseInt(numStr);
return number;
}
public void printSorted() {
try {
FileWriter writer = new FileWriter("sorted.dat");
for (int i = 0; i < number; i++) {
writer.write(list.get(i) + "\n");
}
writer.close();
} catch (IOException exception) {
System.out.println("Error processing file: " + exception);
}
}
public void bubbleSort() {
for (int i = 0; i < number; i++) {
for (int j = 0; j < number - i - 1; j++) {
if (list.get(i).compareTo(list.get(i+1)) > 0) {
swap(i, i + 1);
}
}
}
} // End method
}
BubbleSortTimer:
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JOptionPane;
import java.io.IOException;
public class BubbleSortTimer {
private ArrayList<String> list = new ArrayList<String>();
public void readNames() {
try {
FileReader reader = new FileReader("BetelgeuseNames.dat");
BufferedReader in = new BufferedReader(reader);
boolean done = false;
String name;
while (done == false) {
name = in.readLine();
if (name == null) {
done = true;
} else {
list.add(name);
}
}
reader.close();
} catch (IOException exception) {
System.out.println("Error processing file: " + exception);
}
} // End method
public void runSort() {
readNames();
StopWatch timer = new StopWatch();
BubbleSort sorter = new BubbleSort(list);
int number = sorter.getNumber();
timer.start();
sorter.bubbleSort();
timer.stop();
sorter.printSorted();
String msg = "Number of names sorted: " + number + "\nMilliseconds required to sort: " + timer.getElapsedTime() + "\nOutput file is \"sorted.dat\"";
JOptionPane.showMessageDialog(null, msg);
}
public static void main(String[] args) {
BubbleSortTimer bubble = new BubbleSortTimer();
bubble.runSort();
}
}
StopWatch:
/**
* A stopwatch accumulates time when it is running. You can
* repeatedly start and stop the stopwatch. You can use a
* stopwatch to measure the running time of a program.
* from section 18.2 of Horstmann's CCJ
*/
public class StopWatch {
/**
* Constructs a stopwatch that is in the stopped state
* and has no time accumulated.
*/
public StopWatch() {
reset();
}
/**
* Starts the stopwatch. Times starts accumulating now.
*/
public void start() {
if (isRunning) return;
isRunning = true;
startTime = System.currentTimeMillis();
}
/**
* Stops the stopwatch. Time stops accumulating and is
* added to the elapsed time.
*/
public void stop() {
if (!isRunning) return;
isRunning = false;
long endTime = System.currentTimeMillis();
elapsedTime = elapsedTime + endTime - startTime;
}
/**
* Returns the total elapsed time.
#return the total elapsed time
*/
public long getElapsedTime() {
if (isRunning) {
long endTime = System.currentTimeMillis();
elapsedTime = elapsedTime + endTime - startTime;
startTime = endTime;
}
return elapsedTime;
}
/**
* Stops the watch and resets the elapsed time to 0.
*/
public void reset() {
elapsedTime = 0;
isRunning = false;
}
private long elapsedTime;
private long startTime;
private boolean isRunning;
}
Input:
Moewm
Bmlzvltcso
Aqxjor
Wwgjie
Qqqtpivd
Xgyhaerv
Wqpjwdvxjq
Ecsfnow
Zlptuqxctt
Jhtprwvopk
Expected Output:
Aqxjor
Bmlzvltcso
Ecsfnow
Jhtprwvopk
Moewm
Qqqtpivd
Wqpjwdvxjq
Wwgjie
Xgyhaerv
Zlptuqxctt
Actual Output:
Bmlzvltcso
Aqxjor
Moewm
Qqqtpivd
Wwgjie
Wqpjwdvxjq
Ecsfnow
Xgyhaerv
Jhtprwvopk
Zlptuqxctt
This is how Android did (binary) sorting (edited to fix this situation):
public void binarySort() {
int lo = 0; // sort start
for (int start=lo ; start < number; start++) {
String pivot = list.get(start);
// Set left (and right) to the index where list.get(start) (pivot) belongs
int left = 0;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left].
* pivot < all in [right, start].
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (pivot.compareTo(list.get(mid)) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left] and
* pivot < all in [left, start], so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just reshifter in default case
switch (n) {
case 2: list.set(left + 2,list.get(left + 1));
case 1: list.set(left + 1,list.get(left));
break;
default:
if(n>0){
list.add(left,list.remove(left+n));
}
}
list.set(left,pivot);
}
}
This is how you can do (bubble) sorting:
public void bubbleSort() {
for (int i = 0; i < number; i++) {
for (int j = i + 1; j < number; j++) {
if (list.get(i).compareTo(list.get(j)) > 0) {
swap(i, j);
}
}
}
}
BUBBLE SORTING V/S BINARY SORTING:
OFF TOPIC: As you can compare above, bubble sorting is easier to code/read/understand and is also faster as compared to binary sorting, because binary sorting (actually) uses array recreation many times which ofcourse takes more time compared to swap.
Because there is a problem with your bubbleSort() method. Please try this way.
public void bubbleSort() {
for (int i = 0; i < number; i++) {
for (int j = 1; j < number - i; j++) {
if (list.get(j - 1).compareTo(list.get(j)) > 0) {
swap(j - 1, j);
}
}
}
}
I have to find what is the fastest way to search the max random number from my array within a range
So I create one method that search normal "using one thread" and another one that use threads
I have Class:MaxThread
import java.util.stream.IntStream;
public class MaxThread extends Thread {
private final int from;
private final int to;
public MaxThread(int[] tab, int from, int to) {
this.from = from;
this.to = to;
}
#Override
public void run() {
long start = System.currentTimeMillis();
int max = IntStream.of(from, to)
.max()
.getAsInt();
long end = System.currentTimeMillis() - start;
System.out.println("Max number from threads is : " + max);
System.out.println("Founded in: " + end + " [ms] ");
}
}
Class: Main2
public class Main2{
public static void main(String[] args) {
int[] tab = new int[200000000];
for (int i = 0; i < tab.length; i++) {
tab[i] = random(0, 200000000);
}
int max = searchMax(0, 50000000);
System.out.println("Max number without using threads " + max);
MaxThread maxThread = new MaxThread(tab, 25000000, 150000000);
maxThread.start();
}
public static int random(int start, int end) {
Random rnd = new Random();
return rnd.nextInt(end - start + 1) + start;
}
public static int searchMax(int from, int to) {
long start = System.currentTimeMillis();
int max = IntStream.of(from, to)
.parallel()
.max()
.getAsInt();
long end = System.currentTimeMillis() - start;
System.out.println("Founded in: " + end + " [ms] ");
return max;
}
}
I count the time in ms inside the method but I want to see witch one was the fastest to find the number , but here is where I cannot find out the way to do it.
Can someone give me and hint please?
I have a Runner class which extends Thread. In main class, I have bunch of objects of Runner class which start race at the same time. I want to print the rank of each runner based on the time taken to finish their thread.
private void raceStart() throws InterruptedException
{
long start = System.currentTimeMillis();
Thread.sleep((long) (reaction * 1000));
int track = 100;
int playerLocation = 0;
Random randomDelay = new Random();
double delay = 90 + randomDelay.nextInt(16);
for(int i = 0; i <= track; i++)
{
if(playerLocation == track)
{
long finish = System.currentTimeMillis();
double totalTime = (double)(finish - start) / 1000;
System.out.format("%d %d %d %-12s %-12s %-25s %.3f %.3f%n" , rank, lane, bib, country, lastName, firstName, reaction, totalTime);
}
playerLocation++;
Thread.sleep((long) delay);
}
}
In my main class,
private void run()
{
Runner usainBolt = new Runner(1, 6, 2612, "JAM", "Bolt", "Usain", 0.155);
Runner justinGatlin = new Runner(2, 4, 3069, "USA", "GATLIN", "Justin", 0.152);
Runner andreDeGrasse = new Runner(3, 7, 2196, "CAN", "DE GRASSE", "Andre", 0.141);
Runner yohanBlake = new Runner(4, 9, 2611, "JAM", "BLAKE", "Yohan", 0.145);
Runner akaniSimbine = new Runner(5, 3, 2909, "RSA", "SIMBINE", "Akani", 0.128);
Runner benYoussefMeite = new Runner(6, 8, 2245, "CIV", "MEITE", "Ben Youssef", 0.156);
Runner jimmyVicaut = new Runner(7, 5, 2434, "FRA", "VICAUT", "Jimmy", 0.140);
Runner trayvonBromell = new Runner(8, 2, 3054, "USA", "BROMWELL", "Trayvon", 0.135);
List<Runner> runners = Arrays.asList(usainBolt, justinGatlin, andreDeGrasse,
yohanBlake, akaniSimbine, benYoussefMeite, jimmyVicaut, trayvonBromell);
for (Runner r : runners)
{
r.start();
}
I also want to print the total time taken by the whole program in the end.
I tried
long start = System.currentTimeMillis();
run(0);
long finish = System.currentTimeMillis();
double totalTime = (double)(finish - start) / 1000;
System.out.println("totalTime");
But it always prints 0 or 1 before displaying the results.
Since a lot of this is time recording based, I'd recommend creating a simple StopWatch class that each runner can hold on to and record their individual times.
public class StopWatch {
private long startTime = -1;
private long stopTime = -1;
private long currentTime = 0;
private boolean isRunning = false;
public void start(){
isRunning = true;
startTime = System.nanoTime();
}
public void stop(){
stopTime = System.nanoTime();
}
public long getCurrentTime(){
if (startTime != -1 && stopTime == -1){
currentTime = System.nanoTime() - startTime;
}else if (startTime != -1 && stopTime != -1){
currentTime = stopTime - startTime;
}
return currentTime;
}
public boolean isRunning(){
if(startTime != -1 && stopTime == -1){
isRunning = true;
}
return isRunning;
}
public void reset(){
startTime = -1;
stopTime = -1;
currentTime = 0;
isRunning = false;
}
}
I'm not sure what your Runner class looks like but I've made just a simple one that determines speed randomly and adds a random amount every second to each runner(you can create your own method in Runner to determine how quick each runner is). I would also implement comparable to runner so that you can sort them based on distance traveled and finally overide toString() method in Runner to print the relevant information that will be used for the leaderboard later.
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class Runner extends Thread implements Comparable {
boolean hasFinished = false;
int distanceTraveled = 0;
StopWatch timer = new StopWatch();
Random speed = new Random();
int raceDistanceMeters = 100;
private String nameF;
private String nameL;
public Runner(String nameL, String nameF) {
this.nameF = nameF;
this.nameL = nameL;
}
public void run() {
timer.start();
while(hasFinished == false){
try {
Thread.sleep(1000);
distanceTraveled = distanceTraveled + speed.nextInt(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (distanceTraveled >= raceDistanceMeters){
hasFinished = true;
distanceTraveled = raceDistanceMeters;
timer.stop();
}
}
}
#Override
public int compareTo(Object compareRunner) {
int compareDistanceTraveled = ((Runner)compareRunner).distanceTraveled;
return compareDistanceTraveled-this.distanceTraveled;
}
#Override
public String toString() {
return this.nameF + " " + this.nameL + " " + "Distance: " + distanceTraveled + " Time: " + (Double.valueOf(TimeUnit.NANOSECONDS.toMillis(timer.getCurrentTime())))/1000;
}
}
You can now use ArrayLists of type Runner with Collections.sort and also print each of the runners after sorting.
A Race class makes sense as it will allow some house keeping items related to that specific race such as the runners competing along with printing a leaderboard.
public class Race {
ArrayList<Runner> runners = new ArrayList<>();
public void addRunner(Runner runner){
runners.add(runner);
}
public void start(){
runners.forEach(runner -> runner.start());
}
public void printLeaderboard(){
Collections.sort(runners);
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("-------------------------------------------------------------");
runners.forEach(runner -> System.out.println(runner.toString()));
}
public boolean isRaceOver() {
int count = 0;
for (Runner runner : runners) {
if (runner.hasFinished == true){
count++;
}
}
if (count == runners.size()){
return true;
}
return false;
}
}
So an example of what Main() would look like.
public class Main {
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ArrayList<Runner> runners = new ArrayList<>();
runners.add(new Runner("Bolt", "Usain"));
runners.add(new Runner("GATLIN", "Justin"));
runners.add(new Runner("DE GRASSE", "Andre"));
runners.add(new Runner("BLAKE", "Yohan"));
runners.add(new Runner("SIMBINE", "Akani"));
runners.add(new Runner("MEITE", "Ben Youssef"));
runners.add(new Runner("VICAUT", "Jimmy"));
runners.add(new Runner("BROMWELL", "Trayvon"));
Race race1 = new Race();
runners.forEach(runner -> race1.addRunner(runner));
race1.start();
while (!race1.isRaceOver()){
Thread.sleep(500);
race1.printLeaderboard();
}
System.out.println("Total Run time: " + (Double.valueOf(TimeUnit.NANOSECONDS.toMillis(stopWatch.getCurrentTime())))/1000);
}
}
I need to write a simple program that prints prime numbers up to the given number but no longer than 5 seconds.
Is there some kind of timer to use to interrupt a method after a period of time? (but no interruption if printing is shorter than 5 sec).
Thanks in advance.
My code:
public class Primes {
private static boolean checkIfPrime(int x) {
if (x == 2) return true;
if (x % 2 == 0) return false;
int sqrt = (int) Math.sqrt(x) + 1;
for (int i = 3; i < sqrt; i = i + 2) if (x % i == 0) return false;
return true;
}
private static void printPrimesAndOperationTime(int n) {
long start = System.nanoTime();
for (int i = 2; i <= n; i++) if (checkIfPrime(i)) System.out.println(i);
long end = System.nanoTime();
long timeResult = end - start;
System.out.println("Printing time = " + timeResult + " [ns] => "
+ Math.round(timeResult * 100.0 / 1000000) / 100.0 + " [ms]");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
printPrimesAndOperationTime(n);
}
}
Used Java Concurrency APIs to solve the above problem. please find inline comments for code walk through.
import java.util.Scanner;
import java.util.concurrent.*;
public class TimeoutInterval {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor(); // Start Single thread executor
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Future future = executor.submit(new Primes(n)); // Find prime no.
try {
future.get(5, TimeUnit.SECONDS); // Set the time out of the prime no. search task
executor.shutdown();
} catch (TimeoutException e) {
executor.shutdown();
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
class Primes implements Runnable {
private final int number;
Primes(int number) {
this.number = number;
}
#Override
public void run() {
System.out.println("Started..");
printPrimesAndOperationTime(number);
System.out.println("Finished!");
}
private static boolean checkIfPrime(int x) {
if (x == 2) return true;
if (x % 2 == 0) return false;
int sqrt = (int) Math.sqrt(x) + 1;
for (int i = 3; i < sqrt; i = i + 2) if (x % i == 0) return false;
return true;
}
private static void printPrimesAndOperationTime(int n) {
long start = System.nanoTime();
for (int i = 2; i <= n && !Thread.interrupted(); i++) if (checkIfPrime(i)) {
System.out.println(i);
}
long end = System.nanoTime();
long timeResult = end - start;
System.out.println("Printing time = " + timeResult + " [ns] => "
+ Math.round(timeResult * 100.0 / 1000000) / 100.0 + " [ms]");
}
}
Using ExecutorService, you can submit a task with a timeout. On Receiving the TimeoutException, you should call cancel(true) method on the task to interrupt the thread.
From the documentation
... If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.
I have tried to create a recursive task that divides a set of elements into smaller pieces and runs a series of math works on them, say numerically integration, then tries to use separate results for each element. but it seems that an error occurs before the pool does its works completely. my code tries to reach the elements that are not yet processed.
could you please help me with this?
public void ComputeStiffnessMatrix(DataScanner DS){
ans=new double [2*(DS.getXarray().length)][2*(DS.getXarray().length)];
int nelels=((DS.getNelKsi())*(DS.getNelEta()));
ArrayList<ElementStiffness> elsm=new ArrayList<>();
StiffnessMatrix SM=new StiffnessMatrix(elsm,DS,0,(nelels-1));
ForkJoinPool pool = new ForkJoinPool();
System.out.println("Stiffness Matrix Computation...");
long startTime = System.currentTimeMillis();
pool.invoke(SM);
long endTime = System.currentTimeMillis();
System.out.println("Stiffness Matrix Computation took " + (endTime - startTime) + " milliseconds.");
System.out.println("Arranging into an array...");
long startTime2 = System.currentTimeMillis();
try {
ArrayList<ElementStiffness> kk=(ArrayList<ElementStiffness>) SM.get();
for (int el=0;el<nelels;el++){
ElementStiffness pp=kk.get(el);
System.out.println("EL NO."+el);
double vals[][]=pp.getStiffnessMatrix();
int sup[]=pp.getControlpointsSupport();
for (int i=0;i<sup.length;i++){
for (int j=0;j<sup.length;j++){
ans[(2*sup[i])+0][(2*sup[j])+0]=ans[(2*sup[i])+0][(2*sup[j])+0]+vals[(2*i)+0][(2*j)+0];
ans[(2*sup[i])+0][(2*sup[j])+1]=ans[(2*sup[i])+0][(2*sup[j])+1]+vals[(2*i)+0][(2*j)+1];
ans[(2*sup[i])+1][(2*sup[j])+0]=ans[(2*sup[i])+1][(2*sup[j])+0]+vals[(2*i)+1][(2*j)+0];
ans[(2*sup[i])+1][(2*sup[j])+1]=ans[(2*sup[i])+1][(2*sup[j])+1]+vals[(2*i)+1][(2*j)+1];
}
}
}
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(IGATest.class.getName()).log(Level.SEVERE, null, ex);
}
long endTime2 = System.currentTimeMillis();
System.out.println("Stiffness Matrix rearrangement took " + (endTime2 - startTime2) + " milliseconds.");
try{
FileOutputStream fs=new FileOutputStream("stifmat.tmp");
ObjectOutputStream os=new ObjectOutputStream(fs);
os.writeObject(ans);
os.close();
}catch (IOException e){
e.printStackTrace();
}
ans=null;
}
And the siffnessmatrix class:
public class StiffnessMatrix extends RecursiveTask {
private final int min;
private final int max;
private final DataScanner ds;
ArrayList<ElementStiffness> elsm;
public StiffnessMatrix (ArrayList<ElementStiffness> elsm,DataScanner DS,int min, int max){
this.ds=DS;
this.min=min;
this.max=max;
this.elsm=elsm;
}
protected void compdir(){
for (int i=min;i<=max;i++){
double[] elsp=ds.getElementSpan(i);
Element el=new Element(ds,((elsp[0]+elsp[1])*0.5),((elsp[2]+elsp[3])*0.5));
ElementStiffness els=new ElementStiffness(ds,el);
elsm.add(els);
}
}
#Override
protected ArrayList <ElementStiffness> compute(){
int processors = Runtime.getRuntime().availableProcessors();
if (max-min<processors) {
compdir();
} else {
int center = min + (max - min) / 2;
invokeAll(new StiffnessMatrix(elsm,ds, min, center) , new StiffnessMatrix(elsm, ds, center+1, max));
}
return elsm;
}
}