computing an average from an array list - java

I get an error for
sum = sum + arr[i]; // "i cannot be resolved to a variable"
Why is that?
"i" was declared earlier and I'm trying to use the value arr[i] to find and average of an arraylist from a text file called numbers.txt
public class Statistics {
public static void main(String[] args) {
int [] numbers = readFiles("./bin/q1/numbers.txt");
System.out.println(Arrays.toString(numbers));
}
private static int[] readFiles(String file) {
try {
File f = new File(file);
Scanner s = new Scanner(f);
int ctr = 0;
//counting number of integers in numbers.txt
while (s.hasNextInt()) {
ctr++;
s.nextInt();
}
int [] arr = new int[ctr];
Scanner s1 = new Scanner(f);
//reads integers from file and assigns it to array
for (int i = 0; i < arr.length; i ++)
arr[i] = s1.nextInt();
int sum = 0;
sum = sum + arr[i];
float average = sum / (float) arr.length;
System.out.println("average of array is: " + average + "\n");
System.out.println("length of array is: " + arr.length + " integers \n");
return arr;
}
catch (Exception e) {
return null;
}
}
};

The problem you encounter is, the i you declared only exists in the previous for-loop
//reads integers from file and assigns it to array
for (int i = 0; i < arr.length; i ++)
arr[i] = s1.nextInt();
The i will be destroyed after for-loop, which means you cannot access the i anymore, you may find more details in here
To solve your problem, you have many options, for example:
Created another for-loop
//reads integers from file and assigns it to array
for (int i = 0; i < arr.length; i ++)
arr[i] = s1.nextInt();
int sum = 0;
for (int i = 0; i < arr.length; i ++)
sum = sum + arr[i];
float average = sum / (float) arr.length;
Include in the previous for-loop
//reads integers from file and assigns it to array
int sum = 0;
for (int i = 0; i < arr.length; i ++) {
arr[i] = s1.nextInt();
sum = sum + arr[i];
}
float average = sum / (float) arr.length;

Related

Java How do i repeat sort until no swaps are done in bubblesort?

I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}

Merging 2 Array and Removing Duplicate inputs

im having a problem on how to remove duplicate value on an array,can anyone help me?
I have this code made to just merge 2 arrays and displaying the result but i dont know how to remove the duplicate inputs. (im sorry i just started learning java.)
public static void main(String... args) {
int[] x = new int[3];
int[] y = new int[3];
int[] xy = new int[6];/***new array to hold the integers of arrays x and y ****/
int temp, c = 0;
Scanner myInput = new Scanner(System.in);
/*** input of array x at the same time storing the integers to array xy ***/
System.out.println("enter 3 integers for array x:");
for (int a = 0; a < 3; a++) {
x[a] = myInput.nextInt();
xy[c] = x[a];
c++;
}
/*** input of array y at the same time storing the integers to array xy ***/
System.out.println("enter 3 integers for array y:");
for (int b = 0; b < 3; b++) {
y[b] = myInput.nextInt();
xy[c] = y[b];
c++;
}
/*sorting...*/
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5 - i; j++) {
if (xy[j] > xy[j + 1]) {
temp = xy[j];
xy[j] = xy[j + 1];
xy[j + 1] = temp;
}
}
}
/*printing of array xy sorted*/
for (int w = 0; w < 6; w++)
System.out.print(xy[w] + " ");
}
Since you have sorted your merged array a simplified solution is to not remove the duplicate but instead filter them out when printing by comparing the current value in the loop to the previous
System.out.print(xy[0] + " ");
for (int w = 1; w < 6; w++) {
if (xy[w] != xy[w - 1]) {
System.out.print(xy[w] + " ");
}
}

Stuck on Discrete distribution having an issue with finishing the problem

