sorting positive and negative integers through two integer arrays - java

We gave the following string:
int [] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87}.
There must be two rows, one for storage and the other positive elements for the negative elements of string array, and extracting the necessary logic that will perform the appropriate elements and placing them in the appropriate thread.
In other words, in the line array that is given is to be obtained all the positive elements and be placed in a separate row. Also, all the elements to be obtained and the negative to be placed in a separate row.
You also need to determine the number of duplicates in the string array.
Of course, it is necessary functionality written to be applicable to any number of integers. But MY teacher said that my code doesn't have a target row and He gave me an example: Target strings are two additional rows you will place isolated positive and negative values. For example, if you have a string:
int arr = {1,2,3,4, -1, -2, -3, -4}
then the target ranges will be:
int pos = {1,2,3,4}
int hc = {-1, -2, -3, -4}
of course, this should make it programmable and not hard coded, as in this example. Now how can I improve my code?
public static void main(String[] args) {
int array1[]= {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
System.out.println("Array 1 :");
Arrays.sort(array1);
for (int positive: array1) {
if (positive >= -1)
System.out.println("Positive numbers :" + positive+ "\t");
}
System.out.println();
System.out.println("Array 2 :");
for (int negative: array1) {
if (negative >= -1) {
}else{ System.out.println("Negative numbers :" +negative);
}
}
System.out.println();
for (int i = 0; i < array1.length -1; i++) {
if (array1[i + 1 ] == array1[i]) {
System.out.println("Duplicate element found :" + array1[i]);
i = i + 1;
}
}
}
}

If i have understood your question correctly, you want to make new arrays containing the positive and negative numbers,
Using your variable names i would go for something like this solution:
public static void main(String[] args) {
// Declare variables
int[] array1 = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87}, pos, hc;
int positive = 0, negative = 0;
// Check how many positive and/or negative numbers
for (int i : array1)
{
if (i >= 0)
{
positive++;
} else
{
negative++;
}
}
// Make exact size arrays
pos = new int[positive];
hc = new int[negative];
// Reset variables for new purpose
positive = 0;
negative = 0;
//Put numbers in correct array
for (int i : array1)
{
if (i >= 0)
{
pos[positive] = i;
positive++;
} else
{
hc[negative] = i;
negative++;
}
}
// Display arrays
System.out.print("Starter array: ");
for (int i: array1)
{
System.out.print(" " + i);
}
System.out.print("\nPositive array: ");
for (int i: pos)
{
System.out.print(" " + i);
}
System.out.print("\nNegative array: ");
for (int i: hc)
{
System.out.print(" " + i);
}
}
This outputs:
Starter array: 12 23 -22 0 43 545 -4 -55 43 12 0 -999 -87
Positive array: 12 23 0 43 545 43 12 0
Negative array: -22 -4 -55 -999 -87

