I am working on an assignment to create a bar graph using Java using random numbers, but I do not know how to code it properly, it keeps on giving errors when I move on to the next step.
public class BinSort {
final int N_BINS = 0; //number of bins
final int N_SAMPLES = 0; //total random integers
final float BIN_WIDTH = 0; //width of the bin
int [] nums; //generate and store random numbers
int [] binCount; //array
int max = 0; //largest random number = (max-1)
public void main(String[] args) {
int nBins, nSamples; //initializers
BIN_WIDTH = (float) (max/N_BINS); //calculate BIN_WIDTH
nums = new int[] {}; //initialize nums array
for (int i = 0; i < max; i++) {
int array = nums[i];
}
}
public void generateBins() {
int bin;
int [] binCount = new int [N_BINS]; //set binCount array with N_BINS elements
for (int i = 0; i < N_SAMPLES; i++) {
int array = binCount[i];
bin = (int) Math.floor(nums[i]/BIN_WIDTH);
}
}
public void printBins() {
float freq;
for(int i = 0; i < binCount.length; i++) {
freq = (binCount[i]/N_SAMPLES);
System.out.print(N_SAMPLES + " random integers in " + binCount + " sorted into " + N_BINS + " bins:");
float binMin = i * BIN_WIDTH;
float binMax = binMin + BIN_WIDTH;
System.out.println(binCount[i] + freq + binMin + binMax);
}
}
}
This code is incomplete, but I do not know what to do next. So, I am stuck.
Can someone please help me?
Edit: The program does not compile after running in eclipse. It says the execution is terminated in the console.
Only static variables can be used in the static method . Below code is compiling fine:
public class BinSort {
static final int N_BINS = 0; //number of bins
static final int N_SAMPLES = 0; //total random integers
static float BIN_WIDTH = 0; //width of the bin
static int [] nums; //generate and store random numbers
int [] binCount; //array
static int max = 0; //largest random number = (max-1)
public static void main(String[] args) {
int nBins, nSamples; //initializers
BIN_WIDTH = (float) (max/N_BINS); //calculate BIN_WIDTH
nums = new int[] {}; //initialize nums array
for (int i = 0; i < max; i++) {
int array = nums[i];
}
}
public void generateBins() {
int bin;
int [] binCount = new int [N_BINS]; //set binCount array with N_BINS elements
for (int i = 0; i < N_SAMPLES; i++) {
int array = binCount[i];
bin = (int) Math.floor(nums[i]/BIN_WIDTH);
}
}
public void printBins() {
float freq;
for(int i = 0; i < binCount.length; i++) {
freq = (binCount[i]/N_SAMPLES);
System.out.print(N_SAMPLES + " random integers in " + binCount + " sorted into " + N_BINS + " bins:");
float binMin = i * BIN_WIDTH;
float binMax = binMin + BIN_WIDTH;
System.out.println(binCount[i] + freq + binMin + binMax);
}
}
}
Related
The purpose of this project is to create two arrays of random numbers and run a quick sort and heap sort of them. Keep track of the number of comparison's and then compare them. Both sorts work, but my heap sort wont keep track of the comparison's. it just says 0. My quick sort works and puts the comparisons in an array. How do i fix this?
package sorting;
import java.util.Arrays;
//import java.util.Random;
import java.util.*;
public class project2
{
static int [] heap_sort_comparison = new int[21];
static int [] quick_sort_comparison = new int[21];
static int [] array1 = new int [20];
static int [] array2 = new int [20];
static int compares = 0;
static int heap_compares = 0;
private static void quickSort(int[] array1, int l, int h) {
if(l < h ) {
compares++;
int position = partition(array1, l, h);
quickSort(array1,l, position -1);
quickSort(array1, position +1, h);
}
}
private static int partition(int[] array1, int i, int j) {
int pivot = array1[j] -1;
int small = i -1;
for(int k = i; k < j; k++) {
if(array1[k] <= pivot) {
compares++;
small++;
swap(array1, k, small);
}
}
swap(array1, j, small + 1);
//System.out.println("Pivot = " + array1[small + 1]);
print_quick_sort(array1);
return small + 1;
}
public static void swap(int[] array1, int a, int b) {
int temp;
temp = array1[a];
array1[a] = array1[b];
array1[b] = temp;
}
public static void print_quick_sort(int[] array1) {
for(int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
System.out.println();
}
//HEAP SORT
public void build(int array2[]) {
int length = array2.length;
for(int i = length/2-2; i >=0; i--) {
bubble_down(array2, i, array2.length-1);
heap_compares++;
}
for(int i = length-1; i>= 0; i--) {
swap2(array2, 0,i);
bubble_down(array2,i,0);
heap_compares++;
}
}
void bubble_down(int[] array2, int parent, int size) {
int left = parent*2+1;
int right = 2*parent+2;
int largest = 0;
if(left <= size && array2[left] > array2[largest]) {
largest = left;
heap_compares++;
}
if(right <= size && array2[right] > array2[largest]) {
largest = right;
heap_compares++;
}
if(largest != parent) {
swap2(array2,parent, largest);
bubble_down(array2,largest,size);
heap_compares++;
}
}
public static void swap2(int[] array2, int a, int b) {
int temp = array2[a];
array2[a] = array2[b];
array2[b] = temp;
}
public static void print_heap_sort(int[] array2) {
for(int i = 0; i < array2.length; i++) {
System.out.print(array2[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
for(int x = 0; x < 20; x++) {
for(int y = 0; y < 20; y++) {
for(int i = 0; i < array1.length; i++) {
array1[i] = array2[i]= (int)(Math.random()*20 + 0);
}
System.out.println("Numbers Generated in Array 1: " + Arrays.toString(array1));
System.out.println("");
System.out.println("Numbers Generated in Array 2: " + Arrays.toString(array2));
System.out.println("");
//quickSort
print_quick_sort(array1);
quickSort(array1, 0, array1.length -1);
System.out.println("The number of comparisons in quick sort: "+ compares);
System.out.println("=============================");
quick_sort_comparison[x] = compares;
compares = 0;
System.out.println("Array of quick sort comparison's: ");
System.out.println(Arrays.toString(quick_sort_comparison));
System.out.println("=============================");
//Heap Sort
System.out.println("Before Heap Sort: ");
System.out.println(Arrays.toString(array2));
heap_sort_comparison[y] = heap_compares;
heap_compares = 0;
HeapSort ob = new HeapSort();
ob.sort(array2);
System.out.println("Sorted array is (heap Sort): ");
print_heap_sort(array2);
System.out.println("=============================");
System.out.println("Array of heap sort comparison's: " + heap_compares);
System.out.println(Arrays.toString(heap_sort_comparison));
}
}
}
}
You do not even call the HeapSort method that you've built.
look here...
HeapSort ob = new HeapSort();
ob.sort(array2);
I think you are trying to use a built in sorting method from HeapSort class, So how do you think the counter heap_compares will increase!
I need to fill a 2D Array with numbers between 2 and 6, given by the user (is just part of a bigger proyect) but when I give the number I only get another request for a number.
public static int[][] crearTablero(int tamaño)
{
int[][] tablero = new int[tamaño][tamaño];
return tablero;
}
public static void imprimeTablero(int[][] tablero)
{
for(int i = 0; i<tablero.length; i++)
{
for(int j = 0; j<tablero[i].length; j++)
{
System.out.print(tablero[i][j] + " ");
}
System.out.println();
}
}
public static void swap(int[][] tablero, int x1, int y1, int x2, int y2)
{
int temp = tablero[x1][y1];
tablero[x1][y1] = tablero[x2][y2];
tablero[x2][y2] = temp;
}
public static void rellenarTablero(int[][] tablero) {
for (int x = 0; x < tablero.length; x++) {
for (int y = 0; y < tablero[x].length; y++) {
tablero[x][y] = aleatorio(numeroColores());
}
}
}
public static void shuffleBoard(int[][] tablero)
{
Random rnd = new Random();
int randX = 0;
for(int x = 0; x<tablero.length; x++)
{
randX = rnd.nextInt(tablero.length);
int[] temp = tablero[x];
tablero[x] = tablero[randX];
tablero[randX] = temp;
}
}
public static int numeroColores(){
int colores = 0;
System.out.print("Numero de colores (entre 2 y 6): ");
Scanner scn = new Scanner(System.in);
colores = scn.nextInt();
while(colores < 2 || colores > 6)
{
System.out.println("Invalid matrix size. Re-enter ");
}
return colores;
}
public static int aleatorio(int colores) {
int l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
return l;
}
I would really appreciate some help because I don't know how to continue, Thanks.
You call numeroColores() in a for-loop in a for-loop, so you are of course asked multiple times for it.
Btw. you have an endless loop if you type in 1 or smaller or 7 or bigger with constantly getting the same line printed out and not asking for new input
Try this code to generate the random value between 2 and 6
public static int aleatorio(int colores) {
int l = 0;
while(l < 2 || l > 6) {
l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
}
return l;
}
Situation with the code is I think that the for loop in the private method is not getting int[] userArray. I have spent hours trying to figure out why the for loop is not working, I even tried using while loop.
public class Arrays {
static Scanner scan = new Scanner(System.in);
private static int sizeOfArrayWanted;
private static double average = 0;
/**
* private static int smallestNumber=1;
*
* private static int count = 0; private static int total=0; private static
* int average=total/count; private static int largestNumber=0; private static
* int standardDeviation=0; private static int meanOfSD=0; private static int
* x1=0; private static int[] userArray= new int [0];
**/
private static int total1 = 0;
private static int standardDeviation = 0;
private static int finalAverage = 0;
public static void main(String[] args) {
// int randomNumber = (int)((Math.random() * 9) + 1);
System.out.println("Hello how big would you like the array?");
int sizeOfArrayWanted = scan.nextInt();
int smallestNumber = 1;
int largestNumber = 0;
int total = 0;
int standardDeviation = 0;
int count = 0;
double average = 0;
int[] userArray = new int[sizeOfArrayWanted];
for (int x = 0; x < sizeOfArrayWanted; x++) {
userArray[x] = (int) ((Math.random() * 9) + 0);
total = total + userArray[x];
count++;
if (userArray[x] < smallestNumber) {
smallestNumber = userArray[x];
}
if (userArray[x] > largestNumber) {
largestNumber = userArray[x];
}
System.out.print(userArray[x] + ", ");
average = total / count;
}
System.out.println("");
System.out.println("largest Number= " + largestNumber);
System.out.println("smallest Number= " + smallestNumber);
System.out.println("average =" + (total / count));
Arrays.computeStandardDeviation(userArray, sizeOfArrayWanted);
}
private static int computeStandardDeviation(int[] userArray, int sizeofArrayWanted) {
int x1 = 0;
while (x1 < sizeofArrayWanted) {
x1++;
userArray[x1] = (int) (userArray[x1] - average);
userArray[x1] = (int) Math.pow(userArray[x1], 2);
total1 = total1 + userArray[x1];
finalAverage = total1 / x1;
standardDeviation = (int) Math.sqrt(finalAverage);
}
return standardDeviation;
}
}
When I try to compile the program, I get the following errors:
Exception in thread "main" largest Number= 6
smallest Number= 1
average =4
java.lang.ArrayIndexOutOfBoundsException: 5
at Arrays.computeStandardDeviation(Arrays.java:80)
at Arrays.main(Arrays.java:67)
You increment x1 after the check. Making it 1 too large for array at last iteration. Move x1++ into average calculation.
while(x1<sizeofArrayWanted)
{
// x1++;
finalAverage = total1 / ++x1;
The issue is from the computeStandardDeviation method. The index starts at 0, so increasing it immediately will cause it not to look at the first spot in the array and therefore also check the last index + 1 location. It should be like this
private static int computeStandardDeviation(int [] userArray, int sizeofArrayWanted)
{
int x1=0;
while(x1<sizeofArrayWanted)
{
userArray[x1]=(int) (userArray[x1]-average);
userArray[x1]=(int) Math.pow(userArray[x1], 2);
total1=total1+userArray[x1];
finalAverage=total1/x1;
standardDeviation= (int) Math.sqrt(finalAverage);
x1++; // move this here
}
return standardDeviation;
}
Array index out of bounds exception is because you are incrementing x1 before doing operations, rather you should do all operations and increment x1 at the end. Otherwise, at the last iteration of the loop, you will be accessing an element outside the scope of the array.
private static int computeStandardDeviation(int[] userArray, int sizeofArrayWanted) {
int x1 = 0;
while (x1 < sizeofArrayWanted) {
userArray[x1] = (int) (userArray[x1] - average);
userArray[x1] = (int) Math.pow(userArray[x1], 2);
total1 = total1 + userArray[x1];
finalAverage = total1 / x1;
standardDeviation = (int) Math.sqrt(finalAverage);
x1++; //Increment should be done after all operations
}
return standardDeviation;
}
Also you dont need to pass the size parameter explicitly here, since you can just get the size from the array passed to the method.
UPDATE****
I have my program compiling and executing correctly but now I have faced another problem. I need to create variables that will count each time a certain random number is generated. For example count0 is supposed to record how many times the integer 0 is generated. This is what I have:
import java.util.Random;
public class L10{
public static void main(String[] args){
int total = 100;
Random randObj = new Random();
final int UPPER_BOUND = 10;
for (int i=0; i < total; i++){
int randomInt = randObj.nextInt(UPPER_BOUND);
System.out.print("\n" + randomInt);
int count0 = 0;
if(randomInt==0){
System.out.print(randomInt + count0);
}
int count1 = 1;
if(randomInt==1){
}
int count2 = 2;
int count3 = 3;
int count4 = 4;
int count5 = 5;
int count6 = 6;
int count7 = 7;
int count8 = 8;
int count9 = 9;
}
}
}
The output shows the random number, in this case zero, and prints a zero next to it. I'm not exactly sure how to write code that keeps track of how many times zero is generated. Any suggestions?
Try this:
import java.util.Random;
public class HelloWorld{
public static void main(String []args){
Random randObj = new Random();
final int UPPER_BOUND = 10;
int total = 100;
String star = "*";
for (int i=0; i < UPPER_BOUND; i++){
int randomInt = randObj.nextInt(total);
System.out.print(randomInt);
}
}
}
Modifications:
Random randObj = new Random();
int randomInt = randObj.nextInt(total);
I think your intention is to generate 100 random integers in the range 0-9, and count the frequency of each.
Using separate variables for each count is a poor idea. A better idea is to use a single array of size 10, whose index is the random number.
Modifying your code:
public static void main(String[] args){
final int TOTAL = 100, UPPER_BOUND = 10;
Random randObj = new Random();
int[] count = new int[UPPER_BOUND];
// collect frequencies
for (int i=0; i < TOTAL; i++)
count[randObj.nextInt(UPPER_BOUND)]++;
// report frequencies
for (int i=0; i < UPPER_BOUND; i++)
System.out.print(i + "'s frequency was " + count[i];
}
import java.util.Random;
public class L10{
public static void main(String[] args){
int total = 100;
int[] CountArray = new int[total]; //count numbers
Random randObj = new Random();
final int UPPER_BOUND = 10;
for (int i=0; i < total; i++){
int randomInt = randObj.nextInt(UPPER_BOUND);
System.out.print("\n" + randomInt);
switch(randomInt){
case(0):{
CountArray[0]++;
break;
}
case(1):{
CountArray[1]++;
break;
}
case(2):{
CountArray[2]++;
break;
}
case(3):{
CountArray[3]++;
break;
}
case(4):{
CountArray[4]++;
break;
}
case(5):{
CountArray[5]++;
break;
}
case(6):{
CountArray[6]++;
break;
}
case(7):{
CountArray[7]++;
break;
}
case(8):{
CountArray[8]++;
break;
}
case(9):{
CountArray[9]++;
break;
}
}
}
System.out.println("");
for(int j = 0;j<UPPER_BOUND;j++){
System.out.println("number of "+ j+" generated "+CountArray[j]);
}
}
}
This is the Code that I came up with. I used an array to count each element and used switch case to count them separately. so at the end of the for loop. I printed them. This way you can get the number of elements distinctively.
You are missing () after new Random.
Is there a way to do what the title suggests? What I'm trying to do is create a table of experience values required to level up like so:
int level1 = 50;
int level2 = level1 + (level1 * 0.1);
int level3 = level2 + (level2 * 0.1);
But I want to get to around 100 levels... Is there a way to quickly define x number of usable int values?
Assuming you're continuing that formula...
int[] array = new int[100];
array[0] = 50;
for (int i = 1; i < 100; i++) {
array[i] = (int) (array[i - 1] * 1.1);
}
Use this approach:
public class Level
{
public Level()
{
int[] levels = new int[100]; // 100 Levels
initializeLevels(levels);
printLevels(levels);
}
private void initializeLevels(int[] levels)
{
levels[0] = 50;
for (int i = 1; i < 100; i++)
{
levels[i] = (int) (levels[i - 1] * 1.1f);
}
}
private void printLevels(int[] levels)
{
for (int i = 0; i < 100; i++)
{
System.out.println("Level " + (i + 1) + " = " + levels[i]);
}
}
public static void main(String[] args)
{
new Level();
}
}