Add element into array java - java

Here's what the layout is
index num
0 [10]
1 [20]
2 [30]
(Add 35 here)
3 [40] Move elements down
4 [50]
5 [60]
6 [70]
then my method is this
public static void method(int[] num, int index, int addnum)
{
}
How can i add 35 in there?
Tried this:
public static void method(int[] num, int index, int addnum)
{
int index = 10;
for(int k = num.length k>3; k++)
{
Num[k]=num[k++]
}
Num[3] = 35;

As this is something you should accomplish yourself, I will only provide the method to implement it, not the code:
If you would set the number at position index, you would overwrite the value that was there previously. So what you need to do is move every element one position towards the end of the array starting from index: num[x] becomes num[x+1], etc.
You will find out that you need to do this in reverse order, otherwise you will fill your array with the value in num[index].
During this process you will need to decide what to do with the last entry of the array (num[num.length - 1]):
You could just overwrite it, discarding the value
You could return it from your function
You could throw an exception if it is non-zero
You could create a new array that is 1 entry larger than the current array instead to keep all values
etc.
After this, you have duplicated num[index]: the value is present in num[index+1], too, as you have moved it away.
Now it is possible to write the new value at the desired position without overriding an existing value.
EDIT
You have several errors in your code:
You increment k, you need to decrement it (k--, not k++)
You modify k again in your loop body: it is updated twice in each cycle
If you start with k = num.length, you will try to write at num[num.length + 1], which is not possible

Very crudely, you want to do something like this:
public static void(int[] num, int index, int addnum)
{
// initialize new array with size of current array plus room for new element
int[] newArray = new int[num.length + 1];
// loop until we reach point of insertion of new element
// copy the value from the same position in old array over to
// same position in new array
for(int i = 0; i < index; i++)
{
newArray[i] = num[i];
}
i = i + 1; // move to position to insert new value
newArray[i] = addnum; // insert the value
// loop until you reach the length of the old array
while(i < num.length)
{
newArray[i] = num[i-1];
}
// finally copy last value over
newArray[i + 1] = num[i];
}

You need to
allocate a new array with room for one new element.
int[] newArray = new int[oldArray.length + 1];
Copy over all elements and leave room for the one to insert.
for (int i = 0; i < newArray.length - 1; i++)
newArray[i < insertIndex ? i : i + 1] = oldArray[i];
Insert 35 in the empty spot.
newArray[insertIndex] = numberToInsert;
Note that it's not possible to do in a method like this:
public static void method(int[] num, int index, int addnum)
^^^^
since you can't change the length of num.
You need to allocate a new array, which means that need to return the new array:
public static int[] method(int[] num, int index, int addnum)
^^^^^
and then call the method like this:
myArr = method(myArr, 3, 35);

Since this very closely resembles homework what you need to realize is that you cannot dynamically increase the size of an array. So in your function:
public static void(int[] num, int index, int addnum)
{
int[] temp = new int[num.length *2];
for(int i = 0; i < index; i++)
copy num[i] into temp[i]
insert addnum into temp[index]
fill temp with remaining num values
}
That pseudocode above should get you started.

What you're looking for is an insertion sort.
It's classwork, so it's up to you to figure out the proper code.

Well, you can't unless there is "extra space" in your array, and then you can shift all elements [starting from index] one element to the right, and add 35 [num] to the relevant place.
[what actually happen is that the last element is discarded out].
However - a better solution will probably be to use an ArrayList, and use the method myArrayList.add(index,element)

How about this?
public class test {
public static void main(String[] arg) throws IOException
{
int[] myarray={1,2,3,5,6};//4 is missing we are going to add 4
int[] temp_myarray=myarray;//take a temp array
myarray=addElement(myarray,0);//increase length of myarray and add any value(I take 0) to the end
for(int i=0;i<myarray.length;i++)
{ if(i==3) //becaues I want to add the value 4 in 4th place
myarray[i]=4;
else if(i>3)
myarray[i]=temp_myarray[i-1];
else
myarray[i]=temp_myarray[i];
}
for(int i=0;i<myarray.length;i++)
System.out.print(myarray[i]);//Print new array
}
static int[] addElement(int[] arr, int elem) {
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = elem;
return arr;
}
}

Related

Arrays and For-loop - Incorrect output while printing Random elements

I am pretty new in this world, and I must say sometimes things that looks easy are pretty harsh.
I am stuck with a task that entails dealing with an array and for-loops.
I should iterate over the array and for every iteration step print a different random string. My current code is not working correctly, the only thing I'm getting a random item and the same index printed multiple times.
My output right now:
relax
2
2
2
2
How can I fix that and get a correct randomized output?
My code:
public static void main(String[] args) {
int i;
String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
java.util.Random randomGenerator = new java.util.Random();
int x = Cofee.length;
int y = randomGenerator.nextInt(x);
String frase = Cofee[y] ;
System.out.println(frase);
for(i = 0; i < Cofee.length; i++)
System.out.println(y);
}
You assign a value to y once, and you print y repeatedly. The value of y doesn't change. To do that, you would need to call randomGenerator.nextInt(x) for each iteration of the loop!
However, if you want to randomize and print the array, use:
public static void main(String[] args)
{
String[] coffee = {"pick it","drink it","relax","put it in a cup",};
// this wraps the array,
// so modifications to the list are also applied to the array
List<String> coffeeList = Arrays.asList(coffee);
Collections.shuffle(coffeeList);
for(String value : coffee)
System.out.println(value);
}
As an aside, don't use String coffee[], but use String[] coffee. Although Java allows putting the array type after the variable name, it is considered bad form.
Or use a list directly:
public static void main(String[] args)
{
List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
Collections.shuffle(coffeeList);
for(String value : coffeeList)
System.out.println(value);
}
For that, you can implement a shuffling algorithm.
It's not so scaring as it might sound at first. One of the famous classic shuffling algorithms, Fisher–Yates shuffle is relatively easy to grasp.
The core idea: iterate over the given array from 0 to the very last index, and for each index swap the element that corresponds to the randomly generated index between 0 and the current index (i) with the element under the current index.
Also, I would advise creating a separate array representing indices and shuffle it in order to preserve the array of string its initial state (you can omit this part and change the code accordingly if you don't need this).
That's how it might be implemented:
public static final Random RANDOM = new Random(); // we need an instance for random to generate indices
A Fisher–Yates shuffle implementation:
public static void shuffle(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
swap(arr, i, j); // swapping elements `i` and `j`
}
}
Helper-method for swapping elements:
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Usage-example:
String[] coffee = {"pick it","drink it","relax","put it in a cup"};
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
shuffle(indices);
for (int i = 0; i < coffee.length; i++) {
String next = coffee[indices[i]];
System.out.println(next);
}
Output:
drink it
pick it
put it in a cup
relax

I want to add an element to an array at specific position without reducing its size, i tried this but it shows (OutOfBoundsException)

import java.util.Scanner;
public class AddElementToSpecificPosition {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int[] array =arrayDetails();
scanner.nextLine();
System.out.println("Enter the position for the element \r");
int position = scanner.nextInt();
System.out.println("Enter the element \r");
int element = scanner.nextInt();
addElementToSpecificPositoin(array,position,element);
}
//getting details form user for arry
private static int [] arrayDetails() {
System.out.println("Enter the length for the array \r");
int length = scanner.nextInt();
scanner.nextLine();
int [] intArray = new int[length];
System.out.println("Enter the numbers for the array \r");
for(int i=0; i<intArray.length; i++) {
intArray[i] = scanner.nextInt();
}
return intArray;
}
//trying to add an element to specific position
private static void addElementToSpecificPositoin(int[] array, int position, int element) {
int lastIndexValue = array[array.length-1];
for (int i=array.length-1; i>position-1 ; i-- ) {
array[i]=array[i-1];
}
array[position-1] = element;
int addedPosition = array.length ;
int [] newArray = new int[addedPosition+1];
for (int i =0; i<newArray.length; i++) {
newArray[i] = array[i];
}
newArray[addedPosition] = lastIndexValue;
for (int j =0; j<newArray.length; j++) {
System.out.println(newArray[j]);
}
}
}
Arrays are fixed sized, and java is pass-by-value. Passing an array variable will never assign to that variable.
private static int[] insert(int[] array, int position, int element) {
int[] largerArray = Arrays.copyOf(array, array.length + 1);
System.arraycopy(largerArray, position, largerArray, position + 1,
array.length - position);
largerArray[position] = element;
return largerArray;
}
array = insert(array, 13, 42);
The above uses a class Arrays with nice utility functions. And System.arraycopy is a fast function to copy array slices. It also deals with overlapping slices.
You need to assign to the passed in array variable the resulting larger array.
array is size X. Whatever it might be, let's call it X. Then you do:
int addedPosition = array.length;
int[] newArray = new int[addedPosition + 1];
In other words, newArray has size X+1. You then loop through 0 through newArray.length and resolve array[i] for each i. This, of course, means array[X] is resolved which is a non-existing entry.
Instead of asking on SO, you should invest a little bit of time and learn to debug. It's easy! All you really do is figure out what a line of code should be doing (by just looking at it and basically 'being the computer'. Use pen and paper if you prefer), then run the code line by line and check that the code actually does what you think it should.
If, thinking it through line by line and working it out, you realize the code isn't what you wanted: Great, you found a bug. Fix it and keep applying this process. Otherwise, you'll figure it out when what the code actually does, does not match what you thought it would. Debuggers help a ton when doing this, but a boatload of System.out.println statements can help, too. You'd have figured it out once you realize with e.g. an example input of a 4-size array ends up running newArray[4] = array[4].

