Java fill an array with random with random numbers - java

I have a homework assignment where a user must input the size of an array and then the array must be filled with random values. I am having issues filling the array with something that isn't garbage values. I am sure there are other issues with my code as well but this is the biggest issue I'm currently trying to solve. Any help would be appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
public class rotateArray1
{
public static int randomFill()
{
Random rand = new Random();
int randomInt = rand.nextInt();
return randomInt;
}
void leftRotate(int arr[], int d, int n)
{
int i;
for(i=0; i < d; i++)
leftRotateByOne(arr, n);
}
void leftRotateByOne(int arr[], int n)
{
int i,temp;
temp = arr[0];
for(i=0; i < n -1; i++)
arr[i] = arr[i+1];
arr[i] = temp;
}
void printArray(int arr[],int size)
{
int i;
for (i = 0; i<size;i++)
System.out.print(arr[i]+ "");
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter size of array");
int x= input.nextInt();
int[] arr = new int[x];
for(int i = 0; i<x; i++){
arr[i] = randomFill();
}
rotateArray rotate = new rotateArray();
rotate.leftRotate(arr, 2, x);
rotate.printArray(arr, x);
System.exit(0);
}
}

Just pass a reference to the array to randomFill and do it in one shot. That helps the code in main() read easier and uses one instance of a Random which is probably more what you want as was pointed out.
import java.util.Random;
public class JavaTest {
public static void main(String... args) {
int[] array = new int[10];
randomFill(array);
for(int i = 0; i < array.length ; i++){
System.out.println("array["+i+"] = "+array[i]);
}
}
static void randomFill(int[] array)
{
Random rand = new Random();
for(int i = 0; i < array.length ; i++){
array[i] = rand.nextInt();
}
}
}
Output:
array[0] = 431970257
array[1] = 9846759
array[2] = 1919609165
array[3] = -544686432
array[4] = 655372436
array[5] = -331654257
array[6] = -1187729012
array[7] = 1378209257
array[8] = -1225327561
array[9] = 1887304192

Related

How to determine your programs runtime?

I have to write a divide-and-conquer program to solve the following problem. Let A[1..n] and B[1..n] be two arrays of distinct integers, each sorted in an increasing order.Find the nth smallest of the 2n combined elements. I can not merge the two arrays. My program must be in O(log n) time.
I have written my program but have no clue how to determine if it meets the requirement of the run time.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// this section of code will require user input to have the value of n to be set
Scanner sc = new Scanner(System.in);
System.out.print(("What number would you like to set n equal to : "));
int value = sc.nextInt();
// this section of code set the two array only to hold the value of n
Random rand = new Random();
ArrayList<Integer> setA = new ArrayList<Integer>();
for (int i = 0; i < value; i++) {
int picks = rand.nextInt(1000);
setA.add(picks);
}
Collections.sort(setA);
System.out.println("A1: "+ setA);
ArrayList<Integer> setX = new ArrayList<Integer>();
for (int k = 0; k < value; k++) {
int picks = rand.nextInt(1000);
setX.add(picks);
}
Collections.sort(setX);
System.out.println("A2: "+ setX);
ArrayList<Integer> afinal = new ArrayList<Integer>();
int r = 0;
int f = 0;
int q = 0;
while(afinal.size()!= value) {
if(setA.get(r) < setX.get(f)) {
q = setA.get(r);
afinal.add(q);
r++;
}else {
q = setX.get(f);
afinal.add(q);
f++;
}
}
System.out.println("");
System.out.println(afinal);
int w = value - 1;
int ans = afinal.get(w);
System.out.println("");
System.out.println("The nth smallest integer is "+ ans);
}
}
You can calculate runtime with System.currentTimeMillis().
What we want to do is get the current time before the program runs, then get the time after the program runs. We then handle the two times accordingly.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
long before = System.currentTimeMillis();
// this section of code will require user input to have the value of n to be set
Scanner sc = new Scanner(System.in);
System.out.print(("What number would you like to set n equal to : "));
int value = sc.nextInt();
// this section of code set the two array only to hold the value of n
Random rand = new Random();
ArrayList<Integer> setA = new ArrayList<Integer>();
for (int i = 0; i < value; i++) {
int picks = rand.nextInt(1000);
setA.add(picks);
}
Collections.sort(setA);
System.out.println("A1: "+ setA);
ArrayList<Integer> setX = new ArrayList<Integer>();
for (int k = 0; k < value; k++) {
int picks = rand.nextInt(1000);
setX.add(picks);
}
Collections.sort(setX);
System.out.println("A2: "+ setX);
ArrayList<Integer> afinal = new ArrayList<Integer>();
int r = 0;
int f = 0;
int q = 0;
while(afinal.size()!= value) {
if(setA.get(r) < setX.get(f)) {
q = setA.get(r);
afinal.add(q);
r++;
}else {
q = setX.get(f);
afinal.add(q);
f++;
}
}
System.out.println("");
System.out.println(afinal);
int w = value - 1;
int ans = afinal.get(w);
System.out.println("");
System.out.println("The nth smallest integer is "+ ans);
long after = System.currentTimeMillis();
}
}
In the example above, we've got the two times. Now what do we do?
We can subtract them to get the difference in times (by milliseconds).
Like so:
long ellapsedMilliseconds = after-before;
If you want to get the elapsed time in seconds, divided ellapsedMilliseconds by 100.
So the final code should be;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
long before = System.currentTimeMillis();
// this section of code will require user input to have the value of n to be set
Scanner sc = new Scanner(System.in);
System.out.print(("What number would you like to set n equal to : "));
int value = sc.nextInt();
// this section of code set the two array only to hold the value of n
Random rand = new Random();
ArrayList<Integer> setA = new ArrayList<Integer>();
for (int i = 0; i < value; i++) {
int picks = rand.nextInt(1000);
setA.add(picks);
}
Collections.sort(setA);
System.out.println("A1: "+ setA);
ArrayList<Integer> setX = new ArrayList<Integer>();
for (int k = 0; k < value; k++) {
int picks = rand.nextInt(1000);
setX.add(picks);
}
Collections.sort(setX);
System.out.println("A2: "+ setX);
ArrayList<Integer> afinal = new ArrayList<Integer>();
int r = 0;
int f = 0;
int q = 0;
while(afinal.size()!= value) {
if(setA.get(r) < setX.get(f)) {
q = setA.get(r);
afinal.add(q);
r++;
}else {
q = setX.get(f);
afinal.add(q);
f++;
}
}
System.out.println("");
System.out.println(afinal);
int w = value - 1;
int ans = afinal.get(w);
System.out.println("");
System.out.println("The nth smallest integer is "+ ans);
long after = System.currentTimeMillis();
long ellapsedMilliseconds = after-before;
System.out.println("Execution time: "+elapsedMilliseconds);
}
}

