Why do elements inside a List modify themselves? [duplicate] - java

This question already has answers here:
After ArrayList.add() in a loop, all elements are identical. Why? [duplicate]
(3 answers)
Closed 2 years ago.
I want to get different array elements combinations (permutations) of an array to a List. I swap the first and the last element of the array through a for loop and the combination (permutation) is added to the List. Then the second and the element before the last is swapped and added to the List, so and so forth. Suppose the array is arr[1,2,3,4,5,6,7], the first element added to the List would be arr[7,2,3,4,5,6,1]. The second element would be arr[7,6,3,4,5,2,1]. But what I end up getting is something like arr[7,6,5,4,3,2,1] for all the elements in the List.
The problem is that the elements added to the List are also modified correspondingly with the current modification of the array. I end up getting similar array elements in the List. What I want is different permutations or arrays with different combinations of elements. Can you please help me with this?
private List<Gate[]> generateSolutions(Gate[] solution) {
List<Gate[]> sList= new ArrayList<>();
int i, j;
for (i = 0, j = solution.length - 1; i < solution.length / 2; i++, j--) {
Gate temp;
temp = solution[i];
solution[i] = solution[j];
solution[j] = temp;
sList.add(solution);
}
return sList;
}

import java.util.ArrayList;
import java.util.List;
/**
* Dev Parzival
* Date : 27/10/2020 Time : 22:40
* I have a confidence about my life that comes from standing tall on my own two feet.
*/
public class Permutation {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>(10);
//Make sure that the list has unique numbers
for(int i=0;i<3;i++)
list.add(i+1);
int n =list.size();
Permutation permutation = new Permutation();
//Generater permutation
permutation.permute(list, 0, n-1);
}
private void permute(ArrayList<Integer> list, int l, int r) {
//When l is equal to one less than the length of the list we will display it.
if (l == r)
System.out.println(list);
else{
//The l valuse specifies which position we want to fix
for (int i = l; i <= r; i++) {
//After diciding the position we fix it by swapping it.
swap(list,l,i);
//Here we are fixing l+1 th number
permute(list, l+1, r);
//Swapping it back to its original position so initial order is maintained
swap(list,l,i);
}
}
}
//Swap function will swap ith and jth numbers of the list
private void swap(List<Integer> list, int i, int j) {
int temp=list.get(i);
list.set(i,list.get(j));
list.set(j,temp);
}
}
Above code is used for generating permutation.

Related

How to compare each element in my arraylist to find the nth smallest of the two arrays?