try
int array1[]= {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
System.out.println("Array 1 :");
Arrays.sort(array1);
ArrayList<Integer> pos = new ArrayList<Integer>();
ArrayList<Integer> neg = new ArrayList<Integer>();
for (int num: array1){
if (num>= 0)
pos.add(num);
else
neg.add(num);
}
System.out.println();
if(pos.size()>0)
{
int[] positive = new int[pos.size()];
positive = pos.toArray(positive);
pos=null;
for (int num: positive)
System.out.println("Positive numbers :" + num+ "\t");
}
if(neg.size()>0)
{
int[] negative = new int[neg.size()];
negative = pos.toArray(negative);
neg=null;
for (int num: negative)
System.out.println("Negative numbers :" + num+ "\t");
}
for (int i = 0; i < array1.length -1; i++) {
if (array1[i + 1 ] == array1[i]) {
System.out.println("Duplicate element found :" + array1[i]);
i = i + 1;
}
}

sepratePositiveNegative(int[] arr) {
int size = arr.length;
int k =0;
for(int i =0;i <size; i++){
int temp = 0;
if(arr[i]<0) {
temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
k++;
System.out.println(arr[i]);
}
}

Related

Print only the numbers, which have been changed

I got curious about a Merge-sorting code.
Description:
This code creates two auxillary arrays left and right and store alternate array elements in them and then copying all elements of left and right subarrays back to original array and printing them. So instead of printing back to the original array, how would it be possible to only print the moved numbers?
class Project {
static void join(int arr[], int left[], int right[],int l, int m, int r){
int i;
for (i = 0; i <= m - l; i++)
arr[i] = left[i];
for (int j = 0; j < r - m; j++)
arr[i + j] = right[j];
}
static void split(int arr[], int left[], int right[],int l, int m, int r) {
for (int i = 0; i <= m - l; i++)
left[i] = arr[i * 2];
for (int i = 0; i < r - m; i++)
right[i] = arr[i * 2 + 1];
}
static void generateWorstCase(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
int[] left = new int[m - l + 1];
int[] right = new int[r - m];
split(arr, left, right, l, m, r);
generateWorstCase(left, l, m);
generateWorstCase(right, m + 1, r);
join(arr, left, right, l, m, r);
}
}
public static void main (String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
System.out.println("\nInput array that will result in worst case of merge sort is: \n");
System.out.println(Arrays.toString(arr));
}
}
Here's the output:
System.out.println(Arrays.toString(arr));
My question is..
I would ask, can you, based on the code, only have the output as, like the numbers being moved, and not the entire array?
Example:
The input is:
{ 10 20 30 40 50 }
The output is:
{ 10 50 30 20 40 }
My Desired Output:
{ 50 20 40 }
(The number of inputs varies according to the number of output)..
How would this happen?
Do it as follows:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (map.get(arr[i]) != i) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + list);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
[14, 16, 11, 13]
Another solution:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + list);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
[14, 16, 11, 13]
[Update]
You have requested to change the format of the output so that the numbers are not bounded by []. Note that this is how Arrays.toString or List::toString returns the string. If you do not want an array or a List, you can do it simply as:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
StringBuilder s = new StringBuilder();
int i;
for (i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
s.append(arr[i]).append(", ");
}
}
String output = s.substring(0, s.lastIndexOf(","));
System.out.println("\nInput array that will result in worst case of merge sort is: \n" + output);
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
14, 16, 11, 13
If you want to change the format of the output while keeping the List, you can do it as follows:
public static void main(String[] args) {
int arr[] = { 10, 11, 12, 13, 14, 15, 16 };
int[] original = Arrays.copyOf(arr, arr.length);
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
generateWorstCase(arr, 0, n - 1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (original[i] != arr[i]) {
list.add(arr[i]);
}
}
System.out.println("\nInput array that will result in worst case of merge sort is: \n"
+ list.toString().replace("[", "").replace("]", ""));
}
Output:
Sorted array is
[10, 11, 12, 13, 14, 15, 16]
Input array that will result in worst case of merge sort is:
14, 16, 11, 13
Iterate over both arrays simultaneously. If input[i] is not equal to output[i] then it has been moved.
List<Integer> moved = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
if (input[i] != output[i]) {
moved.add(input[i]);
}
}

Summing Numbers in an Array Greater than an Inputted Value