Java Hackerank left array Rotation

We have a method in which an array and number of rotations are passed as input and we have to return the array after left rotations. Here is my solution.
static int[] rotLeft(int[] a, int d) {
int i = 0;
int logicBreak = d;
int[] copy = new int[a.length]; // SEE HERE GUYS, WHY THIS WORKS
int[] copy = a; // AND WHY NOT THIS,
while(logicBreak < a.length){
copy[i] = a[logicBreak];
i++;
logicBreak++;
}
logicBreak = 0;
while(logicBreak < d){
copy[i] = a[logicBreak];
i++;
logicBreak++;
}
return copy;
}
I hope that there is no confusion until now and if you have then, open this page. So my problem is really basic. Why the answer works when I do this int[] copy = new int[a.length]; but does not work when I do this int[] copy = a;. Can you tell me the difference, because we are changing all the values of copy array, so what is the matter we make it new int[] or same as the array a. I have created an android app but I am still not getting this array concept, if there is a difference then please tell me.
For your ease here is the full code.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the rotLeft function below.
static int[] rotLeft(int[] a, int d) {
int i = 0;
int logicBreak = d;
int[] copy = new int[a.length];
while(logicBreak < a.length){
copy[i] = a[logicBreak];
i++;
logicBreak++;
}
logicBreak = 0;
while(logicBreak < d){
copy[i] = a[logicBreak];
i++;
logicBreak++;
}
return copy;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nd = scanner.nextLine().split(" ");
int n = Integer.parseInt(nd[0]);
int d = Integer.parseInt(nd[1]);
int[] a = new int[n];
String[] aItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int aItem = Integer.parseInt(aItems[i]);
a[i] = aItem;
}
int[] result = rotLeft(a, d);
for (int i = 0; i < result.length; i++) {
bufferedWriter.write(String.valueOf(result[i]));
if (i != result.length - 1) {
bufferedWriter.write(" ");
}
}
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
When you do the following:
int[] copy = a;
You are just assigning the reference of a to copy. They "refer" to the same location in memory.
Here is a demo
int[] a = {1,2,3};
int[] copy = a;
a[1] = 100;
System.out.println(Arrays.toString(copy));
Prints
[1,100,3]

Why is using an object array a better idea in this code?

