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]
Related
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
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
I got this class :
import java.util.*;
public class MatrixArrayList extends AbstractMatrix {
private ArrayList<ArrayList<Integer>> values;
public MatrixArrayList(int nbl, int nbc) {
super(nbl, nbc);
values=new ArrayList<ArrayList<Integer>>();
}
#Override
public int getValue(int x, int y) {
return values.get(x).get(y) ;
}
#Override
public void setValue(int x, int y, int value) {
values.get(x).set(y, value);
}
}
and I got
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
I want to make a matrix with an ArrayList
i have w problem with this :
valeurs.get(x).set(y, valeur);
It's not clear from your code which call causes the exception, however it is clear that you are not initializing your inner array-list, nor are you adding any objects to it.
When you initialize it in the constructor:
values=new ArrayList<ArrayList<Integer>>();
What you're basically doing is instantiating the values object to be an ArrayList of size 0 (no items have been added to it yet).
Then, if say, you're doing setValue at index 0, you get the exception because when you do get(x), you're basically doing get(0) on a collection of size 0 - there is nothing to get, you exceed the bounds of the your array.
What you might want to do is initialize all arrays in the constructor:
public MatrixArrayList(int nbl, int nbc) {
super(nbl, nbc);
values=new ArrayList<ArrayList<Integer>>(nbl);
for (int i = 0; i < nbl; i++) {
values.add(new ArrayList<Integer>(nbc));
}
}
And then you can access them without a problem in getValue or setValue (you'll get this exception if you actually do exceed the bounds or if you haven't set any value at the specific index yet. See comment below:).
Notice, though, that since you're using the ArrayList object, rather than a primitive int[] array, you still don't have values inside your array. Simply doing new ArrayList<Integer>() or even new ArrayList<Integer>(num) still leaves you with a list of size 0. If you want to cover all your bases, you might want to either initailize your ArrayList, or perform bounds checks before each get you make in either getValue or setValue.
new ArrayList<ArrayList<Integer>>() creates an empty list. To fill that list with values, you need to call add().
Assuming you want to fill matrix with nbl lists of nbc null values:
this.values = new ArrayList<>(nbl);
for (int i = 0; i < nbl; i++) {
ArrayList<Integer> row = new ArrayList<>(nbc);
for (int j = 0; j < nbc; j++)
row.add(null);
this.values.add(row);
}
You could also fill it with 0 values if you want.
Of course, if the matrix cannot change size, it would likely be much better to create a simple array version, instead of the ArrayList version you're trying to create.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Shell {
static List<ArrayList<ArrayList<Double>>> read(String filename) {
ArrayList<ArrayList<Double>> A = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> B = new ArrayList<ArrayList<Double>>();
String thisLine;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
// Begin reading A
while ((thisLine = br.readLine()) != null) {
if (thisLine.trim().equals("")) {
break;
} else {
ArrayList<Double> line = new ArrayList<Double>();
String[] lineArray = thisLine.split("\t");
for (String number : lineArray) {
line.add((double) Integer.parseInt(number));
}
A.add(line);
}
}
// Begin reading B
while ((thisLine = br.readLine()) != null) {
ArrayList<Double> line = new ArrayList<Double>();
String[] lineArray = thisLine.split("\t");
for (String number : lineArray) {
line.add((double) Integer.parseInt(number));
}
B.add(line);
}
} catch (IOException e) {
System.err.println("Error: " + e);
}
List<ArrayList<ArrayList<Double>>> res = new LinkedList<ArrayList<ArrayList<Double>>>();
res.add(A);
res.add(B);
return res;
}
static int[][] ijkAlgorithm(ArrayList<ArrayList<Integer>> A,
ArrayList<ArrayList<Integer>> B) {
int n = A.size();
// initialise C
int[][] C = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
C[i][j] += A.get(i).get(k) * B.get(k).get(j);
}
}
}
return C;
}
static void printMatrix(Matrix matrix, int n) {
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder(matrix.length);
for (int j = 0; j < n; j++) {
if (j != 0) {
sb.append("\t");
}
String formattedString = String.format("%.0f", matrix.get(i, j))
sb.append(formattedString);
}
System.out.println(sb.toString());
}
}
public static void main(String[] args) {
String filename;
if (args.length < 2) {
filename = "2000.in";
} else {
filename = args[1];
}
List<ArrayList<ArrayList<Double>>> matrices = read(filename);
ArrayList<ArrayList<Double>> A = matrices.get(0);
ArrayList<ArrayList<Double>> B = matrices.get(1);
int n = A.size();
double[][] Aarray = new double[n][n];
double[][] Barray = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Aarray[i][j] = A.get(i).get(j);
Barray[i][j] = B.get(i).get(j);
}
}
Matrix AM = new Matrix(Aarray);
Matrix BM = new Matrix(Aarray);
Matrix CM = AM.times(BM);
printMatrix(CM, n);
}
}
input file that have matrices you want to do this operation
Hope this code helps happy coding.
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)));
}
Hello Professionals,
I was taking a test online coding challenge in a website. They provide me 2
program. I had done a program and second one is below.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution{
/*
* Complete the function below.
*/
/* Write your custom functions here */
static void mergeArray(int []a, int []b, int M ){
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int _a_cnt = 0;
int[] _a = new int[100001];
int[] _b = new int[200002];
try {
_a_cnt = sc.nextInt();
}catch (Exception e) {
System.out.println("Here: " + e.getMessage());
}
for( int i = 0;i < _a_cnt;i++ ){
_a[i] = sc.nextInt();
}
for( int i = 0;i < _a_cnt;i++ ){
_b[i] = sc.nextInt();
}
mergeArray(_a ,_b,_a_cnt);
for( int i = 0;i < 2 * _a_cnt;i++ ){
System.out.print(_b[i] + " ");
}
}
}
In my understanding we need to write a piece of code for merge two array ( that already defined there like int []a, int []b, int M) and we should return it to main program. Here is my question how can we merge that two array and return it? Is there any technique to handle memory reference ( Like C# out,ref keyword ) in java?
Rule : You should not modify main function.
Here is some output:
Sample Input:
a = {3,5,6,9,12,14,18,20,25,28}
b = {30,32,34,36,38,40,42,44,46,48 }
Expected output :
{3,5,6,9,12,14,18,20,25,28,30,32,34,36, 38,40,42,44,46,48}
It's fairly obvious by the lengths of the arrays that the task is to merge the first array into the second (since the length of her second array is double that of the first, yet they both must contain the same number of inputted values).
It ain't that complex:
static void mergeArray(int[] a, int[] b, int n) {
for (int i = n*2 - 1, x = n - 1, y = n - 1; i >= 0; i--)
b[i] = x >= 0 && a[x] >= b[y] ? a[x--] : b[y--];
}
Tested and works.
Using foreach:
static void mergeArray(int[] a, int[] b, int M) {
int c[] = new int[a.length + b.length];
int k = 0;
for (int i : a)
c[k++] = i;
for (int i : b)
c[k++] = i;
}
Using System.arraycopy:
static void mergeArrays(int[] a, int[] b) {
int aLength = a.length;
int bLength = b.length;
int[] c = new int[aLength + bLength];
System.arraycopy(a, 0, c, 0, aLength);
System.arraycopy(b, 0, c, aLength, bLength);
}
Hope below code snippet helps :)
static void mergeArray(int []a, int []b, int m ){
int[] c= new int[100001];
System.arraycopy(a, 0, c, 0, m);
System.arraycopy(b, 0, c, m, m*2);
System.arraycopy(c, 0, b, 0, m*2);
}
Test Results -> Sample Input:
a = {3,5,6,9,12,14,18,20,25,28}
b = {30,32,34,36,38,40,42,44,46,48 }
output Printed:
{3,5,6,9,12,14,18,20,25,28,30,32,34,36, 38,40,42,44,46,48}
Answer:
static void mergeArray(int []a, int []b, int M ){
for( int i = 0;i < M;i++ ){
b[M+i] = a[i];
}
}
Ofcourse didn't check indexes. may be i <= M in for loop