integer array won't print [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I created this method randomInt, that gives a random number, between -5, and 15. I created another method randomIntArray that calls randomInt, in a loop, and stores the random integers into an array. However, when I try to print it, it just returns an ArrayIndexOutOfBoundsException.
public static int randomInt(int low, int high) {
double e;
double x = Math.random();
e = low + x * (high - low);
return (int) e;
}
public static int[] randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15); //"-5&15 are the lower and upper bounds of the random number array
}
return a;
}
In randomInt, When I didn't cast the return value into an int, it worked, however I need it to return an int for the array to work.

Check your printing code after calling randomIntArray(number);
/**
* #param args the command line arguments
*/
public static void main(String[]args) {
int[] myArray = randomIntArray(10);
// Manual iteration through your array
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
System.out.println("");
// Use of Arrays class to print your array
System.out.println(Arrays.toString(myArray));
}
public static int randomInt(int low, int high) {
double e;
double x = Math.random();
e = low + x * (high - low);
return (int) e;
}
public static int[] randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15);
}//"-5&15 are the lower and upper bounds of the random number array
return a;
}
Results:

http://ideone.com/3OrTei
In the function calling randomIntArray(int n):
int[] array = randomIntArray(5);
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
The code works, just make sure you're printing the results properly

Related

Why do we use two different loop variables while sorting an array using merge sort?

I was learning to merge sort an integer array, when I noticed that while copying the sorted array elements to the original array, we need two separate loop variables to run simultaneously, while the values at those indices are copied to the original array. Here is the code for reference:
class MergeSort {
public static void sort(int arr[], int si, int ei, int mid) {
int merged[] = new int[ei - si + 1];
int index1 = si; // tracks the first array
int index2 = mid + 1; // tracks the second array
int i = 0;
while (index1 <= mid && index2 <= ei) {
if (arr[index1] <= arr[index2]) {
merged[i++] = arr[index1++];
} else {
merged[i++] = arr[index2++];
}
} // end of while
while (index1 <= mid) {
merged[i++] = arr[index1++];
}
while (index2 <= ei) {
merged[i++] = arr[index2++];
}
// to copy merged[] to arr[]
int j = si;
for (i = 0; i < merged.length; i++, j++) {
arr[j] = merged[i];
}
} // end sort()
public static void divide(int arr[], int si, int ei) {
// base case
if (si >= ei) {
return;
} // end of base case
int mid = si + (ei - si) / 2; // same as (ei-si)/2 but with less space complexity
divide(arr, si, mid);
divide(arr, mid + 1, ei);
sort(arr, si, ei, mid);
} // end of divide
public static void main(String args[]) {
int arr[] = { 1, 8, 0, 7, -4 };
int n = arr.length;
divide(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
} // end of for
} // end of main
} // end of class
Notice that while copying the values of the array merged[] to the array arr[], we are using two separate variables i and j. I did try using only one loop variable, which went like:
for (int i = 0; i < arr.length; i++) {
arr[i] = merged[i];
}
but received an incorrect output. If anyone knows why we need two separate variables for the operation, please let me know. Thank you :)
You could use a single variable in this final loop, but you must add the offset of the start of the slice in the destination array:
for (int i = 0; i < arr.length; i++) {
arr[si + i] = merged[i];
}

Generating a discrete random variable in Java? [duplicate]