Need to add all numbers in an array that is greater than an inputted number. The seed is just so the output can be replicated.
Example:
[12,16,45,3,32]
Inputted Value: 30
Output:
77
import java.util.*;
public class SumAbove {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int seed = scnr.nextInt();
Random rand = new Random(seed);
System.out.println("Enter a positive integer between 1-100 to search above:");
int minVal = scnr.nextInt();
int[] arr = new int[rand.nextInt(100)+1];
for (int i=0; i<arr.length; i++) {
arr[i] = rand.nextInt(100)+1;
}
System.out.println(Arrays.toString(arr));
int sum = 0;
for (int i=0; i<arr.length; i++) {
if (arr[i]>minVal) {
sum += i;
}
}
System.out.println(sum);
}
}
Instead of sum += i; you want sum += arr[i]; (as already noted), you also only need one loop (since you know the minimum before the first loop). Like,
int minVal = scnr.nextInt(), sum = 0;
int[] arr = new int[rand.nextInt(100) + 1];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(100) + 1;
if (arr[i] > minVal) {
sum += arr[i];
}
}
System.out.println(Arrays.toString(arr));
System.out.println(sum);
Replace sum += i with sum += arr[i].
The variable i is just the position. arr[i] is the value at that position.
public static void main(String[] args) {
int nums[] = { 12, 16, 45, 3, 32 };
int value;
int sum = 0;
System.out.println("Enter a positive integer between 1-100 to search above: ");
Scanner sc = new Scanner(System.in);
value = sc.nextInt();
for (int i = 0; i < nums.length; i++) {
if (nums[i] > value)
sum = nums[i] + sum;
}
System.out.println(sum);
}
Here is how you can do it with streams in Java 8+.
int nValues = 5;
int minValue = 1;
int maxValue = 30;
Random r = new Random();
for (int i = 0; i < 10; i++) {
int[] values = r.ints(nValues, minValue, maxValue + 1).toArray();
// min to sum is the threshold
int minToSum = r.nextInt(7) + 10; // between 10 an 16 inclusive
int sum = Arrays.stream(values).filter(m -> m > minToSum).sum();
System.out.println("sum = " + sum + " for greater than " + minToSum
+ " : " + Arrays.toString(values));
}
The following output.
sum = 65 for values greater than 11 : [2, 10, 14, 23, 28]
sum = 92 for values greater than 10 : [13, 18, 15, 19, 27]
sum = 94 for values greater than 12 : [25, 6, 14, 25, 30]
sum = 54 for values greater than 10 : [14, 8, 14, 26, 5]
sum = 22 for values greater than 15 : [15, 8, 13, 22, 14]
sum = 28 for values greater than 13 : [3, 28, 9, 6, 5]
sum = 87 for values greater than 13 : [5, 18, 25, 21, 23]
sum = 31 for values greater than 13 : [16, 7, 12, 2, 15]
sum = 42 for values greater than 15 : [7, 22, 20, 10, 5]
sum = 40 for values greater than 12 : [2, 2, 13, 27, 9]

Inserting numbers from one array to an exact position on another one, (Java)