How to create a new array from two and initialize the new one based on values in original arrays

I'm new to Java, and I'm not sure how to ask the right question, so please bear with me. I have 40 total items of 6 different types to put into a new array; each item type has a different cost. The first item (quantity=1) costs $3, the second item (qty=2) costs $5 each, the third item (qty=4) costs $9 each, and so on. The quantity of each item type is in numTypeIndArray and the cost for each type is in costCSDriverArray. A cumulative count of the total items is in numTypeCumulArray.
So, the new array, indItemCostArray, should be single dimensional and have 40 elements. It would look something like {3,5,5,9,9,9,9,...,13,13,13}, but the last fifteen elements are a cost of $13. How do I get to this array with 40 elements? I started with trying to fill the array using a nested for loop but I haven't gotten there yet. The code below is plain wrong.
int[] costArray = new int[]{3,5,9,10,11,13};
int[] numTypeIndArray = new int[]{1,2,4,7,11,15};
int[] numTypeCumulArray = new int[]{1,3,7,14,25,40};
int[] indItemCostArray = new int[numTypeCumulArray[6]];
for (int i = 0; i < indItemCostArray.length; i++) {
for (int j = 0; j < numTypeIndArray[i]; j++) {
indItemCostArray[i+j] = costArray[j];
}
}
First of all, you'll get a ArrayOutOfBoundException at:
int[] indItemCostArray = new int[numTypeCumulArray[6]];
The size of the array numTypeCumulArray is 6, and arrays are 0 indexed. So, The last index number is 5, not 6, as indexing started from 0.
You can do as follows for accessing the last element of the array:
int[] indItemCostArray = new int[numTypeCumulArray[numTypeCumulArray.length - 1]];
Secondly, you're running your outer loop for 40 times and for each iteration your inner loop is trying to iterate for numTypeIndArray[i] times, where i is the iterator variable of outer loop. So, surely after sixth iteration, when value of i will be 6, your program will again throw the ArrayOutOfBoundException as you're accessing a value in the terminator condition of the inner loop from numTypeIndArray whose last index is 5.
Again, inside the inner loop, you're assigning indItemCostArray at index position i+j, which will actually far from your purpose.
To achieve what you are exactly expecting, you can do as follows:
int currentIndex =0;
for (int costIndex = 0; costIndex < costArray.length; costIndex++) {
for(int index = currentIndex; index < currentIndex + numTypeIndArray[costIndex]; index++) {
indItemCostArray[index] = costArray[costIndex];
}
currentIndex = numTypeCumulArray[costIndex];
}
Here, what I did is, in the outer loop I iterated the same amount of time the length of costArray, you can take the length of numTypeIndArray instead too, no issue. I've defined a variable named currentIndex to keep track of the current assignable index for array indItemCostArray. In the inner loop, I tried to begin with the currentIndex and loop upto the time same as the number of items needed for that type, given in numTypeIndArray[costIndex], and for each iteration, set the corresponding index of indItemCostArray with the cost of costIndex in the costArray. Finally, I update the currentIndex with the corresponding cumulative total items from numTypeCumulArray.
Hope you got everything clear.
The whole setup of three arrays is kind of weird. The weiredest is the third array. Think carefully, do you actually need it? You already have all the information in your second array. The third array can introduce a lot of unnacessary mistakes.
But, assuming that you actually need these arrays for some reason and there are no mistakes in making these arrays. You can get your required fourth array as follows,
int[] costArray = new int[]{3,5,9,10,11,13};
int[] numTypeIndArray = new int[]{1,2,4,7,11,15};
int[] numTypeCumulArray = new int[]{1,3,7,14,25,40};
// you want to make sure that your arrays are of same lenght
assert(costArray.length == numTypeIndArray.length && costArray.length == numTypeCumulArray.length);
// length of these arrays is unique items count
int uniqueItemsCount = costArray.length;
// totalItemsCount is last element of numTypeCumulArray
int totalItemsCount = numTypeCumulArray[uniqueItemsCount - 1];
int[] indItemCostArray = new int[totalItemsCount];
// use this to keep track of index in indItemCostArray
int itemCostIndex = 0;
for (int i = 0; i < uniqueItemsCount && itemCostIndex < totalItemsCount; i++) {
for (int j = 0; j < numTypeIndArray[i] && itemCostIndex < totalItemsCount; j++) {
indItemCostArray[itemCostIndex] = costArray[j];
// increase the index for next item cost
itemCostIndex += 1;
}
}
int[] costArray = new int[]{3,5,9,10,11,13};
int[] numTypeIndArray = new int[]{1,2,4,7,11,15};
int[] numTypeCumulArray = new int[]{1,3,7,14,25,40};
int[] indItemCostArray = new int[numTypeCumulArray[5]];
int num = 0;
for (int i = 0; i < numTypeIndArray.length; i++) {
for (int j = 0; j < numTypeIndArray[i]; j++) {
indItemCostArray[num + j] = costArray[i];
}
num += numTypeIndArray[i];
}
System.out.println(Arrays.toString(indItemCostArray));
First, you don't need int[] numTypeCumulArray = new int[]{1,3,7,14,25,40};
It just shows the cumulative values of the numTypeIndArray. The last value, 40 is just the sum of numTypeIndArray and that would be the size of the resulting array from your requirement.
It can be summed in a simple for loop or you can do it like this and then create the target array.
int maxSize = Arrays.stream(numTypeIndArray).sum();
int[] indItemCostArray = new int[maxSize];
Then you could proceed to populate the array with the values as has been shown. Here is another way using streams which you will undoubtedly learn about. The quick explanation is that it creates multiple streams of the proper quantities of cost.
e.g
stream1 -> {3}
stream2 -> {5,5};
stream3 -> {9,9,9,9} etc.
Then it flattens them in a single stream of those values and returns an array.
int[] result = IntStream.range(0, costArray.length)
.flatMap(i -> IntStream.range(0, numTypeIndArray[i])
.map(q -> costArray[i]))
.toArray();
But using a class to hold the information would be better. Here is one example.
class Product {
private String name;
private int cost;
private int quantity;
public Product(String name, int cost, int quantity) {
this.name = name;
this.cost = cost;
this.quantity = quantity;
}
public int getCost() {
return cost;
}
public int getQuantity() {
return quantity;
}
public String getName() {
return name;
}
#Override
public String toString() {
return new StringJoiner(", ","[", "]").add(name).add("cost="+cost).add("quantity="+quantity).toString();
}
}
And it can be used like so.
List<Product> products = new ArrayList<>();
for (int i = 0; i < costArray.length; i++) {
products.add(new Product("Item" + (i+1), costArray[i], numTypeIndArray[i]));
}
products.forEach(System.out::println);
Prints
[Item1, cost=3, quantity=1]
[Item2, cost=5, quantity=2]
[Item3, cost=9, quantity=4]
[Item4, cost=10, quantity=7]
[Item5, cost=11, quantity=11]
[Item6, cost=13, quantity=15]
And once again it can be streamed to create your results exactly as before only using the class getters to get the values.
int[] result2 = products.stream()
.flatMapToInt(
prod -> IntStream.range(0, prod.getQuantity())
.map(q -> prod.getCost()))
.toArray();
The two arrays result and result2 are identical. But you may find that using classes may eliminate the requirement for creating such an array.

