Random array of 1's and 0's using methods - java

I am trying to create a random sized array of 1's and 0's. I can get the program to run and compile if I remove the random aspect of the of it and enter the size of the array manually. For some reason when I bring in the random utility I can not get the program to compile.
mport java.util.Random;
public class Project1a {
int[][] sample={{0,0,1,1,1},
{1,1,0,1,1},
{1,1,1,0,1},
{0,1,0,1,1}};
int box[][];
Random randomNumbers = new Random();
int m = randomNumbers.nextInt(100);
int n = randomNumbers.nextInt(100);
int results[][] = new int [m][n];
int goodData = 1;
public static void main(String[] args){
analyzeTable();
printTable(results);
}
public void analyzeTable() {
int row=0;
while (row < sample.length) {
analyzeRow(row);
row++;
}
}
public void analyzeRow(int row) {
int xCol = 0;
int rCount = 0;
while (xCol < sample[row].length) {
rCount = analyzeCell(row,xCol);
results[row][xCol] = rCount;
xCol++;
}
}
int analyzeCell(int row, int col) {
int xCol = col;
int runCount = 0;
int rowLen = sample[row].length;
int hereData = sample[row][xCol];
while (hereData == goodData && xCol < rowLen) {
runCount++;
xCol++;
if (xCol < rowLen) { hereData = sample[row][xCol];}
}
return runCount;
}
public void printTable(int[][] aTable ) {
for (int[] row : aTable) {
printRow(row);
System.out.println();
}
}
public void printRow(int[] aRow) {
for (int cell : aRow) {
System.out.printf("%d ", cell);
}
}
}

Your class name conflicts with java.util.Random. Renaming your class is the easiest fix here.

the problem is you are declaring your instance variable in a block which makes it in-accessible in methods
check this : remove curly braces { } from here and the way you are accessing your results and goodData you need to declare them static
{ // remove this
Random randomNumbers = new Random();
int m = randomNumbers.nextInt(100);
int n = randomNumbers.nextInt(100);
static int results = new int [m][n];
static int goodData = 1;
} // remove this

Related

array in constructor keeps returning as null? [duplicate]

This question already has answers here:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
(4 answers)
Closed 3 months ago.
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
int[] pascal;
char[] Larray;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
im trying to do this code but pascal, keeps returning as null, when I declare it outside the constructor;
ive also tried this...
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
and I get this error
sierpinski.java:8: error: cannot find symbol
System.out.println(String.valueOf(s1.pascal));
^
symbol: variable pascal
location: variable s1 of type sierpinski
1 error
error: compilation failed
saying it cannot find symbol, any solutions and does anyone know how to fix this??
thanks
tried declaring the variable at the top, but I have no clue how to get this to work, any ideas?
Constructors are essentially methods.
sierpinski(int row) { // this is a constructor
this.row = row; // this sets a field.
int[] pascal = new int[row+1]; // this creates a new local variable
// constructor ends, and with it, all local variables GO AWAY
}
You want to declare a field. You already have one (row), and you already set it (this.row = row). If you want pascal to still exist when the constructor ends, it needs to be a field and not a local:
public Sierpinski {
private int row;
private int[] pascal;
public Sierpinski(int row) {
this.row = row;
this.pascal = new int[row];
}
}

ACM-ICPC 7384 programming challenge