My goal is to insert array B[] into array A[] after the element with index K.
I don't need to lengthen the A[], the last 5 elements should just disappear.
This is what I got so far. Dont really mind the beginning of the program, thats just some extra requirements I had to do determine the arrays.
For example :
If I insert Kas 2, than array A is
0 2 4 6 8 10 12 14 16 18 0 0 0 0 0, and array B is 20 40 60 80 100.
The final array A should look like this:
0 2 4 20 40 60 80 100 6 8 10 12 14 16 18
public static void main(String[] args) {
int A[] = new int [15];
int B[] = new int [5];
int K, i, j;
Scanner sc = new Scanner(System.in);
Random r = new Random();
for (i=10; i<=14; i++) {
A[i] = 0;
}
System.out.println("Matīss Lavrinovičs RDBD0 171RDB075");
System.out.print("K=");
if (sc.hasNextInt())
K = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
sc.close();
if (K<0 || K>9) {
for (i=0; i<=9; i++)
A[i] = r.nextInt(50);
for (j=0; j<=4; j++)
B[j] = r.nextInt(100 - 50) + 50; }
else
for (i=0; i<=9; i++)
A[i] = i*K;
for (j=0;j<=4;j++)
B[j] = 10*(j+1)*K;
System.out.print("A: ");
i = 0;
while (i < 15) {
System.out.print(" " + A[i]);
if (i==14) System.out.println();
i = i + 1;
}
System.out.print("B: ");
j = 0;
while (j < 5) {
System.out.print(" " + B[j]);
j = j + 1;
}
do {
} while;
You can use System.arrayCopy:
int[] a = new int[] { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0, 0, 0, 0, 0 };
int[] b = new int[] { 20, 40, 60, 80, 100 };
int k = 2;
System.arraycopy(a, k + 1, a, k + 1 + b.length, a.length - b.length - k - 1);
System.arraycopy(b, 0, a, k + 1, b.length);
What happens is that we first copy the values after index #2 b.length places to the right (which is five). Then we copy the values of b into array a at the correct positions.
Alternative approach:
List<Integer> list = asList(a).subList(0, a.length - b.length);
list.addAll(k + 1, asList(b));
And a little helper method:
private static List<Integer> asList(int... ints) {
return IntStream.of(ints)
.boxed()
.collect(Collectors.toList());
}
You should take the following into consideration:
You should stick to the Java Naming Conventions: variable names start with a lowercase letter.
Omitting curling brackets {} like that often leads to bugs in the code. You should always use them.
One way to use System.arrayCopy to copy from array b[] to array a[] from position k
int[] a = new int[] { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0, 0, 0, 0, 0 };
int[] b = new int[] { 20, 40, 60, 80, 100 };
int k = 1;
int length = (a.length - k) > b.length ? b.length : (a.length - k);
System.arraycopy(b, 0, a, k, length);
Take care: In case array b[] does not fit in the remaining space in array a[] and as you said you don't want to lengthen array a[], only copy until there is space left (calculate int length with the ternary conditional operator).

making a method to remove the zeros from an array in java

was curious on how to write a method to remove all zeros from an array. If I have the array in the main method. for example my Main Method would look something like
public static void main(String[] args) {
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
System.out.println(Arrays.toString(test) + ": length = " + test.length);
int[] result = removeZeros(test);
System.out.println(Arrays.toString(result) + ": length = " + result.length);
}
and have the code output the length and the array without the zeros like:
[1, 0, 4, 7, 0, 2, 10, 82, 0]: length = 9
[1, 4, 7, 2, 10, 82]: length = 6
I don't know how to write a method for this other than doing something like this:
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
int length = 0;
for (int i=0; i<test.length; i++){
if (test[i] != 0)
length++;
}
int [] intResult = new int[length];
for (int i=0, j=0; i<test.length; i++){
if (test[i] != 0) {
intResult[j] = test[i];
j++;
}
}
any ideas how to make this a method and have it print out both the original array and the new array without zeros in it + the length?
I didn't test it, but this should work:
public class Blah {
public static void main(String[] args) {
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
System.out.println(Arrays.toString(test) + ": length = " + test.length);
int[] result = removeZeros(test);
System.out.println(Arrays.toString(result) + ": length = " + result.length);
}
public int[] removeZeros(int[] test) {
int length = 0;
for (int i=0; i<test.length; i++){
if (test[i] != 0)
length++;
}
int [] intResult = new int[length];
for (int i=0, j=0; i<test.length; i++){
if (test[i] != 0) {
intResult[j] = test[i];
j++;
}
return intResult;
}
}
With only the slightest changes to your own code, it's this simple to make it a method.
int [] removeZeros(int [] test);
{
if (test == null) {
return null;
}
int length = 0;
for (int i=0; i<test.length; i++){
if (test[i] != 0)
length++;
}
int [] intResult = new int[length];
for (int i=0, j=0; i<test.length; i++){
if (test[i] != 0) {
intResult[j] = test[i];
j++;
}
}
return intResult;
}
any ideas how to make this a method and have it print out both the original array and the new array without zeros in it + the length?
There is no significantly better way to remove the zeros. Obviously, you can put it in a method ... if that's what you want to do. The method needs to create and return the new array. (You can't change the size of the array argument passed to the method ...)
To print an array, either use a loop to iterate and print the elements, or Arrays.toString(array) and output the string.
To print an array's length, print array.length.
Using Java 8 :
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0}
int[] result = Arrays.stream(test).filter(i -> i != 0).toArray();
How about this
create array result with same length of array input
use variable length to count length of expected result
if the current element of input more than zero, result[length] =
current element of input test[i] and length++
If the length more than 0 then cut array result using value of length
The code :
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
int[] intResult = new int[test.length];
int length = 0;
for (int i=0; i<test.length; i++){
if (test[i] > 0) {
intResult[length] = test[i];
length++;
}
}
if(length > 0)intResult = Arrays.copyOf(intResult, length);

Arrays-odds and evens to determine how many of the values in the array are odd and how many are even

