Frame of the question:
Write a class called CommonElements with a single method main that will:
Create and obtain two integer arrays (arrayA and arrayB) using RandomIntegerArrayCreator type objects and its methods,
find the number of common elements between arrayA and arrayB (say: if integer 2 appears in arrayA once and twice in arrayB, that counts as ONE common element between the two),
Constraints / notes:
All array elements are integers from the the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and can appear multiple times in each array,
Arrays A and B do NOT have to be of the same size,
Arrays A and B CAN be empty (no elements),
Arrays A and B will NOT be sorted.
The code that I have already created:
import java.util.Random;
public class RandomIntegerArrayCreator {
int[] arr;
RandomIntegerArrayCreator(){
Random rand = new Random();
int size = rand.nextInt(16);
arr = new int[size];
for(int i=0;i<size;i++){
arr[i] = rand.nextInt(11);
}
}
public int getArraySize(){
return this.arr.length;
}
public int[] getArray(){
return this.arr;
}
public static void main(String[] args) {
RandomIntegerArrayCreator r = new RandomIntegerArrayCreator();
System.out.println("Size = "+r.getArraySize());
int[] arr = r.getArray();
System.out.print("Generated array is ");
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
}
Here's the pseudo code for what you're looking for.
for i=0, i<size arrayA
for j=0, j<size arrayB
if arrayA[i] == arrayB[j]
if(arrayA is not in dummyarray)
dummyarray.append(arrayA[i])
counter++
Edit: Basically, you iterate through arrayA and go through each element in arrayB and check if there's something that matches (For instance, arrayA[3] = 4 and arrayB[2] = 4, then there's a match). You add the number to a dummy list which you can check later to see if there's been a duplicate match.
Related
I am creating a program that removes duplicate values based on 10 user inputs. However instead of having distinct values such as [1,2,3,4,5,6] I have zeros in my output as such [0, 1, 0, 2, 0, 3, 0, 4, 5, 6]. Some kind assistance on this matter would be greatly appreciated!
import java.util.*;
public class SOB23_2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc= new Scanner(System.in);
int[]Array= new int[10];
for(int i=0;i<Array.length;i++)
{
System.out.println("Enter number"+(i+1)+":");
Array[i]=sc.nextInt();
}
System.out.println("The distinct values of the array are"+Arrays.toString(eliminateDuplicates(Array)));
}
public static int[]eliminateDuplicates(int[]list)
{
int [] temp=new int[list.length];
for(int i=0;i<list.length-1;i++)
{
if(list[i]!=list[i+1])
{
temp[i]=list[i];
}
}
temp[list.length-1]=list[list.length-1];
return temp;
}
}
First, you're assuming the duplicates will be adjacent. This may be correct (and can be achieved by sorting first).
But then in your loop you only maintain one position variable, i.
Think of the problem as involving reading from one array and writing to another. You need a "read position" in the input and a "write position" in the output.
Also your output array will be longer than needed, because you create it to be the length of the input array. So you might want to make two passes through the input array, the first pass being necessary to discover how many duplicates can be removed, and thus find out how long the output array needs to be.
Then in the second pass you could copy values from the read position in the input and store them in the write position in the output, but only if they are not the same value as the most recently stored output value.
If you were ask to do that manually you can count the zeros in your array, make a new array with length myArray.length-countZero and put every number that's not a zero in the new array, your array has zeros because java primitives (int in this case) can not be null.
public int countZero(int[] a){
int count=0;
for(int i=0;i<a.length;i++){
if(a[i]==0)
count++;
}
return count;
}
public int[] removeZero(int[] a){
int[] myArray=new int[a.length-countZero(a)];
int count=0;
for (int i=0;i<a.length;i++){
if(a[i]!=0)
myArray[count]=a[i];
}
return myArray;
}
But if don't need to do it manually you can just use ArrayList is much easier.
After you are finished you can then do this.
You can do this before or after the array is returned.
int[] array = { 0, 1, 0, 2, 0, 3, 0, 4, 5, 6
};
array = Arrays.stream(array).filter(val -> val != 0).toArray();
System.out.println(Arrays.toString(array));
Prints
[1, 2, 3, 4, 5, 6]
I am trying to save the permutation result of an array into a 2d array. let's say I have an array {1,2,3,4}, I created a 2D array with rows: N! and columns 4. Is it possible to save all the results into 2D array. For example I have the following output I want to save it into 2D array
[1, 2, 3, 4]
[1, 2, 4, 3]
Your question is unclear. Just in case you are wondering how to create and populate a "2D array" here's what I can tell :
import java.util.Arrays;
public class ArraysOfArrays {
public static void main(String[] args) {
// This is your '1D' array
int[] init = {1, 2, 3, 4};
//This is you '2D' array, 24 possibilities of 4 items in order
int[][] combinations = new int[24][4];
// fill your 2D array with the combinations you compute like that :
combinations[0] = new int[] {1,2,3,4};
combinations[1] = new int[] {1,2,4,3};
combinations[2] = new int[] {1,3,2,4};
combinations[3] = new int[] {1,3,4,2};
combinations[4] = new int[] {1,4,2,3};
combinations[5] = new int[] {1,4,3,2};
//...
combinations[23] = new int[] {4,3,2,1};
// or you can assign the individual values one by one :
combinations[0][0] = 1;
combinations[0][1] = 2;
combinations[0][2] = 3;
combinations[0][3] = 4;
System.out.println(Arrays.toString(combinations[3]));
}
}
Hope that helps!
If you want to store many arrays in a "2D" array, then use a loop as follows:
int size = 24; //this should be n! for permutations of n values.
combs[][] = new int[size][];
for (int i = 0; i < size; i++) {
combs[i] = getNextPermutationArray();
}
And Java does not have true multidimensional arrays. It simply has arrays of arrays of arrays, etc.
So, the problem is a bit advanced for a beginner like myself which is why I hope you can ignore my mistakes.
We need to create a method that takes an array, a value that I want to place in the array and the index values (spaces) in the array.
Because my teacher was not concrete with what she wanted, she didn't specify if the array had to be empty or full which is what has confused me the most in this exercise.
The static method has to be named:
addAtIndex( int [] a, int value, int index)
and do the following:
If the last space in the array is 0 or empty and I want to place a new integer value in one of the already occupied spaces, I need to move every element to the right and leave that space free in order to be able to do that.
If the last space has already been taken by an integer value, I need to "resize" the array and make more space so that I can keep entering more integer values. I know that you cannot resize an array and even less keep all the elements intact so I need to create a larger array to do that.
I have been programming in Java less than two months so I find this quite difficult.
I have been able to create an empty array, and I have entered different numerical values in the array with the given parameters. All of this has been done in public static void main and not in a method. I can't seem to be able to do this in a method, especially I have no idea how I can move everything in an array to the right.
import java.util.Arrays;
import java.util.Scanner;
public class Array{
public static void main (String args []){
Scanner input = new Scanner(System.in);
int [] array = new int[10];
for (int x = 0; x <= 9; x++){
int index = input.nextInt();
int value = (int)(Math.random()*50);
//move elements below insertion point.
for (int i = array.length-1; i > index; i--){
array[i] = array[i-1];
}
//insert new value
array[index] = value;
}
System.out.println(Arrays.toString(array));
}
}
This of course is way off from what the teacher wants me to do. What I'm doing here is just creating an array, entering random integers in the indexes that I choose and printing it out. I need some help.
That's how I'd do it in the most minimalistic way.
You might need to adjust because I didn't spend that much time on it.
However it should give you a big boost.
Remember an int[] array cannot have nulls. So I've taken an "empty" value to be zero.
Follow the comments!
static int[] addAtIndex(
final int[] array,
final int value,
final int index) {
if (array == null || array.length == 0) {
// We cannot do anything.
// Simply return to the caller
return array;
}
// This is the array reference holder
int[] localArray = array;
// Get the last element of the array
final int last = localArray[localArray.length - 1];
// Is the last element 0? Remember an int array cannot contain nulls
if (last == 0) {
if (array[index] != 0) {
// We need to shift everything to the right
// to give space to the new element
shiftRight(localArray, index);
}
} else {
// Create a bigger array of length = actualLength + 1
// and assign it to the reference holder
localArray = new int[array.length + 1];
// Copy the array elements to the new array, leaving a space
// for the new element
copyArrayAndLeaveSpace(index, array, localArray);
}
// Assign the new value
localArray[index] = value;
// Return the modified array reference
return localArray;
}
static void shiftRight(
final int[] array,
final int index) {
System.arraycopy(array, index, array, index + 1, array.length - index - 1);
}
static void copyArrayAndLeaveSpace(
final int index,
final int[] array,
final int[] newArray) {
System.arraycopy(array, 0, newArray, 0, index);
System.arraycopy(array, index, newArray, index + 1, array.length - index);
}
Usage
final int[] nums = {1, 2, 3, 4, 5, 6, 8, 9, 0};
final int[] result = addAtIndex(nums, 7, 4);
Output: [1, 2, 3, 4, 7, 5, 6, 8, 9]
final int[] nums = {1, 2, 3, 4, 5, 6, 8, 9, 1};
final int[] result = addAtIndex(nums, 7, 4);
Output: [1, 2, 3, 4, 7, 5, 6, 8, 9, 1]
I want to sum up each i array and store it as an element of a new array.
I expect to get int[] sumUp={10,30}
What am I doing wrong?
My result is instead {0,10}
int[][] matrixOne= {{1,2,3,4},{10,20}};
int [] sumUp=new int[matrixOne.length];
int toSum=0;
for(int i=0;i<matrixOne.length;i++) {
sumUp[i]=toSum;
for(int j=0;j<matrixOne[i].length;j++) {
toSum+=matrixOne[i][j];
}
}
System.out.println(Arrays.toString(sumUp));
You're storing the result before you sum the numbers.
EDIT: forgot to reset the sum
toSum = 0;
for(int j=0;j<matrixOne[i].length;j++) {
toSum+=matrixOne[i][j];
}
sumUp[i]=toSum;
I would prefer a stream on the int[][] which you can map (and stream() to sum()) in one pass. Like,
int[][] matrixOne = { { 1, 2, 3, 4 }, { 10, 20 } };
int[] sumUp = Arrays.stream(matrixOne).mapToInt(x -> Arrays.stream(x).sum()).toArray();
System.out.println(Arrays.toString(sumUp));
Outputs (as expected)
[10, 30]
As the others are pointing out you are storing your sum in toSum not sumUp in your inner loop.
If you want to avoid these mistakes, and you are using Java 8, you could simply do something like:
int[][] matrixOne= {{1,2,3,4},{10,20}};
int [] sumUp=new int[matrixOne.length];
for(int i=0;i<matrixOne.length;i++) {
sumUp[i] = Arrays.stream(matrixOne[i]).sum();
}
You could even stream and map the outer array, but it becomes a bit more complicated.
I have an assignment that requires me to create a method that takes an array of double named dArray as parameter and returns another array whose elements are squares of the elements of dArray.
For example,
if dArray is {1, 4, 6, 7}, the the returned array will be {1, 16, 36, 49}.
Any help would be greatly appreciated!
Here is what I have written so far, but it doesn't work right.
public static double[] squareArray(double[] dArray) {
double[] squareArray = new double[10];
for(int i = 0; i < dArray.length ; i++) {
dArray[] = dArray * dArray;
}
return squareArray;
}
class Test {
public static void main(String [ ] args) {
double[] scores = {3, 9, 3, 3};
double[] scoresSquared = squareArray(scores);
for (int i =0; i <scoresSquared.length; i++) {
System.out.println(scoresSquared[i] + " ");
}
}
public static double[] squareArray(double[] dArray){
double[] squareArray = new double[dArray.length];
for (int i = 0; i < dArray.length ; i++){
squareArray[i]= dArray[i] * dArray[i];
}
return squareArray;
}
}
It would appear that you are squaring the array more than you need to. If every element in the array needs to be squared, you should only have to loop over that array once, but in your code you have two loops.
That's part of the issue.
Another is that you're trying to multiply arrays, which isn't allowed. Inside that method, you need to loop over the array and square each element in it.
Try this:
In your squareArray(), create a List< Double> or something like that.
Iterate through each double in the double[] and add that double squared to the List.
Return (listname).toArray();
You're almost there.
Copy the contents of the array you're receiving and place them into your internal squareArray.
Iterate over squareArray and apply your algorithm (to access specific indexes while in the loop, use squareArray[i])
Return squareArray.