Our assignment was to solve the Hackerrank question on arraylist without using 2D arrays or lists. Basically, you would need to input multiple arrays of different sizes and display an element based on the input of (array number, position). My implementation seemed to work just fine for my test cases but failed 4/6 of Hackerrank's test cases. Our lecturer's code (of course) worked perfectly. But what I fail to understand, is advantage of his approach:
My Code ::
import java.io.PrintStream;
import java.util.Scanner;
class arraylist {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int NoOfLines = sc.nextInt();
int[] input = new int[20000];//To store all input arrays one after the other in one 1D array.
int[] index = new int[NoOfLines];//Starting positions of each array input.
int[] NoOfArrayElements = new int[NoOfLines];//Sizes of each corresponding input array.
int position = 0;
int count = 0;
int arrayelementpos = 0;
//Store the input and note the size of each array and the index position.
for (int i = 0; i < NoOfLines; i++) {
int arrarLength = sc.nextInt();
NoOfArrayElements[arrayelementpos++] = arrarLength;
index[position++] = count;
for (int j = 0; j < arrarLength; j++)
input[count++] = sc.nextInt();
}
//Code to input queries (array no, element position)
int NoOfQueries = sc.nextInt();
int[] result = new int[NoOfQueries];
int pos = 0;
for (int i = 0; i < NoOfQueries; i++) {
int arrayNo = sc.nextInt();
int element = sc.nextInt();
if ((arrayNo > NoOfLines) || element > NoOfArrayElements[arrayNo - 1]) {
System.out.println("ERROR!");
continue;
}
pos = index[arrayNo - 1] + element - 1;
System.out.println("THE ELEMENT IS ::" + input[pos]);
}
}
}
My lecturer's code ::
import java.io.*;
import java.util.*;
public class arraylistsolved {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Object [] store=new Object[n];
for(int i=0; i<n;i++){
int d=sc.nextInt();
int [] ar=new int[d];
for(int j=0;j<d;j++) {
ar[j]=sc.nextInt();
}
store[i]=ar;
}
int q=sc.nextInt();
for(int i=0;i<q;i++){
int array=sc.nextInt()-1;
int element=sc.nextInt()-1;
Object obj=store[array];
int [] retrieve = (int []) obj;
if(array>n||element>retrieve.length-1)
System.out.println("ERROR!");
else
System.out.println(retrieve[element]);
}
}
}
As mentioned, both the codes are working for small test cases, but mine breaks down for very large ones for some reason. You can try copy-pasting the code here: https://www.hackerrank.com/challenges/java-arraylist/problem

Java ArrayIndexOutOfBoundsException 1 Error

I am trying to do a factorial trailing zero exercise, but I keep getting array index out of bound error. Need help fixing this. Thanks!
import java.util.Scanner;
class Exercise3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] list = new int [n];
int num = 1;
int div = 5;
int count = 0;
for (int i=0;i<n;i++) {
list[i] = sc.nextInt();
}
for (int i=0;i<num;i++) {
while (list[i] > div) {
count += list[i] / div;
div=div*5;
num++;
}System.out.println(count);
}
}
You have
for (int i=0;i<num;i++) {
and then
num++;
that increments at every circle.
Thats why.

illegal start of type: Often this message means that you are missing a { BEFORE this line

Could anyone help me out with this error?
I couldn't rectify this code.
I can't understand the error.
import java.io.*;
import java.util.Scanner;
public class findMax{
public static int findMax(int[] arr){
int max = 0;
for (int i = 1; i < value.length; i++){
if (value[i] > max){
max = value[i];
}
}
return max;
}
public static void main(String[] args){
int value[];
Scanner in = new Scanner(System.in);
value = in.nextInt();
findMax(value);
}
}
In the function findMax, you need to be consistent with your array variable name (you're currently passing int[] arr but accessing value). Also, you don't want to default max to 0 (you could use arr[0]). Something like,
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
Next, you need to instantiate and assign values into your array (and do something with the result of findMax as is the result isn't used). There are a few ways to do that. One might be,
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] value = new int[] { in.nextInt() };
int max = findMax(value);
System.out.printf("The max value in %s is %d.%n", Arrays.toString(value), max);
}
Alternatively, you could create the array like
int[] value = new int[1];
value[0] = in.nextInt();
Also, you could eliminate the if if you use Math.max(int, int) in findMax like
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
return max;
}
import java.util.ArrayList;
import java.util.Scanner;
public class Stack{ public static int findMax(ArrayList<Integer> arr){
int max = 0;
for (int i = 1; i < arr.size(); i++){
if (arr.get(i) > max){
max = arr.get(i);
}
}
return max;
}
public static void main(String[] args){;
Scanner in = new Scanner(System.in);
ArrayList<Integer> value = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (in.hasNextInt()) {
value.add(in.nextInt());
}
System.out.println(findMax(value));
}}
Try this
public static int findMax(ArrayList<Integer> arr){
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++){
if (arr.get(i) > max){
max = arr.get(i);
}
}
return max;
}
public static void main(String[] args){;
Scanner in = new Scanner(System.in);
ArrayList<Integer> value = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (in.hasNextInt()) {
value.add(in.nextInt());
}
System.out.println(findMax(value));
}

Categories