Here is the problem: When given an array arr, return an array which contains only odd integers in the original order from arr.
A Few Examples:
youMakeMeOdd({1,2,3}) → {1, 3}
youMakeMeOdd({1,3,5}) → {1, 3, 5}
youMakeMeOdd({2,4,6}) → {}
And here is my code:
public int [] youMakeMeOdd(int [] arr)
{
int x=0;
for (int i=0; i<arr.length; i++)
{
if (arr[i]%2==1)
{
x++;
}
}
for (int i=0, m=0, j=0; j<x; m++, j++)
{
if (arr[i]%2==1)
{
arr[m]=arr[j];
}
}
return arr;
}
Thank you very much!
Arrays in Java are fixed-size: their length cannot be changed.
So you need to create and return a new array because the result might contain fewer elements.
Determine the size of the output array (count the odd values) to know the length of the result array, then iterate over your input and add the odd numbers to the output.
Example:
public static int[] youMakeMeOdd(int[] arr) {
int count = 0;
for (int n : arr)
if (n % 2 == 1)
count++;
int[] result = new int[count];
int i = 0;
for (int n : arr)
if (n % 2 == 1)
result[i++] = n;
return result;
}
Related
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 12 months ago.
I'm just a beginner and I'm trying to write a method returning only unique elements from Java array. What's wrong with this code? Could you please point my mistakes and help me correct them? I've got no idea what to do with it.
P.S. I know I could use packages, but it has to be done in the simplest way.
public static void main(String[] args) {
int[] arr = {1, 1, 2, 3};
int[] items = returnNonRepeated(arr);
System.out.print(items);
}
public static int[] returnNonRepeated(int[] arr) {
int[] temp = new int[0];
int n = 0;
for (int i = 0; i < arr.length; i++) {
if (i == 0) {
temp[i] = arr[i];
} else {
if (arr[i] != arr[i - 1]) {
temp[numbersCount] = arr[i];
numbersCount++;
}
}
}
return temp;
}
}
I know it's not code golf here, but:
if you want to keep only unique values (like a Set would do), you can use a "one-liner". You don't have to implement loops.
public static void main(String[] args) {
int[] dupes = {0, 1, 2, 1, 3, 2, 3};
int[] uniques = Arrays.stream(dupes) // stream ints
.boxed() // make Integer of int
.collect(Collectors.toSet()) // collect into set to remove duplicates
.stream() // stream Integers
.mapToInt(Integer::intValue) // make int of Integer
.toArray(); // and back into an array
System.out.println(Arrays.toString(uniques));
}
Please not that you have to use java.util.Arrays.toString() to get useful output in the last statement. With your variant it will print only something like "[I#531be3c5" which denotes that it is an array of int, but says nothing about the contents.
Nevertheless - if you want to understand, how arrays and loops work, the looping solution is better!
I'm not sure if you mean non-repeat or unique
But here is a method for checking for duplicates:
public static int[] returnUniqueArray(int[] arr) {
int dupes = new int[arr.length]; // The most dupes you could have is the length of the input
int numberOfDupes = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if(arr[i] == arr[j]) {
dupes[numberOfDupes] = arr[i];
numberOfDupes++;
}
}
}
return dupes;
}
This loops round the arr array twice, therefore comparing every variable in arr to every other variable. If they are the same, it adds that value to a new array.
You could also do similar for non-repeat:
public static int[] returnNonRepeatArray(int[] arr) {
int dupes = new int[arr.length];
int numberOfDupes = 0;
for (int i = 0; i < arr.length - 1; i++) {
if(arr[i] == arr[i+1]) {
dupes[numberOfDupes] = arr[i];
numberOfDupes++;
}
}
return dupes;
}
This loops round the arr array once, but does not check the last item (-1 in the for loop). It then compares the item against the next item, if they are the same it adds that to the dupes.
public static void main(String[] args) {
int[] arr = {1, 1, 2, 2, 3, 4, 5, 5, 5, 6};
int[] items = returnNonRepeated(arr);
System.out.print(Arrays.toString(items));
}
public static int[] returnNonRepeated(int[] arr) {
int[] temp = new int[arr.length];
int numbersCount = 1;
for (int i = 0; i < arr.length; i++) {
if (i == 0) {
uniques[numbersCount] = arr[i];
numbersCount++;
} else {
if (arr[i] != arr[i - 1]) {
uniques[numbersCount] = arr[i];
numbersCount++;
}
}
}
return uniques;
}
For some reason I have only managed as far as printing the odd numbers, but it somehow still prints what appears to be values that are null. I am trying to only print the values that returned as odd.
public class Odd {
public int[] removeEvens(int [] nums) { //start of method
int [] newArray = new int[nums.length];
int count = 0;
// start of array conversion
for(int i = 0; i < nums.length; i++) {
newArray[count] = nums[i];
count++;
}
int counter = 0;
for (int i = 0; i < nums.length; i++)
if (newArray[i] % 2 == 1)
newArray[counter++] = newArray[i];
for (int i=counter; i < nums.length; i++)
newArray[i] = 0;
return newArray;
}
// end of method
public static void main(String[] args) {
Odd labObject = new Odd();
int [] input = {1,2,3,4,5,6,7,8,9};
int [] result = labObject.removeEvens(input);
// Helper method Arrays.toString() converts int[] to a String
System.out.println(Arrays.toString(result)); // Should print [1, 3, 5, 7, 9]
}
}
change it to return Arrays.copyOfRange(newArray, 0, counter); when you make in array of ints in java with a specified size, it sets every value in the array to 0. Doing this will remove all of the extraneous 0s at the end.
This can be easily solved by working out the correct size of the new array first before you create it. Then simply loop the array and only store the odd numbers. Otherwise, remove/trim the array size before returning it.
Here is a solution by modifying your removeEvens method:
public int[] removeEvens(int[] nums)
{ //start of method
int count = 0;
// start of array conversion
// Count the odd numbers to work out the array length
for (int i = 0; i < nums.length; i++)
{
if (nums[i] % 2 == 1 || nums[i] % 2 == -1)
{
count++;
}
}
// Now create a new array of the correct length
int[] newArray = new int[count];
// Now loop through the original array and only store the odd numbers in the new array
int counter = 0;
for (int i = 0; i < nums.length; i++)
{
if (nums[i] % 2 == 1 || nums[i] % 2 == -1)
{
newArray[counter] = nums[i];
counter ++;
}
}
// Return the result
return newArray;
}
Result:
[1, 3, 5, 7, 9]
I am trying to get the sum of all elements in the array and multiply it by its index+1
Then I want to add all of these sums to create a total sum
however if the current indexes sum is not larger than the previous sum don't add it to the end total as it is a bad value (add all the values that aren't bad) and return the result
```java
import java.util.List;
import java.util.LinkedList;
public class Main {
public static int[] solve(int[] arr) {
if (arr.length == 0)
return new int[0];
for (int i = 0; i < arr.length; i++)
arr[i] *= i + 1;
int start = 0;
List<Integer> result = new LinkedList<>();
for (int num: arr)
if (num >= start) {
result.add(num);
start += num;
}
int[] found = result.stream().mapToInt(i -> i).toArray();
return found;
}
public static void main(String[] args)
{
int [] array = {-1,3,4};
int total=0;
int[] array2= solve(array);
for(int i=0; i<array2.length; i++){
// System.out.println(i+"\t"+array2[i]);
total+=array2[i];
System.out.println(total);
}
}
```
output should be 17 it is 18
So if I'm reading this right you take in an array of numbers, multiply each one by its index + 1, then remove any that are not in increasing order? I'm not sure what the question is, but you should try to break the problem into steps to make it easier to approach.
int[] arr = {6, 2, 4, 4, 5};
// Maybe this is what you were trying to do?
public static int[] solve(int[] arr) {
if (arr.length == 0)
return new int[0];
for (int i = 0; i < arr.length; i++)
arr[i] *= i + 1;
int start = 0;
List<Integer> result = new LinkedList<>();
for (int num: arr)
if (num >= start) {
result.add(num);
start += num;
}
return result.toArray();
}
Given an array of integers return an array in the same order with all 0's removed.
Sample Input #1
remove({1,2,3,4,5,0,1,2,0,0,2})
Sample Output #1
{1,2,3,4,5,1,2,2}
Sample Input #2
remove({0,0,1,2})
Sample Output #2
{1,2}
Sample Input #3
remove({0,0,0,0})
Sample Output #3
{}
MyApproach
I first counted how many zeros are there and then I created a new array and added only those elements which are not zero.
But I am not getting correct output.
Can anyone guide me what I am doing wrong?
Below is my code for the above program:
public int[] remove(int[] arr)
{
int count=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]==0)
{
count++;
}
}
int p[]=new int[arr.length-count];
for(int m=0;m<p.length;)
{
if(arr[m]==0)
{
m++;
}
else
{
p[m]=arr[m];
m++;
}
}
return p;
}
Parameters Actual Output Expected Output
'{0,1,2,3,0,1}' {0,1,2,3} {1,2,3,1}
You need two counters, one for where you are copying from and one for where you are copying to.
for (int n = 0, m = 0; m < p.length; m++)
if (arr[m] != 0)
p[n++] = arr[m];
or you can do
int n = 0;
for (int x : arr)
if (x != 0)
p[n++] = x;
In Java 8 you can do
public static int[] removeZero(int[] ints) {
return IntStream.of(ints)
.filter(i -> i != 0)
.toArray();
}
Try to use this for removing zeros in your array:
public int[] remove(int[] array)
{
int j = 0;
for( int i=0; i<array.length; i++ )
{
if (array[i] != 0)
array[j++] = array[i];
}
int [] newArray = new int[j];
System.arraycopy( array, 0, newArray, 0, j );
return newArray;
}
CodingBat > Java > Array-1 > reverse3:
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
public int[] reverse3(int[] nums) {
int[] values = new int[3];
for (int i = 0; i <= nums.length - 1; i++) {
for (int j = nums.length-1; j >= 0; j--) {
values[i] = nums[j];
}
}
return values;
}
I can't get this to work properly, usually the last int in the array, becomes every single int in the new array
You don't want a two-level loop. Just have one loop:
for(int i = 0, j = nums.length - 1; i < nums.length; i++,j--) {
values[i] = nums[j];
}
or, alternately, just don't track j sepearately, and do this:
for(int i = 0; i < nums.length; i++) {
values[i] = nums[nums.length - 1 - i];
}
Unless this is a homework, why not just use Apache ArrayUtils'
ArrayUtils.reverse(nums)
Never re-invent the wheel :)
The length of the input int[] is fixed at 3? Then it doesn't get any simpler than this.
public int[] reverse3(int[] nums) {
return new int[] { nums[2], nums[1], nums[0] };
}
See also:
CodingBat/Java/Array-1/reverse3
Note that Array-1 is "Basic array problems -- no loops." You can use a loop if you want, but it's designed NOT to be solved using loops.
Firstly, while creating new array give it size of old array.
Next, when you're reversing an array, you don't need two loops, just one:
int length = oldArray.length
for(int i = 0; i < length; i++)
{
newArray[length-i-1] = oldArray[i]
}
You only want a single loop, but with indices going both ways:
public int[] reverse(int[] nums) {
int[] back = new int[nums.length];
int i,j;
for (i=0,j=nums.length-1 ; i<nums.length ; i++,j--)
back[i] = nums[j];
return back;
}
public int[] reverse3(int[] nums) {
int rotate[]={nums[2],nums[1],nums[0]};
return rotate;
}
This code gives correct output:-
public int[] reverse3(int[] nums) {
int[] myArray=new int[3];
myArray[0]=nums[2];
myArray[1]=nums[1];
myArray[2]=nums[0];
return myArray;
}
I got this with Python.. So you can get the idea behind it
def reverse3(nums):
num = []
for i in range(len(nums)):
num.append(nums[len(nums) - i - 1])
return num
In your code, for each value of i, you are setting target array elements at i to value in "nums" at j. That is how you end up with same value for all the elements at the end of all iterations.
First of all, very bad logic to have two loops for a simple swap algorithm such as :
public static void reverse(int[] b) {
int left = 0; // index of leftmost element
int right = b.length-1; // index of rightmost element
while (left < right) {
// exchange the left and right elements
int temp = b[left];
b[left] = b[right];
b[right] = temp;
// move the bounds toward the center
left++;
right--;
}
}//endmethod reverse
or simplified:
for (int left=0, int right=b.length-1; left<right; left++, right--) {
// exchange the first and last
int temp = b[left]; b[left] = b[right]; b[right] = temp;
}
Why go through all this pain, why dont you trust Java's built-in APIs and do something like
public static Object[] reverse(Object[] array)
{
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
return list.toArray();
}
public int[] reverse3(int[] nums) {
int[] values = new int[nums.length];
for(int i=0; i<nums.length; i++) {
values[nums.length - (i + 1)]=nums[i];
}
return values;
}