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
Related
I'm very new to java and have been playing around with sorting algorithms. I have the following code working for a set array. I was just wondering what I'd need to change to get it to sort arrays of randoms lengths and integers. I guess the answer is pretty obvious any help is appreciated!
public static void main(String[] args) {
int number[]={8,5,3,2,9};
int temp;
boolean fixed=false;
while(fixed==false){
fixed=true;
for(int i=0; i<number.length-1 ; i++){
if(number[i] > number[i+1]){
temp = number[i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for(int i=0; i<number.length; i++)
System.out.println(number[i]);
}
}
I mean, your algorithm would work regardless of the array's length. About how to generate such arrays, you could do this:
int n = Math.random()*10000 + 1; //so its never 0.
int number[] = new int[n];
for(int i=0;i<n;i++) number[i]=Math.random()*10000;
Everything else stays the same :).
EDIT: You commented on the question that you'd rather generate the array by taking an input from the keyboard. You can do that by using a scanner.
Scanner scanIn = new Scanner(System.in);
do{
int n = scanIn.nextInt();
} while (n<1);
int number[] = new int[n];
for(int i=0;i<n;i++) number[i] = scanIn.nextInt();
scanIn.close();
What you are looking for is probably a method to extract your bubblesort to. Please note that this method changes the input array and does not return a new array.
private static void bubblesort(int[] array) {
int temp;
boolean fixed = false;
while (!fixed) {
fixed = true;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
fixed = false;
}
}
}
}
You can then call it using different approaches.
Fixed size array:
// fixed size array
int number[] = {8, 5, 3, 2, 9};
bubblesort(number);
System.out.println(Arrays.toString(number));
Read numbers from System.in.
// read from sys.in like "2 6 4"
Scanner s = new Scanner(System.in);
String line = s.nextLine();
int[] parsedInts = Arrays.stream(line.split("\\s+")).mapToInt(Integer::parseInt).toArray();
bubblesort(parsedInts);
System.out.println(Arrays.toString(parsedInts));
You can the use Scanner Class in java and need to import java.util.Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array length :");
int n = sc.nextInt();
int number[] = new int[n];
System.out.println("Enter the numbers :");
for(int i = 0; i < number.length; i++) {
number[i] = sc.nextInt();
}
I am new to java programming and i am trying to sort arrays using Arrays.sort() function. After using Arrays.sort(array),I am printing the final sorted array.
For example:
Input : 1 3 2 4
Output comes as : 0 0 0 0.
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n,temp,count;
int[] array = new int[MAX_SIZE];
n = input.nextInt();
for(int i = 0 ; i < n ; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for(int i = 0 ; i < n ; ++i) {
System.out.print(array[i]+" ");
}
}
}
You have initialized you array to hold 20 integers but you input only 5. Hence the first 15 elements will be 0 followed by the numbers you have inputted once the array is sorted.
To fix the issue you can initialize the array with n instead of MAX_SIZE as shown below:-
n = input.nextInt();
int[] array = new int[n];
Set the size of the array to match what your input should be, not to the maximum allowed size:
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, temp, count;
n = input.nextInt();
if (n > MAX_SIZE) {
//handle error somehow
}
int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; ++i) {
System.out.print(array[i] + " ");
}
}
}
When you initialize an array in Java it gets default value of 0 for primitive int:
int[] array = new int[MAX_SIZE];
The fact that you are not seeing your desired input of 1,2,3,4 is a separate problem with your Scanner code.
I want to take the average while value in column A is lower than its next value and value in column B is the same as its next value. The average is taken from column C value based on column A value as column C index. Following is the data sample:
columnA,B,C
0,0,0.36
1,0,0.23
2,0,0.14
3,1,0.41
4,1,0.44
5,2,0.16
6,2,0.03
7,2,0.09
Following is my current code:
import java.io.*;
import java.util.*;
public class dtw_post {
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
int x = 655;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
while(scannerFile.hasNextLine()){
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[x];
for(int i = 0; i<N; i++)
{
a[i]=Integer.parseInt(lineVector[0]);
b[i]=Integer.parseInt(lineVector[1]);
c[i]=Double.parseDouble(lineVector[2]);
}
System.out.println((dtw_post.lookup(a,b,c)));}
}
static String lookup (int[] a, int[] b, double[] c){
int j=0; int i=0;
String[] final_result = new String[c.length];
while(i < a.length-1){
if (a[i] < a[i+1] && b[i] == b[i+1]) {
double[] d = {c[a[i]],c[a[i+1]]};
double sum = 0;
int number = 0;
for (double val : d) {
++number;
sum += val;
}
double e = sum/number;
final_result[i] = String.valueOf(e);
i++;
}
else {
final_result[i] = String.valueOf(c[a[i]]);
i++;
}
}
String result = final_result[j]; j++;
return result;
}
}
I expect it to output 0.243 in the first line as the average of 0.36,0.23,and 0.14. I figure that the problem is in the if condition in the lookup method. It seems to skip the if and run the else condition only. My current code output column C exactly as it is. What went wrong in my if condition loop? Thank you for your time.
The first issue is you are parsing the file wrong. You are parsing the file line by line in a while loop. But you are creating new a, b and c arrays for each line. Move the initialization out of the for loop :
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
int x = 655;
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[x];
int i = 0;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
while (scannerFile.hasNextLine()) {
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
a[i] = Integer.parseInt(lineVector[0]);
b[i] = Integer.parseInt(lineVector[1]);
c[i] = Double.parseDouble(lineVector[2]);
++i;
}
System.out.println((dtw_post.lookup(a, b, c)));
}
Based on that you will only get an average of two consecutive values. You also need to rethink the lookup function. Increase the sum until the value in b changes and then calculate the average and print it. E.g
static String lookup(int[] a, int[] b, double[] c) {
String result = "";
double sum = c[a[0]];
int consecutive = 1;
for (int i = 1; i < a.length - 1; ++i) {
if (a[i - 1] < a[i] && b[i - 1] == b[i]) {
sum += c[a[i]];
++consecutive;
} else {
result += String.valueOf(sum / consecutive) + '\n';
sum = c[a[i]];
consecutive = 1;
}
}
return result;
}
Ad a side note, you should also consider StringBuilder for concatenating strings in a loop
In your if condition you required that a[i] is less than a[i+1], shouldn't it be a[i] greater than a[i+1]?
So the if should be:
if(a[i]>a[i+1] && b[i]==b[i+1]){
....
You are processing only one line of the file at a time. The loop reads one line from the file and splits it to get values for a,b,c. Then it copies these values into EVERY cell in the corresponding arrays, and then calls lookup. Since every value of a is the same, if statement is never true.
What you want to do is fill in each successive cell in a,b,c with the next line read, and call lookup outside the while loop. What I think you want is:
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[N];
int i = 0;
while(scannerFile.hasNextLine()){
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
a[i]=Integer.parseInt(lineVector[0]);
b[i]=Integer.parseInt(lineVector[1]);
c[i]=Double.parseDouble(lineVector[2]);
i++;
}
System.out.println((dtw_post.lookup(a,b,c)));
}
I'm trying to get num to create multiple scenarios and get 10 inputed variables from the user which I will then utilize to print out. Once the variables are printed out I need to average them but I got stuck. Could you give me some tips?
final static int num = 10;
static Scanner scan = new Scanner(System.in);
public static void main (String[]args)
{
int[] list = new int [num];
for(int i = 0; i<=num; i++)
{
System.out.println("Enter an integer");
int num[] = scan.nextInt();
}
System.out.println(Print_it(list) / 10);
}
public static double Print_it(int[] list)
{
int number = 0;
for (int i = 0; i<10; i++)
{
number = number + list[i];
}
return(number);
}
The for loops should be using the correct test. 'i<=num' will cause an exception when i == num.
The "int num[] = scan.nextInt()" statement has illegal syntax.
You should be using 'num' wherever you currently use 10, and it should be named 'NUM' to conform to standard Java naming conventions for constants.
Print_it (which should be named more like 'printIt') is not printing anything.
Here is a better implementation:
import java.util.Scanner;
public class Main {
final static int NUM = 10;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
final int[] list = new int[NUM];
for (int i = 0; i < NUM; i++) {
System.out.println("Enter an integer");
list[i] = scan.nextInt();
}
printIt(list);
}
public static void printIt(int[] list) {
final int length = list.length;
int total = 0;
for (int i = 0; i < length; i++) {
final int n = list[i];
System.out.println(n);
total += n;
}
System.out.println("Average: " + (double)total / length);
}
}
How do I change a set array sized into a random sized array chosen by the user.
Here is how I have it setup for set a sized array. I just do not know how to convert over to a random sized....
import java.util.Scanner;
public class Project1a {
public static void scanInfo()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: ");
int rows = input.nextInt();
System.out.println("Enter number of columns: ");
int columns = input.nextInt();
int[][] nums = new int[rows][columns];
static int[][] sample = nums;
}
static int[][] results = new int[4][5];
static int goodData = 1;
public static void main(String[] args) {
analyzeTable();
printTable(results);
}
static void analyzeTable() {
int row=0;
while (row < sample.length) {
analyzeRow(row);
row++;
}
}
static void analyzeRow(int row) {
int xCol = 0;
int rCount = 0;
while (xCol < sample[row].length) {
rCount = analyzeCell(row,xCol);
results[row][xCol] = rCount; // instead of print
xCol++;
}
}
static int analyzeCell(int row, int col) {
int xCol = col; // varies in the loop
int runCount = 0; // initialize counter
int rowLen = sample[row].length; // shorthand
int hereData = sample[row][xCol]; // shorthand
while (hereData == goodData && xCol < rowLen) {
runCount++;
xCol++;
if (xCol < rowLen) { hereData = sample[row][xCol];}
}
return runCount;
}
/* Start Print Stuff */
public static void printTable(int[][] aTable ) {
for (int[] row : aTable) {
printRow(row);
System.out.println();
}
}
public static void printRow(int[] aRow) {
for (int cell : aRow) {
System.out.printf("%d ", cell);
}
}
}
/* End Print Stuff */
I am now only getting one error at line 18: illegal start of expression. I do not think I have the variables defined correctly.
You could re-write your code in order to use ArrayList's:
import java.util.ArrayList;
//Here you create an 'array' that will contain 'arrays' of int values
ArrayList<ArrayList<Integer>> sample = new ArrayList<ArrayList<Integer>>();
then add each row:
sample.add(new ArrayList<Integer>());
and add an element to a row:
sample.get(0).add(5); // get(0) because is the first row, and 5 is int
Of course you will have to modify your code to use this kind of array.
You can't change array sizes in Java, although it gets complicated when working with multi-dimensional arrays. I would recommend familiarizing yourself with the Java Array docs.
What you can do is create a new array of the desired size and then copying data from the old array into the new one.
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: "); // get number of rows
int rows = input.nextInt();
System.out.println("Enter number of columns: "); // get number of columns
int columns = input.nextInt();;
int[][] nums = new int[rows][columns]; // new 2D array, randomly
// sized by user input
Is this all you're looking for? Based off your question, that's what it seems like
If you want a method populate it with random 1's and 0's, Just do this
static void populate(int[][] nums) {
for (int i = 0; i < row.length; i++) {
for (int j = 0; j < column.length; i++) {
nums[row][column] = (int)(Math.random() + 1);
}
}
}
Now num is a 2D matrix with random 1's and 0's