import java.util.*;
public class Main {
public static void main(String[] args) {
// this section of code will require user input to have the value of n to be set
System.out.println(("What number would you like to set n equal to ?"));
Scanner sc = new Scanner(System.in);
System.out.print(("n= "));
int value = sc.nextInt();
System.out.println((""));
// this section of code set the two array only to hold the value of n
Random rand = new Random();
ArrayList<Integer> setA = new ArrayList<Integer>();
for (int i = 0; i < value; i++) {
int picks = rand.nextInt(1000);
setA.add(picks);
}
Collections.sort(setA);
System.out.println(setA);
ArrayList<Integer> setX = new ArrayList<Integer>();
for (int k = 0; k < value; k++) {
int picks = rand.nextInt(1000);
setX.add(picks);
}
Collections.sort(setX);
System.out.println(setX);
solution(setA,setX,value);
}
private static int solution(ArrayList<Integer> A1, ArrayList<Integer> X1, int value) {
// This section of code is where the arrays will be compared to find the nth smallest.
ArrayList<Integer> setF = new ArrayList<Integer>();
for (int c = 0; c < A1.size(); c++) {
for(int k = 0; k < X1.size(); k++) {
if(A1.get(c) < X1.get(k)) {
}
}
}
System.out.print(setF);
return value;
}
}
So far i have my program set up to have the user enter a number that will be used for the size of the array. Once the number has been entered the arrays are created with random numbers that will be place in order. Next I would like to go through each element of my arrays and compare to see which numbers can be placed in my Final array. In my final array is the nth smallest number which will be return. I can not merge the two array together.
For example if n = 10 below are my two arrays
A [124, 264, 349, 450, 487, 641, 676, 792, 845, 935]
B [2, 159, 241, 323, 372, 379, 383, 475, 646, 836]
124 < 2 this statement is false so 2 would get added to my final array list. Array B should move to the next element in the list.
124 < 159 this is true so 124 gets added to my final array list. Array A should move to the next element in the list.
264 < 159 this statement is false so 159.
Final Array [2,124, 159,...]
n smallest is 383.
Hopefully that example gives you an ideal of what I'm trying to accomplish.if you have something better let me know please..
Your solution would work but you can make your solution's time complexity o(n) rather than o(n^2).
What you could do is, since the arrays are equally sorted, you can compare both elements at position zero (like you're doing) and then whichever element is smaller, pop that element from the array and add it to the final array. Keep testing the zero(th) indexed element until one of the arrays is empty. Once its empty, you can just append the remaining other array on the end of the final array and that should achieve what you want.
So in some java code implementation:
private ArrayList<Integer> sortTwoArrays(ArrayList<Integer> arrayA, ArrayList<Integer> arrayB) {
ArrayList<Integer> finalArray = new ArrayList<>();
while(!arrayA.isEmpty() && !arrayB.isEmpty()) {
if (arrayA.get(0) < arrayB.get(0)) {
// remove element and store
finalArray.add(arrayA.remove(0));
}
else {
finalArray.add(arrayB.remove(0));
}
}
// Find out which array is not empty
// Adds remaining contents of non-empty array to end of finalArray
if (!arrayA.isEmpty()) {
finalArray.addAll(arrayA);
}
else if (!arrayB.isEmpty()) {
finalArray.addAll(arrayB);
}
return finalArray;
}
To get the nth smallest value, just add the value the user passes in as an argument to the function and then when you're returning the function, just return finalArray.get(nthIndex)
Example code showcase here.
Note: The original two ArrayLists will get destroyed from this method
If you want preserve the two arrays, I recommend keeping track of both indexes in the list inside variables and then incrementing based on when one item is less than another. Additionally, change the If statement check after the whie-loop from an isEmpty() check to a comparison like so indexOfArrayA == arrayA.size() - 1.
I hope this helps in anyway.

Java- How to find the permutation of all values in a 1 dimensional array and store them in a 2 dimensional array

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.

How to get the insertion point of an int input in an ArrayList without using Collections.binarySearch [duplicate]

This question already has answers here:
Insert element to ArrayList with ascending order and no duplicate elements
(7 answers)
Closed 4 years ago.
Having a method and arr being already sorted...
public int search(ArrayList<Integer> arr, int numberToBeSearched) {
//Code here
return //insertion point
}
Let arr be{1, 4, 7} and numberToBeSearched 2.
return would be 1 because it would be between 1 and 4 in order to maintain the order.
How would you guys get the insertion point of numberToBeSearched inside arr without using Collections.binarySearch?
The insertion point is the index position where
the number would need to be inserted in the array-list so as to maintain the sort order.
public int search(ArrayList<Integer> arr, int numberToBeSearched) {
int i=0;
for (i = 0; i < size(); i++) {
// if the element you are looking at is smaller than numberToBeSearched,
// go to the next element
if (arr.get(i) < numberToBeSearched) continue;
// if the element equals numberToBeSearched, return, because we don't duplicates
if (arr.get(i) == numberToBeSearched) return -1;
// otherwise, we have found the location of numberToBeSearched
return i;
}
// we looked through all of the elements, and they were all
// smaller than numberToBeSearched, so the index is end of the list
return i;
}

Arraylist swap elements [duplicate]

This question already has answers here:
How to change value of ArrayList element in java
(7 answers)
Closed 8 years ago.
How do I swap the the first and last elements of an ArrayList?
I know how to swap the elements of an array: setting a temporary value to store the first element, letting the first element equal the last element, then letting the last element equal the stored first element.
int a = values[0];
int n = values.length;
values[0] = values[n-1];
values[n-1] = a;
So for an ArrayList<String> would it be like this?
String a = words.get(0);
int n = words.size();
words.get(0) = words.get(n-1);
words.get(n-1) = a
You can use Collections.swap(List<?> list, int i, int j);
In Java, you cannot set a value in ArrayList by assigning to it, there's a set() method to call:
String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)
Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc
public static void swap(List list,
int i,
int j)
Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)
Parameters:
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.
Read The official Docs of collection
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29
import java.util.*;
import java.lang.*;
class Main {
public static void main(String[] args) throws java.lang.Exception
{
//create an ArrayList object
ArrayList words = new ArrayList();
//Add elements to Arraylist
words.add("A");
words.add("B");
words.add("C");
words.add("D");
words.add("E");
System.out.println("Before swaping, ArrayList contains : " + words);
/*
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range. */
Collections.swap(words, 0, words.size() - 1);
System.out.println("After swaping, ArrayList contains : " + words);
}
}
Oneline compilation example http://ideone.com/MJJwtc
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
if (list.get(i) > list.get(i + 1)) {
int j = list.get(i);
list.remove(i);
list.add(i, list.get(i));
list.remove(i + 1);
list.add(j);
i = -1;
}
}
}