Here is what I am suppose to be getting.
This is what I am actually getting.
Write a program DiscreteDistribution.java that takes an integer command-line argument m, followed by a sequence of positive integer command-line arguments a1,a2,…,an, and prints m random indices (separated by whitespace), choosing each index i with probability proportional to ai.
So far I have
public static void main(String[] args) {
// number of random indices
int m = Integer.parseInt(args[0]);
// read in frequency of occurrence of n values
int n = args.length;
int[] freq = new int[n];
for (int i = 0; i < n; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 0; i < n; i++) {
total += freq[i];
}
for (int j = 0; j < m; j++) {
// generate random integer with probability proportional to frequency
int r = (int) ((total) * Math.random() - 1); // integer in [0, total)
int sum = 0;
int event = -1;
for (int i = 0; i < n && sum <= r; i++) {
sum += freq[i];
event = i;
System.out.println(freq[i]);
}
}
}
Under the assumption that I understand your problem correctly, then you can use the following algorithm to produce m random numbers in the range 1 to n according to the given frequencies:
public static void main(String[] args) {
// number of random indices
int m = Integer.parseInt(args[0]);
// read in frequency of occurrence of n values
int n = args.length;
int[] freq = new int[n];
for (int i = 1; i < n; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 1; i < n; i++) {
total += freq[i];
}
double[] summedProbabilities = new double[n];
for (int i = 1; i < summedProbabilities.length; i++) {
final double probability = freq[i] / (double) total;
summedProbabilities[i] = summedProbabilities[i -1] + probability;
}
for (int j = 0; j < m; j++) {
// generate random integer with probability proportional to frequency
double randomProbability = Math.random();
int i = 1;
while (randomProbability > summedProbabilities[i]) {
i++;
}
System.out.print(i + " ");
if (j % 10 == 0) {
System.out.println();
}
}
}
I strongly suggest you to refactor the code in a way that you use methods to calculate small pieces and compose it then.
public class DiscreteDistribution{
public static void main(String[] args) {
// takes in number of times we must loop to print indices
int m = Integer.parseInt(args[0]);
// set the array size to the number of input from command line
//minus the first input
//because we are not considering the input at args[0]
int [] n = new int[args.length-1];
// cSum to store the cummulatives
int [] cSum = new int[args.length];
// to store an array of random generated
//number of size m
int [] rand = new int[m];
int count = 1;
int cCount = 1;
int sum = 0; // to add the inputs n;
// to store user input in an array in n ignoring the first input
for(int i =0; i < n.length; i++)
{
n[i] = Integer.parseInt(args[count]);
count++;
}
//stores the cummulatives of n in cSum
for(int j = 0; j < n.length; j++)
{
sum = sum + n[j];
cSum[j+1] = sum;
}
//generate a random number and stores in rand representing the //probabilites
for(int p = 0; p < m; p++) {
int r = (int)(1+Math.random()*cSum[cSum.length-1]);
rand[p] = r;
}
// loop from 0 to m to print the indices of n;
for(int s = 0; s < m; s++) {
//prints the indices corresponding to the condition
for(int q = 1; q < n.length; q++) {
if(rand[s] <= cSum[q-1]) {
System.out.print(q+" ");
}
}
}
}

How to find the sum of all the numbers entered before or after finding the Sorted array list?

I have written a program in ArrayList to find the sorted array. But I have to find the sum of the numbers entered as well.
I couldn't succeed in getting the results as it is in the array list
import java.util.ArrayList;
import java.util.Scanner;
public class project1 {
public static void main(String[] args) {
int add = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter 5 numbers: ");
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 5; i++) list.add(input.nextInt());
System.out.println("add" +add);
System.out.println("Sorting numbers...");
sort(list);
System.out.println("Displaying numbers...");
System.out.println(list);
}
public static void sort(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i++) {
int currentMin = list.get(i);
int currentIndex = i;
for (int j = i + 1; j < list.size(); j++) {
if (currentMin > list.get(j)) {
currentMin = list.get(j);
currentIndex = j;
}
}
if (currentIndex != i) {
list.set(currentIndex, list.get(i));
list.set(i, currentMin);
}
}
}
}
I am looking to get the sum of the entered numbers along with sorting. Any help will be very appreciated.
change this
for (int i = 0; i < 5; i++) list.add(input.nextInt());
to this
int sum = 0;
for (int i = 0; i < 5; i++){
int num = input.nextInt();
list.add(num);
sum += num;
}
the value of the sum is saved inside sum and you can do what ever you want with it.
I am using the For loop to add the values the user entered to a var name sum that is located out side of the for loop and when the for loop is done you have the sum
You could just write sum += currentMin at the bottom of the for (int i; ... loop. This way you count every number exactly once, after it is put in its final place.
ArrayList<Integer> list = new ArrayList<>();
int sum = 0
for (int i = 0; i < 5; i++) {
int in = input.nextInt();
sum = sum + in;
list.add(in);
}

How to swap the largest number with the last number in an array?

I'm trying to create a program that asks the user to input a number which is how many random numbers between 1-100 will be generated in an array. Then I want the largest number to be swapped with the last number and the smallest number to be swapped with the first number. Here is my code so far:
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
}
if (myArray[i] < smallest) {
smallest = myArray[i];
}
}
for (int j = 1; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
}
}
}
I can't seem to get the numbers to properly swap. I created a loop which determines the smallest and largest numbers from the ones generated and these are stored. Then I create a loop which performs the necessary swaps but I can't seem to get it to work properly. It works fine for swapping the largest number with the last number but most of the time(not always) the outputted last number is also present somewhere else in the array. Here is what I mean:
input: 10
output: 62 48 34 0 91 14 64 60 91
I know there is a swapper method that I could use but I want to do it by manually swapping the numbers. Any help is appreciated, thanks.
you have one simple mistake, your loop should start from '0' when you perform the swap
for (int j = 0; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
Instead of a loop do
//find and stores poition of small
int smallPos = myArray.indexOf(small);
//stores tge values at 0
int tempSmall = myArray[0];
//swaps the values
myArray[0] = small;
myArray[smallPos] = smallTemp;
Just repeat this with the largest value and print it using a for loop. Tell me if it works.
I just tried this. Hope this helps.
public class App {
static int[] a = new int[100];
public static void main(String[] args) {
int i;
for(i = 0; i<a.length;i++)
a[i] = (int)(java.lang.Math.random() * 100);
int smallest = 0, largest = 0;
for(i =1; i<a.length; i++){
if(a[i] < a[smallest])
smallest = i;
if(a[i] > a[largest])
largest = i;
}
swap(0,smallest);
swap(a.length-1,largest);
for(i =0; i<a.length;i++)
System.out.print(a[i] + " ");
}
public static void swap(int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Your last loop doesn't do anything loopy. It just does the same thing over and over. And what it does is not correct. It is swapping the smallest into the first element but it's not moving the first element anywhere: it's gone.
You need to keep track of where the largest and smallest elements were. Your swap logic doesn't take that into consideration.
Write this code
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
int pos1,pos2;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
pos1=i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
pos2=i;
}
}
myArray[pos1]=myArray[myArray.length-1];
myArray[myArray.length-1]=largest;
myArray[pos2]=myArray[0];
myArray[0]=smallest;
for (int j = 1; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
}
i would advise against using a scanner or random values for testing since the result cannot be reproduced (at least not in an easy way). Be careful with what is an arrays index and what is the value at a specific index. This can lead to confusion very quickly. ^^
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
private static int[] myArray;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
//int num = scan.nextInt(); //skip this for testing ^^-d
int num = 10;
myArray = new int[num];
for (int i = myArray.length-1; i > 0; i--) {
//int randomInt = randomGenerator.nextInt(100);
int randomInt = i; //use test condition that can be reproduced!
myArray[i] = myArray.length-i;
}
int smallest = 0;
int largest = 0;
int smallestIndex = 0;
int largestIndex = 0;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
largestIndex = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
smallestIndex = i;
}
}
switchIndexOfmyArray(0, smallestIndex);
switchIndexOfmyArray(myArray.length-1, largestIndex);
for (int j = 0; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
public static void switchIndexOfmyArray(int index, int switchWithIndex){
int temp = myArray[index];
myArray[index] = myArray[switchWithIndex];
myArray[switchWithIndex] = temp;
}
}
Yielding
0 1 8 7 6 5 4 3 2 9
I admit i was slow on this one since i am hungry and tired xD
Happy coding! ^^
You did well by finding smallest and largest. Issue was in swap. I refactor the swap method. May be it works.
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
System.out.println();
int smallest = myArray[0];
int largest = myArray[0];
int sIndx = 0;
int lIndx = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
lIndx = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
sIndx = i;
}
}
System.out.println();
System.out.println("Smallest = "+smallest);
System.out.println("largest = "+largest);
System.out.println("Smallest Index = "+sIndx);
System.out.println("largest Index = "+lIndx);
swapSmallAndLargest(num, myArray, sIndx, lIndx);
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
}
private static void swapSmallAndLargest(int num, int[] myArray, int sIndx, int lIndx) {
int temp = 0;
temp = myArray[sIndx];
myArray[sIndx] = myArray[0];
myArray[0] = temp;
temp = myArray[lIndx];
myArray[lIndx] = myArray[num-1];
myArray[num-1] = temp;
}
}

Categories

Resources