This question already has answers here:
Random weighted selection in Java
(7 answers)
Closed 1 year ago.
Today in interview they asked me this question? How to generate a discrete random variable in Java? I couldn't do it but I wonder the solution.
They gave me an array:
double[] probabilities={.2,.1,.3,.4};
double[] outcomes ={4,5,8,11.5};
And this should give the answer:
double discreteRV = problem.randPMF(probabilities,outcomes);
I couldn't understand how to solve this question.
Since all the probabilities will always add up to 1, you can generate a random number between 0 and 1 then iterate through the probabilities and subtract them. When the number is less than or equal to 0, the index of the last subtracted probability is the index of the outcome:
import java.util.Random;
public static double randPMF(double[] prob, double[] out) {
double rand = Math.random();
int index = -1;
while (rand >= 0) {
index++;
rand -= prob[index];
}
return out[index];
}
Here's my idea for a solution:
private double randPMF(double[] probabilities, double[] outcomes) {
double random = Math.random();
double p = 0;
for (int i = 0; i < probabilities.length; i++) {
p += probabilities[i];
if (random < p) {
return outcomes[i];
}
}
return outcomes[outcomes.length - 1];
}
This is what I came up with
private static double randPMF(double[] probabilities, double[] outcomes) {
int n = 10;
boolean nNotFound;
for (double probability: probabilities){
nNotFound = true;
while(nNotFound)
if (probability*n == (double)((int)(probability*n)))
break;
else
n *= 10;
}
double[] numbers = new double[n];
//j tracks the probability/occurence
int j;
//k tracks the new array
int k = 0;
//i tracks each element in our old arrays
for (int i = 0; i<probabilities.length; i++) {
j = 0;
while (j < (probabilities[i]*n)) {
numbers[k] = outcomes[i];
k++;
j++;
}
}
int index = new Random().nextInt(n);
System.out.println(numbers.length);
return numbers[index];
}

Print all possible permutations of an array elements [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am working on a program,I have tried to find a way how to find all possible permutations of an array elements in Java, but it didn't work .
My code is:
public class Permutation {
public static void main(String[] args) {
int[] list = new int[3];
System.out.println("enter the elements of array");
Scanner sc = new Scanner(System.in);
for (int i = 0; i < list.length; i++) {
list[i] = sc.nextInt();
}
System.out.println(Arrays.toString(list));
int n = list.length;
permutation(list, n, 0);
}
public static void permutation(int[] list, int n, int l) {
if (l == n - 1) {
printArray(n, list);
return;
}
for (int i = 1; i < n; i++) {
swap(list, list[i], list[l]);
permutation(list, n, l + 1);
swap(list, list[i], list[l]);
}
}
public static void swap(int[] list, int x, int y) {
int temp = list[x];
list[x] = list[y];
list[y] = temp;
}
public static void printArray(int n, int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.print(list[i]);
}
}
}
This code is continuously throws an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Permutation.swap(Permutation.java:34)
at Permutation.permutation(Permutation.java:27)
at Permutation.permutation(Permutation.java:28)
at Permutation.main(Permutation.java:15)
I'm not able to understand what to do in this program so that it'll produce desired output.
And what is the meaning of this error which is thrown by program??
you are getting this error because you are trying to access items, not in the array try changing
i = 0 in line 25

Determining if a program is fast, memory-efficient and does not have large time-complexity

Could someone please help me how I could determine whether my program is memory-efficient, fast and has low time-complexity? For one of my programs, I implemented merge sort and then called some methods here and there but since it has around 100 lines of code, I am skeptical whether it is memory efficient. Thanks guys
import java.util.*;
public class Question6 {
static void mergeSort(Integer arr1[], int o, int k, int x) {
int num1 = k - o + 1;
int num2 = x - k;
int temp1[] = new int[num1]; //creation of two temporary arrays to store in
int temp2[] = new int[num2];
for (int i = 0; i < num1; ++i) //for loops to copy the data to the temporary arrays
temp1[i] = arr1[o + i];
for (int j = 0; j < num2; ++j)
temp2[j] = arr1[k + 1 + j];
int i = 0, j = 0; //starting position of temporary arrays
int s = o; //starting position of the merged two temporary arrays
while (i < num1 && j < num2) {
if (temp1[i] <= temp2[j]) {
arr1[s] = temp1[i];
i++;
} else {
arr1[s] = temp2[j];
j++;
}
s++;
}
//code to copy elements from temp1
while (i < num1) {
arr1[s] = temp1[i];
i++;
s++;
}
//code to copy elements from temp2
while (j < num2) {
arr1[s] = temp2[j];
j++;
s++;
}
}
void forSorting(Integer arr2[], Integer t, Integer x) //main method that carries out merge sort
{
if (t < x) {
// Find the middle point
Integer a = (t + x) / 2;
// Sort first and second halves
forSorting(arr2, t, a);
forSorting(arr2, a + 1, x);
// Merge the sorted halves
mergeSort(arr2, t, a, x);
}
}
public static void main(String[] args) {
Question6 qs = new Question6();
Scanner sc = new Scanner(System.in);
Integer[] duplicate = new Integer[10];
System.out.println("Please input the numbers to be checked for repetition.");
for (int x = 0; x < 10; x++) {
duplicate[x] = sc.nextInt(); //filling array
}
int length = duplicate.length;
qs.forSorting(duplicate, 0, length - 1); //calling method forSorting
System.out.println(Arrays.toString(duplicate)); //displays the array which user fills
List<Integer> list = Arrays.asList(duplicate); //makes the array duplicate available as a list
Set<Integer> set = new LinkedHashSet<Integer>(list);
for ( Integer element : set) {
if(Collections.frequency(list, element) > 1) {
System.out.println(" Duplicate: " + element);
}
}
}
}
You can use Profiler. For Java - JProfiler, VisualVM, etc. You can check there all you looking for - how much memory yours algorithms need, the time complexity, and some more stuff.

