import java.util.*;
import java.util.Random;
class ArraySorting {
public static void main(String[]args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Random generate = new Random();
for (int nums = 0; nums < 20; nums++) {
int randomnumbers = generate.nextInt(50);
arr.add(randomnumbers);
}
System.out.println("First list of 20 generated numbers: ");
System.out.println(arr);
System.out.println("");
int dupe = 0;
for (int n = 0; n < arr.size(); n++) {
Integer check1 = arr.get(n);
for (int n2 = n+1; n2 < arr.size(); n2++) {
Integer check2 = arr.get(n2);
//remove second num if two numbers akike
if (check1.equals(check2)) {
arr.remove(check2);
n2 = n2-1;
dupe = 1;
}
}
n = n-dupe;
dupe = 0;
}
System.out.println("Duplicates: " + (20 - arr.size()));
for (int n3 = arr.size(); n3 < 20; ++n3) {
int randomnumbers = generate.nextInt(50);
arr.add(randomnumbers);
//check for duplicates again
for (int n = 0; n < arr.size(); n++) {
Integer check1 = arr.get(n);
for (int n2 = n+1; n2 < arr.size(); n2++) {
Integer check2 = arr.get(n2);
if (check1.equals(check2)) {
arr.remove(check2);
n2 = n2-1;
dupe = 1;
}
}
n = n - dupe;
dupe = 0;
}
}
//before sort
System.out.println(arr);
System.out.println("");
for(int a=0; a<20; a++){
for (int b = 0; b < 19; b++) {
if(arr[b] > arr[b+1]){
int temporary = arr[b];
arr[b] = arr[b+1];
arr[b+1] = temporary;
}
}
}
System.out.println("\nSorted Array:\n");
for (int a = 0; a < 20; a++) {
System.out.println("Array [" + a + "]: " + arr[a]);
}
}
}
Can anyone tell me what I did wrong for this one, I can't seem to generate the last part. Shouldn't the ArrayList arr = new ArrayList(); run same with the last part where arr[b] is work? I'm new to Java so would greatly appreciate if simple explaination/metaphor is ued provided with solution.
P.S: I'm not planning to use a library sort function like Collection, I'm required to use the sorting method at the last part.
arr[a] is the syntax to access array elements. For ArrayLists you use arr.get(a). And to assign a value to an ArrayList, you use arr.set(b,value). You can't use the assignment operator.
The problem you are having is that you are trying to remove your duplicates before sorting. First, sort your integers, duplicates and all, and then remove the duplicates.
import java.util.ArrayList;
import java.util.Random;
public class ArraySorting {
public static void main(String[]args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Random generate = new Random();
for (int nums = 0; nums < 20; nums++) {
int randomnumbers = generate.nextInt(10);
arr.add(randomnumbers);
}
System.out.println("First list of 20 generated numbers: ");
System.out.println(arr);
System.out.println("");
// SORT YOUR LIST FIRST
bubbleSort(arr);
System.out.println(arr);
// NOW YOU CAN REMOVE YOUR DUPLICATES
removeDuplicates(arr);
System.out.println(arr);
}
public static void bubbleSort(ArrayList<Integer> list){
for(int i = 0; i < list.size(); i++) {
for(int j = 1; j < (list.size() -i); j++) {
if(list.get(j - 1) > list.get(j)) {
int temp = list.get(j-1);
list.set(j-1, list.get(j));
list.set(j, temp);
}
}
}
}
public static void removeDuplicates(ArrayList<Integer> list){
for(int i = 0; i < list.size(); i++) {
if(i < list.size()-1) {
int prev = list.get(i);
int curr = list.get(i + 1);
if(curr == prev) {
list.remove(list.get(i + 1));
i--;
}
}
}
}
}
Output
First list of 20 generated numbers:
[9, 2, 2, 1, 3, 4, 0, 9, 5, 2, 5, 7, 4, 9, 0, 4, 0, 6, 6, 6]
[0, 0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 6, 6, 6, 7, 9, 9, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 9]
Related
How do I make a program that multiplies the numbers within the list?
example 1: if given the list: [2, 5, 6] return should be: [10, 12, 30]
example 2: if given the list: [1, 8, 10, 12] return should be: [8, 10, 12, 80, 96, 120]
so the numbers don't multiply with themselves and if two pairwise multiplication have the same number as a result, the number should only be written once.
I tried many things, but I am just incapable.
public class PairwiseMultiplications {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
getPairwiseMultiplications(list);
}
public static int[] getPairwiseMultiplications(List<Integer> numbers) {
int[] Array = {6,2,4,3};
int[] result = new int[Array.length];
for (int i = 0; i < Array.length; i++) {
int[] temp = new int[Array.length - 1];
System.arraycopy(Array, 0, temp, 0, i);
System.arraycopy(Array, i + 1, temp, i, Array.length - i - 1);
int product = 1;
for (int j = 0; j < temp.length; j++) {
product *= temp[j];
}
result[i] = product);
}
System.out.println();
return result;
int[] numbers = new List<Integer> list;
for (int i = 0; i < numbers.length; i++) {
int[] temporary = new int[numbers.length - 1];
System.arraycopy(numbers, 0, temporary, 0, i);
System.arraycopy(numbers, i + 1, temporary, i, numbers.length - i - 1);
int product = 1;
for (int j = 0; j < temporary.length; j++) {
product *= temporary[j];
}
getPairwiseMultiplications[i] = product;
}
}
}
I know, I'm doing something terribly wrong, but I'm just stuck with what to do.
Here is an example of how it works with arrays. With lists it works similarly, but I'm sure you can do it yourself :)
You need the following operations:
Iteration 1: (1) * 2, (1) * 3, (1) * 4
Iteration 2: (2) * 3, (2) * 4
Iteration 3: (3) * 4
So you multiply every number with all following numbers.
The outer loop is a for loop that goes through each number in the array:
final int[] numbers = new int[] {1, 2, 3, 4};
for (int i = 0; i < numbers.length; i++) {
final int a = numbers[i];
// ...
}
Next, we go through each successive digit, multiplying it by the current one of the outer loop:
for (int j = i + 1; j < numbers.length; j++) {
final int b = numbers[j];
System.out.println(a * b);
}
combined:
for (int i = 0; i < numbers.length; i++) {
final int a = numbers[i];
for (int j = i + 1; j < numbers.length; j++) {
final int b = numbers[j];
System.out.println(a * b); // TODO: add the result to a list
}
}
public class array12 {
static void merge_sort(int A[], int start, int end) {
if (end - start > 1) {
int middle1 = (2 * start + end + 1) / 3 - 1;
int middle2 = 2 * middle1 - start + 1;
merge_sort(A, start, middle1);
merge_sort(A, middle1 + 1, middle2);
merge_sort(A, middle2 + 1, end);
merge(A, start, middle1, middle2, end);
}
}
static void merge(int[] x, int start, int middle1, int middle2, int end) {
int n1 = middle1 - start + 1;
int n2 = middle2 - middle1;
int n3 = end - middle2;
int left[] = new int[n1]; // defining and initialising three arrays .
int mid[] = new int[n2];
int right[] = new int[n3];
for (int i = 0; i < left.length; i++) {
left[i] = x[i + start];
}
for (int i = 0; i < mid.length; i++) {
mid[i] = x[i + middle1 + 1];
}
for (int i = 0; i < right.length; i++) {
right[i] = x[i + middle2 + 1];
}
int i = 0;
int j = 0;
int k = 0;
int c = start;
// finding minimum element from the three arrays .
while (i < n1 && j < n2 && k < n3) {
if (left[i] <= mid[j] && left[i] <= right[k]) {
x[c] = left[i];
i++;
c++;
} else if (mid[j] <= left[i] && mid[j] <= right[k]) {
x[c] = mid[j];
j++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
// now only two arrays are left to be compared
while (i < n1 && j < n2) {
if (left[i] <= mid[j]) {
x[c] = left[i];
i++;
c++;
} else {
x[c] = mid[j];
j++;
c++;
}
}
while (j < n2 && k < n3) {
if (mid[j] <= right[k]) {
x[c] = mid[j];
j++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
while (i < n1 && k < n3) {
if (left[i] <= right[k]) {
x[c] = left[i];
i++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
// now only single array is left out of left[] , mid[] and right[].
while (i < n1) {
x[c] = left[i];
i++;
c++;
}
while (j < n2) {
x[c] = mid[j];
j++;
c++;
}
while (k < n3) {
x[c] = right[k];
k++;
c++;
}
System.out.println("");
// printing array elements after every merge operation .
for (int e = 0; e < x.length; e++) {
System.out.print(x[e] + " ");
}
}
public static void main(String[] args) {
int[] x = new int[9];
for (int i = 0; i < x.length; i++) {
x[i] = x.length - i;
}
System.out.println("initial array is : ");
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
System.out.println("");
merge_sort(x, 0, x.length - 1);
System.out.println("");
System.out.println("");
System.out.println(" sorted array is : ");
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
}
I am trying to merge 3 sorted arrays . I have been able to develop code for array size equal to power of 3 . I am unable to implement it with some other array size . I have tried to change values of middle1 and middle2 but am experiencing serious trouble . Setting their values is the main concern . Merging step is quite simple and is not causing problems .
What changes are required in my code so that it may work for any array size ? Can it be implemented using this approach ? I dont want size of any of the three arrays , left[] , mid[] and right[] to be zero at any time .
Please help .
Here's a similar answer to YCF_L's, but simplified (still uses Java 8):
public static int[] sortMultipleArrays(int[]... arrays) {
return Arrays.stream(arrays)
.flatMapToInt(Arrays::stream)
.sorted()
.toArray();
}
Output:
[1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 17, 20, 21, 24]
I don't follow your merge code. It seems overly complicated.
Here is a method for merging an unlimited number of sorted arrays, each a varying size.
private static int[] mergeSortedArrays(int[]... arrays) {
int totalLen = 0;
for (int[] arr : arrays)
totalLen += arr.length;
int[] idx = new int[arrays.length];
int[] merged = new int[totalLen];
for (int i = 0; i < totalLen; i++) {
int min = 0, minJ = -1;
for (int j = 0; j < arrays.length; j++)
if (idx[j] < arrays[j].length)
if (minJ == -1 || min > arrays[j][idx[j]]) {
min = arrays[j][idx[j]];
minJ = j;
}
merged[i] = min;
idx[minJ]++;
}
return merged;
}
Test
int[] a = { 3, 5, 9, 13, 17, 21 };
int[] b = { 2, 10, 20 };
int[] c = { 1, 7, 12, 24 };
int[] d = { 6 };
int[] merged = mergeSortedArrays(a, b, c, d);
System.out.println(Arrays.toString(merged));
Output
[1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 17, 20, 21, 24]
If using class "Integer" instead of primitive int is not a problem you can use this, basically first do the merge and after sort them: you can do the call Arrays.sort even in the same method and call it mergeAndSort, if you want...
import java.util.Arrays;
public class Main {
public static Integer[] merge(Integer[]... arrays) {
int count = 0;
for (Integer[] array : arrays) {
count += array.length;
}
Integer[] mergedArray = (Integer[]) java.lang.reflect.Array.newInstance(arrays[0][0].getClass(), count);
int start = 0;
for (Integer[] array : arrays) {
System.arraycopy(array, 0, mergedArray, start, array.length);
start += array.length;
}
return mergedArray;
}
public static void main(String[] args) {
Integer[] array1 = {3, 5, 6, 7, 78, 100};
Integer[] array2 = {5, 6, 7, 8, 9};
Integer[] array3 = {2, 6, 7};
Integer[] merged1 = merge(array1, array2);
Arrays.sort(merged1);
Integer[] merged2 = merge(array1, array2, array3);
Arrays.sort(merged2);
printArray(merged1);
printArray(merged2);
}
public static void printArray(Integer[] x) {
System.out.println("--ToString--");
for (Integer var : x) {
System.out.println(var);
}
System.out.println("----");
}
}
I have 10 numbers in a vector container contains: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. And I want n numbers in a group, for example:
n = 3
[1,2,3], [4,5,6], [7,8,9], [10]
[2,3,4], [5,6,7], [8,9,10], [1]
Is there an algorithm to find all the combinations?
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k = 3;
List<int[]> subsets = new ArrayList<>();
int[] s = new int[k]; // here we'll keep indices
// pointing to elements in input array
if (k <= input.length) {
// first index sequence: 0, 1, 2, ...
for (int i = 0; (s[i] = i) < k - 1; i++);
subsets.add(getSubset(input, s));
for(;;) {
int i;
// find position of item that can be incremented
for (i = k - 1; i >= 0 && s[i] == input.length - k + i; i--);
if (i < 0) {
break;
}
s[i]++; // increment this item
for (++i; i < k; i++) { // fill up remaining items
s[i] = s[i - 1] + 1;
}
subsets.add(getSubset(input, s));
}
}
System.out.println();
for(int i = 0; i < subsets.size();i++) {
int[] result = subsets.get(i);
for(int j = 0; j < result.length; j++) {
System.out.print(result[j]+" ");
}
System.out.println();
}
}
int[] getSubset(int[] input, int[] subset) {
int[] result = new int[subset.length];
for (int i = 0; i < subset.length; i++)
result[i] = input[subset[i]];
return result;
}
Thank you.
I need to make 2 arrays and sort one into the other in ascending order and display it. I've managed to move ar[] into sorted[], but I can't get it to actually sort.
Here's what I have so far:
public class SortArray
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[7];
for (int i=0; i<ar.length-1; i++)
{
int smallest = 1000000;
int index = 0;
for (int j=i+1; j<sorted.length; j++)
{
if (ar[i] < smallest)
{
smallest=i;
int tmp = ar[i];
ar[i] = sorted[j];
sorted[j] = tmp;
}
}
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
Just try to understand and use java algorithms here. If you have problems with understanding the idea please do not hesitate to ask.
http://www.java2novice.com/java-sorting-algorithms/
They are more efficient and they are not error prone.
Assuming that you are trying to learn sorting algorithms and coding, here is what you are trying to; Please be aware that if there are identical values it will get only one of them.
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[6];
int smallestFound=-1;
for (int i=0; i<ar.length-1; i++)
{
int smallest = 1000000;
for (int j=0; j<sorted.length; j++)
{
if (ar[j] < smallest && ar[j]>smallestFound) {
smallest = ar[j];
}
}
smallestFound=smallest;
sorted[i] = smallest;
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
you can use a TreeSet , it sort the element naturally:
public class SortArray
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[7];
List<Integer> sortedList = new TreeSet<Integer>();
for (int i=0; i<ar.length-1; i++) {
sortedList.add(ar[i]);
}
// transform into array
for(int i = 0; i< sortedList.size(); i++) {
sorted[i] = sortedList.get(i)
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
I got array of ints, and I want in order to last element of this array will be shift on top N times, something like this:
int[] array = {1, 2, 3, 4, 5};
And now, last element will be shifted for example 3 times, and it should be expected result:
3, 4, 5, 1, 2
I tried like this:
int[] tab = new int[5];
tab[0] = 1;
tab[1] = 2;
tab[2] = 4;
tab[3] = 5;
tab[4] = 6;
int[] secondTab = new int[5];
int N = 3;
int j = 0;
for (int i=0; i<tab.length-1; i++){
secondTab[i] = tab[(tab.length-1)-N];
N--;
if (secondTab[i+1]==0){
secondTab[i+1] = tab[j];
}
}
It's obviously bad code, j is not getting increment at all so it works only for this example, but I'm wondering what is the best way to do it?
If you want to shift right N times, it means the element at the i-th position will be at the (i+N)%tab.lenth-th position:
for (int i = 0; i < tab.length; i++) {
secondTab[(i+N)%tab.length] = tab[i];
}
If you want to shift the elements in the original array you can try something like this :
int[] array = {1, 2, 3, 4, 5};
int nbShift = 1; // the number of desired shift
for(int i = -1; i < nbShift; i++){
int f = array[0];
for(int j = 0; j < array.length -1 ; j++){
array[j] = array[j + 1];
}
array[array.length - 1] = f;
}
public static void main(String[] args) {
final int[] test = { 1, 2, 3, 4 };
shiftNTimes(test, 2);
for (final int i : test) {
System.out.println(i);
}
}
public static void shiftNTimes(int[] array, int numShifts) {
int timesShifted = 0;
while (timesShifted < numShifts) {
final int temp = array[0];
for (int i = 0; i < (array.length - 1); i++) {
array[i] = array[i + 1];
}
array[array.length - 1] = temp;
timesShifted++;
}
}
For details