grouping algorithm java n choose k - java

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.

Related

how to program a pairwise multiplications between numbers from a given list of numbers

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
}
}

How to remove rows and columns containing only zeros from a 2d matrix?

Given an integer matrix of size, say, M x N, you have to write a program to remove all the rows and columns consisting of all zeros. Your program must remove those rows and columns that consist of zero valued elements only. That is, if all the elements in a row (column) are zeros, then remove that row (column). All the remaining rows and columns should be output.
Input Specification:
The first line of input will have two integers, say, M and N. M specifies the number of rows in the matrix and N specifies the number of columns in the matrix.
This will be followed by M lines, each consisting of N integers. Note: Assume 1 <= M <= 10 and 1 <= N <= 10. Also, you may assume that there is at least one non-zero element in the given matrix.
Output Specification:
The output should be the resulting matrix.
Each row of the output matrix should be terminated by a newline character.
There should be exactly one space (not tab) between successive elements in each row.
Example1:
Sample Input:
4 4
1 2 3 4
0 0 0 0
5 6 7 8
0 0 0 3
Sample Output:
1 2 3 4
5 6 7 8
0 0 0 3
Example2:
Sample Input:
4 5
1 2 0 3 5
0 0 0 0 0
4 5 0 6 9
7 8 0 9 1
Sample Output:
1 2 3 5
4 5 6 9
7 8 9 1
The solution I found was as follows. It works only for rows and columns having either non-negative or non-positive numbers:
import java.util.Scanner;
public class RemoveZeroFromMatrix {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter rows and column");
int m = s.nextInt();
int n = s.nextInt();
int[][] a = new int[m][n];
int[][] b = new int[m][n];
int[][] c = new int[m][n];
System.out.println("enter the matrix");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = s.nextInt();
}
}
System.out.println("input matrix");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
int sumRow = 0, x = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sumRow += a[i][j];
}
if (sumRow != 0) {
for (int k = 0; k < n; k++) {
b[i - x][k] = a[i][k];
}
} else {
x++;
}
sumRow = 0;
}
int sumCol = 0, y = 0, temp = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n - x; j++) {
sumCol += b[j][i];
}
if (sumCol != 0) {
for (int k = 0; k < n - x; k++) {
if (temp == 0) {
c[k][i] = b[k][i];
}
if (temp == 1 && n > 3) {
c[k][i] = b[k][i + 1];
}
}
} else {
for (int k = 0; k < n - x; k++) {
c[k][i] = b[k][i + 1];
temp = 1;
}
}
sumCol = 0;
}
System.out.println("outut matix:");
for (int i = 0; i < m - x; i++) {
for (int j = 0; j < n - y - temp; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Removing columns from a matrix is more difficult than removing rows. For this reason, to simplify the code, you can use the matrix transposition something like this:
Try it online!
public static void main(String[] args) {
int[][] arr1 = {
{1, 2, 3, 4},
{0, 0, 0, 0},
{5, 6, 7, 8},
{0, 0, 0, 3}};
int[][] arr2 = {
{1, 2, 0, 3, 5},
{0, 0, 0, 0, 0},
{4, 5, 0, 6, 9},
{7, 8, 0, 9, 1}};
int[][] arr3 = removeZeroRowsNColumns(arr1);
int[][] arr4 = removeZeroRowsNColumns(arr2);
// output
Arrays.stream(arr3).map(Arrays::toString).forEach(System.out::println);
//[1, 2, 3, 4]
//[5, 6, 7, 8]
//[0, 0, 0, 3]
Arrays.stream(arr4).map(Arrays::toString).forEach(System.out::println);
//[1, 2, 3, 5]
//[4, 5, 6, 9]
//[7, 8, 9, 1]
}
public static int[][] removeZeroRowsNColumns(int[][] arr) {
return removeZeroRows(removeZeroColumns(arr));
}
public static int[][] removeZeroColumns(int[][] arr) {
return transposeMatrix(removeZeroRows(transposeMatrix(arr)));
}
public static int[][] transposeMatrix(int[][] arr) {
// assume that we have a rectangular array, i.e. matrix
int[][] transposed = new int[arr[0].length][arr.length];
IntStream.range(0, arr.length)
.forEach(i -> IntStream.range(0, arr[0].length)
.forEach(j -> transposed[j][i] = arr[i][j]));
return transposed;
}
public static int[][] removeZeroRows(int[][] arr) {
return Arrays.stream(arr)
// filter out rows consisting of all zeros
.filter(row -> !Arrays.stream(row).allMatch(i -> i == 0))
.toArray(int[][]::new);
}

How can I print an increasing number of elements of an array per line

I want to print out an increasing number of elements in my array per line but I'm not sure how I could do it.
public static void main(String[] args) {
int[] x = new int[21];
for (int i = 0; i < x.length; i++) {
x[i] = i + 1;
}
System.out.println(Arrays.toString(x));
}
I would like my output to look like:
[1]
[2, 3]
[4, 5, 6]
etc...
instead of what I get right now which is
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
I'm really new to java so any tips would really be appreciated, thanks.
Add this below your code.
for (int i = 0, ctr = 0; i < x.length; ctr++) {
System.out.print("[ ");
for (int j = 0; j <= ctr; i++) {
System.out.print(x[i]);
j++;
if (j <= ctr) {
System.out.print(" ,");
}
}
System.out.println(" ]");
}
This method does not require storage
int start = 1;
int count = 1;
int outer = 6;
for (int y = 0; y < outer; y++) {
System.out.print ("[");
int x = start;
for (; x < start + count; x++) {
System.out.print (x);
if (x < start + count - 1)
System.out.print(",");
}
System.out.println ("]");
count++;
start = x;
}
result
[1]
[2,3]
[4,5,6]
[7,8,9,10]
[11,12,13,14,15]
[16,17,18,19,20,21]
You can use this code
int[] x = new int[21];
for (int i = 0; i < x.length; i++) {
x[i] = i + 1;
}
int start = 0, len = 1;
while(start + len <= x.length) {
int[] newArray = Arrays.copyOfRange(x, start, start + len);
System.out.println(Arrays.toString(newArray));
start += len;
len++;
}
Using two loops you can achieve the result, the outer loop will create an empty array with each iteration and the inner one will populate it with numbers. Also using a third variable to keep track of the last number generated.
public static void main(String[] args) {
int n = 21;
int lastNumber = 0;
int x[] = null;
for(int j = 0; j< n; j++) {
x = new int[j];
for (int i = 0, k = lastNumber; i< j; i++,k++) {
x[i] = k + 1;
}
if(x.length != 0){
lastNumber = x[x.length - 1];
System.out.println(Arrays.toString(x));
}
}
}
Output:
[1]
[2, 3]
[4, 5, 6]
[7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20, 21]

How to shift N times last element of the list on top

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

Problems in ArrayList<Integer>

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]

Categories