index is out of range, removing item from am array

I'm trying to add the functionality to remove an item from an array via method call but am running into the problem posted in the title.
Heres the instructions:
Write a new method for the ArrayIntList class called remove that takes an integer index and that removes the value at the given index, shifting subsequent values to the left. For example, if a variable called list stores the following values:
[3, 19, 42, 7, -3, 4]
after making this method call:
"list.remove(1);"
would remove 3 from the array (not this is not specific to just the first value of the array
I tried to implement doing this:
public void remove(int index) {
int target = index;
int[] elementDataCopy = new int[size];
size = elementData.length;
if (index < 0 || index >= size) {
throw new IllegalArgumentException("invalid index");
}
//loop through each value until the index given is == to loop value
//create a copy of elementData where length is one less and value at
//index given is not present
//each time something is removed, the tracked values decrease by one
size--;
for(int i = 0; i < elementData.length + 2; i++){
if (elementData[i] == target){
continue;
}else{
elementDataCopy[i] = elementData[i];
}
}
}
``
but get this error:
Failed: Index 12 out of bounds for length 12
with the numbers differing depending on what input is.
note that elementData is an array of ints and index is an int that is pointing at a point in said array
all help is appreciated, pretty sure this is something basic
Try it like this. The big mistake is using i for both source and destination indices. Use a separate one (k here) for destination. Only increment the destination index when the copy is made. Once done,
reassign the elementDataCopy to elementData.
int k = 0;
for(int i = 0; i < elementData.length; i++) {
if (i == index) { // skip the one to "delete"
continue;
}
elementDataCopy[k++] = elementData[i];
}
elementData = elementDataCopy;

Two sum - Doesn't work

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
I should get output as [1,2] which are the indices for 2 and 4 respectively
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] arr = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < len; i++)
{
int value = nums[i] - target;
if(map.containsKey(value))
{
System.out.println("Hello");
arr[0] = value;
arr[1] = map.get(value);
return arr;
}
else
{
map.put(nums[i],i);
}
}
return null;
}
I don't get where the problem is, please help me out
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
Okay, let's take a step back for a second.
You have a list of values, [3,2,4]. You need to know which two will add up 6, well, by looking at it we know that the answer should be [1,2] (values 2 and 4)
The question now is, how do you do that programmatically
The solution is (to be honest), very simple, you need two loops, this allows you to compare each element in the list with every other element in the list
for (int outter = 0; outter < values.length; outter++) {
int outterValue = values[outter];
for (int inner = 0; inner < values.length; inner++) {
if (inner != outter) { // Don't want to compare the same index
int innerValue = values[inner];
if (innerValue + outterValue == targetValue) {
// The outter and inner indices now form the answer
}
}
}
}
While not highly efficient (yes, it would be easy to optimise the inner loop, but given the OP's current attempt, I forewent it), this is VERY simple example of how you might achieve what is actually a very common problem
int value = nums[i] - target;
Your subtraction is backwards, as nums[i] is probably smaller than target. So value is getting set to a negative number. The following would be better:
int value = target - nums[i];
(Fixing this won't fix your whole program, but it explains why you're getting the behavior that you are.)
This code for twoSum might help you. For the inputs of integer array, it will return the indices of the array if the sum of the values = target.
public static int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
outerloop:
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if((nums[i]+nums[j]) == target){
indices[0] = i;
indices[1] = j;
break outerloop;
}
}
}
return indices;
}
You can call the function using
int[] num = {1,2,3};
int[] out = twoSum(num,4);
System.out.println(out[0]);
System.out.println(out[1]);
Output:
0
2
You should update the way you compute for the value as follows:
int value = target - nums[i];
You can also check this video if you want to better visualize it. It includes Brute force and Linear approach:

Categories

Resources