I am having problem printing the array after changes. The code is supposed to contain an array, and then I insert a number which is supposed to become the index number (this case 4). That number is then taken and moved to the back of the array, while all the other numbers move one index higher up in the array to fill the empty spot. For some reason it doesn´t allow me to print the array after making the changes.
public static int SendaAftast(int a[], int i) {
for(int k = 0; k <a.length; k++) {
int temp = a[k];
while(k <a.length) {
a[k] = a[k] - 1;
}
a[a.length] = temp;
}
return a[i];
}
public static void main(String[] args) {
int[] a = new int [20];
for(int i = 0; i < a.length; i++) {
a[i] = (int)(Math.random()*a.length)+1;
}
System.out.println(SendaAftast(a, 4));
1. Infinite loop
You don't get anything printed because you have an infinite loop in your code which is:
while(k < a.length) {
a[k] = a[k] - 1;
}
If the condition k < a.length is true it will always be true since you never change its state within the loop in other words k is never modified in this loop it is only modified outside and a.length never changes either.
2. ArrayIndexOutOfBoundsException
The second issue in your code is a[a.length] = temp; which will throw a ArrayIndexOutOfBoundsException if reached because the index of an array goes from 0 to a.length - 1.
3. The new code of SendaAftast
Moreover your method SendaAftast doesn't seem to be properly written, as far as I understand your context, it should rather be something like this:
public static int SendaAftast(int a[], int i) {
int temp = a[i];
// Move everything from i to a.length - 2
for(int k = i; k < a.length - 1; k++) {
a[k] = a[k + 1];
}
// Set the new value of the last element of the array
a[a.length - 1] = temp;
return a[i];
}
Or even faster with a System.arraycopy(src, srcPos, dest, destPos, length):
public static int SendaAftast(int a[], int i) {
int temp = a[i];
// Move everything from i to a.length - 2
System.arraycopy(a, i + 1, a, i, a.length - 1 - i);
// Set the new value of the last element of the array
a[a.length - 1] = temp;
return a[i];
}
4. How to print an array?
To print an array, you must first convert it as a String and the easiest way to do it, is with Arrays.toString(myArray) so you can print it like this:
System.out.println(Arrays.toString(a));
public static int SendaAftast(int a[], int i) {
int temp = a[i];
for (int k = i; k < a.length-1; k++) {
a[k] = a[k+1] ;
}
a[a.length - 1] = temp;
return a[i];
}
Your SendaAftast should look like this. The inner while loop was useless,and also the reason for your the infinite loop that made your program not print. Also variable 'a' cannot be indexed by its own size as counting in an array starts from 0 - a.length-1,hence to get the last value of the array you should use a[a.length-1] and not a[a.length].
Change the line:
a[k] = a[k] - 1;
to
a[k] = a[k-1];
Bye!
Related
Here is the question:
Given an integer array nums and an integer val, remove all
occurrences of val in nums in place. The relative order of the
elements may be changed.
Since it is impossible to change the length of the array in some
languages, you must instead have the result be placed in the first
part of the array nums.
More formally, if there are k elements after removing the duplicates,
then the first k elements of nums should hold the final result. It
does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of
nums.
Do not allocate extra space for another array. You must do this by
modifying the input array in-place with O(1) extra memory.
I've tried to remove the given target val by shifting the value to the end of the array index by iteration of nums.length-1 every time the val is found in the given array. I just want to know what's wrong with my approach.
Below is the code I've tried:
class Solution {
public int removeElement(int[] nums, int val) {
for (int i = 0; i < nums.length; i++) {
if (val == nums[i]) {
for (int j = i; j < nums.length - 1; j++) {
nums[j + 1] = nums[j];
}
break;
}
}
return nums;
}
}
Your algorithm correctly would be the following. The error was returning the array, but that was changed in-situ. You should have returned the new reduced length.
public int removeElement(int[] nums, int val) {
int k = nums.length;
for (int i = 0; i < k; i++) {
if (val == nums[i]) {
--k;
//for (int j = i; i < k; j++) {
// nums[j] = nums[j + 1];
//}
System.arraycopy(nums, i+1, nums, i, k-i);
--i; // Check the new nums[i] too
}
}
return k;
}
The for-j loop can be replaced with System.arraycopy (which handles overlapping of the same array too).
Or:
public int removeElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < n; i++) {
if (val != nums[i]) {
nums[k] = nums[i];
++k;
}
}
return k;
}
This is my code in leetcode. Hope will help you
class Solution {
public int removeElement(int[] nums, int val) {
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<nums.length;i++){
if(nums[i]!=val){
list.add(nums[i]);
}
}
for(int i=0;i<list.size();i++){
nums[i]= list.get(i);
}
return list.size();
}
}
Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of str at most K times.
Example 1:
Input:
K = 4
str = "1234567"
Output:
7654321
Explanation:
Three swaps can make the
input 1234567 to 7654321, swapping 1
with 7, 2 with 6 and finally 3 with 5
I am trying to solve it using two loops. For every index i, I am finding the largest integer between (i+1)th index to (N-1)th index, where N is the size of string. If the largest number is greater than arr[i], then swap it. Below is the code I have written.
public static String findMaximumNum(String str, int k) {
int N = str.length();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = Integer.valueOf(str.charAt(i) + "");
}
int swaps = 0;
for (int i = 0; i < N - 1; i++) {
if(swaps == k)
break;
int maxIndex = findMaxInRange(arr, i + 1, N - 1);
if (arr[i] < arr[maxIndex]) {
swap(arr, i, maxIndex);
swaps++;
}
}
String out = "";
for (int i = 0; i < N; i++) {
out = out + arr[i] + "";
}
return out;
}
private static int findMaxInRange(int[] arr, int i, int j) {
int max = Integer.MIN_VALUE;
int maxIndex = i;
for (int k = i; k <= j; k++) {
if (arr[k] >= max) {
max = arr[k];
maxIndex = k;
}
}
return maxIndex;
}
private static void swap(int[] arr, int i, int j) {
System.out.println("swapping "+arr[i]+" and "+arr[j]+" from "+Arrays.toString(arr));
int ch = arr[i];
arr[i] = arr[j];
arr[j] = ch;
}
public static void main(String[] args) {
System.out.println(findMaximumNum("61892795431", 4));
}
It is failing for few test cases. One of the test cases where it is failing is
Input:
4
61892795431
Its Correct output is:
99876215431
And MyCode's output is:
99876125431
I am not able to figure out how the output is '99876215431' and what is wrong in my approach. Please help me understand. Thanks a lot in advance :)
The basic steps how to solve this problem:
0. cast string to array of integers
make a loop K times
in this loop go from i+1 (LOOP VAR) to end of a collection and search for higher value
when we find higher value then collection[i], we will remember its value and index on witch it is. Important thing to note is that we want to swap biggest number but i also has to be last possible number.
at the end of iteration we swap the elements (i with best index)
we are done so all its left is convert our int list back to string.
code: (its python because java is pain)
def sort(swaps, string):
l = list(map(int, list(string)))
print(l)
for i in range(swaps):
best = l[i] + 1
bestIndex = i
for j in range(i+1, len(l)):
if best <= l[j]:
best = l[j]
bestIndex = j
print(i, bestIndex)
l[i], l[bestIndex] = l[bestIndex], l[i]
return "".join(map(str, l))
print(sort(4, "61892795431"))
Your code is correct. The problem comes from the parameter 4 (max number of swaps). If you use 10, the sorting is completed successfully.
Maybe the deeper problems comes from the fact that you are comparing the swaps of your algorithm with the swaps that you would do efficiently to sort the numbers. Your algorithm may work but probably it is not the most efficient, so the number of swaps needed is above the optimum.
class Insertionsort
{
int A[] = {5,2,4,6,1,3};
void insertionSort()
{
for(int j=2;j<A.length;j++)
{
int key = A[j];
int i = j-1;
while(i>0 && A[i]>key)
{
A[i+1]=A[i];
i=i-1;
}
A[i+1]=key;
}
for(int j = 0;j<=A.length;j++)
{
System.out.println(A[j]);
}
}
public static void main(String args[])
{
Insertionsort is = new Insertionsort();
is.insertionSort();
}
}
Problem is:
The Output of this is 5 1 2 3 4 6 instead of 1 2 3 4 5 6.
What to do?
This is causing the error:
for(int j = 0;j<=A.length;j++)
System.out.println(A[j]);
Max index of an array is length - 1 so change it to:
for(int j = 0;j<A.length;j++)
System.out.println(A[j]);
Better yet, why not use the enhanced for? That way you don't make this kind of mistake:
for(int a : A)
System.out.println(a);
Back to your algorithm:
Starting from j=2 you leave out your first element so change it to j=1.
Also your inner loop should go until i>=0 else you also leave out the 0th element (array index is 0-based):
for (int j = 1; j < A.length; j++) {
int key = A[j];
int i = j - 1;
while (i >= 0 && A[i] > key) {
A[i + 1] = A[i];
i = i - 1;
}
A[i + 1] = key;
}
This will print out 1 2 3 4 5 6 (in new lines since println() is used).
If you want to sort an Array, you just need to use Sort() from Arrays class.
Arrays.sort(yourArray);
for(int j = 0;j<=A.length;j++)
change to j<A.length to make your OutOfBounds Exception go away.
also, your other loops have wrong start/end conditions
for(int j=2;j<A.length;j++) should start at j=1 and while(i>0 && A[i]>key) should have i>=0 or the first element in the array will be skipped in your sort (the 5).
In your sorting loop you initialize j = 2 and then get an number from the array with int key = A[j]; so the first number in the array you try to sort is index 2. Since the first element in an array has the index 0, you are leaving out 5 and 2 when sorting. Change the loop to
for(int j = 0; j < A.length(); j++){
int key = A[j];
int i = j-1;
....
class Insertionsort
{
int A[] = {5,2,4,6,1,3};
void insertionSort()
{
for(int j=1;j<A.length;j++)
{
int key = A[j];
int i = j-1;
while(i>=0 && A[i]>key)
{
A[i+1]=A[i];
i=i-1;
}
A[i+1]=key;
}
for(int j = 0;j<A.length;j++)
{
System.out.print(A[j] + " ");
}
}
public static void main(String args[])
{
Insertionsort is = new Insertionsort();
is.insertionSort();
}
}
So I know how to get the size of a combination - factorial of the size of the array (in my case) over the size of the subset of that array wanted. The issue I'm having is getting the combinations. I've read through most of the questions so far here on stackoverflow and have come up with nothing. I think the issue I'm finding is that I want to add together the elements in the combitorial subsets created. All together this should be done recursively
So to clarify:
int[] array = {1,2,3,4,5};
the subset would be the size of say 2 and combinations would be
{1,2},{1,3},{1,4},{1,5},{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}
from this data I want to see if the subset say... equals 6, then the answers would be:
{1,5} and {2,4} leaving me with an array of {1,5,2,4}
so far I have this:
public static int[] subset(int[] array, int n, int sum){
// n = size of subsets
// sum = what the sum of the ints in the subsets should be
int count = 0; // used to count values in array later
int[] temp = new temp[array.length]; // will be array returned
if(array.length < n){
return false;
}
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < n; j++) {
int[] subset = new int[n];
System.arraycopy(array, 1, temp, 0, array.length - 1); // should be array moved forward to get new combinations
**// unable to figure how how to compute subsets of the size using recursion so far have something along these lines**
subset[i] = array[i];
subset[i+1] = array[i+1];
for (int k = 0; k < n; k++ ) {
count += subset[k];
}
**end of what I had **
if (j == n && count == sum) {
temp[i] = array[i];
temp[i+1] = array[i+1];
}
}
} subset(temp, n, goal);
return temp;
}
How should I go about computing the possible combinations of subsets available?
I hope you will love me. Only thing you have to do is to merge results in one array, but it checks all possibilities (try to run the program and look at output) :) :
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int n = 2;
subset(array, n, 6, 0, new int[n], 0);
}
public static int[] subset(int[] array, int n, int sum, int count, int[] subarray, int pos) {
subarray[count] = array[pos];
count++;
//If I have enough numbers in my subarray, I can check, if it is equal to my sum
if (count == n) {
//If it is equal, I found subarray I was looking for
if (addArrayInt(subarray) == sum) {
return subarray;
} else {
return null;
}
}
for (int i = pos + 1; i < array.length; i++) {
int[] res = subset(array, n, sum, count, subarray.clone(), i);
if (res != null) {
//Good result returned, so I print it, here you should merge it
System.out.println(Arrays.toString(res));
}
}
if ((count == 1) && (pos < array.length - 1)) {
subset(array, n, sum, 0, new int[n], pos + 1);
}
//Here you should return your merged result, if you find any or null, if you do not
return null;
}
public static int addArrayInt(int[] array) {
int res = 0;
for (int i = 0; i < array.length; i++) {
res += array[i];
}
return res;
}
You should think about how this problem would be done with loops.
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == sum) {
//Add the values to the array
}
}
}
Simply convert this to a recursive code.
The best way I can think to do this would be to have each recursive call run on a subset of the original array. Note that you don't need to create a new array to do this as you are doing in your code example. Just have a reference in each call to the new index in the array. So your constructor might look like this:
public static int[] subset(int[] array, int ind, int sum)
where array is the array, ind is the new starting index and sum is the sum you are trying to find
I am working on a java assignment where I need to delete an integer element in an array and shift the below elements up on space to keep them in order. The array is currently random integers in descending order. I am not allowed to use array.copy because I will need to collect array usage information as part of the assignment. I have tried a ton of different ways of doing this but cannot seem to get it working.
public static void deletionArray(int anArray[], int positionToDelete) {
for (int j = anArray[positionToDelete] - 1; j < anArray.length; j++) {
System.out.println("j is " + j);
anArray[j] = anArray[j + 1];
}
displayArray(anArray);
}
You're iterating until anArray.length (exclusive), but inside the loop, you're accessing anArray[j + 1], which will thus be equal to anArray[anArray.length] at the last iteration, which will cause an ArrayIndexOutOfBoundsException.
Iterate until anArray.length - 1 (exclusive), and decide what should be stored in the last element of the array instead of its previous value.
You're also starting at anArray[positionToDelete] - 1, instead of starting at positionToDelete.
You have two bugs there.
Since this is an assignment, I won't give a complete answer - just a hint. Your loop definition is wrong. Think about this: what happens on the first and on the last iteration of the loop? Imagine a 5-element array (numbered 0 to 4, as per Java rules), and work out the values of variables over iterations of the loop when you're erasing element number, say, 2.
Use System.arraycopy faster than a loop:
public static void deletionArray( int anArray[], int positionToDelete) {
System.arraycopy(anArray, positionToDelete + 1, anArray,
positionToDelete, anArray.length - positionToDelete - 1);
//anArray[length-1]=0; //you may clear the last element
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
if (anArray.length == 0) {
throw new IlligalArgumentException("Error");
}
int[] ret = new int[anArray.length - 1];
int j = 0;
for (int i = 0; i < anArray.length; ++i) {
if (i != positionToDelete) {
ret[j] = anArray[i];
++j;
}
}
return ret;
}
Why do we reserve a new array?
Because if don't, we would use C\C++-style array: an array and a "used length" of it.
public static int deletionArray(int anArray[], int positionToDelete, int n) {
if (n == 0) {
throw new IlligalArgumentException("Error");
}
for (int i = positionToDelete; i < n - 1; ++i) {
anArray[i] = anArray[i + 1];
}
return n - 1; // the new length
}
How's this ? Please note the comment, I don't think you can delete an element in an array, just replace it with something else, this may be useful : Removing an element from an Array (Java)
Updated with 'JB Nizet' comment :
public class Driver {
public static void main (String args []){
int intArray[] = { 1,3,5,6,7,8};
int updatedArray[] = deletionArray(intArray , 3);
for (int j = 0; j < updatedArray.length; j++) {
System.out.println(updatedArray[j]);
}
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
boolean isTrue = false;
for (int j = positionToDelete; j < anArray.length - 1; j++) {
if(j == positionToDelete || isTrue){
isTrue = true;
anArray[j] = anArray[j + 1];
}
}
anArray[anArray.length-1] = 0; //decide what value this should be or create a new array with just the array elements of length -> anArray.length-2
return anArray;
}
}