Method that takes an int array, int index and int value - java

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]

Related

How I could find the maxim value of an array with recursive without having an index?

I have that method valorMaxim([1, 5, 252, 24, 7, 82, 3]) returns 252.
I don't know how to do it. I have been thinking if I could decrease the array length.
public static int valorMaxim(int arr[]){
int max;
if(arr.length==1)
return arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < arr[i+1]) {
max=arr[i+1];
return arr[i+1];
}
}
return valorMaxim(arr);
//Retorna el valor màxim en un array no buit d’enters.
}
I modified the accepted answer to Finding Max value in an array using recursion.
As you suggested (i.e. decrease the array length with each recursive method invocation), I create a copy of the method parameter whose length is one less than the parameter and remove the first element. Then I recursively call the method with the array copy.
public class Main {
public static int valorMaxim(int arr[]){
if (arr.length == 1) {
return arr[0];
}
else {
int[] tmp = new int[arr.length - 1];
System.arraycopy(arr, 1, tmp, 0, tmp.length);
return Math.max(arr[0], valorMaxim(tmp));
}
}
public static void main(String[] args) {
System.out.println(valorMaxim(new int[]{1, 5, 252, 24, 7, 82, 3}));
}
}
Basically, the recursive idea is:
If the array has length 1, return the only element;
Otherwise, split the array into x the first element, and xs the rest;
Find the maximum element within xs, compare it to x and yield the greater.
There are two ways to achieve such a "split":
Create a new copy of part of the array for xs
You can either use System.arraycopy (see answer by #Abra) or Arrays.copyOfRange, which is simpler:
int x = arr[0];
int[] xs = Arrays.copyOfRange(arr, 1, arr.length);
And now we lookup the maximum element within xs (which is valorMaxim(xs)), and compare it to x as the final result:
return Math.max(x, valorMaxim(xs));
Put everything together, and don't forget to add a length checker:
public static int valorMaxim(int arr[])
{
if (arr.length == 1) return arr[0];
int x = arr[0];
int[] xs = Arrays.copyOfRange(arr, 1, arr.length);
return Math.max(x, valorMaxim(xs));
}
And that's it! Since we have the length checker in the first place,
we can safely make sure xs would never be empty, and hence valorMaxim(xs) would
never result in ArrayIndexOutOfBoundsException.
Set a boundary for the array
You may have found that copying a new array at each time could be time- and memory-consuming.
Instead of creating a physical copy for xs, we can conceptualise the idea
and use a bounded array instead. We would need to define a helper method to do so:
private static int findMaxBound(int arr[], int startFrom)
{
// does "xs" have length 1?
if (startFrom == arr.length - 1) return arr[startFrom];
int x = arr[startFrom];
int maxInXs = findMaxBound(arr, startFrom + 1);
return Math.max(x, maxInXs);
}
And then we can define valorMaxim as
public static int valorMaxim(int arr[])
{
return findMaxBound(arr, 0);
}
In the end, we did not create any new copies of arr
but uses different ranges of itself and treat them as xs throughout the process.

How do I delete the last element of an array without conflicting another add method?

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));

Common elements between two randomly formed java arrays

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.

How to remove zeros in an array after removing duplicate values?

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]

How do I get the index of an array which I don't know?

The Task
Method:
public int indexOfTarget (int[] values, int target)
Description:
Compulsory Exercise 8) Complete the indexOfTarget method which is passed two parameters: an array of ints(values) and an int(target). The method returns the index position within the array of the first occurrence of the specified integer target. If target occurs in the array, then the index of the first such occurrence is returned.
For example, if the input array is
{3, 7, 2, 4} and the target is 7
the method returns 1
If no such integer occurs in this array, then -1 is returned.
An example:
indexOfTarget({3, 7, 2, 4}, 7)` should return 1.
So Far I Have Written:
public int indexOfTarget (int[] values, int target) {
int targetMatch=-1;
for(int i=0;i<values.length;i++){
if(values[i]==target){
targetMatch=values[i];
}
}
return targetMatch;
}
The Results of CodeWrite Errors
(source: gyazo.com)
you should have targetMatch = i instead. You want the index value, not the value of the array at that index.
You want targetMatch = i; not targetMatch=values[i];
You should be saving the index, not the value.
I would also add break; inside the if statement, immediately after you set the value of targetMatch
This java code should work for all scenarios when the array contains a valid int value. * is not a valid int value.
public class Program
{
public static void main(String[] args)
{
int[] values= {3, 7, 2, 4};
int target = 7;
int position = indexOfTarget(values,target);
if(position>-1)
System.out.println("Pass");
else
System.out.println("Fail");
}
public static int indexOfTarget (int[] values, int target) {
int targetMatch=-1;
for(int i=0;i<values.length;i++){
if(values[i]==target){
targetMatch=i;
return i;
}
}
return targetMatch;
}
}

Categories