I'm trying to solve the Popular Vote problem, but I get runtime error and have no idea why, I really appreciate the help. Basically my solution is to get the total of votes, if all candidates have the same amount of votes; then there's no winner, otherwise I calculate the percentage of votes the winner gets in order to know if he's majority or minority winner.
import java.util.Scanner;
class popular {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos=s.nextInt();
int cont=0;
int ganador=0;
float num=0;
while(cont!=casos){
n=s.nextInt();
int votos[]= new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
suma=sumar(votos);
if(suma==-1){
System.out.println("no winner");
}
else{
ganador=ganador(votos, suma);
num=(float)votos[ganador]/(float)suma;
if( num> 0.5){
System.out.println("majority winner "+(ganador+1));
}
else{
System.out.println("minority winner "+(ganador+1));
}
}
cont++;
ganador=0;
}
}
public static int sumar(int arreglo[]){
int resp1=-1, resp=0;
int temp=arreglo[0];
boolean sol=true;
for (int i = 0; i < arreglo.length; i++) {
resp=resp+arreglo[i];
if(temp!=arreglo[i]){
sol=false;
}
}
if(sol==false){
return resp;
}
return resp1;
}
public static int ganador(int arreglo[], int suma){
int mayor=0;
int ganador=0;
for (int i = 0; i < arreglo.length; i++) {
if(arreglo[i]>mayor){
mayor=arreglo[i];
ganador=i;
}
}
return ganador;
}
}
I submitted your code to the OJ, but I didn't get a runtime error, but I got Compilation error. I have to figure out there are some problems in your code. First of all, if you want to submit a java code to OJ, you need to name the public class as Main instead of popular or something else. Second, your code logic is not correct. Suppose a test case:
4
1
1
2
2
Your program will print "minority winner 3" but it's should be "no winner".
Here is a modified source code from yours (you can get accepted with this code):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos = s.nextInt();
int cont = 0;
int ganador = 0;
float num = 0;
while (cont != casos) {
n = s.nextInt();
int votos[] = new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
ganador = findMaximum(votos);
if (getMaximumCount(votos, votos[ganador]) > 1) {
System.out.println("no winner");
} else {
suma = sumOf(votos);
if (votos[ganador] * 2 > suma) {
System.out.println("majority winner " + (ganador + 1));
} else {
System.out.println("minority winner " + (ganador + 1));
}
}
cont++;
ganador = 0;
}
}
private static int sumOf(int[] arreglo) {
int sum = 0;
for (int x : arreglo) {
sum += x;
}
return sum;
}
private static int getMaximumCount(int[] arreglo, int maximum) {
// Check if there are more than one items have the maximum value
int count = 0;
for (int x : arreglo) {
if (x == maximum) {
count++;
}
}
return count;
}
private static int findMaximum(int[] arreglo) {
int x = 0, pos = 0;
for (int i = 0; i < arreglo.length; i++) {
if (x < arreglo[i]) {
x = arreglo[i];
pos = i;
}
}
return pos;
}
}
Hope it could help you!

Implementing merge sort in java 7