I'm trying to find the evens and odds of an array for practice.
Sample Data :
2 4 6 8 10 12 14
1 2 3 4 5 6 7 8 9
2 10 20 21 23 24 40 55 60 61
Sample Output :
Odds - []
Evens - [2, 4, 6, 8, 10, 12, 14]
Odds - [1, 3, 5, 7, 9]
Evens - [2, 4, 6, 8]
Odds - [21, 23, 55, 61]
Evens - [2, 10, 20, 24, 40, 60]
And here is my code so far:
import java.util.Scanner;
public class OddsAndEvens
{
private static int countEm(int[] array, boolean odd)
{
int count = 0;
int dum = 0;
for(int i=0; i< array.length; i++)
{
dum = array[i] / 2;
if(dum == 0 )
{
count++;
}
}
return count;
}
public static int[] getAllEvens(int[] array)
{
int numberEvens=0;
for(int i =0; i<array.length; i++)
{
if(array[i]%2 ==0)
{
numberEvens++;
}
}
int[] evens = new int[array.length - countEm(array,false)];
int count=0;
for(int i=0; i<array.length; i++)
{
if(array[i]%2==0)
{
evens[count] = array[i];
count++;
}
}
return evens;
}
public static int[] getAllOdds(int[] array)
{
int numberEvens = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
numberEvens++;
}
}
return null;
}
}
But I been getting errors in my output. These errors are the fact I am getting zeros in my output .
I'm just starting out and I'm hoping anyone can help me.
Your main problem comes from your countEm method. It is also the reason for all the extra zeroes behind your array. By doing minimal changes can solve these problems and make your program work.
One of the major careless mistake is that you used / instead of % for checking evens and odds in your countEm method.
Your countEm method is incomplete
Using wrong operator to count even/odd
Your incomplete countEm method now only counts the number of even number no matter the Boolean value is true or false. I've helped you implemented the complete countEm:
private static int countEm(int[] array, boolean odd)
{
int numEven = 0;
int numOdd = 0;
for(int i=0; i< array.length; i++)
if(array[i] % 2 == 0 ) //You used / instead of % earlier!
numEven++;
else
numOdd++;
if(odd)
return numOdd;
else
return numEven;
}
Make the above changes, I am sure it will work. Of course, you haven't complete your method for getting getAllOdds yet. Above changes will make your getAllEvens work properly.
Alternatively, for myself, I like to write it this way. I prefer shorter codes:
private static int countEm(int[] array, boolean odd)
{
int numEven = 0;
for(int i=0; i< array.length; i++)
if(array[i] % 2 == 0 )
numEven++;
return odd?array.length-numEven:numEven;
}
I prevent using data structures like array list because when I see such questions, I know what are the only things you are allowed to use.
I think this would be the best way to do that:
import java.util.ArrayList;
import java.util.List;
public class EvensAndOdds {
public static List<Integer> getOdds(int[] numbers){
List<Integer> odds = new ArrayList<>();
for(int i = 0; i < numbers.length; i++){
if((numbers[i]%2) != 0){
odds.add(numbers[i]);
}
}
return odds;
}
public static List<Integer> getEvens(int[] numbers){
List<Integer> evens = new ArrayList<>();
for(int i = 0; i < numbers.length; i++){
if((numbers[i]%2) == 0){
evens.add(numbers[i]);
}
}
return evens;
}
public static void main(String[] args){
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
List<Integer> evens = getEvens(numbers);
List<Integer> odds = getOdds(numbers);
System.out.println("Evens: ");
for(Integer even: evens){
System.out.print(even.toString() + " ");
}
System.out.println("");
System.out.println("Odds: ");
for(Integer odd: odds){
System.out.print(odd.toString() + " ");
}
}
}
What about ;):
public class EvenOddSorter {
public void sort(int[] numbers) {
Arrays.sort(numbers,new Comparator<int>() {
#Override
public int compare(int i, int y) {
if(i % 2 == 0)
return -1;
if(y % 2 == 0)
return 1;
return 0;
}
});
}
}
then extract odds and evens from your array by finding the first odd number and using
int[] evens = Arrays.copyOfRange(numbers, 0, numberOfFirstOdd);
int[] odds = Arrays.copyOfRange(numbers, numberOfFirstOdd, numbers.length)
;)
You are creating a new array with too many initial items - hence the zeros at the end. Your getAllEvens() method could look more like:
public static int[] getAllEvens(int[] array)
{
int numberEvens = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
numberEvens++;
}
}
int[] evens = new int[numberEvens]; // This has changed
int count = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
evens[count] = array[i];
count++;
}
}
return evens;
}
This creates a new array with exactly the number of items you are about to populate it with.
Edit: To address your comment, here is my main() method and the output from the method above.
public static void main(String[] args)
{
int[] input =
{
2, 4, 6, 8, 10, 12, 14,
1, 2, 3, 4, 5, 6, 7, 8, 9,
2, 10, 20, 21, 23, 24, 40, 55, 60, 61
};
int[] evens = getAllEvens(input);
System.out.println(Arrays.toString(evens));
}
Which gives
[2, 4, 6, 8, 10, 12, 14, 2, 4, 6, 8, 2, 10, 20, 24, 40, 60]

Categories

Resources