I have a program that sorts though a text file and pulls out the maximum value using 10 threads. How can I then sort through the 10 threads and find the highest value of those 10? My logic would be to store each result in an array and compare that result to the previous, but I'm unsure on how to properly implement it with threading. I added this for loop but it's not correct.Any help would be greatly appreciated!
for (int x = 0; max <=max; x++) {
max = worker.getMax();
System.out.println("Final Max " = max);
}
This is the actual program including the code above. It runs fine without this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class datafile{
public static void main(String[] args) throws IOException {
int[] array = new int[100000];
int count;
int index = 0;
String datafile = "dataset529.txt"; //string which contains datafile
String line; //current line of text file
try (BufferedReader br = new BufferedReader(new FileReader(datafile))) { //reads in the datafile
while ((line = br.readLine()) != null) { //reads through each line
array[index++] = Integer.parseInt(line); //pulls out the number of each line and puts it in numbers[]
}
}
Thread[] threads = new Thread[10];
worker[] workers = new worker[10];
int range = array.length / 10;
for (count = 0; count < 10; count++) {
int startAt = count * range;
int endAt = startAt + range;
workers[count] = new worker(startAt, endAt, array);
}
for (count = 0; count < 10; count++) {
threads[count] = new Thread(workers[count]);
threads[count].start();
}
boolean isProcessing = false;
do {
isProcessing = false;
for (Thread t : threads) {
if (t.isAlive()) {
isProcessing = true;
break;
}
}
} while (isProcessing);
for (worker worker : workers) {
System.out.println("Max = " + worker.getMax());
}
for (int x = 0; max <=max; x++) {
max = worker.getMax();
System.out.println("Final Max " = max);
}
}
public static class worker implements Runnable {
private int startAt;
private int endAt;
private int randomNumbers[];
int max = Integer.MIN_VALUE;
public worker(int startAt, int endAt, int[] randomNumbers) {
this.startAt = startAt;
this.endAt = endAt;
this.randomNumbers = randomNumbers;
}
#Override
public void run() {
for (int index = startAt; index < endAt; index++) {
if (randomNumbers != null && randomNumbers[index] > max)
max = randomNumbers[index];
}
}
public int getMax() {
return max;
}
}
}
Basically your max calculation was wrong. Here is the corrected code.
int finalMax = workers[0].getMax(); //Sets max as first worker's max
for (int x = 1; x < workers.length; x++) {
if(finalMax < workers[x].getMax())//checks whether finalMax is less than worker's max at x'th position and if yes assigns it to finalMax
finalMax = workers[x].getMax();
}
System.out.println("Final Max " + finalMax );
Related
I'm new to Java. I've spent hours trying to figure out why this code doesn't work. It's supposed to take user input integers separated by whitespace, and load them into an int array. Then, the numbers are supposed to be sorted in descending order, and the frequency of repeated inputs has to be displayed in a separate int array.
I'm getting zeroes in the output though. Can anyone help me fix this program?
This is what I have:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] inputNumbers = new int[50];
int[] ocurrences = new int[50];
int size = 0;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
System.out.println("Enter eaach of the numbers. Please put a space between each number.");
String arrayString = input.next();
input = new Scanner(arrayString);
while(input.hasNextInt())
{
int nextNumber = input.nextInt();
if(!isInArray(inputNumbers, size, nextNumber))
{
inputNumbers[size] = nextNumber;
ocurrences[size] = 1;
size++;
}
else
{
int index = search(inputNumbers, size, nextNumber);
ocurrences[index]++;
}
}
sort(inputNumbers, ocurrences, size);
System.out.println("N\t\tCount");
for(int i = 0; i < size; i++)
{
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
}
public static void sort(int[] inputNumbers, int[] ocurrences, int size)
{
for(int current = 0; current < size; current++)
{
int max = current;
for(int i = current; i < size; i++)
{
if(inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return true;
}
return false;
}
}
The current output is:
How many numbers to enter? (At most 50)
4
Enter eaach of the numbers. Please put a space between each number.
5 5 4 7 8
N Count
5 1
0 0
0 0
0 0
0 0
BUILD SUCCESSFUL (total time: 11 seconds)
It should have been something like
N Count
8 1
7 1
5 2
4 1
Initialize the array where we know the exact size, so it avoid unnecessary memory utilization.
Also input.next() will read only the next complete token not the entire line. That was the mistake in the code.
Finally the scanner resource was not closed.
I have refactored your code, please check it.
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
int[] inputNumbers, ocurrences;
int index = 0, size;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
inputNumbers = new int[size];
ocurrences = new int[size];
System.out.println("Enter each of the numbers. Please put a space between each number.");
for (int i = 0; i < size; i++) {
int nextNumber = input.nextInt();
if (!isInArray(inputNumbers, nextNumber)) {
inputNumbers[index] = nextNumber;
ocurrences[index] = 1;
index++;
} else {
int oIndex = search(inputNumbers, nextNumber);
ocurrences[oIndex] ++;
}
}
sort(inputNumbers, ocurrences);
System.out.println("N\t\tCount");
for (int i = 0; i < index; i++) {
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
} finally {
input.close();
}
}
public static void sort(int[] inputNumbers, int[] ocurrences) {
int size = inputNumbers.length;
for (int current = 0; current < size; current++) {
int max = current;
for (int i = current; i < size; i++) {
if (inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return true;
}
return false;
}
The time-limit-extended is the status when executing the successfully compiled class file of the following code.
import java.io.*;
public class CandidateCode {
public static int ThirstyCrowProblem(int[] input1, int input2, int input3) {
int[] arrK = new int[input3];
int minstones = 0;
for (int i = 0; i < input3; i++) //create an array of k Os.
{
int smallest = input1[0], place = 0;
for (int j = 0; j < input2; j++) {
if ((smallest >= input1[j]) && (input1[j] >= 0)) {
smallest = input1[j];
place = j;
}
}
input1[place] = -1;
arrK[i] = smallest;
}
int n = input2, i = 0;
while (i < input3)
minstones = minstones + arrK[i] * (n - i);
return minstones;
}
public static void main(String[] args) {
int[] arr = new int[] {
5, 58
};
int stones_min = CandidateCode.ThirstyCrowProblem(arr, 2, 1);
System.out.println("The result is" + stones_min);
}
}
The cursor is waiting and waiting, but I don't think there is an error in the code!??
Option A :
Change your while into an if statement :
if(i<input3) {
minstones= minstones + arrK[i]*(n-i);
}
Option B : or increment i (i++) but I don't this that's what you want
while(i<input3) {
minstones = minstones + arrK[i]*(n-i);
i++;
}
You need to increment i in your while loop.Since you are not incrementing,its going in infinite loop.
while(i<input3)
{
minstones= minstones + arrK[i]*(n-i);
i++;
}
After making this change,I got
The result is10
I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);
I am trying to write the Count inversion algorithm. It works on an array of size 10. However, things went terribly wrong, when I tried to test on an array of size 100000. I was still able to sort the array but the number of inversions is NEGATIVE, which is wrong. I don't understand which part of my logic went wrong.
My main logic: I created an array object called myArray and it has a CountSplitInv instance method that is suppose to sort the sub-arrays and return number of inversions involved.
Please help me out. I have been stuck in this for a long time now and I still wasn't able to figure out what went wrong.
I have a feeling that I don't understand Recursion concept fully.
import java.io.*;
import java.util.*;
import java.math.*;
class myArray{
private int[] input_array;
private int nElems;
public myArray(int max){
input_array = new int[max];
nElems = 0;
}
public void insert(int value){
input_array[nElems++] = value;
}
public void display(){
for(int j = 0; j < nElems; j++){
System.out.print(input_array[j] + " ");
}
System.out.println("");
}
public void SortAndCount(){
int[] output_array = new int[nElems];
int ans = SortNInversionCounts(output_array,0, nElems -1);
System.out.println("number of inversions IS: " + ans);
}
public int SortNInversionCounts(int[] output_array, int lowerBound, int upperBound){
if(lowerBound == upperBound){
return 0;
} else{
int mid = (lowerBound + upperBound)/2;
int x, y , z;
x = SortNInversionCounts(output_array, lowerBound, mid);
y = SortNInversionCounts(output_array, mid+1, upperBound);
z = CountSplitInv(output_array, lowerBound, mid+1, upperBound);
return x + y + z;
}
}
public int CountSplitInv(int[] output_array, int lowPtr, int highPtr, int upperBound){
int j = 0;
int lowerBound = lowPtr;
int mid = highPtr - 1;
int n = upperBound - lowerBound + 1;
int numOfInversions = 0;
while(lowPtr <= mid && highPtr <= upperBound){
if( input_array[lowPtr] < input_array[highPtr]){
output_array[j++] = input_array[lowPtr++];
} else{
output_array[j++] = input_array[highPtr++];
// WHERE I count number of inversions
numOfInversions = numOfInversions + (mid - lowPtr + 1);
}
}
while(lowPtr <= mid){
output_array[j++] = input_array[lowPtr++];
}
while(highPtr <= upperBound){
output_array[j++] = input_array[highPtr++];
}
for(j = 0; j < n; j++){
input_array[lowerBound+j] = output_array[j];
}
return numOfInversions;
}
}
class NumOfInversionsApp{
public static void main(String[] args) throws IOException{
// Read input file
FileInputStream fil = new FileInputStream("IntegerArray.txt");
BufferedReader br = new BufferedReader( new InputStreamReader(fil));
myArray in_array = new myArray(100000);
String element = null;
while( ( element = br.readLine()) != null){
in_array.insert( Integer.parseInt(element) );
}
// input_array.display();
in_array.SortAndCount();
// input_array.display();
}
}
I made 2 small scripts in physics today, but now it is starting to bug me.
The first script, is 100% accurate: It is used to calculate the number of bill and coins required for the desired amount of cash.
First Script:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Change {
static Money[] coins;
static int[] counts;
public static void main(String[] args) throws IOException {
coins = new Money[11];
counts = new int[11];
coins[0] = new Money(100);
coins[1] = new Money(50);
coins[2] = new Money(20);
coins[3] = new Money(10);
coins[4] = new Money(5);
coins[5] = new Money(2);
coins[6] = new Money(1);
coins[7] = new Money(25, true);
coins[8] = new Money(10, true);
coins[9] = new Money(5, true);
coins[10] = new Money(1, true);
System.out.println("Please type the change:\n");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String values = br.readLine();
String[] split = values.split("\\.");
System.out.println();
int whole = Integer.parseInt(split[0]);
int small = Integer.parseInt(split[1]);
for (int i = 0; i < 7; i++) {
while (whole >= coins[i].getValue()) {
whole -= coins[i].getValue();
counts[i]++;
}
}
for (int i = 7; i < 11; i++) {
while (small >= coins[i].getValue()) {
small -= coins[i].getValue();
counts[i]++;
}
}
for (int i = 0; i < 11; i++) {
if (counts[i] > 0)
System.out
.println((coins[i].getValue() == 100 ? "" : " ")
+ (coins[i].isDecimal() ? (" 0."
+ (coins[i].getValue() < 10 ? "0" : "") + coins[i]
.getValue()) + ": " + counts[i]
: ((coins[i].getValue() <= 5 ? " " : "") + coins[i]
.getValue())
+ ".00: "
+ counts[i]));
}
}
public static class Money {
int value;
boolean decimal;
Money(int value) {
this(value, false);
}
Money(int value, boolean decimal) {
this.value = value;
this.decimal = decimal;
}
boolean isDecimal() {
return decimal;
}
int getValue() {
return value;
}
}
}
Second script:
import java.io.IOException;
public class ChangeMax {
static Money[] coins;
static int[] nums = new int[2];
static int max = -2147483648;
public static void main(String[] args) throws IOException{
coins = new Money[11];
coins[0] = new Money(100);
coins[1] = new Money(50);
coins[2] = new Money(20);
coins[3] = new Money(10);
coins[4] = new Money(5);
coins[5] = new Money(2);
coins[6] = new Money(1);
coins[7] = new Money(25, true);
coins[8] = new Money(10, true);
coins[9] = new Money(5, true);
coins[10] = new Money(1, true);
for(int i = 0; i < 100; i++){
int temp1 = i;
for(int h = 1; h < 100; h++){
int temp2 = h;
int[] counts = new int[100];
for (int j = 0; j < 7; j++) {
while (temp1 >= coins[j].getValue()) {
temp1 -= coins[j].getValue();
counts[j]++;
}
}
for (int k = 7; k < 11; k++) {
while (temp2 >= coins[k].getValue()) {
temp2 -= coins[k].getValue();
counts[k]++;
}
}
int sum = 0;
for(int p : counts){
sum += p;
}
if(sum > max){
max = sum;
nums[0] = i;
nums[1] = h;
}
}
}
System.out.println("\nMax coins and bills required at: $"+nums[0]+"."+(nums[1] > 9 ? nums[1] : "0" + nums[1]) + ": "+max+"\n");
}
public static class Money {
int value;
boolean decimal;
Money(int value) {
this(value, false);
}
Money(int value, boolean decimal) {
this.value = value;
this.decimal = decimal;
}
boolean isDecimal() {
return decimal;
}
int getValue() {
return value;
}
}
}
The second script, does the same thing, but runs through all the values under $100.
The problem is, is that the second script says the max amount is 9, and achieved at $0.94.
The first, script, when you type something like $1.94, does not register that 10 is the new highest number, instead of 9.
What seems to be the problem?
Since I am not planning on doing your homework I am not going to provide you with working code, but both scripts can be easily improved
1) Your money objects know whether a value of e.g. 10 represents 10 whole dollars, or 10 cents (or whatever you use in America, I would use Euro's and cents). But still you use an hard-coded index of your array where you switch from dollars to cents
2) The first script will fail when somebody uses a nice rounded number as input, without decimal part
3) If you would convert your input first to cents, and all your values in your coin array as well, your code will end up much cleaner and easier to understand. Something in the form of
int startAmount = ... ;//in cents
int remainder = startAmount;
int coinCounter = new int[coins.length];
for ( int i = 0; i < coins.length; i++ ){
int currentCoin = coins[i];//in cents
coinCointer[i] = 0;
while( remainder >= currentCoin ){
coinCointer[i] = coinCointer[i] + 1;
remainder = remainder - currentCoin;
}
}
//print out by looping over coinCounter,
//and use the info contained in the Money class