I am trying to create a program that will take an array of integers, say {2,0,32,0,0,8} that can be of any length, and make it so all of the nonzero numbers are to the left at the lower indexes, and all the zeros are moved to the end.
For example, {2,0,32,0,0,8} becomes {2,32,8,0,0,0}.
This array can be of any length and contain any nonnegative integers.
This is what I have so far:
public static int[] moveLeft(final int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
for (int j = 0; j < a.length; j++) {
if (a[j] == 0) {
a[j] = a[i];
a[i] = 0;
}
}
}
}
return a;
}
However, when I do this, it doesn't work for the first and second characters. If I have {1,2,0,1} it will return {2,1,1,0} when it should return {1,2,1,0}. Any help?
Your inner loop should stop before index i. Change this
for (int j = 0; j < a.length; j++) {
to
for (int j = 0; j < i; j++) {
And then your code works for me.
Related
I am attempting to write a recursive method that COUNTS the number of combinations of k size in an integer array.
I can easily do this for a known value k (e.g. 3) as so:
int[] arr = {1,2,3,4};
int count = 0;
for(int i = 0; i < arr.length; i++) {
for(int j = i+1; j < arr.length; j++) {
for(int k = j+1; k < arr.length; k++) {
count++;
}
}
}
However, I would like to be able to do this without a known k. I have found methods online that print the combinations using recursion, such as this one:
https://www.techiedelight.com/find-distinct-combinations-of-given-length/, but none that count them.
Simple case of modifying the method linked.
public static int recur(int[] A, int i, int k)
{
int count = 0;
if (k == 0) {
count++;
}
for (int j = i; j < A.length; j++) {
count = count + recur(A, j + 1, k - 1);
}
return count;
}
The problem is to count how many times my bubble sort algorithm switches the places of numbers. I tried to use a variable which increments by one each time, but I think there may be an error with scopes or something similar. Instead of returning a number such as 6 (which means numbers were swapped 6 times), it returns 0, which is what I initialized my variable as. How would I get my program to work?
public static int sort(int arr[]) {
int length = arr.length;
int temp;
int count = 0;
for (int i = 0; i < (length); i++) {
for (int j = 1; j < (length); j++) {
if (arr[j - 1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
count++;
}
}
}
return count;
}
Looks like your algorithm is not optimized because of your for loop condition and initialization. As a result you are comparing an element with itself which is redundant.
Proper approach should be like below:
int yourCounter = 0;
for (int i = 0; i < length; i++)
for (int j = 1; j < length-i; j++)
if (arr[j - 1] > arr[j]) {
//swap code
//yourCounter++;
}
your counter should give you proper result then.
Recently, I took Linkedin placement test in which there was a question in which output for 4 test cases were wrong for me. I could not figure out what was my mistake becasue inputs/outputs were hidden.
Anyways here was the question:
Find the maximum element from an array where product of any other two elements would be equal to that number and return that number .If no, such element is there then return -1.
Here was my solution:
static int maxElement(int[] arr) {
Arrays.sort(arr);
int max = arr[arr.length-1];
int result = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
result = arr[i] * arr[j];
if (result == max) {
return max;
}
}
}
return -1;
}
I guess you need to find the possible maximum number in the array and the product of two elements in the array.
If I assume this, your code fails for this test case:
int[] arr = {2,4,5,3,7,6}; , where the answer should be 6
Check this below code it will work for above test-case.
Just add one more reverse for loop to check the possible value and product.
static int maxElement(int[] arr) {
Arrays.sort(arr);
for (int k = arr.length-1; k >= 0; k--) {
int max = arr[k];
int result = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
result = arr[i] * arr[j];
if (result == max) {
return max;
}
}
}
}
return -1;
}
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
list.add(a[i]);
}
int maxSum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if ((a[i] * a[j]) > maxSum) {
if(list.contains(a[i] * a[j]))
maxSum = a[i] * a[j];
}
}
}
if (maxSum != 0)
return maxSum;
return -1;
Given an array of integers with rows of different lengths, is it possible to print the whole two-dimensional array but doing so column by column? I understand how to do it row by row but I am struggling with this.
int[][] a = new int[5][];
a[0] = new int[4];
a[1] = new int[2];
a[2] = new int[5];
a[3] = new int[3];
a[4] = new int[1];
int longestRowLength = a[0].length;
for(i = 1; i < a.length; i++)
{
if(a[i].length > longestRowLength)
longestRowLength = a[i].length;
}
for(i = 0; i < a.length; i++)
{
for(j = 0; j < a[i].length; j++)
{
a[i][j] = rand.nextInt(10);
System.out.print(a[i][j]);
}
System.out.println();
}
for(j = 0; j < longestRowLength; j++)
{
for(i = 0; i < a.length; i++)
{
if(a[i].length < longestRowLength)
continue;
System.out.print(a[i][j]);
}
}
}
I have done this but the issue is with how to recognize we are going out of bounds with one of the arrays. My if(a[i].length < longestRowLength doesn't work as it will not even print any numbers if its length is not the longest ones. How can I achieve this?
EDIT:
Ok I have changed that line to:
if(longestRowLength - a[i].length > 0 && (j+1) > a[i].length)
continue;
System.out.print(a[i][j]);
Now it works but it prints the columns as rows. Is there anyway to make it print column by column but to make it print just like it would with rows? (P.S. yeah the first condition of the if statement is unecessary).
Replace your last loop with:
for(j = 0; j < longestRowLength; j++)
{
for(i = 0; i < a.length; i++)
{
if(a[i].length <= j)
continue;
System.out.print(a[i][j]);
}
System.out.println();
}
Prints the columns one by one.
Instead of:
if(a[i].length <= j)
continue;
you can do:
if(a[i].length <= j) {
System.out.print(' ');
continue;
}
to leave a space for arrays which are too short. This way you print the transposed “jagged” matrix.
Basically, I am given an array of numbers and I have to count all the negative numbers.
Then make a new array that contains all of the positive numbers from the previous with the length of the array being firstarray-numberOfNegatives
Here is my code:
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length-1; i++)
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
I am getting the wrong result: negative numbers are replaced with 0s
At first write i < numbers.length; or i <= numbers.length-1; instead of i < numbers.length-1;
And then fix code.
Also note that you can have zeros in your 'numbers' array, so in if() in first for() you should write <=0 instead of <0
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] > 0) numbers2[count] = numbers[i];
count++;
System.out.println(numbers2[count-1]);
}
Firstly: you have an off-by-one error in your first for loop. Walk through some small example arrays in your head or on paper and you'll see.
Secondly: I think you are using your two index counters backwards in the second section. The count is supposed to be used in your new array, and i in your old one.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++) //
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) numbers2[count++] = numbers[i]; //
}
numbers = numbers2;
}
Run through a debugger and watch this line...
That -1 is suspicious
for(int i = 0; i < numbers.length-1; i++)
:)
Need to reverse your index variables in the second pass. Also the first loop had a length-1 instead of length. The second loop should go over the full length of the original array not the resulting array.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++)
if (numbers[i] < 0)
numberOfNegative++;
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) {
numbers2[count] = numbers[i];
System.out.println(numbers2[count]);
count++;
}
}
numbers = numbers2;
}
In
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
You are iterating as many times as numbers2 has positions, however, you increase i at every pass (in the for loop) regardless of whether you fund a positive number or not. Your output arrray would therefore have the first numbers2.length positive integers of numbers interleaved with a bunch of 0s!