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
Related
I'm trying to write a method that takes two int [] as arguments and returns a new int [] which is filled in an alternating sequence from the two given arrays. Ex: given arrays [1,2,3] and [10,20,30] would return [1,10,2,20,3,30]. Any help would be great, thanks.
This is what I have right now:
public int [] alternate(int [] a, int [] b){
int[] c = new int[a.length + b.length]
for (int i = 0; i < c.length; i + 2){
c[i] = a[i];
c[i + 1] = b[i];
}
return c;
Missing semicolon
Increment only to length of a - assume a and b are same size
Have counter to keep track of where new elements are inserted, or use idea as per #ErwinBolwidt
increment i normally
Note to self to test code before posting
So
public static int [] alternate(int [] a, int [] b){
int[] c = new int[a.length + b.length];
int counter = 0;
for (int i = 0; i < a.length; i++){
c[counter++] = a[i];
c[counter++] = b[i];
// or
//c[2 * i] = a[i];
//c[2 * i + 1] = b[i];
}
return c;
}
Main Test:
public static void main(String[] args) {
int[] a = {1,2,3} ;
int[] b = {10,20,30} ;
int[] test = alternate(a,b);
System.out.println(Arrays.toString(test));
}
Console Output:
[1, 10, 2, 20, 3, 30]
If a and b arrays are not of same length, you can use the following method
public static int[] alternate(int[] a, int[] b) {
int min, max;
int count = 0;
min = Math.min(a.length, b.length);
max = Math.max(a.length, b.length);
int c[] = new int[min+max];
for(int i=0; i<max; i++) {
if(i<min) {
c[count++] = a[i];
c[count++] = b[i];
}else {
if(a.length==min) {
c[count++] = b[i];
}else {
c[count++] = a[i];
}
}
}
return c;
}
Main test
public static void main(String[] args) {
int[] a = {1,2,3,4} ;
int[] b = {10,20,30} ;
int[] test = alternate(a,b);
System.out.println(Arrays.toString(test));
}
Output:
[1, 10, 2, 20, 3, 30, 4]
I have two data sets, the first one is 3D and the second is 2D.
How can I implement the subtract of the two sets.
:
import java.util.*;
class test28{
public static void main ( String[] args ) {
int [][][] arr1 = {{{6,3,9,0},{8,6,5,3}}};
int [][] arr2= {{6,3,9,0},{8,6,5,3}};
test28 test = new test28();
System.out.println(test.subtract(arr1,arr2));
}
public static int [][] subtract(int[][][] a, int[][] b) {
int [][] diff = new int[a.length][a[0].length];
for (int i = 0; i < a.length - 1; i++) {
for ( int j=0; j<a[0].length; j++){
for ( int k=0; k<a[0][0].length; k++) {
diff[0][i] = a[i][j][k]- b[i][j];
}
}
}
return diff;
}
}
the code below generates an error :
i changed the diff instantiated, then i have indexoutofbound error
at diff[0][i] = a[i][j][k]- b[i][j];
One reasonable explanation is the following:
int [][] diff = new int[a[0].length][a[0][0].length];
for ( int j=0; j<a[0].length; j++){
for ( int k=0; k<a[0][0].length; k++)
diff[j][k] = a[0][j][k]- b[j][k];
Of course the dimensions must match so you have to perform that checking.
I dont see the purpose of this.
Dear fellow Stackoverflowers,
My swap method isn't working inside the insertionSort method; it is not swapping my array elements.
What's wrong with my insertion sort algorithm?
package AlgoExercises;
import java.util.Arrays;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length - 1; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(numbersArray[j], numbersArray[j - 1]);
j = j - 1;
System.out.println(Arrays.toString(numbersArray));
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}
Solution:
After fixing the swap method where int[] was included in its parameters, swap now works! I've also edited numbersArray.length-1 to numbersArray.length.
Thank you for your help guys!
package AlgoExercises;
import java.util.Arrays;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int i, int j) {
int temp = numbersArray[j];
numbersArray[j] = numbersArray[i];
numbersArray[i] = temp;
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(j, j - 1);
j = j - 1;
System.out.println(Arrays.toString(numbersArray));
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}
Java is a pass by value language, so swapping the int variables passed to the swap method makes no difference. You should pass the array itself + the two indices to swap to the method, and modify the array in the swap method.
static void swap(int[] arr, int i, int j) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
and call it
swap(numbersArray, j, j-1);
Note that I didn't check the logic of your insertion sort implementation. This answer only deals with the swap issue.
Just to give you another way of thinking why your existing swap method doesn't work: if you write code like this:
void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
void callSwap() {
int x = 1;
int y = 2;
swap(x, y);
System.out.println(x + ", " + y);
}
You can 'inline' the swap method, basically copying it into the callSwap method. The semantically equivalent code would be:
void callSwap() {
int x = 1;
int y = 2;
// Start of inlined swap method.
{
int a = x;
int b = y;
int t = a;
a = b;
b = t;
}
// End of inlined swap method.
System.out.println(x + ", " + y);
}
Hopefully, you wouldn't expect x and y to have swapped values.
Note that this behaviour has nothing to do with the fact that the variable names a and b are different to x and y; I simply chose them to be different. Were the parameters of swap called x and y, it would be necessary to rename them to something else when inlining, since they are completely separate from the x and y in callSwap.
public class intersect {
public static void find(int[] a, int[] b, int[] acc)
{
int position = 0;
for (int j = 0; j < a.length; j++) {
for (int k = 0; k<b.length; k++) {
if (a[j] == b[k]) {
acc[position] = b[k];
position++;
}
}
}
System.out.println(java.util.Arrays.toString(acc));
}
public static void main (String[] s)
{
int[] acc = new int[2];
int[] a = {1,2,3};
int[] b = {2,3,4};
find(a, b, acc);
}
}
I have written the above code to solve the problem.
But if you see, the function is very limited because I have to change the length of the acc every time. That means I have to know how many elements are intersecting. In this case, the array {1,2,3} and {2,3,4} have {2,3} in common, so the length of the acc would be 2.
I am sure there are millions of ways of tackling this problem, but I cannot seem to think of a way of fixing this.
Please help!
If your professor wants you to use arrays, you can use the following method:
public static int[] resize(int[] arr)
{
int len = arr.length;
int[] copy = new int[len+1];
for (int i = 0; i < len; i++)
{
copy[i] = arr[i];
}
return copy;
}
This will increase the size of the array by 1. You can use that instead. By the way, you're not using the fact that they're sorted in your find() method. What you should do is this:
public static void find(int[] a, int[] b, int[] acc)
{
int a_index = 0, b_index = 0, acc_index = -1;
int a_element, b_element;
while (a_index < a.length && b_index < b.length)
{
a_element = a[a_index]; b_element = b[b_index];
if (a_element == b_element)
{
acc = resize(acc);
acc[++acc_index] = a_element;
a_index++; b_index++;
} else if (b_element < a_element) {
b_index++;
} else {
a_index++;
}
}
System.out.println(java.util.Arrays.toString(acc));
}
This method is more efficient now. Working example.
To find intersection of 2 sorted arrays, follow the below approach :
1) Use two index variables i and j, initial values with 0
2) If array1 is smaller than array2 then increment i.
3) If array1 is greater than array2 then increment j.
4) If both are same then print any of them and increment both i and j.
check this link for more information
https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/
public class FindIntersection {
static void findInterSection(int array1[], int array2[], int array1NoOfElements, int
array2NoOfElements) {
int i = 0, j = 0;
while (i < array1NoOfElements && j < array2NoOfElements) {
if (array1[i] < array2[j]) {
i++;
} else if (array2[j] < array1[i]) {
j++;
}
// if both array elements are same
else {
System.out.println(array2[j++] + " ");
i++;
}
}
}
public static void main(String[] args)
{
int myFirstArray[] = { 1, 2, 4, 5, 5 };
int mySecondArray[] = { 2, 3, 5, 7 };
int m = myFirstArray.length;
int n = mySecondArray.length;
findInterSection(myFirstArray, mySecondArray, m, n);
}
}
Make your intersection array's size the size of the smaller of your original arrays. That way, you won't ever have to increase it's capacity.
Then you can use Arrays.copy to transfer your results into an appropriately sized array.
Not sure if this is the best solution, but you don't need to hard-code the size of the intersection ahead of time (which is one thing you were concerned about).
As you iterate through both arrays, you can add elements found in both sets to a StringBuilder (along with some delimiter, I used a comma in the example below). Once you're finished, you can call toString() & then split() using the delimiter afterwards to get a String[]. At that point, you can put convert those String objects to int primitives & return an int[].
public class Scratch {
public static void main(String[] s) {
int[] a = {1, 2, 3};
int[] b = {2, 3, 4};
int[] intersection = findIntersection(a, b);
System.out.println(Arrays.toString(intersection));
}
public static int[] findIntersection(int[] a, int[] b) {
StringBuilder intersectionStringBuilder = new StringBuilder();
for (int j = 0; j < a.length; j++) {
for (int k = 0; k < b.length; k++) {
if (a[j] == b[k])
intersectionStringBuilder.append(a[j] + ",");
}
}
String[] intersectionStringArray = intersectionStringBuilder.toString().split(",");
int[] intersection = new int[intersectionStringArray.length];
for (int current = 0; current < intersectionStringArray.length; current++) {
intersection[current] = Integer.parseInt(intersectionStringArray[current]);
}
return intersection;
}
}
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j] && !index.contains(j)){
list.add(arr1[i]);
index.add(j);
break;
}
}
}
int result[]=new int[list.size()];
int k=0;
for(int i:list){
result[k]=i;
k++;
}
for(int i=0;i<result.length;i++){
System.out.println(result[i]);
}
return result;
}
Grid Walking (Score 50 points):
You are situated in an N dimensional grid at position (x_1,x2,...,x_N). The dimensions of the grid are (D_1,D_2,...D_N). In one step, you can walk one step ahead or behind in any one of the N dimensions. (So there are always 2N possible different moves). In how many ways can you take M steps such that you do not leave the grid at any point? You leave the grid if you for any x_i, either x_i <= 0 or x_i > D_i.
Input:
The first line contains the number of test cases T. T test cases follow. For each test case, the first line contains N and M, the second line contains x_1,x_2...,x_N and the 3rd line contains D_1,D_2,...,D_N.
So, in the above solution I'm trying to take one dimensional array.
The website claims 38753340 to be the answer, but I'm not getting it.
public class GridWalking {
/**
* #param args
*/
public static void main(String[] args) {
try {
long arr[] = new long[78];
long pos = 44;
long totake = 287;
/*
* Double arr[] = new Double[3]; Double pos = 0; Double totake = 5;
*/
Double val = calculate(arr, pos, totake);
System.out.println(val % 1000000007);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
public static HashMap<String, Double> calculated = new HashMap<String, Double>();
private static Double calculate(long[] arr, long pos, long totake) {
if (calculated.containsKey(pos + "" + totake)) {
return calculated.get(pos + "" + totake);
}
if (0 == totake) {
calculated.put(pos + "" + totake, new Double(1));
return new Double(1);
}
if (pos == arr.length - 1) {
Double b = calculate(arr, pos - 1, totake - 1);
Double ret = b;
calculated.put(pos + "" + totake, new Double(ret));
return ret;
}
if (pos == 0) {
Double b = calculate(arr, pos + 1, totake - 1);
Double ret = b;
calculated.put(pos + "" + totake, new Double(ret));
return ret;
}
Double a = calculate(arr, pos + 1, totake - 1);
Double b = calculate(arr, pos - 1, totake - 1);
Double ret = (a + b);
calculated.put(pos + "" + totake, ret);
return ret;
}
}
You need to change key values as for pos + "_" + totake.
I have rewritten it but I'm not sure it working or not. It takes too much time to complete if ever.
public class GridWalking {
static long arr_length = 78;
static long pos = 44;
static long totake = 287;
static long count = 0;
/**
* #param args
*/
public static void main(String[] args) {
try {
calculate(pos, totake);
System.out.println(count % 1000000007);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
private static void calculate(long pos, long totake) {
if (pos < 0 || pos > arr_length - 1)
return;
if (0 == totake) {
count++;
return;
}
calculate(pos + 1, totake - 1);
calculate(pos - 1, totake - 1);
}
}
I have tried solving that Grid walking problem in Hackerrank. this is the code that had worked(in ecclipse atleast). but i donno why it does not match with given answers. Nut i think you can get the idea from it. Since it does not use recursion, no problem with execution time..
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int count=0;
public static void main(String[] args) throws FileNotFoundException {
String filename = "src/testcases.txt";//testcases is just a file containing input
File file = new File(filename);
Scanner in = new Scanner(file);
//in.useDelimiter("[^0-9]+");
//-----------------------------------------------------------------
int T=in.nextInt();
for(int t=0;t<1;t++){
int N=in.nextInt();
int M=in.nextInt();System.out.println("M="+M);
int[] X=new int[N];
long max=1000000007;
int[] D=new int[N];
for(int i=0;i<N;i++) X[i]=in.nextInt();
for(int i=0;i<N;i++) D[i]=in.nextInt();
int Dmax=D[0];
int Dtotal=1;
for(int i=0;i<N;i++) if(Dmax<D[i]) Dmax=D[i];
for(int i=0;i<N;i++) X[i]--;
for(int i=0;i<N;i++) Dtotal*=D[i];//total number of fields
long[] mainarray= new long[Dtotal];
long[] mainarraynext=new long[Dtotal];
int[][] ways=new int[N][Dmax];
set( X, mainarray,D, 1);
int temp[]=new int[N];
for(int h=0;h<10;h++){
for(int j=0;j<Dtotal;j++){
mainarraynext[j]=getsum(inverse(j,D),mainarray, D );
}
for(int j=0;j<Dtotal;j++){
mainarray[j]=mainarraynext[j];
mainarray[j]%=max;
}
System.out.println(Arrays.toString(mainarray));
}
long finalsum=0;
for(int j=0;j<Dtotal;j++){
finalsum+=mainarray[j];
//System.out.println(finalsum);
}
System.out.println(finalsum);
//System.out.println(Arrays.toString(inverse(44,D)));
}
}
public static long get(int[] x, long[] mainarray, int[] D){
for(int i=0;i<x.length;i++){
if(x[i]>=D[i]) return 0;
if(x[i]<0) return 0;
}
int index=0;
for(int i=0;i<D.length;i++){
index=(index*D[i])+x[i];
}
return mainarray[index];
}
public static int[] inverse(int index,int[] D){
int[] temp=new int[D.length];
for(int i=D.length-1;i>=0;i--){
temp[i]=index%D[i];
index=index/D[i];
}
return temp;
}
public static void set(int[] x, long[] mainarray, int[] D, int value){
int index=0;
for(int i=0;i<D.length;i++){
index=(index*D[i])+x[i];
}
mainarray[index]=value;
}
public static long getsum(int[] x,long[] mainarray, int[] D ){
int[] temp=new int[x.length];
long sum=0;
//for 2n different sides
for(int j=0;j<x.length;j++){//sum in each side
temp[j]=x[j];
}
for(int j=0;j<x.length;j++){//sum in each side
temp[j]--;
sum+=get(temp, mainarray, D);
temp[j]+=2;
sum+=get(temp, mainarray, D);
temp[j]--;
}
return sum;
}
}
Here's a Java solution I've built for the original hackerrank problem. For big grids runs forever. Probably some smart math is needed.
long compute(int N, int M, int[] positions, int[] dimensions) {
if (M == 0) {
return 1;
}
long sum = 0;
for (int i = 0; i < N; i++) {
if (positions[i] < dimensions[i]) {
positions[i]++;
sum += compute(N, M - 1, positions, dimensions);
positions[i]--;
}
if (positions[i] > 1) {
positions[i]--;
sum += compute(N, M - 1, positions, dimensions);
positions[i]++;
}
}
return sum % 1000000007;
}