find longest linked lists in an array of linked lists

I have an array of linked lists (an adjacency list) most of the lengths of the linked lists are 4 but there are some that will randomly have more than that. My goal is to go through the array and find the ones that are more than length 4 (thats the easy part) then add the index's to an array so something like
for (int i = 0; i < 1000; i++){
if(sWorld[i].length > 4)
//add i to an array
// then sort the array
couldnt really figure out how to do this. i tried to add to a inked list then linked list toArray() but then it was messing up. i just dont really know how to add the 'i' point in my sWorld array to say the first position in the new array im going to use for the ones that are grater than size 4.
Any help would be much appreciated!
EDITED TO CLARIFY A BIT
i need the indexes of the the locations that are size > 4, but then i want to know which of those indexes that i get have the greatest size. Maybe i wasnt 100% clear in my op, but basically im trying to find which of the 1000 indexes in the array have the most connections (the longest linked list) make sense?
I want to know the top 10 connected indexes of the array (aka which 10 have the greatest size of linked list)
You can use an ArrayList to store the indexes:
List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++){
if (sWorld[i].length > 4) {
//add i to a list (not an array yet)
indexes.add(i);
}
...
}
// then sort the list
// not necessary, as indexes are inserted in the right order, but if you must...
// Collections.sort(indexes);
// and, if you need an array instead of a list
Integer[] indexesArray = indexes.toArray(new Integer[indexes.size()]);
A List, or an ArrayList, work as variable-length arrays. Though not as efficiently as an actual array.
As seen above, there is no need to sort the array later, but, if you must, you can use Collections.sort().
Also, if you must have an int[] instead of an Integer[], please check: How to convert List<Integer> to int[] in Java?
Update:
As you want to know the size and index of the bigger arrays, it's a whole new problem. Below is a working code that deals with it.
Basically, everytime you find an array with size larger than 4, you add a pair (index, size) to the list. This list is then ordered by size, in descending order.
At the end of the main() method, an array is created (int[] topTenIndexes) which contains the indexes of the 10 biggest arrays (the indexes are presented in descending order of it's array's length). The result is -1 when there weren't enough big (length > 4) arrays.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<ArrayIndexAndSize> indexes = new ArrayList<ArrayIndexAndSize>();
int[][] sWorld = {{1},{2,5,5,5,5},{3,6,6,6,6,6}};
for (int i = 0; i < sWorld.length; i++){
if (sWorld[i].length > 4) {
// add a pair (index, size) to the list
indexes.add(new ArrayIndexAndSize(i, sWorld[i].length));
}
//...
}
// then sort the list by array SIZE, in descending order
Collections.sort(indexes);
// Print it!
System.out.println(indexes);
/* output:
"[[Array index: 2; Array size: 6], [Array index: 1; Array size: 5]]"
*/
// Generating an array with the top ten indexes
int[] topTenIndexes = new int[10];
Arrays.fill(topTenIndexes, -1);
for (int i = 0; i < indexes.size() && i < 10; i++) {
topTenIndexes[i] = indexes.get(i).index;
}
// Print it
System.out.println(Arrays.toString(topTenIndexes));
/* output: [2, 1, -1, -1, -1, -1, -1, -1, -1, -1] */
}
public static class ArrayIndexAndSize implements Comparable<ArrayIndexAndSize> {
public int index;
public int size;
public ArrayIndexAndSize(int index, int size) {
this.index = index;
this.size = size;
}
/* Order by size, DESC */
/* This is called by Collections.sort and defines the order of two elements */
public int compareTo(ArrayIndexAndSize another) {
int thisVal = this.size;
int anotherVal = another.size;
return -(thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
#Override
public String toString() {
return "[Array index: "+index+"; Array size: "+size+"]";
}
}
}
If you have an array LinkedList<?>[] sWorld (fill the type you're using in for ?), then do this:
ArrayList<Integer> listOfLists = new ArrayList<>();
for (int i=0; i<sWorld.size(); i++) {
if (sWorld[i].size > 4) {
listOfLists.add(i);
}
}
Comparator<Integer> sizeComparator = new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return Integer.compare(sWorld[a].size(), sWorld[b].size());
}
}
Collections.sort(listOfLists, sizeComparator);

Categories

Resources