Merging 2 arrays into 1 in Java - java

Okay so i have this following exercise i need to merge 2 arrays together into 1 array.
The new array has to containt elements of each array e.g: newArray index 0 = array1Element from 0 index, newArray index 1 = array2Element from index 0 and so on..
If one of those arrays has no more elements, continue putting elements from the longer array... so far i have come to this..which is of not right or isn't giving the right solution..can you please give me a proper solution and explain everything that was done in the code..
public static void main(String[] args) {
int[] array1 = {1,1,1,1,1,1};
int[] array2 = {2,2,2,2,2,2,2,2,2,2};
arrayMan(array1,array2);
}
public static int[] arrayMan(int[] firstArray,int[] secondArray) {
int[] newArray = new int[firstArray.length + secondArray.length];
int array1Pos;
int array2Pos;
System.arraycopy(firstArray,0,newArray,0,firstArray.length);
for (int i = 0; i < newArray.length -1 ; i++) {
for (int j = 0; j < secondArray.length ; j++) {
if(newArray[i] == newArray[i+1]) {
array1Pos = newArray[i+1];
array2Pos = secondArray[j];
newArray[i] = array1Pos;
newArray[i + 1] = array2Pos;
}
}
}
for (int i = 0; i < newArray.length ; i++) {
System.out.println(newArray[i]);
}
return newArray;
}
The expected output should be {1,2,1,2,1,2,1,2,1,2,1,2,2,2,2}

I won't write the code for you but I'll try to point you in the right direction.
I think you would find it helpful to first do this on paper, writing out the state after each number is added to the destination array.
For example:
Start:
sourceArray1 = [1,1,1,1,1,1]
sourceArray2 = [2,2,2,2,2,2,2,2,2,2]
targetArray = []
targetIndex = 0 <- where to put the next item
source1Index = 0 <- where to get the next item from sourceArray1
source2Index = 0 <- where to get the next item from sourceArray2
Step (take from sourceArray1)
targetArray = [1]
targetIndex = 1
source1Index = 1
source2Index = 0
Step (take from sourceArray2)
targetArray = [1,2]
targetIndex = 2
source1Index = 1
source2Index = 1
Step (take from sourceArray1)
targetArray = [1,2,1]
targetIndex = 3
source1Index = 2
source2Index = 1
Keep doing this until targetArray is filled. At some point you won't be able to increment source1Index and will have to draw exclusively from sourceArray2.
Once you understand how to do this on paper you'll find the code much easier to write (and you'll see there's no need for System.arrayCopy).

Related

I can't see what's wrong with my Java code?