I have a problem with implementation of merge sort in java. I am looking for the error almost week unfortunately without result. ArrayList at the entrance is the same as the output.
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
ArrayList<Integer> arrayListA = new ArrayList<Integer>();
ArrayList<Integer> arrayListB = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int firstIndexOfArrayList = 0;
private int lastIndexOfArrayListA;
private int lastIndexOfArrayListB;
public void Scal(ArrayList<Integer> basicArrayList, int p, int q, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListA = q;
this.lastIndexOfArrayListB = r;
int numberOfElementsArrayListA = lastIndexOfArrayListA
- firstIndexOfArrayList + 1;
int numberOfElementsArrayListB = lastIndexOfArrayListB
- lastIndexOfArrayListA;
for (int i = 0; i < numberOfElementsArrayListA; i++) {
arrayListA.set(i, basicArrayList.get(firstIndexOfArrayList + i));
}
for (int j = 0; j < numberOfElementsArrayListB; j++) {
arrayListB.set(j, basicArrayList.get(lastIndexOfArrayListA + j));
}
arrayListA.add(Integer.MAX_VALUE);
arrayListB.add(Integer.MAX_VALUE);
int i = 0;
int j = 0;
for (int k = firstIndexOfArrayList; k <= lastIndexOfArrayListB; k++) {
if (arrayListA.get(i) <= arrayListB.get(j)) {
basicArrayList.set(k, arrayListA.get(i));
i = i + 1;
} else {
basicArrayList.set(k, arrayListB.get(j));
j = j + 1;
}
}
}
public void MergeSort(ArrayList basicArrayList, int p, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListB = r;
if (firstIndexOfArrayList < lastIndexOfArrayListB) {
int lastIndexOfArrayListA = (firstIndexOfArrayList + lastIndexOfArrayListB) / 2;
MergeSort(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA);
MergeSort(basicArrayList, lastIndexOfArrayListA + 1,
lastIndexOfArrayListB);
Scal(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA,
lastIndexOfArrayListB);
}
}
public void setSize() {
System.out.println("Enter the number of elements to sort: ");
this.lastIndexOfArrayListB = input.nextInt();
}
public int getSize() {
return lastIndexOfArrayListB;
}
public void setData() {
System.out.println("Enter the numbers: ");
for (int i = 0; i < lastIndexOfArrayListB; i++) {
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable() {
System.out.println(basicArrayList.toString());
}
public static void main(String[] args) {
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.MergeSort(output.basicArrayList,
output.firstIndexOfArrayList, (output.getSize() - 1));
output.getTable();
}
}
In terms of fixing your code I had a crack at it and as far as I can tell this seems to work. To do this a lot of your code had to be changed but it does now sort all Integers properly
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int numbersToSort;
public void doMergeSort(int firstIndexOfArrayList,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
if(firstIndexOfArrayList<lastIndexOfArrayListB && (lastIndexOfArrayListB-firstIndexOfArrayList)>=1)
{
int mid = (lastIndexOfArrayListB + firstIndexOfArrayList)/2;
doMergeSort(firstIndexOfArrayList, mid, arrayList);
doMergeSort(mid+1, lastIndexOfArrayListB, arrayList);
Scal(firstIndexOfArrayList,mid,lastIndexOfArrayListB, arrayList);
}
}
public void Scal(int firstIndexOfArrayList,int lastIndexOfArrayListA,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
ArrayList<Integer> mergedSortedArray = new ArrayList<Integer>();
int leftIndex = firstIndexOfArrayList;
int rightIndex = lastIndexOfArrayListA+1;
while(leftIndex<=lastIndexOfArrayListA && rightIndex<=lastIndexOfArrayListB)
{
if(arrayList.get(leftIndex)<=arrayList.get(rightIndex))
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
else
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
}
while(leftIndex<=lastIndexOfArrayListA)
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
while(rightIndex<=lastIndexOfArrayListB)
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
int i = 0;
int j = firstIndexOfArrayList;
while(i<mergedSortedArray.size())
{
arrayList.set(j, mergedSortedArray.get(i++));
j++;
}
}
public void setSize()
{
System.out.println("Enter the number of elements to sort: ");
this.numbersToSort = input.nextInt();
}
public int getSize()
{
return numbersToSort;
}
public void setData()
{
System.out.println("Enter the numbers: ");
for (int i = 0; i < numbersToSort; i++)
{
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable()
{
System.out.println(basicArrayList.toString());
}
public void runSort(ArrayList<Integer> arrayList)
{
doMergeSort(0, this.numbersToSort-1, arrayList);
}
public static void main(String[] args)
{
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.runSort(output.basicArrayList);
output.getTable();
}
}
Try this code. The following code takes an ArrayList input and outputs an ArrayList as well so it still works along the same basis of your code. The actual sort is handled in a different class MergeSort and is passes into ForMergeSort. Hope this helps
MergeSort.java
public class MergeSort
{
private int[] array;
private int[] tempMergArr;
private int length;
public void sort(int[] inputArr)
{
}
public int[] getSortedArray(int[] inputArr)
{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
for(int i=0;i<length;i++)
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Merge Sort is: "+inputArr[i]);
}
return inputArr;
}
private void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
{
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++)
{
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex)
{
if (tempMergArr[i] <= tempMergArr[j])
{
array[k] = tempMergArr[i];
i++;
}
else
{
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle)
{
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
ForMergeSort.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ForMergeSort
{
ArrayList<Integer> arrayList = new ArrayList<Integer>();
ArrayList<Integer> sortedArrayList = new ArrayList<Integer>();
MergeSort mS = new MergeSort();
public void buildArrayList()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements to sort: ");
int toSort = input.nextInt();
System.out.println("Enter the numbers: ");
for(int i =0; i<toSort; i++)
{
int number = input.nextInt();
arrayList.add(number);
}
}
public void runMergeSort(ArrayList<Integer> arrayList)
{
int[] arrayOfValues = new int[arrayList.size()];
int i = 0;
for(int a:arrayList)
{
arrayOfValues[i] = a;
i++;
}
MergeSort mS = new MergeSort();
for(int intOfArray:mS.getSortedArray(arrayOfValues))
{
sortedArrayList.add(intOfArray);
}
System.out.println(sortedArrayList.toString());
}
public static void main(String[] args)
{
ForMergeSort fMS = new ForMergeSort();
fMS.buildArrayList();
fMS.runMergeSort(fMS.arrayList);
}
}

How to fill a multidimensional array dependant on variables

The program I am working on is a simple shipping program. What I am having difficulty with is populating a multidimensional array factoring in certain variables.
Example
320 items need to be shipped out to 1 receiver using different box sizes.
XL can hold 50 items
LG can hold 20 items
MD can hold 5 items
SM can hold 1 items
Use the least number of boxes so far.
Code
This is my code so far.
import java.util.Scanner;
public class Shipping {
public static void main(String [] args) {
Scanner kbd = new Scanner(System.in);
final int EXTRA_LARGE = 50;
final int LARGE = 20;
final int MEDIUM = 5;
final int SMALL = 1;
String sBusinessName = "";
int iNumberOfGPS = 0;
int iShipmentCount = 0;
displayHeading(kbd);
iShipmentCount = enterShipments(kbd);
int[][] ai_NumberOfShipments = new int [iShipmentCount][4];
String[] as_BusinessNames = new String [iShipmentCount];
for (int iStepper = 0; iStepper < iShipmentCount; iStepper++) {
sBusinessName = varifyBusinessName(kbd);
as_BusinessNames[iStepper] = sBusinessName;
iNumberOfGPS = varifyGPS(kbd);
calculateBoxes(ai_NumberOfShipments[iStepper],iNumberOfGPS, EXTRA_LARGE, LARGE, MEDIUM, SMALL);
}
//showArray(as_BusinessNames);
}
public static void displayHeading(Scanner kbd) {
System.out.println("Red River Electronics");
System.out.println("Shipping System");
System.out.println("---------------");
return;
}
public static int enterShipments(Scanner kbd) {
int iShipmentCount = 0;
boolean bError = false;
do {
bError = false;
System.out.print("How many shipments to enter? ");
iShipmentCount = Integer.parseInt(kbd.nextLine());
if (iShipmentCount < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
bError = true;
}
} while (bError == true);
return iShipmentCount;
}
public static String varifyBusinessName(Scanner kbd) {
String sBusinessName = "", sValidName = "";
do {
System.out.print("Business Name: ");
sBusinessName = kbd.nextLine();
if (sBusinessName.length() == 0) {
System.out.println("");
System.out.println("**Error** - Name is required\n");
} else if (sBusinessName.length() >= 1) {
sValidName = sBusinessName;
}
} while (sValidName == "");
return sValidName;
}
public static int varifyGPS(Scanner kbd) {
int iCheckGPS = 0;
int iValidGPS = 0;
do {
System.out.print("Enter the number of GPS receivers to ship: ");
iCheckGPS = Integer.parseInt(kbd.nextLine());
if (iCheckGPS < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
} else if (iCheckGPS >= 1) {
iValidGPS = iCheckGPS;
}
} while(iCheckGPS < 1);
return iValidGPS;
}
public static void calculateBoxes(int[] ai_ToFill, int iNumberOfGPS) {
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++)
}
//public static void showArray( String[] ai_ToShow) {
// for (int iStepper = 0; iStepper < ai_ToShow.length; iStepper++) {
// System.out.println("Integer at position " + iStepper + " is " + ai_ToShow[iStepper]);
// }
//}
}
Change your definition of calculateBoxes() to also take an array that represents the volume of each of the boxes (in your case this will be {50, 20, 5, 1}:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
// while the remaining items to pack is greater than the current box size
while(iNumberOfGPS >= boxVolumes[iStepper]) {
// increment the current box type
ai_ToFill[iStepper]++;
// subtract the items that just got packed
iNumberOfGPS -= boxVolumes[iStepper];
}
}
}
Another way of calculating this (using / and % instead of a while loop) would be:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
if(iNumberOfGPS >= boxVolumes[iStepper]) {
// calculate the number of boxes that could be filled by the items
ai_ToFill[iStepper] = iNumberOfGPS/boxVolumes[iStepper];
// reset the count of items to the remainder
iNumberOfGPS = iNumberOfGPS%boxVolumes[iStepper];
}
}
}