StackOverflowError exception ruining interesting and complex program

So this problem is a little bit complicated to understand what I'm trying to do.
Basically, I am trying to randomly generate 3 vectors, all of size 11.
The first vector must have a 1 at position 0 with the next 5 positions being 0 (e.g. 100000) while the next five digits can be either 0 1 or 2, however there can only be one zero used in the last 5 digits, hence 10000012101 would be valid but 10000012001 wouldn't.
The same is applicable to the second and third vector however the first 1 will move a place for the second and the third (010000xxxxx for the second, and 001000xxxxx for the third).
There are more conditions that have to be satisfied. Each vector must differ from each other in at least 5 positions (10000011210 would differ from 01000022100 in 5 positions which would work).
However, there is also a final constraint which states that if you add the vectors modulo 3, then the result of adding these two must have at least 5 NON zero values in the vector.
I have went about this by using arraylists. As I know the first 6 elements of each arraylist for each vector I manually put these in, and for the next 5 elements I randomly assign these, if there is more than one 0 in the last five digits, i call the method again recursively.
The problem I have with this program is that when I try to run my code it comes up with a
Exception in thread "main" java.lang.StackOverflowError
at java.util.ArrayList.get(Unknown Source)
I think it's because it's continuously trying to loop and therefore crashing but I'm not sure. See below for the code.
import java.util.ArrayList;
/**
* The purpose of this class is to be able to capture different ways
* of generating six vectors that will produce a collection of 729
* vectors that guarantee 9 out of 11 correct.
*/
public class GenerateVectors {
static ArrayList<Integer> firstVector = new ArrayList<Integer>();
static ArrayList<Integer> secondVector = new ArrayList<Integer>();
static ArrayList<Integer> thirdVector = new ArrayList<Integer>();
static ArrayList<Integer> sumOfXandY = new ArrayList<Integer>();
//Creates the first vectors to ensure it starts with "1,0,0,0,0,0"
//and has at most one more zero in the last 5 digits
public void createFirstVector(){
int[] fir stVector1 = {1,0,0,0,0,0};
for (int i=0; i<firstVector1.length; i++) {
firstVector.add(firstVector1[i]);
}
for(int i = 0; i < 5; i++){
int x = (int) (Math.random()*3);
firstVector.add(x);
}
int j = 0;
for(int i = 6; i<firstVector.size(); i++){
if(firstVector.get(i).equals(0)){
j++;
}
}
if(j>1){
OneZeroInLastFive(firstVector);
}
int[] sum = {0,0,0,0,0,0,0,0,0,0,0};
for (int i=0; i<sum.length; i++) {
sumOfXandY.add(sum[i]);
}
}
//Edits the vector if there is more than 0 in the last five digits
public void OneZeroInLastFive(ArrayList<Integer> x){
int j = 0;
for(int i = 6; i<x.size(); i++){
if(x.get(i).equals(0)){
j++;
}
}
if(j>1){
x.set(6, (int) (Math.random()*3));
x.set(7, (int) (Math.random()*3));
x.set(8, (int) (Math.random()*3));
x.set(9, (int) (Math.random()*3));
x.set(10, (int) (Math.random()*3));
j = 0;
OneZeroInLastFive(x);
}
}
//Creates the second vector with the last 5 digits random
public void createSecondVector(){
int[] secondVector1 = {0,1,0,0,0,0};
for (int i=0; i<secondVector1.length; i++) {
secondVector.add(secondVector1[i]);
}
for(int i = 0; i < 5; i++){
int x = (int) (Math.random()*3);
secondVector.add(x);
}
}
//Creates the third vector with the last 5 digits random
public void createThirdVector(){
int[] thirdVector1 = {0,0,1,0,0,0};
for (int i=0; i<thirdVector1.length; i++) {
thirdVector.add(thirdVector1[i]);
}
for(int i = 0; i < 5; i++){
int x = (int) (Math.random()*3);
thirdVector.add(x);
}
}
/**
* Will edit the second vector to ensure the following conditions are satisfied
* - The sum of x and y modulo 3 has at least 5 NON zeros
* - x and y must DIFFER in at least 5 places
* - There is only one zero within the last 5 digits
*
*/
public void checkVectors(ArrayList<Integer> x, ArrayList<Integer> y){
int k = 0;
int m = 0;
for(int j = 0; j < x.size(); j++){
if(x.get(j).equals(y.get(j))){
;
}
else{
k++;
}
}
for(int i = 6; i<y.size(); i++){
if(y.get(i).equals(0)){
m++;
}
}
if((k>4 && m<1)&& checkNonZeros(x,y)){
System.out.println("Conditions met");
}
else{
y.set(6, (int) (Math.random()*3));
y.set(7, (int) (Math.random()*3));
y.set(8, (int) (Math.random()*3));
y.set(9, (int) (Math.random()*3));
y.set(10, (int) (Math.random()*3));
k = 0;
m = 0;
checkVectors(x,y);
}
}
public ArrayList<Integer> addTwoVectors(ArrayList<Integer> x, ArrayList<Integer> y, ArrayList<Integer> z){
for(int i = 0; i<x.size(); i++){
int j = x.get(i);
int k = y.get(i);
z.set(i, ((j+k)%3));
}
return z;
}
public boolean checkNonZeros(ArrayList<Integer> x, ArrayList<Integer> y){
addTwoVectors(x,y, sumOfXandY);
int j = 0;
for(int i = 0; i<firstVector.size(); i++){
if(sumOfXandY.get(i).equals(0)){
;
}
else{
j++;
}
}
if(j<5){
return false;
}
else {
return true;
}
}
public static void main(String[] args){
GenerateVectors g = new GenerateVectors();
g.createFirstVector();
g.createSecondVector();
g.createThirdVector();
g.checkVectors(firstVector,secondVector);
g.checkVectors(secondVector,thirdVector);
System.out.println(firstVector);
System.out.println(secondVector);
System.out.println(thirdVector + "\n");
System.out.println(g.checkNonZeros(firstVector, secondVector));
System.out.println(g.checkNonZeros(secondVector,thirdVector));
System.out.println(sumOfXandY);
}
}
Any help would be much appreciated!!!
The problem is that you have methods that recursively call themselves in order to 'redo', which may happen many times before you get a success. This is fine in languages like scheme or ml which do proper tail recursion, but java does not, so you get stack overflows.
In order to fix this you need to manually convert the recursive code into a loop. Code that looks like:
method(arg1, arg2) {
Code_block_1;
if (test) {
Code_block_2;
} else {
Code_block_3;
method(newarg1, newarg2);
}
}
needs to become something like:
method(arg1, arg2) {
Code_block_1;
while(!test) {
Code_block_3;
arg1 = newarg1;
arg2 = newarg2;
Code_block_1;
}
Code_block_2;
}
You can then refactor stuff to get rid of/merge the duplicated code if you wish.

Categories

Resources