I am making a program that puts all data from one array, into a different array, backwards.
So, if
String[] originalArray = {"you", "see", "I"};
then it should transfer that into a new array like this:
String[] newArray = new String[3];
newArray = "I", "see", "you"
Here's my code.
public class ReverseArray {
public static void reverse() {
String[] originalArray = {"cool", "really", "are", "You"};
String[] newArray = {"", "", "", ""};
for(int b = 0; b < newArray.length; b++) {
for(int a = 3; a < -1; a--) {
newArray[b] = originalArray[a];
}
}
for(int c = 0; c < newArray.length; c++) {
System.out.print(newArray[c] + "+");
}
}
}
I'm not sure what is wrong. When I try to print it out, it just prints out (+ + + +)
I've tried changing
String[] newArray = {"", "", "", ""};
to
String[] newArray = new String[4];
But it just made then output as
null
Any help?
Your problem is in your inner loop...
for (int a = 3; a < -1; a--) {
Read this out loud...
a equals 3
while a is less than -1 do a--
See where it falls down, the for-loop will only run while a is -1, but you've initialised it to 3
You can actually get away with a single loop, for example...
String[] newArray = new String[originalArray.length];
for (int index = 0; index < newArray.length; index++) {
newArray[index] = originalArray[originalArray.length - index - 1];
}
Basically this uses the index value for both arrays, but adjust the originalArray so it moves from the end instead of the start, as one possible solution ;)
An alternative way using Collections.reverse():
List<String> list = Arrays.asList("cool", "really", "are", "You");
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
Output:
[cool, really, are, You]
[You, are, really, cool]
Okay, so the steps are the following:
You have an array A of size X. You want to put these elements in an array B of size X. So basically what you want is that the element in A[0] (the first element) is in the last position of B, being B[2]. To do this, you need to calculate the "reverse" index.
So first you loop over your array:
for(int index = 0; index < A.length;index++)
{
String thisElement = A[index];
}
Next, you want to put it in the other array at the last position, right? So then you need to take the length of that array, minus the current index.
for(int index = 0; index < A.length;index++)
{
String thisElement = A[index];
// The other index
int otherIndex = (B.length - 1) - index; // We do -1 because we have zero-indexing.
B[otherIndex] = thisElement;
}
This should now contain all your elements in reverse order.
Some things you did wrong
I've tried changing
String[] newArray = {"", "", "", ""};
to
String[] newArray = new String[4];
These things are basically the same. The latter tells the compiler "Give me room for 4 strings". In the former you give it 4 strings and it makes room for them. So that's not really necesarry, but correct.
for(int b = 0; b < newArray.length; b++) {
for(int a = 3; a < -1; a--) {
newArray[b] = originalArray[a];
}
}
This piece of code is quite wrong as well. You walk over your array in the outer loop. And for each element you try to loop again. That is not needed either. Even so, your loop goes from 3 to 2 to ... But the condition is "as long as a is smaller than -1". It is not smaller than -1 to start with, so this loop will never execute.
You have big problems in your code here:
for(int b = 0; b < newArray.length; b++) {
for(int a = 3; a < -1; a--) {
newArray[b] = originalArray[a];
}
}
With "a < -1" you probably wanted "a > -1" otherwise the inner loop does not start. But most importantly you have two nested loops (two for loops) which doesn't make sense, you need only one for loop two reverse an array and you don't even need the new array to put the result:
for (i = 0; i < originalArray.length / 2; i++) {
int temp = originalArray[i];
originalArray[i] = originalArray[originalArray.length - 1 - i];
originalArray[originalArray.length - 1 - i] = temp;
}
This for loop works from both sides of the array inwards replacing the positions.
When you reach code mastery (or are not required to provide your own algorithm) you'll just use:
Collections.reverse()
:)

Filling Array List with random data

