Given a collection of integers, what's a Java algorithm that will give all pairs of items as follows..
Given the example collection: [1,3,5], we'd want the output:
[1-1]
[3-3]
[5-5]
[1-3]
[1-5]
[3-5]
Note that ordering is not important, so we want one of [1-3], [3-1] but not both.
This should work with a collection of n numbers, not just the the three numbers as in this example.
Below function should do this
private void printPermutations(int[] numbers) {
for(int i=0;i<numbers.length; i++) {
for (int j=i; j<numbers.length; j++) {
System.out.println("[" + numbers[i] + "-"+ numbers[j] +"]");
}
}
}
Example call to this function
int[] numbers={1,2,3};
printPermutations(numbers);
Sounds like homework...but here it is anyway. Obviously you can do without an ArrayList, etc. - just quick and dirty.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
int[] input = {1, 3, 5};
ArrayList<String> output = new ArrayList<String>();
int n = input.length;
for (int left = 0; left < n; left++) {
output.add("["+input[left]+"-"+input[left]+"]");
for (int right = left + 1; right < n; right++) {
output.add("["+input[left]+"-"+input[right]+"]");
}
}
System.out.println(output.toString());
}
}
Here's the logic you want.
function subsequences (arr) {
arr.sort ();
var subseqs = [];
for (var i = 0; i < arr.length; ++i) {
for (var j = i; j < arr.length; ++j) {
subseqs.push ("" + arr [i] + "-" + arr [j]);
}
}
return subseqs;
}
Related
Hello I am having difficulty implementing a counting sort method in java. I believe the problem comes from the last two loops I have in the method. I am getting an ArrayIndexOutOfBounds exception : 8. I believe this comes from my second to last for loop when at index 5 the value is 8 but I am not sure how to resolve this. Any help is appreciated. Thank you!
In my code k is the highest value in the input array.
Code:
public static void main(String[] args) {
int [] arrayOne = {0,1,1,3,4,5,3,0};
int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
System.out.println(Arrays.toString(arrayOne));
countingSort(arrayOne, output, 5);
System.out.println(Arrays.toString(output));
}
public static void countingSort(int[] input, int[] output , int k){
int [] temp = Arrays.copyOf(input, k+1);
for (int i = 0; i <= k; i++){
temp[i] = 0;
}
for (int j = 0; j <= input.length - 1; j++){
temp[input[j]] = temp[input[j]] + 1;
}
for (int i = 1; i <= k; i++){
temp[i] = temp[i] + temp[i-1];
}
for (int j = input.length; j >= 1; j--){
output[temp[input[j]]] = input[j];
temp[input[j]] = temp[input[j]] - 1;
}
}
The problem is in the first loop because the array temp lenght is 6 and you are doing 7 interations in there.
So at the end of the for it is trying to do temp[6]=0 and the last position of your array is temp[5].
To fix this change your first loop to:
for (int i = 0; i < k; i++){
In the last loop you will get the same exception cause input[8] doesn't exist.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] input = {0,1,1,3,4,5,3,0};
int[] output = new int[input.length];
int k = 5; // k is the largest number in the input array
System.out.println("before sorting:");
System.out.println(Arrays.toString(input));
output = countingSort(input, output, k);
System.out.println("after sorting:");
System.out.println(Arrays.toString(output));
}
public static int[] countingSort(int[] input, int[] output, int k) {
int counter[] = new int[k + 1];
for (int i : input) { counter[i]++; }
int ndx = 0;
for (int i = 0; i < counter.length; i++) {
while (0 < counter[i]) {
output[ndx++] = i;
counter[i]--;
}
}
return output;
}
}
Above code is adapted from: http://www.java67.com/2017/06/counting-sort-in-java-example.html
this may help but try using the Arraya.sort() method.
e.g:
//A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
example is a snippet from https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/
As per algorithm following implementation, I have prepared for the count sort technique
public static int[] countSort(int elements[]) {
int[] sorted = new int[elements.length+1];
int[] range = new int[getMax(elements)+1];
for(int i=0;i<range.length;i++) {
range[i] = getCount(i, elements);
try {
range[i] = range[i]+range[i-1];
}catch(ArrayIndexOutOfBoundsException ae) {
continue;
}
}
for(int i=0;i<elements.length;i++) {
sorted[range[elements[i]]] = elements[i];
range[elements[i]] = range[elements[i]]-1;
}
return sorted;
}
public static int getCount(int value,int[] elements) {
int count = 0;
for(int element:elements) {
if(element==value) count++;
}
return count;
}
public static int getMax(int elements[]) {
int max = elements[0];
for(int i=0;i<elements.length;i++) {
if(max<elements[i]) {
max = elements[i];
}
}
return max;
}
Please review and let me know if any feedback and it is more helpful.
Note :
Non-negative no won't support in the above implementation.
don't use 0th index of the sorted array.
public static void main(String[] args) {
int[] HwArray = new int[10];
int count = 0;
String separate = "";
for (int i = 0; i < HwArray.length; i++) {
System.out.print(separate);
//Generate random numbers
HwArray[i] = (int) (100 + Math.random() * 100);
System.out.println("HwArray[" + i + "]=" + HwArray[i]);
}
int location = linearSearch(HwArray, 150);
System.out.println("\nLinear Search Result: " + location);
}
// Reverse the order of all elements, then print HwArray.
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
System.out.println("HwArray[" + i + "]=" + result[j]);
}
return result;
}
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++) {
if (list[i] == key)
return i; //return the index location
}
return -1; //return if number is not found in the index
}
I'm trying to print out the elements in Reverse, but It will only print out the elements. I'm not sure what's wrong.
Please research a little more before asking questions, maybe google "java reverse array". That's what I did, and found that this person asked the same thing. Reversing an Array in Java
The solution is simple:
List<Integer> lst = Arrays.asList(list); //Converts the int "list" into a list.
Collections.reverse(lst); //Reverses the list.
result = list.toArray(lst);
I need to find all the permutations for a given n(user input) without backtracking.
What i tried is:
import java.util.Scanner;
import java.util.Vector;
class Main {
private static int n;
private static Vector<Vector<Integer>> permutations = new Vector<>();
private static void get_n() {
Scanner user = new Scanner(System.in);
System.out.print("n = ");
n = user.nextInt();
}
private static void display(Vector<Vector<Integer>> permutations) {
for (int i = 0; i < factorial(n) - 1; ++i) {
for (int j = 0; j < n; ++j) {
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
}
System.out.println();
}
}
private static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
private static int max(Vector<Integer> permutation) {
int max = permutation.elementAt(0);
for (int i = 1; i < permutation.size(); ++i)
if (permutation.elementAt(i) > max)
max = permutation.elementAt(i);
return max;
}
// CHECKS FOR ELEMENT COUNT AND 0 - (n-1) APPARITION
public static int validate_permutation(Vector<Integer> permutation) {
// GOOD NUMBER OF ELEMENTS
if (max(permutation) != permutation.size() - 1)
return 0;
// PROPER ELEMENTS APPEAR
for (int i = 0; i < permutation.size(); ++i)
if (!permutation.contains(i))
return 0;
return 1;
}
private static Vector<Integer> next_permutation(Vector<Integer> permutation) {
int i;
do {
i = 1;
// INCREMENT LAST ELEMENT
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
// IN A P(n-1) PERMUTATION FOUND n. "OVERFLOW"
while (permutation.elementAt(permutation.size() - i) == permutation.size()) {
// RESET CURRENT POSITION
permutation.set(permutation.size() - i, 0);
// INCREMENT THE NEXT ONE
++i;
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
}
} while (validate_permutation(permutation) == 0);
// OUTPUT
System.out.print("output of next_permutation:\t\t");
for (int j = 0; j < permutation.size(); ++j)
System.out.print(permutation.elementAt(j) + " ");
System.out.println();
return permutation;
}
private static Vector<Vector<Integer>> permutations_of(int n) {
Vector<Vector<Integer>> permutations = new Vector<>();
// INITIALIZE PERMUTATION SET WITH 0
for (int i = 0; i < factorial(n); ++i) {
permutations.addElement(new Vector<>());
for(int j = 0; j < n; ++j)
permutations.elementAt(i).addElement(0);
}
for (int i = 0; i < n; ++i)
permutations.elementAt(0).set(i, i);
for (int i = 1; i < factorial(n); ++i) {
// ADD THE NEXT PERMUTATION TO THE SET
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
System.out.print("values set by permutations_of:\t");
for (int j = 0; j < permutations.elementAt(i).size(); ++j)
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
System.out.println("\n");
}
System.out.print("\nFinal output of permutations_of:\n\n");
display(permutations);
return permutations;
}
public static void main(String[] args) {
get_n();
permutations.addAll(permutations_of(n));
}
}
Now, the problem is obvious when running the code. next_permutation outputs the correct permutations when called, the values are set correctly to the corresponding the vector of permutations, but the end result is a mass copy of the last permutation, which leads me to believe that every time a new permutation is outputted by next_permutation and set into the permutations vector, somehow that permutation is also copied over all of the other permutations. And I can't figure out why for the life of me.
I tried both set, setElementAt, and an implementation where I don't initialize the permutations vector fist, but add the permutations as they are outputted by next_permutation with add() and I hit the exact same problem. Is there some weird way in which Java handles memory? Or what would be the cause of this?
Thank you in advance!
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
This is literally setting the vector at permutations(i) to be the same object as permutations[i-1]. Not the same value - the exact same object. I think this the source of your problems. You instead need to copy the values in the vector.
Sorry am kind of lame at this. I've looked on here for a way to Bubble sort so that I can get an array to go from largest number to smallest. I've found some error in my current iteration of the sort, I can't seem to get the array to sort once it compares a smaller number to a bigger number. Here what I am using thus far.
//bubble sort
for(int i=0;i<size;i++)
{
for(int v=1;i<(size-i);i++)
{
if(arrInt[v-1]<arrInt[v])
{
temp = arrInt[v-1];
arrInt[v-1]=arrInt[v];
arrInt[v]=temp;
}
}
}
int n = arrInt.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int v = 1; v < (n - i); v++) {
if (arrInt[v - 1] < arrInt[v]) {
temp = arrInt[v - 1];
arrInt[v - 1] = arrInt[v];
arrInt[v] = temp;
}
}
}
Try this.
Update - Replaced j with v
The problem is the inner loop should be from 1 to n. Instead your inner loop stops early.
Also you are testing i in the inner loop condition, but you should be testing v.
Try this:
//bubble sort
for(int i=0;i<size;i++)
{
for(int v=1;v<size;v++)
{
if(arrInt[v-1]<arrInt[v])
{
temp = arrInt[v-1];
arrInt[v-1]=arrInt[v];
arrInt[v]=temp;
}
}
}
Bubble Sort Method for Descending Order
public static void BubbleSort( int[ ] arr){
int records=arr.length-1;
boolean notSorted= true; // first pass
while (notSorted) {
notSorted= false; //set flag to false awaiting a possible swap
for( int count=0; count < records; count++ ) {
if ( arr[count] < arr[count+1] ) { // change to > for ascending sort
arr[count]=arr[count]+arr[count+1];
arr[count+1]=arr[count]-arr[count+1];
arr[count]=arr[count]-arr[count+1];
notSorted= true; //Need to further check
}
}
}
}
In this method when array is sorted then it does not check further.
Usually I implement Bubble sort like this,
for(int i=0;i<size-1;i++) {
for(int v=0;v<(size-1-i);v++){
if(arrInt[v]<arrInt[v+1])
{
temp = arrInt[v];
arrInt[v]=arrInt[v+1];
arrInt[v+1]=temp;
}
}
}
You know what is the problem is, in your code??? Look at the inner loop, you are initializing v but checking and changing i. Must be a copy paste error.. :P
Hope it helped...
Here you go:
int x = 0;
for(int i = 0; i < array.length; i++)
for(int j = 0; j < array.length; j++)
if(array[i] > array[j + 1])
x = array[j + 1];
array[j + 1]= array[i];
array[i] = x;
x here is a temporary variable you only need for this operation.
here's a complete running program for you. Hope that keeps you motivated
package test;
public class BubbleSort {
private static int[] arr = new int[] { 1, 45, 65, 89, -98, 2, 75 };
public static void sortBubbleWay() {
int size = arr.length-1;
int temp = 0; // helps while swapping
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i; j++) {
if (arr[j] < arr[j+1]) { /* For decreasing order use < */
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
private static void showShortedArray() {
for (int elt : arr) {
System.out.println(elt);
}
}
public static void main(String args[]) {
sortBubbleWay();
showShortedArray();
}
}//end of class
Hello I'm new to programming and registered to this forum :)
So I created a little program with nested for loops that prints out all combinations of five numbers which can have a value from 0 to 5. With nested for-loops this works fine. But isn't there a cleaner solution? I tried it with calling the for loop itself, but my brain doesn't get the solution.. :(
//my ugly solution
int store1, store2, store3, store4, store5;
for (int count = 0; count <= 5; count++) {
store1 = count;
for (int count2 = 0; count2 <= 5; count2++) {
store2 = count2;
for (int count3 = 0; count3 <= 5; count3++) {
store3 = count3;
for (int count4 = 0; count4 <= 5; count4++) {
store4 = count4;
System.out
.println(store1 + " " + store2 + " " + store4);
}
//I'm trying around with something like this
void method1() {
for (int count = 0; count <= 5; count++) {
list.get(0).value = count;
count++;
method2();
}
}
void method2() {
for (int count = 0; count <= 5; count++) {
list.get(1).value = count;
count++;
method1();
}
}
Usually when people try to use recursion or functional, using a loop is simpler or faster. However, in this case recursion is the simpler option in combination with a loop.
public static void method(List<Integer> list, int n, int m) {
if (n < 0) {
process(list);
} else {
for(int i = 0; i < m; i++) {
list.set(n, i);
method(list, n-1, m);
}
}
}
I know that you are trying combinations but this might help.
Permutation with repetitions
When you have n things to choose from ... you have n choices each time!
When choosing r of them, the permutations are:
n × n × ... (r times) = n^r
//when n and r are known statically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i = 0, j = 0;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
System.out.println(values[j] + " " + values[i]);
}
}
}
}
//when n and r are known only dynamically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i[] = new int[r];
int rc = 0;
for(int j=0; j<Math.pow(n,r); j++)
{
rc=0;
while(rc<r)
{
System.out.print(values[i[rc]] + " ");
rc++;
}
System.out.println();
rc = 0;
while(rc<r)
{
if(i[rc]<n-1)
{
i[rc]++;
break;
}
else
{
i[rc]=0;
}
rc++;
}
}
}
}
Something like this?
// Print all sequences of len(list)+n numbers that start w/ the sequence in list
void method( list, n ) {
if ( list.length == n )
// print list
else for ( int c=0; c<=5; c++ ) {
// add c to end of list
method( list, n );
// remove c from end of list
}
}
Initial call would be method( list, 5 ) where list is initially empty.
here another interative but less elegant version
while (store1 < 6) {
store5++;
if (store5 == 6) {
store5 = 0;
store4++;
}
if (store4 == 6) {
store4 = 0;
store3++;
}
if (store3 == 6) {
store3 = 0;
store2++;
}
if (store2 == 6) {
store2 = 0;
store1++;
}
System.out.println(store1 + " " + store2 + " " + store3 + " " + store4 + " " + store5 + " ");
}
The simplest code I can think of would tackle the problem with an entirely different approach:
public class TestA {
public static void main(String[] argv) {
for (int i=0; i<(6 * 6 * 6 * 6 * 6); ++i) {
String permutation = Integer.toString(i, 6);
System.out.println("00000".substring(permutation.length()) + permutation);
}
}
}
From your text (not your code) I gather you have 5 places and 6 symbols, which suggests there are 6 to the 5th power combinations. So the code just counts through those numbers and translates the number to the output combination.
Since this can also be viewed as a number system with base 6, it makes use of Integer.toString which already has formatting code (except the leading zeros) for this. Leading zeros are added where missing.