Aid with quick sort algorithm in java (netbeans)

I am quite new to programming and I am just starting using java. My task was to write a program using quick sort, I managed to write it but it always gives me an index out of bounds. Could anyone take a look at my code and help me by identifying what I am doing wrong? Thanks
This is the code for the main class.
package quicksort;
public class Quicksort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] x = {5,3,10,1,9,8,7,4,2,6,0};
quicksort_class q = new quicksort_class(x);
q.sort();
for(int i = 0; i < 11-1; i++)
{
System.out.println(x[i]);
}
}
}
This is the code for quicksort_class.
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
public void partitionstep(int leftlimit, int rightlimit)
{
int LPointer = leftlimit;
int RPointer = rightlimit;
Random random = new Random();
int midpoint = random.nextInt(11);
int checknumber = array1[midpoint];
while(LPointer < RPointer)
{
while(array1[LPointer] <= checknumber)
{
LPointer = LPointer + 1;
}
while(array1[RPointer] >= checknumber)
{
RPointer = RPointer --;
}
swap(LPointer, RPointer);
partitionstep(leftlimit, midpoint - 1);
partitionstep(midpoint + 1, rightlimit);
}
}
public void swap(int x, int y)
{
int temp = array1[x];
array1[x] = array1[y];
array1[y] = temp;
}
public void sort()
{
partitionstep(0, array1.length - 1);
}
}
Your midpoint value should be calculated based on your leftLimit and rightLimit. It should not be a random value based off of the fixed value 11.

Categories

Resources