I have the following variables and ArrayList:
int rowLength, columnLength;
ArrayList<String[]> data = new ArrayList<String[]>();
I need to fill this array list with random data. The data must be string (recommended int that has been converted to String). The main goal is to fill multidimensional array list with random data.
I've tried to do that but I had too many troubles. I'm new in Java, so sometime I need help with basic things as well.
Try using nextInt() from Random. This will create a random int which you can wrap in Integer.toString(int i). Then add it to a String[] then add it to the ArrayList.
For example:
Random r = new Random();
for (int i = 0; i < columnLength; i++) {
String[] s = new String[rowLength];
for (int i = 0; i < s.length; i++) {
s[i] = Integer.toString(r.nextInt());
{
data.add(s);
}
Use nested for loops like below:
int rowLength = 10, columnLength = 5; //Initialize sizes
ArrayList<String[]> data = new ArrayList<String[]>();
for (int row = 0; row<rowLength; row++) {
String[] stringsColumn = new String[columnLength];
for (int col = 0; col <columnLength; col++) {
stringsColumn[col]=Integer.toString(col);
}
data.add(stringsColumn);
}
Output loop
//Note that this output loop will interchange the columns for rows but it works fine for demonstration
for (String[] col:data){
for (String s:col){
System.out.print("\t"+s);
}
System.out.println();
}
Output
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
You can try something like this:
public String generateRandomString(int len) {
String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rnd = new Random();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
And this:
public Integer generateRandomInteger(int range) {
Random rnd = new Random();
Integer val = rnd.nextInt(range);
return val;
}
Having these 2 functions you can add random data to your ArrayList:
data.add(generateRandomString(10));
data.add(generateRandomInteger(200));
There is many, many, many ways to do this. From what I see from your snippet is that you do expect some static range of this "multi dimenesional" "Array":isch thingy.
int rowLength, columnLength;
would then imply two dimensions, is that the case or are you expecting more dimensions, is the dimension(s) dynamic? If two is the limit I guess String[][] would do, else some more dynamic construct of Map or List should work.

2D array not printing the last element during comparison

I am trying to replace rows from an original 2d array to a updated 2d array. Problem is it won't store the last element during the replacement.
Here's my code:
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < updatedArray[i].length; j++){
for(int x = 0; x < originalArray.length;x++){
for(int z = 0; z < originalArray[x].length;z++){
if(originalArray[x][0].equals(updatedArray[i][0])) {
updatedArray[i][j] = originalArray[x][j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
}
}
System.out.println("originalArray:");
System.out.println(Arrays.deepToString(originalArray));
System.out.println("updatedArray:");
System.out.println(Arrays.deepToString(updatedArray));
For example, initially updatedArray in last row "purple" has {"purple","a","b","c"}. When it does the replacement using values from originalArray, the code above only outputs:
... [purple, nn, mm, bb]
which is wrong because it doesn't add the last element "hello". It should output:
... [purple, nn, mm, bb, hello]
I am aware the problem is in this line:
updatedArray[i][j] = originalArray[x][j];
Problem is no matter what I try to change originalArray[x][j] to originalArray[x][z] ... its screws up everything.
Any ideas on this? Still trying to get the jist of 2D arrays.
If there is a match, instead of trying to set each element in the updatedArray to the corresponding element in the original array you can just set the entire array to the original array.
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < originalArray.length; j++){
if(originalArray[j][0].equals(updatedArray[i][0])) {
updatedArray[i] = originalArray[j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
The issue is how you chose to iterate over the dimensions of updatedArray which are different than the dimensions of originalArray.
Let just look at the case i=2 which is the 'row' for purple:
for (int j = 0; j < updatedArray[i].length; j++){
updatedArray[i=2].length = 4
in updated:
index = 0 , 1 , 2 , 3
{"purple","a","b","c"}
in original:
index = 0 , 1 , 2 , 3 , 4
{"purple","nn","mm","bb","hello"}
Therefore since j will always be < 4 it can never be used to index originalArray[x][4] = "hello"
DANGER: this code also doesn't handle the fact that you would need to extend the purple array for updatedArray. Java may do some magic to handle this for you but I wouldn't trust it to work that way.
Suggestion:
- compare the lengths of each row and allocate extra memory where necessary before copying data from originalArray to updatedArray
- if possible just copy the whole row between original and updated.

Iterating an array from both ends using two indices

This is more of an self defined programming exercise than a real problem. I have an array of java.lang.Comparable items. I need to maintain two pointers (an index into the array i.e., int values) i,j . i starts at the beginning of array and moves right until it encounters an element which is less than or equal to the previous element. When it does it stops moving right and ends up pointing to the element which is out of order(element which is not greater than the previous). Similarly j starts at the end of the array and moves left until it finds an element which is not less than the previous.
Also, I need to make sure that the indices don't run out of the array i.e., i cannot go below 0 and j cannot go above arraylength-1
lets say we have an array of 5 elements.
i = 0;
j = 4;(which is the arraylength-1 )
if C,D,E,F,G is the array ,the final values of i and j will be
i = 4 and j = 0
if array is J,D,E,F,G ,the final values of i, j will be
i = 0 , j = 0
if array is B,C,A,D,G , final values of i,j will be
i = 2 , j = 1
I tried to code the logic for moving i to the right, using a while loop as below. I was able to get it working for the i pointer in two cases.
public class PointerMovement{
public static void ptrsPointToOutOfOrderElements(Comparable[] a){
int lo = 0;
int hi = a.length-1;
int i = lo;
int t=i+1;
int j = hi;
//only for moving i to the right .
while(less(a[i],a[t])){
if(t == hi){
i=t;
break;
}
i++;
t++;
}
i=t;
for(Comparable x:a){
System.out.print(x+",");
}
System.out.println();
System.out.println("bad element or end of array at i="+i+"==>"+a[i]);
}
private static boolean less(Comparable x,Comparable y){
return x.compareTo(y) < 0;
}
public static void main(String[] args) {
String[] a = new String[]{"C","D","E","F","G"};//works
//String[] a = new String[]{"B","C","A","D","G"};//works
//String[] a = new String[]{"J","D","E","F","G"};//fails!
ptrsPointToOutOfOrderElements(a);
}
}
My line of reasoning given below
I maintain i=0; and another variable t=i+1
when the while loop fails, less(a[i],a[t]) is false .We need to return a pointer to a[t] which is out of order. so i=t and return i.
if we reach right end of array, the test if(t == hi) passes and we assign i=t and now i points to end of array.
However, the code fails when the out of order element is in the 0th position in the array.
J,D,E,F,G
Instead of i (=0) we get i=1 because i=t is assgined.i ends up pointing to D instead of J.
Can someone point me in the right direction?
update:
this seems to work
public static void ptrsPointToOutOfOrderElements(Comparable[] a){
int lo = 0;
int hi = a.length-1;
int i = lo;
while(less(a[i],a[i+1])){
if(i+1 == hi){
break;
}
i++;
}
i++;
int j = hi;
while(less(a[j-1],a[j])){
if(j-1 == lo){
break;
}
j--;
}
j--;
for(Comparable x:a){
System.out.print(x+",");
}
System.out.println();
if(i>=j){
System.out.println("pointers crossed");
}
System.out.println("bad element or end of array at i="+i+"==>"+a[i]);
System.out.println("bad element or end of array at j="+j+"==>"+a[j]);
}
I do not think you have a problem:
String[] a = new String[]{"C","D","E","F","G"};//works, index should be 4 (but should it be so? It would indicate that G is out of order while it is not. I think you should return 5, indicating that none is out of order.
String[] a = new String[]{"B","C","A","D","G"};//works, index should be 2 as A is out of order
String[] a = new String[]{"J","D","E","F","G"};//works since the first out of order element is indeed D, with index 1
I have tried using simple for loop.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = arr.length - 1; i <= j; i++, j--) {
console.log(arr[i] + ' , ' + arr[j]);
}
Output :
1 , 10
2 , 9
3 , 8
4 , 7
5 , 6

java array traversal in circular manner

I have an array which have 1 2 3 4 5 values.
array a = [ 1 , 2, 3, 4, 5]
Now i want to traverse it in circular manner.
like i want to print 2 3 4 5 1 or 3 4 5 1 2 or 5 1 2 3 4 and so on.
any algorithm on this?
Edit: I want to print all the combination in circular manner. i don't want to state starting point at its initial phase.
int start = ...
for (int i = 0; i < a.length; i++) {
System.out.println(a[(start + i) % a.length]);
}
(If you want to iterate the array backwards from start, change start + i to start - i in the array subscript expression.)
I should note that this is probably not the most efficient way of expressing the loop ... in terms of execution speed. However, the difference is small, and most likely irrelevant.
A more relevant point is whether using % in this way gives more readable code. I think it does, but maybe that's because I've seen / used this particular idiom before.
How about the following:
int start = // start position, must be in bounds
int i = start;
do {
....
i++;
if(i == a.length) i = 0;
} while(i != start);
int st = n ; // n is the starting position from where you print
for(int i = st; i < a.length; i++)
{
-- print each array[i];
}
if(st != 0)
{
for(int i = 0 ; i < st ; i++)
{
--- print each array[i];
}
}
Basically you just need to loop through the array, and change the current index if necessary (like move it to the start of the array when it meets the end)
public static void main(String[] args) {
int[] array = new int[] { 1, 2, 3, 4, 5 };
System.out.println(printCircularly(array, 4));
}
private static String printCircularly(int[] array, int startIndex) {
StringBuilder sb = new StringBuilder();
int currentIndex = startIndex;
do {
sb.append(array[currentIndex++]);
if (currentIndex > array.length - 1) {
currentIndex = 0;
}
}
while (currentIndex != startIndex);
return sb.toString();
}
In addition to Stephen C's answer
int start = ...
for (int i = 0; i < a.length; i++) {
System.out.println(a[(start - i + a.length) % a.length]);
}
Use this for reverse loop from start index. It's a little unclear, but in some cases very useful. For example: UI components like carousel.
And there's no ArrayIndexOutOfBoundsException!!!
Instead of using a for loop with indexes, which is harder to read, you can use Iterables from Google Guava as follows :
List<Integer> myList = List.of(1,2,3);
Iterator<Integer> myListIterator = Iterables.cycle(myList).iterator();
then you will only have to use myListIterator.next(). example :
System.out.println(myListIterator.next());
System.out.println(myListIterator.next());
System.out.println(myListIterator.next());
System.out.println(myListIterator.next());
This will print : 1 2 3 1

Categories