char[] someArray = new char[10];
someArray[0] ='a';
someArray[0] ='b';
someArray[0] ='c';
I want to add 'd' at the 4th position. How to get to the index which is one greater than the last valid element index in the array? someArray.length-1 is returning 9. I want to get 4th position?
EDIT:
The code should be:
char[] someArray = new char[10];
someArray[0] ='a';
someArray[1] ='b';
someArray[2] ='c';
In this case I am aware of the fact that 4th index is free. If I have:
void abc(int[] x){
//I want to add element in the next free index of the array x.
}
Indexing in arrays starts from 0.
When you do someArray.length-1, it takes the length as it was initialized using char[] someArray = new char[10];
If you wish to reach the 4th location in your array, start counting from the 0th index and you would find that you need to use index 3 in your array and hence you might want to use someArray[3] = desired_value
You can use a method to find out the index number of the first empty location in an array :
public static int getFirstEmptyIndex(char[] arr){
int index=0;
for(char a:arr){
if(a==0)
break;
else
index++;
}
return index;
}
public static void main(String[] args) {
char[] someArray = new char[10];
someArray[0]='a';
someArray[1]='b';
someArray[2]='c';
someArray[getFirstEmptyIndex(someArray)]='d';
System.out.println(someArray[3]);
}
First of all, but doing someArray[0] = .. you set the char in the first position of the array, and you override this value in this position in your code.
Secondly, the answer to your question is by doing someArray[3] = 'd'.
All elements in your array are valid, as long you are not reaching an index which is beyond your array size.
here is what I think you need, it's similar to #Mohsen answer, just I think this will be more readable and straight forward.
private int nextFree(char[] arr){
int i = 0;
for(Character x : arr){
if(x == 0)
return i;
i++;
}
return -1;
}
So you will get -1 if no free space rather than getting 0 and accidentally replacing index 0 value.
Bonus::
if you which to get all the free space as an array in Ascending order, look below:
private int[] allFree(char[] ar){
int s = 0;
for(char c : ar){
if(c==0)
s++;
}
int[] k= new int[s];
s=0;
int ss=s;
for(char c : ar){
if(c==0){
k[ss] = s;
ss++;
}
s++;
}
return k;
}
By the way, this is not the best algorithm for such operations, let anyone feel free to improve this.
Related
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].
When I sort a 2-D Array which is an argument to a function by Copying it to a 1-D Array, the output is correct but the iterations are repeating. Is my approach correct? I have used an Array "Sort" to copy both the unsorted Arrays & then sort this result set Array.
package learningJava;
import java.util.Arrays;
public class VarArgDemoThree
{
public static void main(String... args)
{
//First one D unsorted Array
int a[]= {10,2,56,17,81,92};
//Second one D unsorted Array
int b[]= {12,77,22,98,101,6};
//Static method Sort which to which both Arrays a & b are passed
Sort(a,b);
}
//Definition of Static method Sort
public static void Sort(int[]...x )//This method has a one d array as variable argument which is int[][] it get array (a[],b[])
{
//Declaring another one-d Sort of which the length is 12
int[] Sort = new int[x[0].length+x[1].length];
//Copying the one D array at location x[0] to another Array Sort using System.arraycopy
System.arraycopy(x[0], 0, Sort, 0, x[0].length);
//Copying the one D array at location x[1] to another Array Sort using System.arraycopy
System.arraycopy(x[1], 0, Sort, x[0].length, x[1].length);
//Sorting the Elements of the Array Sort
for(int i=0;i<Sort.length;i++)
{
int flag=0;
for(int j=i+1;j<Sort.length;j++)
{
if(Sort[i]>Sort[j])
{
int temp = Sort[i];
Sort[i] = Sort[j];
Sort[j] = temp;
flag=1;
}
}
System.out.print(Arrays.toString(Sort));
System.out.println();
if(flag==0)
{
break;
}
}
}
}
You are doing that loop more than it is needed.
just see the code below:
for(int i=0;i<Sort.length;i++) // line a
{
int flag=0;
for(int j=i+1;j<Sort.length;j++) // line b
{
if(Sort[i]>Sort[j])
{
int temp = Sort[i];
Sort[i] = Sort[j];
Sort[j] = temp;
flag=1;
}
}
System.out.print(Arrays.toString(Sort)); // line c
System.out.println();
in "line a" the loop is repeating until i == Sort.length.
in "line b" the loop is starting from j = i + 1 till j == Sort.length.
it is obvious that the last time the inner loop in "line b" does not run but "line c" that is printing Sort will run. that's why you're printing the array one extra time.
imagine the inner loop started from Sort.length + 1 till Sort.length.
to avoid that you would better to change the first loop to i < Sort.length - 1.
some more matters (which are optional):
why do you need flag ? you are looping till the end.
try to start the name of fields and local variables in lower case. for example use sort instead of Sort.
you can use System.out.print("something") and empty System.out.println() together, like System.out.println("something").
i<Sort.length-1 for the outer loop only works thanks..
int a[]= {10,6,18,23,97,188,67,45,52};
int b[]= {4,15,28,77,60,71,90,33,24};
for(int i=0;i<Sort.length-1;i++)
{
for(int j=i+1;j<Sort.length;j++)
{
if(Sort[i]>Sort[j])
{[![enter image description here][1]][1]
int temp = Sort[i];
Sort[i] = Sort[j];
Sort[j] = temp;
}
}
System.out.println(Arrays.toString(Sort));
}
[1]: https://i.stack.imgur.com/5jB1G.png
I am trying to write a program that will iterate through all possible permutations of a String array, and return a two dimensional array with all the permutations. Specifically, I am trying to use a String array of length 4 to return a 2D array with 24 rows and 4 columns.
I have only found ways to print the Strings iteratively but not use them in an array. I have also found recursive ways of doing it, but they do not work, as I am using this code with others, and the recursive function is much more difficult.
For what I want the code to do, I know the header should be:
public class Permutation
{
public String[][] arrayPermutation(String[] str)
{
//code to return 2D array
}
}
//I tried using a recursive method with heap's algorithm, but it is very //complex with its parameters.
I am very new to programming and any help would be greatly appreciated.
Your permutation-problem is basically just an index-permutation problem.
If you can order the numbers from 0 to n - 1 in all possible variations, you can use them as indexes of your input array, and simply copy the Strings. The following algorithm is not optimal, but it is graphic enough to explain and implement iteratively.
public static String[][] getAllPermutations(String[] str) {
LinkedList<Integer> current = new LinkedList<>();
LinkedList<Integer[]> permutations = new LinkedList<>();
int length = str.length;
current.add(-1);
while (!current.isEmpty()) {
// increment from the last position.
int position = Integer.MAX_VALUE;
position = getNextUnused(current, current.pop() + 1);
while (position >= length && !current.isEmpty()) {
position = getNextUnused(current, current.pop() + 1);
}
if (position < length) {
current.push(position);
} else {
break;
}
// fill with all available indexes.
while (current.size() < length) {
// find first unused index.
int unused = getNextUnused(current, 0);
current.push(unused);
}
// record result row.
permutations.add(current.toArray(new Integer[0]));
}
// select the right String, based on the index-permutation done before.
int numPermutations = permutations.size();
String[][] result = new String[numPermutations][length];
for (int i = 0; i < numPermutations; ++i) {
Integer[] indexes = permutations.get(i);
String[] row = new String[length];
for (int d = 0; d < length; ++d) {
row[d] = str[indexes[d]];
}
result[i] = row;
}
return result;
}
public static int getNextUnused(LinkedList<Integer> used, Integer current) {
int unused = current != null ? current : 0;
while (used.contains(unused)) {
++unused;
}
return unused;
}
The getAllPermutations-method is organized in an initialization part, a loop collecting all permutations (numeric), and finally a convertion of the found index-permutation into the String-permutations.
As the convertion from int to String is trivial, I'll just explain the collection part. The loop iterates as long, as the representation is not completely depleted, or terminated from within.
First, we increment the representation (current). For that, we take the last 'digit' and increment it to the next free value. Then we pop, if we are above length, and look at the next digit (and increment it). We continue this, until we hit a legal value (one below length).
After that, we fill the remainder of the digits with all still remaining digits. That done, we store the current representation to the list of arrays.
This algorithm is not optimal in terms of runtime! Heap is faster. But implementing Heap's iteratively requires a non-trivial stack which is tiresome to implement/explain.
Write a method deleteElement which takes as input an int[] and an int target and deletes all occurrences of target from the array. The method should return the newint[]
. Question to consider:
Why is it that we have to return an array and can't simply change the input parameter array?
public class warm5{
public static void main(String[] args){
int[] array1= {1,2,2,3,4,5,2};
int target1 = 2;
deleteElement(array1,target1);
public static int[] deleteElement(int[] array, int target){
for(int i = 0, i<array.length, i++){
if(array1[i] == target){
}
}
}
}
}
Here is what i wrote, im not sure how to continue it to remove the 2's in the array.
please help!
You can't delete elements from an array, by definition they're of fixed size. What you can do is create a new array, copy all the elements from the old array except the ones that you intend to delete and return the new array. Or, use an ArrayList, which has operations that allow removing elements:
public E remove(int index)
public boolean remove(Object o)
public boolean removeAll(Collection<?> c)
protected void removeRange(int fromIndex, int toIndex)
First, iterate through your array and figure out how many of your target element are present.
Once you know that, you know the size of your new array. As Oscar mentions, you can't "remove" from an array, you just make a new array without the elements you don't want in it.
int targetCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
targetCount++;
}
}
Now you know how many items will be in your new array: array.length-targetCount.
int[] newArray = new int[array.length-targetCount];
int newArrayIdx = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != target) {
newArray[newArrayIdx] = target;
newArrayIdx++;
}
}
Here we iterate through the old array and check each element to see if it's our target. If it's not, we add it to the new array. We have to keep track of our old array's index and our new array's index independently or we may risk trying to assign an index outside of the array bounds.
This is a common interview question. In the solution presented by Oscar you do not know what will be the size of the new array. So the solution does not work or is memory inefficient.
Trick is to loop over the array and at any time when you encounter an element equal to the given element you put that element towards the end of the array and swap it with the element that was there at the end position. By doing this you are collecting all occurrences of given element at the end of the array.
Here is a working logic
deleteElement(int[] given, int elem) {
int endIdx = array.length - 1;
for(int idx = 0; idx <= endIdx; idx++) {
if(given[idx] == elem) {
//swap idx with endIdx
int tmp = given[endIdx];
given[endIdx] = given[idx];
given[idx] = tmp;
endIdx--;
}
}
return Arrays.copyOfRange(given, 0, endIdx);
}
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;
}
}