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]
Related
I made this code with some help, and am new to Java. I was wondering if I can remove and add something to an array. I tried to add a digit to the end of a array but i'm trying to remove it. To make it a challenge I don't want to use the old array variable. I didn't import the java.util for the add{} statement and it worked fine, but when I add it for the delete method the code stopped entirely. I spent a few days trying to figure this out, by looking online on multiple sites to see what I can do as well as asked a couple of schoolmates how (because they learned Java), but they couldn't figure it out either. I'm learning Java on the side in elementary school so I can be a Game maker so I want to finish this before summer ends. How do I make it so I can print the deleted array after the added one. I learned about array lists, but I saw online about Static Methods. How do I do it with that? I put the code on the bottom. This one doesn't have the import so its half working.
public class Arrays {
public static int[] add(int[] arr, int val) {
int[] newArray = java.util.Arrays.copyOf(arr, arr.length + 1);
newArray[arr.length] = val;
return newArray;
}
public static int[] del() {
int[] del_arrays = {1, 2, 3};
int[] DelArray = java.util.Arrays.removeElement(del_arrays [-1] );
return DelArray;
}
public static void main(String[] args) {
int[] array = { 1, 2, 3 };
System.out.println(java.util.Arrays.toString(array));
int[] new_array = add(array, 4);
System.out.println(java.util.Arrays.toString(new_array));
del();
}
}
Terminal
/usr/bin/env /Library/Java/JavaVirtualMachines/jdk-18.0.1.1.jdk/Contents/Home/
bin/java -agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=localhost:52122 --enable-preview -XX:+Sho
wCodeDetailsInExceptionMessages -cp /private/var/folders/hx/s_5smg5s6510w9_szj6xk8200000gn/T/vscodesws_37f78/jdt
_ws/jdt.ls-java-project/bin Arrays
[1, 2, 3]
[1, 2, 3, 4]
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method removeElement(int) is undefined for the type Arrays
at Arrays.del(Arrays.java:11)
at Arrays.main(Arrays.java:21)
aadavnnimalthas#Aadavns-iMac ~ %
Problems Section
Arrays.java
Arrays.java is a non project file, only syntax errors are reported
I am using Visual Studio on a iMac
This is probably what you are trying to do. The add method append a new element to the array and the delete method remove the last element. Del would look like the other answer if you want to delete specific element.
import java.util.Arrays;
class Main {
public static int[] add(int[] arr, int val) {
int[] newArray = Arrays.copyOf(arr, arr.length + 1);
newArray[arr.length] = val;
return newArray;
}
public static int[] del(int[] arr) {
return Arrays.copyOf(arr, arr.length - 1);
}
public static void main(String[] args) {
int[] a = { 1, 2, 3 };
System.out.println(Arrays.toString(a));
a = add(a, 4);
System.out.println(Arrays.toString(a));
a = del(a);
System.out.println(Arrays.toString(a));
}
}
Output
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]
Just like your add method, you need to provide an array and element index to delete. For a static method you need to provide everything it needs. In this case, you need to provide the array and the index of the element you intend to delete from that array. Remember the edge case of what happens when you want to delete the last element of an array or an array with no elements.
Something like the following should suffice:
public static int[] del(int[] arrayToDeleteFrom, int indexToDelete)
{
boolean empty = false;
if(arrayToDeleteFrom.length <= 1)
empty = true;
int[] newArrayAfterDelete = new int[(empty ? 0 : arrayToDeleteFrom.length - 1)];
for(int index = 0; index < arrayToDeleteFrom.length; index++)
{
//if the index is the one we want to delete, then skip adding it to our new array
if(indexToDelete == index)
continue;
else
newArrayAfterDelete[index] = arrayToDeleteFrom[index];
}
return newArrayAfterDelete;
}
In order to call this method you need to provide all the required parameters. For this del method you need to first provide an int array and second, provide an index of the element you wish to delete.
int[] a = { 1, 2, 3 };
System.out.println(Arrays.toString(a));
a = add(a, 4);
System.out.println(Arrays.toString(a));
a = del(a, 1); //<-- provide the array AND the index of the element to remove, with index 1 we should remove number 2 from the a array
System.out.println(Arrays.toString(a));
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.
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.