How to add Node<Integer> list to get average? - java

I am supposed to create a method that calculates the average. I can't figure out why i am having so much trouble. My list has a set of random numbers generated but i keep getting an error in my method saying " Exception in thread "main" java.lang.ArithmeticException: / by zero
at Node.avg(Node.java:58)
at Node.main(Node.java:51)"
public class Node<T>
{
private T data; // data portion
private Node<T> next; // link to next node
public Node(T dataPortion)
{
data = dataPortion;
next = null;
} // end constructor
public Node(T dataPortion, Node<T> nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
public T getData()
{
return data;
} // end getData
public void setData(T newData)
{
data = newData;
} // end setData
public Node<T> getNextNode()
{
return next;
} // end getNextNode
public void setNextNode(Node<T> nextNode)
{
next = nextNode;
} // end setNextNode
public static void main(String[] args)
{
Integer num;
LList<Integer> firstNode = new LList<Integer>();
for (int counter = 0; counter < 5; counter ++)
{
num = new Integer((int)(Math.random() * 100));
firstNode.add(num);
avg(firstNode);
}
}
public static int avg(LList<Integer> firstNode)
{
int count = 0, total = 0;
int avg = total/count;
for (int i = 1; i < 5; i++)
{
total += ((ListInterface<Integer>) firstNode).getEntry(i);
count++;
}
return avg;

You're trying to calculate the average before you find out what the count and the total is.
Right now, you're doing:
int count = 0, total = 0;
int avg = total / count;
// for loop to find count and total
return avg
When you try and find the average, total and count are still equal to zero so naturally you end up with a divide by zero exception. Instead, do the division after the loop:
public static int avg(LList<Integer> firstNode)
{
int count = 0, total = 0;
for (int i = 1; i < 5; i++)
{
total += ((ListInterface<Integer>) firstNode).getEntry(i);
count++;
}
return total / count;
}

You have a bug in here:
int count = 0, total = 0;
int avg = total/count; //HERE
You are initializing count to 0 and then trying to divide by 0 to initialize the avg. That will fail every single time.

you can divid anything by zero
you divided total/count which both are initialized with 0
you should find avg after the for loop

You may want to do the division after the for loop, otherwise it is clear that count is zero:
int count = 0, total = 0;
for (int i = 1; i < 5; i++)
{
total += ((ListInterface<Integer>) firstNode).getEntry(i);
count++;
}
int avg = total/count;
return avg;
Moreover, the average is likely a real number, not an integer. So the calculation is better done as:
double avg = ((double)total) / count;

Related

how to construct an array of 100 elements containing the numbers 1 -100 for which shellsort, with the increments 1 4 13 40 (The worst case)?

This is the original question
"Shell Sort worst case. Construct an array of 100 elements containing the numbers 1 through 100 for which shellsort, with the increments 1 4 13 40, uses as large a number of compares as you can find."
There are 100! permutations for an array of 100 elements, it's terrifying to go through each permutation and find which one has the maximum number of compares. Is there any smarter way to approach this problem? My approach this problem is through violence, but only randomly shuffle the array 100000000 time which is less than 100! and it take me half an hour to get the final output.
I pasted my code below. I appreciate any suggestions from you guys!
`
package ch_2_1;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.Arrays;
public class exer_19
{
public static void main(String[] args)
{
// initial permutation
int[] array = new int[100];
for ( int i = 1; i < 101; i++)
{
array[i-1] = i;
}
// find the worst case and the number of compares
worst_input(array);
}
private static void worst_input(int[] array)
{
int max_count = 0;
int[] copy = new int[100];
int[] worst_case = new int[100];
for ( int i = 0; i < 100000000; i++)
{
int[] temp = generate(array);
for (int j = 0; j < 100; j++){ copy[j] = temp[j];}
Shell_sort operation = new Shell_sort();
operation.shell_sort(temp);
if (operation.compare() > max_count)
{
max_count = operation.compare();
worst_case = copy;
}
System.out.println(i);
}
for ( int s : worst_case){ System.out.print(s + " ");}
System.out.println();
System.out.println(max_count);
System.out.println();
}
private static int[] generate( int[] array)
{
StdRandom.shuffle(array);
return array;
}
private static class Shell_sort // it's necessary to create a private class to hold the shell sort method
// b/c the method must record the # of compares to sort the array, and this # count need to be returned
// to the worst_input method. Therefore, having a class to encapsulate the two methods is very helpful
{
private int count = 0;
private void shell_sort(int[] test)
{
int N = test.length;
int h = 1;
while (h < N/3) h = 3*h + 1; // 1, 4, 13, 40, 121...
while ( h > 0)
{
for ( int i = h; i < N; i++) // starting from the largest h-value th element of the array (simplified: ith element)
{
// if ith element is less than i-h th element, swap the two, continue this process until the condition is not met
for ( int j = i; j >= h && less( test[j], test[j-h]); j = j - h)
{
exchange( test, j, j-h);
count++;
}
}
// when reached the end of the array, update h value
h = h/3;
}
}
private int compare()
{
return count;
}
}
private static boolean less( int current, int previous)
{
return current < previous;
}
private static void exchange(int[] array, int cur_index, int pre_index)
{
int temp = array[pre_index];
array[pre_index] = array[cur_index];
array[cur_index] = temp;
}
}
`

Return a value given an index as input for the Fibonacci sequence

So given this.
//Fibonacci Series using Recursion
class fibonacci
{
static int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
public static void main (String args[])
{
int n = 10;
System.out.println(fib(n));
}
}
How could I transform it so it takes an index as a parameter and returns the given Fibonacci number at that index? So say I put in index = 5 and it should return 8.
static int fib(int index)
{
int counter = 0;
int current = 0;
int previous = 0;
int temp = 0;
while(counter < index)
{
temp = previous;
previous = current;
current += temp;
counter++;
}
return current;
}
If it does not have to be recursive, then I think this might work. Haven't tested it but tried to answer your question
int main(){
int index, temp1 = 0, temp2 = 1, value_at_index = 0;
printf("Enter index: ");
scanf("%d",&index);
if(index==1){
printf("Fib value at index 1 = 1");
}
else{
for (int i = 2; i <= index; ++i){
value_at_index = temp1 + temp2;
temp1 = temp2;
temp2 = value_at_index;
}
printf("Fib value at index %d = ", index);
printf("%d\n", value_at_index);
return 0;
}
}

Successfully converts to binary on odd numbers, fails on even numbers

I have an issue with my Java program. I made a program that takes an integer and converts it to it's value in binary. When the number is odd, there aren't any problems. 15 converts to 1111, 17 converts to 10001 and so on. The issue comes when the number is even. If I put in 16, 18, 20, etc, it just returns 0. Every time. Also, important to note that I get my number by using a recursive method that stops once it arrives at it's number.
Here's my code. Appreciate any help I can get, even if it doesn't solve the problem.
public class binaryConverter {
static int nr = 16;
static int max = 0;
static int[] bin;
static int[] array;
static int finalBin;
public static void main(String[] args) {
maxFinder();
binMaker();
toBinary(array, 0,true);
}
//finds out how many binary numbers are used in order to decide what length to make the array,
//15 = 1111, 10000 = 16 15<16
private static void maxFinder(){
for(int i = 0, n = 1; i<nr; i++){
if(n>nr){
max = i;
break;
}
n*=2; //n doubles for every i loop, starts with one
}
}
//makes a library of standard to binary (0 = 1, 1 = 2; 2 = 4; 3 = 8...)
private static void binMaker(){
int[] temp = new int[max];
for(int i = 0; i<temp.length; i++){
if(i == 0) temp[i] = 1;
else temp[i]=2*temp[i-1];
}
bin = temp;
array = new int[bin.length];
}
//adds the array together in order to access what number the array currently resembles in binary
private static int sum(int[] ar, int length){
int sum = 0;
for(int i = 0; i<=length; i++) if(ar[i]==1) sum += bin[i];
return sum;
}
//loops until the array becomes the number in binary
private static void toBinary(int[] ar, int i, boolean one){ //i = the current number it's on, eg. 10i01, i is the third slot
if(i==array.length) return; //break if
ar[i] = (one) ? 1:0;
if(sum(ar, i)==nr){ //if the temporary array is the number but in binary ...
array = ar; //turns the static array into the temporary array
String temp = "";
for(int z = 0; z<array.length; z++) temp += array[z];
finalBin = Integer.parseInt(temp); //makes finalBin represent the original number but in binary
return;
}
else{ //else go to the next slot
toBinary(ar, i+1, true);
toBinary(ar, i+1, false);
}
}
}
Edit: I have now added the following line to my main:
if(finalBin != nr) toBinary(array,0,false);
System.out.println(finalBin);
This is to make sure that it can start with 0 aswell. However, I still get the incorrect answer, as it gives me pretty seemingly random returns on even numbers.
You starting you recursion always with a one at the first place of the binary:
toBinary(array, 0, true);
This way you never can get an even number. An even number always has a zero at the "first" bit (representing "2 to the power of 0").
You could start the recursion like so:
toBinary(array, 0, true);
if (/* not found a solution */)
toBinary(array, 0, false);
You can use this code as converter and replace String type to some List:
public static String decToBin(int value) {
String result = "";
while (value > 1) {
result += value % 2;
value /= 2;
}
result += value;
result = new StringBuilder(result)
.reverse()
.toString();
return result;
}
This is how you could get it to work:
public class binaryConverter {
static int nr = 16;
static int max = 0;
static int[] bin;
static int[] array;
static int finalBin;
static boolean foundSolution = false;
public static void main(String[] args) {
maxFinder();
binMaker();
toBinary(array, 0, true);
if (!foundSolution)
toBinary(array, 0, false);
for (int i = array.length - 1; i >= 0; i--)
System.out.print(array[i]);
System.out.println();
}
//finds out how many binary numbers are used in order to decide what length to make the array,
//15 = 1111, 10000 = 16 15<16
private static void maxFinder(){
for(int i = 0, n = 1; i<nr; i++){
if(n>nr){
max = i;
break;
}
n*=2; //n doubles for every i loop, starts with one
}
}
//makes a library of standard to binary (0 = 1, 1 = 2; 2 = 4; 3 = 8...)
private static void binMaker(){
int[] temp = new int[max];
for(int i = 0; i<temp.length; i++){
if(i == 0) temp[i] = 1;
else temp[i]=2*temp[i-1];
}
bin = temp;
array = new int[bin.length];
}
//adds the array together in order to access what number the array currently resembles in binary
private static int sum(int[] ar, int length){
int sum = 0;
for(int i = 0; i<=length; i++) if(ar[i]==1) sum += bin[i];
return sum;
}
//loops until the array becomes the number in binary
private static void toBinary(int[] ar, int i, boolean one){ //i = the current number it's on, eg. 10i01, i is the third slot
if(i==array.length || foundSolution) return; //break if
ar[i] = (one) ? 1:0;
if(sum(ar, i)==nr){ //if the temporary array is the number but in binary ...
array = ar; //turns the static array into the temporary array
String temp = "";
for(int z = 0; z<array.length; z++) temp += array[z];
finalBin = Integer.parseInt(temp); //makes finalBin represent the original number but in binary
foundSolution = true;
return;
}
else{ //else go to the next slot
toBinary(ar, i+1, true);
toBinary(ar, i+1, false);
}
}
}

Java Method Definition is Slowing Execution Considerably

I am currently learning Java. Below is a list of methods from a simple Java program I have written. Is there anything that stands out in these methods would cause the execution of the program to go very slow? It's taking four seconds to execute using an array containing just 6 integers:
EDITED: here's the entire program as requested. I wrote it in Textpad. I realise it is not the most efficient algorithm. It does what it is supposed to do, but takes too long to do it.
import java.util.*;
public class Supermarket
{
public static void main(String [] args)
{
int[] custTimes =
{
1, 6, 7, 4, 4, 3, 5, 1, 2, 1, 3, 6, 4
};
int checkOuts = 6;
int answer;
answer = Solution.solveSuperMarketQueue(custTimes, checkOuts);
System.out.println("Answer is " + answer);
}
}//~public class Supermarket...
class Solution
{
static int myTotal;
static int solveSuperMarketQueue(int[] customers, int n)
{
// ******************* INITIALIATION ***********************
myTotal = 0;
int len = customers.length; // length of customer queue
if (len < 1)
{
return 0;
}
int[] till = new int[n]; // array to store all tills and till queues
int tillMin; // Minimum time
int tillMax; // Maximum time
// Put the customers into an arraylist:
ArrayList<Integer> times = new ArrayList<Integer>();
for (int i = 0; i < len; i = i + 1)
{
times.add(i, customers[i]);
}
// create the array of tills and set all queue intial values to 0
for (int i = 0; i < n; n = n + 1)
{
till[i] = 0;
}
// Move the queue to tills to start off
ReturnPair result = copyQueue(till, times);
till = result.getArr();
times = result.getList();
int s = times.size();
tillMax = getMaxTime(till);
tillMin = getMinTime(till);
// ***************** END OF INITIALIATION ******************
// *****************MAIN LOOP ******************************
while (tillMax > 0)
{
// Find customer(s) with least time use that time to move all queues
// and update myTotal time.
// STEP 1: get minimum time in tills array (ignore zero)
tillMin = getMinTime(till);
// STEP 2: subtract minimum value from all the tills, but not if till has a zero
if (tillMin > 0)
{
till = subtractTime(till, tillMin);
}
// Move the queue to tills
if (s > 0)
{
result = copyQueue(till, times);
till = result.getArr();
times = result.getList();
}
tillMax = getMaxTime(till);
tillMin = getMinTime(till);
}
return myTotal;
// **************** END OF LOOP *****************************
}//~public static int solveS...
// ****************** METHODS **********************************
// Method to move queue foward
// For each till, a time is copied from the customer array.
// The values are copied in order.
// The value is coped only if array value is zero.
private static ReturnPair copyQueue(int[] arr, ArrayList<Integer> arrList)
{
int n = arr.length; // for each till...
for (int i = 0; i < n; i = i + 1)
{
if (arr[i] == 0 && arrList.size() > 0) // only copy if it current till value is 0 AND arrayList value exists
{
arr[i] = arrList.get(0);
arrList.remove(0);
}
}
// returns an instance of the object myResult which is a container for an array and an arraylist
return new ReturnPair(arr, arrList);
}
// Method to get minimum time from array (but not zero).
private static int getMinTime(int[] arr)
{
int minValue = 0;
// make sure arr[i] isn't zero.
for (int i = 0; i < arr.length; i = i + 1)
{
if (arr[i] != 0)
{
minValue = arr[i];
break;
}
}
// Find minimum value that isn't zero.
for (int i = 1; i < arr.length; i = i + 1)
{
if (arr[i] != 0 && arr[i] < minValue)
{
minValue = arr[i];
}
}
return minValue;
}//~static int getMinTime(in...
// Method to subtract minimum time from tills
private static int[] subtractTime(int[] arr, int min)
{
int n = arr.length;
for (int i = 0; i < n; i = i + 1)
{
if (arr[i] != 0)
{
arr[i] = arr[i] - min;
}
}
// update myTotal
myTotal = myTotal + min;
return arr;
}//~static void subtractTime...
private static int getMaxTime(int[] arr)
{
int maxValue = arr[0];
for (int i = 1; i < arr.length; i = i + 1)
{
if (arr[i] > maxValue)
{
maxValue = arr[i];
}
}
return maxValue;
}
}//~class Solution...
// Special class designed to return an array and an array list as an object
class ReturnPair
{
// set up fields
int[] newArr;
ArrayList<Integer> newArrList;
// define method
public ReturnPair(int[] first, ArrayList<Integer> second)
{
this.newArr = first;
this.newArrList = second;
}
public int[] getArr()
{
return newArr;
}
public ArrayList<Integer> getList()
{
return newArrList;
}
}
for (int i = 0; i < n; n = n + 1)
This line is incrementing n instead of i. it will loop until n overflows. It should be:
for (int i = 0; i < n; i++)
Because int arrays are initialized to 0 anyway, you can remove this loop completely.

Identify the maximum times consequently happens character and returns the starting index

Here is my code ,
Find me the way to finish this off .
I had this question in paper this is the code at that time I could do.
In following example it should return 3.(starting point of "d")
public class HelloWorld {
public static void main(String []args){
int result = getMax("haaddddddddccf");
System.out.println(result);
}
public static int getMax(String input){
int length = input.length();
int count = 0;
int max = 0;
int tempCount = 0;
for(int i=0;i<length-1;i++) {
if(input.charAt(i) == input.charAt(i+1)) {
count ++ ;
}
tempCount = count;
count = 0;
if(max > tempCount) {
max = tempCount;
return i;
}
tempCount = 0;
}
return 0;
}
}
How about something like this:
public class HelloWorld {
public static void main(String []args){
int result = getMax("haaddddddddccf");
System.out.println(result);
}
public static int getMax(String input){
int length = input.length();
int maxIndex = 0;
int max = 0;
int count = 1;
char current = input.charAt(0);
int index = 0;
for(int i=1; i<length-1; i++) {
if(input.charAt(i) == current) {
count ++ ;
if(count > max) {
max = count;
maxIndex = index;
}
}
else {
count = 1;
current = input.charAt(i);
index = i;
}
}
return maxIndex;
}
}
This goes over the entire string and counting consecutive occurrences of characters. If the count goes over the observed maximum, the start index of that series of consecutive characters is saved as well as the number of characters. If the character changes, the current values reset and counting starts over. After going over the entire list, the index of the longest series of consecutive characters is in maxIndex.

Categories