In the code below you need to get a array of negative articles and a array of positive articles. How to get a arrays without zero.
package niz;
import java.util.HashSet;
public class Niz {
public static void main(String[] args)
{
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
int array1[] = new int[array.length];
int array2[] = new int[array.length];
for (int i = 0; i < array.length; i++)
if (array[i] < 0)
array1[i] = array[i];
else
if (array[i] > 0)
array2[i] = array[i];
HashSet<Integer> notDupes = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();
for (int i = 0; i < array.length; i++)
{
if (!notDupes.contains(array[i]))
{
notDupes.add(array[i]);
continue;
}
duplicates.add(array[i]);
}
System.out.println("negative members of the array: " + java.util.Arrays.toString(array1));
System.out.println("positive members of the array : " + java.util.Arrays.toString(array2));
System.out.println("number of duplicates : " + duplicates.size());
}
}
The following is the output:
run:
negative members of the array: [0, 0, -22, 0, 0, 0, -4, -55, 0, 0, 0, -999, -87]
positive members of the array : [12, 23, 0, 0, 43, 545, 0, 0, 43, 12, 0, 0, 0]
number of duplicates : 3
BUILD SUCCESSFUL (total time: 1 second)
When you initialize an array of integers, the default elements in the array are zero. Therefore, after filling these arrays, you will still have zero elements inside it corresponding to the numbers that you did not fill. To solve this you can use Lists instead for which you don't have to initialize to a fixed size. If you still would like to have arrays at the end, you can convert the List to an array.
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++)
if (array[i] < 0)
list1.add(array[i]);
else if (array[i] > 0)
list2.add(array[i]);
Integer array1[] = list1.toArray(new Integer[list1.size()]);
Integer array2[] = list2.toArray(new Integer[list2.size()]);
By the way, it would not take much time at all to detect this with a debugger.
As a lazy person I would do following:
public static void main(String... args) {
int[] numbers = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
int[] positiveNumbers = Arrays.stream(numbers).filter(n -> n > 0).toArray();
int[] negativeNumbers = Arrays.stream(numbers).filter(n -> n <= 0).toArray();
int numOfDuplicates = numbers.length - (int)Arrays.stream(numbers).distinct().count();
System.out.println("negative members of the array: " + java.util.Arrays.toString(positiveNumbers));
System.out.println("positive members of the array : " + java.util.Arrays.toString(negativeNumbers));
System.out.println("number of duplicates : " + numOfDuplicates);
}
Java arrays are not dynamically sized. When you create the two arrays (one negative, and one positive) but both the same size as the original array; you will get entries that are 0 (because that's the default initial value for an int in an array). Use two List(s),
List<Integer> al1 = new ArrayList<>();
List<Integer> al2 = new ArrayList<>();
for (int i = 0; i < array.length; i++)
if (array[i] < 0)
al1.add(array[i]);
else if (array[i] > 0)
al2.add(array[i]);
Then to print the List(s),
System.out.println(al1);
System.out.println(al2);
Use List instead of arrays to leverage their power of shrinking, getting wider and smaller as long as you add new items and remove others.
Note that when you instantiate a new array Object, it will initialize all elements with default types, in you case the int items will be initialized to 0 thus you will have as much zeros as the array size.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Niz
{
public static void main(String[] args)
{
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
List<Integer> array1 = new ArrayList<Integer>();
List<Integer> array2 = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++)
if (array[i] < 0)
array1.add(array[i]);
else
array2.add(array[i]);
HashSet<Integer> notDupes = new HashSet<Integer>();
HashSet<Integer> duplicates = new HashSet<Integer>();
for (int i = 0; i < array.length; i++)
{
if (!notDupes.contains(array[i]))
{
notDupes.add(array[i]);
continue;
}
duplicates.add(array[i]);
}
System.out.println("negative members of the array: " + array1);
System.out.println("positive members of the array : " + array2);
System.out.println("number of duplicates : " + duplicates.size());
}
}
As a side note, you should avoid unnecessary condition block, such as else if statement since when an int literal is negative (if (array[i] < 0)), then it will be positive for sure thus no need for the (else if (array[i] < 0)) check.
You have maintain a counter while inserting data both for positive array and negative array. Otherwise your array will display 0 for places where you have not put data. This is because all the elements on an array of int will contain 0 by default. for eg
if(array[i] < 0)
array1[i] = array[i];
should be
if(array[i] < 0)
array1[negativeInde++] = array[i];
Also I am of the opinion that using primitive data types is more suited to your cause as using a wrapper like Integer will mean more overheads and incase you have a large array you will take too much time to execute.
Your code should be like this but you will still get zeros at the end as you have unwanted size.
int ctr1 =0;
int ctr2 =0;
for(int i=0;i<array.length;i++)
if(array[i] < 0)
array1[ctr1++] = array[i];
else
if(array[i] > 0)
array2[ctr2++] = array[i];
To get rid of them as well. Use the following code.
int ctr1 = 0;
int ctr2 = 0;
for (int i = 0; i < array.length; i++){
if (array[i] < 0) {
ctr1++;
} else if (array[i] > 0) {
ctr2++;
}
}
int array1[] = new int[ctr1];
int array2[] = new int[ctr2];
ctr1=ctr2=0;
for (int i = 0; i < array.length; i++){
if (array[i] < 0) {
array1[ctr1++] = array[i];
} else if (array[i] > 0) {
array2[ctr2++] = array[i];
}
}
I suggest to you an object-oriented approach, taking advance of the facilities of the Collections API. It is quite clearer:
Code an extension of ArrayList overriding the add() method, so that it only includes positive numbers. Code another extension for negatives.
Then, all you need is create four collections:
A List to include the original array items.
A positive ArrayList.
A negative ArrayList.
A Set for the not-duplicates.
... and just ONE loop, to iterate the original array adding an item to every collection.
After all, remove the not-duplicates from the original list through the removeAll method.
Related
For my program I need to make a 10 element array and the goal is to print out the even numbers from 2 to 20. I have to do this by adding 2 to the beginning element. This is what I have so far. I think I should use a loop as shown but I don't know how to go about adding 2 and printing that out. Thanks!
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
}
if you want program print even number between 2 & 20
for(int i=2;i<=20;i++)
{
if(i%2 == 0)
print(i)
}
Start at 2 and increment by 2 to get the even numbers:
int[] array = new int[10]
for(int counter=2; counter <= 20; counter += 2) {
array[counter/2 - 1] = counter
}
or
int[] array = new int[10]
for(int i=0; i <= 10; i++) {
array[i] = i*2 + 2
}
this is also an option
int i, value;
int nums[] = new int[10];
for (i = 0, value = 2; i < nums.length; value = value + 2, i = i + 1) {
nums[i] = value;
}
for (i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
int[] array = new int[10];
for (int i = 0, j = 1; i < array.length && j <= 20; j++) {
if (j % 2 == 0) {
array[i] = j;
i++;
}
}
System.out.println(Arrays.toString(array));
Java 8: int[] array = IntStream.range(1, 11).map(x -> x * 2).toArray();
Or, to just print: IntStream.range(1, 11).map(x -> x * 2).forEach(System.out::println);
From java-9 you can use IntStream.iterate to create int array
int[] arr= IntStream.iterate(2, i->i<=20, i->i+2).toArray();
for Integer array you can use Stream.iterate
Integer[] ary = Stream.iterate(2, i->i<=20, i->i+2).toArray(Integer[]::new);
Dear Alexis,
Below is an example using do-while.
you can simply define a range of expected even numbers using minVal and maxVal.
Program will execute and return list of ordered even numbers for given range. Assuming input values are correct even numbers. You can improve to apply validations.
public class EvenNumberGenerator {
static int minVal=2; //enter valid min value even number
static int maxVal = 20; //enter valid max value even number
public static void main(String[] args) {
List<Integer> evenNumbers = new ArrayList();
do {
if(minVal % 2 == 0) {
evenNumbers.add(minVal);
}
minVal++;
} while (!evenNumbers.contains(maxVal));
System.out.println(evenNumbers);
// evenNumbers.toArray(); in case you need an array
}
}
OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Hope it helps!
Using your code as a start, this will work:
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
array[counter] = (counter + 1) * 2;
}
System.out.println(Arrays.toString(array));
The following will also work with Eclipse Collections:
int[] array = IntInterval.evensFromTo(2, 20).toArray();
System.out.println(Arrays.toString(array));
Note: I am a committer for Eclipse Collections
I have an array of integers as shown in the below code. I have to find pair of largest numbers in the array. But there is a small twist.
Please see the below code and output.
public class ArraySort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { -9, -2, -10, -1, -4 };
int[] b = null;
int n = a.length;
int temp = 0;
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Ascending Order:");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + ",");
}
System.out.println("\nPair of larger numbers");
for (int i = 0; i < n; i++) {
if (k < 2) {
if (a[i] > a[n - 1 - i]) {
System.out.println(a[i]);
} else {
System.out.println(a[n-1-i]);
}
}
k++;
}
}
}
The output of which is displayed as
Ascending Order:
-10,-9,-4,-2,-1,
Pair of larger numbers
-1
-2
But instead of displaying the largest number as -1,-2. i have to display -10 and -9. the comparison should be without minus sign even though the array contains negative value.
Simply add this:
for(int i = 0; i < a.length; i++){
a[i] = Math.abs(a[i]);
}
This would convert the numbers to positive. Or you can follow what JF said. But that approach won't work if some of them are positive.
If all your integers are negative, why not just display the smallest two integers?
For the task to be meaningful ("difficult") the array should possibly contain both negative and positive numbers.
The candidates for absolute largest numbers reside either at the beginning or end of the array:
-13a, -7, -3, -2, -1, 9, 10b
-10b, -7, -3, -2, -1, 9, 13a
-13a, -11b, -3, -2, -1, 9, 10
-8, -7, -3, -2, -1, 9b, 13a
So you probably got two indices in one loop, one from the beginning, one from the end. No overlap (for -2, 4).
As this is home work, good luck.
Suppose we have a stream of int array of positive and negative integers.I want to use negative numbers as separators, and reverse the positive subarrays. for instance [1, 2, 3, 4, -5, 6, 7, 8, -9, ...] becomes [4,3,2,1,-5, 8, 7, 6, -9, ...]
I'm trying to come up with a linear (and possibly in place) solution but i can't.
Loop into your array while testing for negatif numbers.
Creates arrays 0f integer and use Collections.reverse() on the arrays created.
ArrayList<ArrayList<Integer>> lists = ArrayList<ArrayList<Integer>>();
int subCounter=0;
lists.add(new ArrayList<Integer>());
for(int i=0; i originalArray.length; i++){
(if originalArry[i] < 0){
lists.add(new ArrayList<Integer>());
subCounter++;
}
else{
lists.get(subCounter).add(originalArry[i]);
}
}
int[] newArray = new int[oroginalArray.length];
int counter = 0;
for(ArrayList<Integer> list : lists){
Collections.reverse(list);
for(int i=0; i < list.size(); i++){
newArray[counter] = list.get(i);
counter++;
}
newArray[counter] = originalArray[counter]; // add the separator
counter++;
}
It may need debugging but the philosophy is there.
This works. I just tested it. (short and sweet)
int[] array = new int[]{1,2,3,4,-5,6,7,8,-9,10,-11,12,13,14,15};
ArrayList<Integer> positives = new ArrayList<Integer>();
ArrayList<Integer> preFinalArray = new ArrayList<Integer>();
for(int i: array){
if(i>0) positives.add(new Integer(i));
else{
for(int j = positives.size()-1; j>=0; j--) preFinalArray.add(positives.get(j));
preFinalArray.add(new Integer(i));
positives.clear();
}
}
if(positives.size()>0) for(int i = positives.size()-1; i>=0; i--) preFinalArray.add(new Integer(positives.get(i)));
int[] newArray = new int[preFinalArray.size()];
for(int i = 0; i < newArray.length; i++) newArray[i]=preFinalArray.get(i).intValue();
for(int i: newArray)System.out.println(i);
I didn't try this code, but it should work:
public int[] convert(int[] c){
int[] ret = new int[c.length];
ArrayList<Integer> rev = new ArrayList<>();
for(int i = 0; i<c.length; i++){
if(c[i]>=0){
//If the number is positive, schedule it to be reversed
ret.add(i);
}else{
//If the number is negative, add the array reversed
//and then the number itself
int s = rev.size();
for(int y = 0; y<s; y++){
ret[i-1-y] = rev.get(y);
}
//Recreate the list to clear the scheduled content
rev = new ArrayList<>();
ret[i] = c[i];
}
}
//Flush the end of the array
int s = rev.size();
for(int y = 0; y<s; y++){
ret[c.length-1-y] = rev.get(y);
}
}
Ok, so I have this problem where when given an Array arr, return an Array which contains only odd integers in the original order from arr.
My code:
public int [] youMakeMeOdd(int [] arr)
{
int[] odds;
odds = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 2 != 0)
{
odds[i] = arr[i];
}
}
return odds;
}
Few Testers:
Expected...........................................................Run:
youMakeMeOdd({1,2,3}) → {1, 3}.....................{1, 0, 3}
youMakeMeOdd({2,1,3,5,7}) → {1, 3, 5, 7}.......{0, 1, 3, 5, 7}
youMakeMeOdd({2,4,6,8}) → {}........................{0, 0, 0, 0}
.
I can't seem to figure out how to put a blank space there instead of 0's. Help appreciated, thanks :)
The output array is being initialized to the size of the input array. I guess this being java code, the array elements are initialized to zero by default. So whenever the if condition does skips the ith position the default value (zero) is being shown.
public int[] youMakeMeOdd(int [] arr) {
List<Integer> odds = new ArrayList<Integer>();
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 2 != 0)
{
odds.add(arr[i]);
}
}
return convertIntegers(odds);
}
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
You could have a pre-computation loop where you just increment a counter and then allocate odds:
int counter = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 != 0)
{
counter ++;
}
}
odds = new int[counter];
I would use an ArrayList. Your problems seems to be the fact that arrays are immutable, so you it automatically fills your array with a bunch of unneeded 0s. ArrayLists can change dimensions, so you don't have to have the 0s.
You can have a look at them here: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Make sure you import the util package.
import java.util.*;
public ArrayList<Integer> youMakeMeOdd(int [] arr)
{
You need to specify the type that you want to hold in the angle braces. Because int is a primitive, you need to use the Integer class
ArrayList<Integer> odds;
odds = new ArrayList<>();
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 2 != 0)
{
The add method adds an integer to the end
odds.add(new Integer(arr[i]));
}
}
return odds;
}
var result = input.Select(a=>a % 2 != 0 ? a : 0).ToArray()
You can use linq easily, basically you use the original array and then use the Select to select either the value itself of the array or 0 if it's even, and then convert to an array using ToArray method.
I am trying to create a method which returns an int - the value of the largest integer in the sent array.
The way I want this method to work, is to check the first and the last element of the array in a for-loop, and work their way to the middle. So i = first integer, k = last integer. When i = 0, k = n-1 (indexes), when i = 1, k = n-2 if you catch my drift. In every loop it needs to check if a[i]>a[k]. Then they switch places. Then I know that the largest number is in the leading half of the array, and then I want it to check that half, so ultimately the largest int is at index 0.
I tried like this:
public static int maxOfArray(int[] a)
{
int length = a.length;
if(length<1)
throw new NoSuchElementException("Not at least one integer in array");
while (length > 1)
{
int k = length;
for(int i = 0; i < length/2; i++)
{
k--;
if(a[i]<a[k])
{
int j = a[i];
a[i] = a[k];
a[k] = j;
}
}
length /=2;
}
return a[0];
}
..but I don't really get it.. I'm having a hard time "picturing" what's happening here.. But it's not always working.. (though sometimes).
EDIT
Also: The array {6,15,2,5,8,14,10,16,11,17,13,7,1,18,3,4,9,12}; will spit out 17 as the largest number. I realize I have to fix the odd-length bug, but I would like to solve this even-length array first..
A bug is when encountering length is odd.
In these cases, you "miss" the middle element.
Example: for input int[] arr = { 8, 1, 5, 4, 9, 4, 3, 7, 2 }; - the element 9 will be compared and checked against itself, but then you reduce the size of length, you exclude 9 from the array you are going to iterate next.
I believe it can be solved by reducing the problem to ceil(length/2) instead of length/2 (and handling special case of length==1)
The other issue as was mentioned in comments is: you need to iterate up to length/2 rather then up to length, otherwise you are overriding yourself.
Lastly - the sign is wrong.
if(a[i]>a[k])
should be
if(a[i]<a[k])
Remember - you are trying to swap the elements if the first is smaller the the second in order to push the larger elements to the head of your array.
but I don't really get it.. I'm having a hard time "picturing" what's happening here.. But it's not always working.. (though sometimes).
In that case you should use a debugger to step through the code to get a picture of what each line of code does.
What I would do is:
public static int maxOfArray(int[] a) {
int max = a[0];
for (int i : a)
if (max < i)
max = i;
return max;
}
public static int findMaxTheHardWay(int[] array) {
for (int length = array.length; length > 1; length = (length + 1) / 2) {
for (int i = 0; i < length / 2; i++) {
if (array[i] < array[length - i - 1])
array[i] = array[length - i - 1]; // don't need to swap.
}
}
return array[0];
}
public static void main(String... args) {
Random rand = new Random(1);
for (int i = 1; i <= 1000; i++) {
int[] a = new int[i];
for (int j = 0; j < i; j++) a[j] = rand.nextInt();
int max = maxOfArray(a);
int max2 = findMaxTheHardWay(a);
if (max != max2)
throw new AssertionError(i + ": " + max + " != " + max2);
}
}
This is rather a crazy way to solve the problem, but I'll play along.
The problem is in the inner loop.
You start out with i = 0 and k = length - 1.
If a[i] > a[k] you swap them.
...
You end up with k = 0 and i = length - 1
If a[i] > a[k] you swap them.
If you look at that carefully you will notice that if we swapped the elements in the first swap, we will also swap them in the last swap; i.e. we will UNDO the effects of the first swap. And the same applies pair-wise through the entire array slice.
See?
What you need to do is to stop the inner loop half way ... and then take account of the case where length is odd.
By the way, the reason I called this "rather crazy", because the obvious and simple way is much faster: O(N) versus O(NlogN)
int a[] = {1,7,3};
List<Integer> list = Arrays.asList(a);
Integer largest = Collections.max(list);
This will give you Largest number in Array.
Here is a solution that fits the specifications that you want (unlike many other here, humm, humm):
final Integer[] input = {1, 2, 6, 32, 4, 44 ,12, 42, 3, 7, 17, 22, 57, 23, 102, 103 };
int half = (input.length / 2);
int mod = input.length % 2;
while (half >= 0) {
for (int i = 0, j = (half * 2) + mod - 1; i <= half && j >= half; i++, j--) {
if (input[i] < input[j]) {
final int tmp = input[i];
input[i] = input[j];
input[j] = tmp;
}
}
if (half == 0) break;
half = half / 2;
mod = half % 2;
}
//Here, input[0] = the biggest number in the original input.
Edit: Added mod, so it works if the last element is the largest..
I think your code is working, you just have to ceil the length / 2 in case of odd array but my tests return proper result:
package org.devince.largestinteger;
import java.util.NoSuchElementException;
public class LargestInteger {
final static int[] input = {1, 2, 6, 32, 4, 44 ,12, 42, 3, 7, 17, 22, 57, 23, 102, 103 };
// final static int[] input = { 8, 1, 5, 4, 9, 4, 3, 7, 2 };
// final static int[] input = {1,3,7};
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(String.valueOf(maxOfArray(input)));
}
public static int maxOfArray(int[] a)
{
int length = a.length;
if(length<1)
throw new NoSuchElementException("Not at least one integer in array");
while (length > 1)
{
int k = length;
for(int i = 0; i < length; i++)
{
k--;
if(a[i]>a[k])
{
int j = a[i];
a[i] = a[k];
a[k] = j;
}
}
length = (int) Math.ceil(length / 2f);
}
return a[0];
}
}
Why not just store the first value of the array to a variable max.
After that just loop through the array starting from second position till the last ,
in the loop just check if the current value is greater than max or not.If it is greater just assign max that value.
Return max and you have the largest number.
public int FindLargest()
{
int[] num = { 1, 2, 5, 12, 13, 56, 16, 4 };
int max = num[0];
for (int i = 1; i <num.length; i++)
{
if (num[i] > max)
{
max = num[i];
}
}
return max;
}
As the same u can approach like also,
int length = a.length;
while (length > 1)
{
int k = length;
for(int i = 0; i < length; i++)
{
for(int y = k-1; y >= i; y--)
{
if(a[i]<a[y])
{
int j = a[i];
a[i] = a[y];
a[y] = j;
}
}
}
length /=2;
}
final int validSampleRates[] = new int[]{
5644800, 2822400, 352800, 192000, 176400, 96000,
88200, 50400, 50000, 4800,47250, 44100, 44056, 37800, 32000, 22050, 16000, 11025, 4800, 8000};
ArrayList <Integer> YourArray = new ArrayList <Integer> ():
for (int smaple : validSampleRates){
YourArray.add(smaple);
}
Integer largest = Collections.max(YourArray);
System.out.println("Largest " + String.valueOf(largest));
The best way is to use Array that extends List Collection as ArrayList