This question already has answers here:
Permutation algorithm for array of integers in Java
(9 answers)
Closed 8 years ago.
There's a lot of guide on finding Permutation for a String, but how would I do this for every element in an ArrayList? Given that:
ArrayList<String> list = [bob, cat, dog]
Output:
[bob, cat, dog]
[bob, dog, cat]
[dog, bob, cat]
[dog, cab, bob]
....
Here's a code that I have that will permute a single word:
public class permutations {
public ArrayList<String> performPermutations(String s){
ArrayList<String> arrayList = new ArrayList<String>();
if (s == null) {
return null;
}
else if (s.length() == 0) {
arrayList.add("");
return arrayList;
}
else {
for (int i = 0; i < s.length(); i++) {
ArrayList<String> remaining = performPermutations(s.substring(0, i) + s.substring(i + 1));
for (int j = 0; j < remaining.size(); j++) {
arrayList.add(s.charAt(i) + remaining.get(j));
}
}
return arrayList;
}
}
public static void main(String[] args) {
permutations p = new permutations();
ArrayList<String> arr = p.performPermutations("abc");
for(int i = 0; i<arr.size();i++) {
System.out.println(arr.get(i));
}
}
See the code here for permutation of numbers :
Java code for permutation of a list of numbers
And now in your case, the list of numbers will be nothing but the list of indices for the ArrayList of strings. So basically permutation of indices will lead to permutation of the strings.
A simple solution to reverse anything (words in a sentence, items in a list etc) is to use a stack:
create a stack
loop on each item of your list, push the current item on the stack
loop on each item of the stack, pop the current item in a new list
That may not be the best in terms of performance though, but it works with everything as long as you can put it in a stack. And the two loops are not embedded in each other, so it's better than your example.
Related
I want to create a method in which, when given a 1 dimensional array, it'll find all permutations of the values in that array and make it into a 2 dimensional array. I found some algorithms online which finds all the permutations but only prints the values out in the form of a 2d array(example), but I couldn't quite modify the code to store the output into a single 2d array. Any help would be appreciated, thank you.
Here's how I would do it - adapted from the link in your question:
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
// Java program to calculate all permutations using
// Heap's algorithm
class HeapAlgo
{
List<int[]> heapPermutation(int a[]) {
LinkedList<int[]> list = new LinkedList<int[]>();
heapPermutation(a, a.length, a.length, list);
return list;
}
//Generating permutation using Heap Algorithm
void heapPermutation(int a[], int size, int n, List<int[]> list)
{
// if size becomes 1 then adds the obtained
// permutation to the list
if (size == 1)
list.add(a.clone());
for (int i=0; i<size; i++)
{
heapPermutation(a, size-1, n, list);
// if size is odd, swap first and last
// element
if (size % 2 == 1)
{
int temp = a[0];
a[0] = a[size-1];
a[size-1] = temp;
}
// If size is even, swap ith and last
// element
else
{
int temp = a[i];
a[i] = a[size-1];
a[size-1] = temp;
}
}
}
// Driver code
public static void main(String args[])
{
HeapAlgo obj = new HeapAlgo();
int a[] = {1,2,3};
List<int[]> list = obj.heapPermutation(a);
for(Iterator<int[]> i = list.iterator(); i.hasNext();) {
int[] array = i.next();
for(int j = 0; j < array.length; j++) {
System.out.print(array[j] + " ");
}
System.out.println();
}
}
}
// Based on code contributed by Amit Khandelwal.
Another approach would be to create an array of int[] arrays. The length would be the factorial of the length of a. You could create a stack class that tracks the lowest empty index to add the next permutation to.
This question already has answers here:
Common elements in two lists
(15 answers)
Closed 8 years ago.
I have two lists of Strings which contains around 100 string items in each list in which some are common.
I want to obtain the items which are common to both the lists and store it another list.
How can this be done. Please help.
You can use retainAll method of List
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainClass {
public static void main(String args[]) {
String orig[] = { "a", "b", "b", "c" };
String act[] = { "x", "b", "b", "y" };
List origList = new ArrayList(Arrays.asList(orig));
List actList = Arrays.asList(act);
origList.retainAll(actList);
System.out.println(origList);
}
}
This will print [b, b]
try Collection#retainAll()
listA.retainAll(listB);
What you want is called set intersection. (Or multiset, if you want see several duplicates.)
Simple but efficient solution is to sort both arrays and iterate over them.
for(int i = 0; i < a.length(); )
{
for(int j = 0; j < b.length(); )
{
int comparison = a[i].compareTo(b[j]);
if(comparison == 0)
{
// Add a[i] or b[j] to result here.
// If you don't want duplicate items
// in result, compare a[i] to
// last item in result and add
// only if a[i] is strictly greater.
++i;
++j;
}
else if(comparison < 0)
++i;
else
++j
}
}
If your string is long enough, you should add to HashSet strings from first list and iterate over second array checking if element is in set.
This is for class homework. She is making us use array and array list in two parts. Basically she is showing us how using arraylist is alot easier than arrays.
I am having alot of trouble getting the array part to work.
Create a class called CustomerLister1 with a main method that instantiates an array of String objects called customerName. The array should have room for six String objects. Use an initializer list to put the following names into the array:
Chris
Lois
Meg
Peter
Stewie
Write an enhanced for loop to display the array of names. What is displayed for the last array element? Why is it that value?
Add the Strings "Meg" and "Brian" into index 3, and 4, respectively, so that the array contains the following elements:
Chris
Lois
Meg
Meg
Brian
Peter
Stewie
Write an enhanced for loop to display the array of names.
Write a second, traditional for loop that checks each element for the String “Meg”, if found in the array, remove it, shift the remaining elements, and display the array of names. Are both instances of "Meg" removed correctly from the array?
This is my code
public class CustomerLister1
{
public static void main(String[] args)
{
String[] customerName = new String[7];
customerName[0] = "Chris";
customerName[1] = "Lois";
customerName[2] = "Meg";
customerName[3] = "Peter";
customerName[4] = "Stewie";
for (int i = customerName.length-1;i > 3; i--)
{
customerName[i] = customerName[i - 2];
}
customerName[3] = "Meg";
customerName[4] = "Brian";
for (int m = 0; m <= customerName.length-1; m++)
{
if(customerName[m].equals("Meg"))
{
for(int j = m;j < customerName.length;j++)
{
if(j < customerName.length-2) {
customerName[j]= customerName[j+1];
} else {
customerName[j]="";
}
}
m--;
}
for (String element : customerName)
{
System.out.println(element);
}
}
}
}
The output is wrong though it removes both the megs and then adds brian peter then two empty lines and then stewie. I need the empty lines to be gone and the output to print continuously.
Here's a solution. It uses an aditional counter to know when you should put the "" in the array instead of shifting the next element.
int customerSize = 7;
for (int m = 0; m <= customerName.length-1; m++)
{
if(customerName[m].equals("Meg"))
{
customerSize--;
for(int j = m;j < customerName.length;j++)
{
if(j >= customerSize)
customerName[j] = "";
else
customerName[j] = customerName[j+1];
}
m--;
for (String element : customerName)
{
if(! element.equals(""))
System.out.println(element);
}
System.out.println();
}
}
Output:
Chris
Lois
Meg
Brian
Peter
Stewie
Chris
Lois
Brian
Peter
Stewie
This question already has answers here:
creating k -itemsets from 2-itemsets
(2 answers)
Closed 9 years ago.
I have an declared an ArrayList a = [1,2,3,4,5] in java. I created another ArrayList b using the loop below:
for(int i = 0; i<a.size(); i++)
{
for(int j=i+1; j<a.size();j++)
{
b.add("{" + a.get(i)+ "," + a.get(j) + "}");
}
}
Now the ArrayList b will contain elements [{1,2},{1,3},{1,4},{1,5},{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}]. Now if I print the statement using System.out.println(b.get(0)), then the output will be {1,2}.
Now, I want to create 3-element sets from the 2-elements set c = [{1,2,3},{1,2,4},{1,2,5},{2,3,4},{2,3,5},{3,4,5}].
Again, I want to create 4-element sets from the 3-element set above as d = [{1,2,3,4}, {1,2,3,5},{1,2,4,5},{2,3,4,5}]
Again I want to create 5-element set lilkewise... How can I modify the above loop system to achieve it?
Put that in a method that takes two sets s1, s2.
To generate b, just call the method with (a, a).
To generate c, just call the method with (a, b) or (b,a).
Repeat at will.
You just have to add some logic to remove the } or { from the items in the set. Alternatively, don't put them at all and use them only to print results.
I've written a recursive method to do make all permutations of an array of numbers for you:
public static void main(String ... args) {
List<Integer> numbers= new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
for (int i=0; i<numbers.size(); i++) {
dfs(numbers.get(i), numbers, new ArrayList<Integer>(), numbers.size(), 0);
}
}
private static List<List<Integer>> resultOfResults= new ArrayList<>();
private static void dfs(int startNumber, List<Integer> numbers, List<Integer> result, int depth, int currentDepth) {
result.add(startNumber);
for (int i= 0; i < numbers.size(); i++) {
if (!result.contains(numbers.get(i))) {
dfs(numbers.get(i), numbers, new ArrayList<Integer>(result), depth, currentDepth + 1);
}
}
if (currentDepth + 1 == depth) {
resultOfResults.add(result);
return;
}
}
Then, just go over resultOfResults and print each array:
for (List<Integer> result : resultOfResults) {
System.out.println(Arrays.toString(result.toArray()));
}
This question already has answers here:
Compare elements in an array for duplicates
(8 answers)
Closed 9 years ago.
The problem with this code is that it will print out 5 9 9, instead of just 5,9. Because there is a third 9 in the array. What am I missing?
Edit: I need to write a function that will get the duplicates from the array given. I am trying to do this, but it is printing out a 5,9,9 instead of 5,9.
Edit 2: Well I figured it out after reading up on HashSet and got it to work using the code below. I hope this can help others with the same problem.
import java.util.HashSet;
public class Duplicator {
/**
* #param args
*/
public static void main(String[] args) {
int[] a = {3,5,5,8,9,9,9};
HashSet<Integer> hash = new HashSet<Integer>();
for(int i = 0; i < a.length; i++){
for(int j = i+1; j< a.length; j++){
if(a[i] == a[j]){
hash.add(a[i]);
}
}
}
System.out.println(hash);
}
}
You are trying to find the number who are duplicates, but you are actually just comparing with the previous element.So it prints the number every times it is the same as the one preceding it, which means: 5, 9 and 9.
You can add a variable to keep track of the last element printed. The code would still break if the array is not sorted, though.
You can also use Sets:
public static void main(String[] args) {
int[] a = {3,5,5,8,9,9,9};
Set<Integer> encounteredNumbers = new HashSet<Integer>();
Set<Integer> duplicateNumbers = new LinkedHashSet<Integer>(); // LinkedHashSet to keep in same order as encountered.
for (int i : a) {
if (encounteredNumbers.contains(i)) {
duplicateNumbers.add(i);
}
encounteredNumbers.add(i);
}
System.out.println(duplicateNumbers);
}
Try advancing through the array while keeping track of what value the last element was.
If the value changed, set boolean duplicateFound to false.
If the value did not change, and duplicateFound is false, set duplicateFound to true and print.
Also be sure to sort the array first if it may be unsorted.
You can use a set to avoid duplicate values. For example :
Set<Integer> values=new HashSet<Integer>();
values.add(5);
values.add(9);
values.add(9);
for(Integer val: values) {
System.out.println(val);
}
it prints :
5
9
Another example :
int[] a = {3,5,5,8,9,9,9};
List<Integer> list=new ArrayList<Integer>();
for(int i=0; i<a.length; i++) {
if(!list.contains(a[i])) {
list.add(a[i]);
}
}
for(int index=0; index<list.size(); index++) {
System.out.println(list.get(index));// prints the value in the corresponding index.
}
It prints as follows:
3
5
8
9
I am not clear about the question. If you need to eliminate duplicates a simple way depending on the size of the input array would be to construct a java.util.Set and iterate through it.