Initializing an array inside of adding it to an Array List - java

Hi so pretty much what I have been trying to do is create a method that is passed an Array List of Integers and returns an ArrayList of int arrays. I want each array inside of the returned Array List to contain on of the values of passed Array List. here is what I have so far
public static ArrayList<int[]> createPossible(ArrayList<Integer> al)
{
ArrayList<int[]> returned = new ArrayList<int[]>();
for(int i = 0; i < al.size(); i++)
{
returned.add(new int [1]{al.get(i)});
}
return returned;
}
I think that you can see the basic point of what I'm getting at here. Just cant figure out how to properly initialize each new array inside of where I'm adding it to the returned ArrayList

Just use
new int[] {al.get(i)}
The length of the array is useless, since you pass a given number of values inside the curly braces.

This will work similar to what you have described but it uses List<Integer[]> rather than a List<int[]>. If you must have List<int[]> then it could be augmented to suit your needs.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackOverflow {
public static List<Integer[]> createPossible(List<Integer> al) {
List<Integer[]> returned = new ArrayList<Integer[]>();
for (int i = 0; i < al.size(); i++) {
returned.add(al.toArray(new Integer[0]));
}
return returned;
}
public static void main(String[] args) {
List<Integer> al = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
List<Integer[]> result = createPossible(al);
System.out.println(Arrays.deepToString(result.toArray()));
}
}
The output of the code above:
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

Related

How to save the contents of a powerSet into a 2d array in Java

I'm trying to save the contents of a PowerSet, obtained from a 1d Array into a 2d Array. I tried assigning the values in the array inside the "if" Statement but I'm getting the indices completely wrong
int[] set = new int[]{2,4,5,8}
int powSetLength = (int) Math.pow(2,set.length);
int[][] powSet = new int[powSetLength][];
for (int i = 0; i<powSetLength; i++){
for (int j = 0; j<set.length; j++){
if ((i & (1<<j))>0) {
powSet[i] = new int[] //here needs to be the length corresponding to the subset
powSet[i][j] = set[j]; //I know this is wrong but my idea was to assign each number of a subset into the 2d array
}
}
}
Since your inner array is of variable length, you might want to use an inner java.util.ArrayList<Integer> instead. Something like this:
int[] set = new int[]{2,4,5,8};
int powSetLength = (int) Math.pow(2,set.length);
List<Integer>[] powSet = new List[powSetLength];
for (int i = 0; i<powSetLength; i++){
for (int j = 0; j<set.length; j++){
if ((i & (1<<j))>0) {
// If the `i`'th powerSet isn't initialized yet: create an empty ArrayList:
if(powSet[i] == null)
powSet[i] = new ArrayList<>();
// And add the current set-value to the List:
powSet[i].add(set[j]);
}
}
}
System.out.println(Arrays.toString(powSet));
After which your array of Lists will contain the following powerset:
[null, [2], [4], [2, 4], [5], [2, 5], [4, 5], [2, 4, 5], [8], [2, 8], [4, 8], [2, 4, 8], [5, 8], [2, 5, 8], [4, 5, 8], [2, 4, 5, 8]]
Try it online.

How to return the elements in an arraylist that's in an arraylist

static int minValueOfElements(ArrayList<ArrayList<Integer>> input){
// Return the minimum value in the input list of lists (matrix)
return 0;
}
I need to get all the elements that are in the Array List so for example :
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
needs to return 1.
There is one Array List and that contains Array Lists that have elements in them. So I need to find out how to get all those elements.
public Integer getMinimumOfListOfLists(List<List<Integer>> listOfLists) {
List<Integer> mergedList = new ArrayList<>();
//merge all
for(int i=0; i<listOfLists.size(); i++) {
mergedList.addAll(listOfLists.get(i));
}
//sort
Collections.sort(mergedList);
// return first element from sorted list - this will be the smallest element
return mergedList.get(0);
}
This answer is to get the minimum element out of all elements in all lists. not sure from the question what you were looking for exactly.
I am trying to get you means:
I think the first we should flatten the list and then get the max element.
If you are using JDK7, I suggestion use Guava to solve it.
If you are using JDK8 it will very easy.
Here is the example:
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class FlattenCollection {
public static void main(String[] args) {
List<List<Integer>> wrapList = new ArrayList<>();
List<Integer> first = new ArrayList<>();
first.add(1);
first.add(2);
List<Integer> second = new ArrayList<>();
second.add(3);
second.add(4);
wrapList.add(first);
wrapList.add(second);
System.out.println(wrapList);
//JDK7
List<Integer> result1 = Lists.newArrayList(Iterables.concat(wrapList));//flatten list
System.out.println(result1);
Integer max1 = Collections.max(result1);//max element
System.out.println(max1);
//JDK8
List<Integer> result2 = wrapList.stream().flatMap(List::stream).collect(Collectors.toList());//flatten list
System.out.println(result2);
Integer max2 = result2.stream().max((o1, o2) -> o1 - o2).get();//max element
System.out.println(max2);
}
}
Output:
[[1, 2], [3, 4]]
[1, 2, 3, 4]
4
[1, 2, 3, 4]
4

How to generate arrays with some very specific constraints

I want to print 100 int arrays according to some specific constraints.
each array can have a variable length from 2 to 10.
every item in each array must be unique
items in each array are sorted from the lowest to the highest
there are no identical arrays, meaning two arrays having same lenght and same items
At the moment I have this code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
public class prova {
public static void main(String[] args) {
Integer[] elements = new Integer[]{1,2,3,4,5,6,7,8,9,10};
Set<List<Integer>> seenAlready = new HashSet<>();
for (int i = 0; i < 100; i++) {
final Integer[] array = generateRandomArrayFromElements(elements);
Arrays.sort(array);
if (seenAlready.add(Arrays.asList(array)))
System.out.println(Arrays.toString(array));
}
}
private static Integer[] generateRandomArrayFromElements(Integer[] elements) {
int size = ThreadLocalRandom.current().nextInt(1, elements.length) + 1;
Integer[] array = new Integer[size];
ArrayList<Integer> usedIndices = new ArrayList<>(size);
for (int i = 0; i < array.length; i++) {
int randomIndex = getUniqueRandomIndex(usedIndices, size);
usedIndices.add(randomIndex);
array[i] = elements[randomIndex];
}
return array;
}
private static int getUniqueRandomIndex(ArrayList<Integer> usedIndices, int max) {
int randomIndex = ThreadLocalRandom.current().nextInt(0, max);
final boolean contains = usedIndices.contains(randomIndex);
if (contains)
randomIndex = getUniqueRandomIndex(usedIndices, max);
return randomIndex;
}
}
The problem is that it just generates arrays too similar too each other.
They all look the same!
Have a look at one of its possible outputs:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7]
[1, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I'm never getting arrays like:
[3,4,8,9]
[2,3,6,7,8]
Everytime they start with [1,2,3,4] and so on!
I don't get it!
The problem is that You are generating index in range from 0 to array.length.
So if the array size is 2, then Your range is <0,2)
If the array size is 3, then Your range is <0,3)
...
If the array size is 10, then Your range is <0,10)
And in that situation there is no way to generate different results than You showed us.
Spots to fill |Elements to choose from based on range
=======================================
[_,_] |[1,2,................] range <0,2)
[_,_,_] |[1,2,3,..............] range <0,3)
[_,_,_,_] |[1,2,3,4,............] range <0,4)
...
You should invoke it like this int randomIndex = getUniqueRandomIndex(usedIndices, elements.length);
Notice that max changed to elements.length.
1 - Start to generate 100 empty arrays with a variable length from 2 to 10.
2 - Count the total size.
3 - Generate x uniques integers and add them to a Set.
Set<Integer> set = new HashSet<Integer>();
while(set.size()< xxx) {
set.add(generateRandomInteger());
}
Collections.sort(set);
(where xxx is the total array size
4 - add the integers into your arrays.

How do you split an Array List into sublists everytime there is a duplicate value in the Array List

I have the following array list which contains the following
point ids (1,2,3,4,1,8,5,6,8,9,7,9). I am using Java 7
I was wondering how it could be split into sublists i.e the sublists below
(1,2,3,4,1)
(8,5,6,8)
(9,7,9)
I have had problems trying to use a loop within a loop (i.e check each point
from the outer loop with each of the other points in the inner loop) to get
index positions (starPosIndex and endPosIndex) where there are duplicate point ids and ArrayList.sublist(startPosIndex,endPosIndex) to get the correct sublist
int startPos = 0;
int endPos = 0;
for (int j = 0; j < polygonList3.size(); j++){
Point pointToCheck = polygonList3.get(j);
for (int k = 1; k < polygonList3.size(); k++){
Point pointToCheck2 = polygonList3.get(k);
if (pointToCheck.getID() == pointToCheck2.getID()){
startPos = startPos + endPos;
endPos = endPos + k;
//startPos = startPos + endPos;
//for (int startPos = j; startPos < polygonList3.size(); startPos = (startPos) + endPos) {
//endPos = Math.min(startPos + endPos, polygonList3.size());
finalPolygonLists.add(new ArrayList<Point>(polygonList3.subList(startPos, endPos)));//originalPtsSublist2);
//}
}
}
I would solve it in the following manner:
Allocate a HashSet to contain unique values encountered
Allocate a new list for the first sublist
Iterate over the whole list, adding each value to the set. When we encounter a value that is already in the set, we are done with the first sublist, so clear the set, and allocate a new sublist
After iteration, you will have your list of sublists, obtained in O(n) runtime
You can walk along the list, and create slices of the list (using List#subList) as you go. This can be done efficiently, by always checking whether the first element of the current segment of the list appears somewhere else in the list. If it does, you can store this "slice", and continue with the "tail" of the list. If it doesn't, you are finished (and the tail of the list may or may not be part of the result - that's up to you)
Implemented here as an example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListSlicing
{
public static void main(String[] args)
{
runTest(1,2,3,4,1,8,5,6,8,9,7,9);
runTest(1,2,3,4);
runTest(1,1,1,1);
runTest(1,2,1,2,1,2,1,2,1,2,1,2);
runTest();
}
private static void runTest(Integer ... numbers)
{
List<Integer> list = Arrays.asList(numbers);
System.out.println("Input: "+list);
System.out.println("Output: "+slices(list));
}
private static <T> List<List<T>> slices(List<T> input)
{
List<List<T>> slices = new ArrayList<List<T>>();
List<T> current = input;
while (current.size() > 0)
{
T first = current.get(0);
int appearance = current.subList(1, current.size()).indexOf(first);
if (appearance == -1)
{
slices.add(current);
return slices;
}
List<T> slice = current.subList(0, appearance+2);
slices.add(slice);
current = current.subList(appearance+2, current.size());
}
return slices;
}
}
The output is
Input: [1, 2, 3, 4, 1, 8, 5, 6, 8, 9, 7, 9]
Output: [[1, 2, 3, 4, 1], [8, 5, 6, 8], [9, 7, 9]]
Input: [1, 2, 3, 4]
Output: [[1, 2, 3, 4]]
Input: [1, 1, 1, 1]
Output: [[1, 1], [1, 1]]
Input: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
Output: [[1, 2, 1], [2, 1, 2], [1, 2, 1], [2, 1, 2]]
Input: []
Output: []
The following code tracks the last position for each number and as soon as it founds a duplicate, it will create the sublist and clears all previously tracked entries.
List<Integer> list = Arrays.asList( 1,2,3,4,1,8,5,6,8,9,7,9);
List<List<Integer>> sublists = new ArrayList<>();
Map<Integer,Integer> lastPos = new HashMap<>();
for(int i = 0; i < list.size(); i++) {
Integer current = list.get(i);
if(lastPos.containsKey(current)){
sublists.add(list.subList(lastPos.get(current), i+1));
lastPos.clear();
} else {
lastPos.put(current, i);
}
}
System.out.println(sublists);

Sorting 2D Array but keeping column elements together

I have a 2D array with 2 rows and n columns.
I am trying to sort the array using the built in Arrays.sort method, but I am struggling with the comparator. I want to sort the 2D array by the first row, so that the 2nd row elements will remain with the original elements they were aligned with ie. keep the columns together.
For example original array:
int[] unsortedArray = new int[][]{
{ 6, 3, 1, 2, 3, 0},
{ 2, 1, 6, 6, 2, 4},
sorted array:
int[] unsortedArray = new int[][]{
{ 0, 1, 2, 3, 3, 6},
{ 4, 6, 6, 1, 2, 2},
What is the best way to go about doing this?
Cheers.
Here is an alternative way of keeping your columns aligned. This uses a simple class to hold both column elements.
class TwoInts {
public final int aElement;
public final int bElement;
public TwoInts(int a_element, int b_element) {
aElement = a_element;
bElement = b_element;
}
}
One by one, each column (from sub-array one and two) are placed in this object, and immediately put into a Map<Integer,List<TwoInts>>. The key is the element from intArrayArray[0], and the value is a list of TwoInts, because there may be (and in your example code, are) duplicate values in intArrayArray[0].
You then iterate through the map's key-set, and replace them into the array.
Full code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
<P>{#code java SortOneArrayKeepSecondArrayElementsAligned}</P>
**/
public class SortOneArrayKeepSecondArrayElementsAligned {
public static final void main(String[] ignored) {
int[][] intArrayArray = new int[][]{
{ 6, 3, 1, 2, 3, 0},
{ 2, 1, 6, 6, 2, 4}};
output2DArray("Unsorted", intArrayArray);
Map<Integer,List<TwoInts>> twoIntMap = new TreeMap<Integer,List<TwoInts>>();
for(int i = 0; i < intArrayArray[0].length; i++) {
int intIn0 = intArrayArray[0][i];
if(!twoIntMap.containsKey(intIn0)) {
List<TwoInts> twoIntList = new ArrayList<TwoInts>(intArrayArray.length);
twoIntList.add(new TwoInts(intArrayArray[0][i], intArrayArray[1][i]));
twoIntMap.put(intIn0, twoIntList);
} else {
twoIntMap.get(intIn0).add(new TwoInts(intArrayArray[0][i], intArrayArray[1][i]));
}
}
int idx = 0;
Iterator<Integer> itr2i = twoIntMap.keySet().iterator();
while(itr2i.hasNext()) {
List<TwoInts> twoIntList = twoIntMap.get(itr2i.next());
for(TwoInts twoi : twoIntList) {
intArrayArray[0][idx] = twoi.aElement;
intArrayArray[1][idx++] = twoi.bElement;
}
}
output2DArray("Sorted", intArrayArray);
}
private static final void output2DArray(String description, int[][] twoD_array) {
System.out.println(description + ":");
System.out.println("0: " + Arrays.toString(twoD_array[0]));
System.out.println("1: " + Arrays.toString(twoD_array[1]));
System.out.println();
}
}
class TwoInts {
public final int aElement;
public final int bElement;
public TwoInts(int a_element, int b_element) {
aElement = a_element;
bElement = b_element;
}
}
Output:
[C:\java_code\]java SortOneArrayKeepSecondArrayElementsAligned
Unsorted:
0: [6, 3, 1, 2, 3, 0]
1: [2, 1, 6, 6, 2, 4]
Sorted:
0: [0, 1, 2, 3, 3, 6]
1: [4, 6, 6, 1, 2, 2]
Try the following:
Disclaimer: Not tested :)
myarray = new int[10][2];
// populate the array here
Arrays.sort(myarray, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else {
return 0;
}
}
};
You will have to write a custom sort. Look into Comparable and Comparator.
Something along the lines of:
public class MyComparator implements Comparator<T[]> {
int columnToSortOn;
public MyComparator(int columnToSortOn) {
this.columnToSortOn = columnToSortOn;
}
#Override
public int compare(T[] array1, T[] array2) {
return array1[columnToSortOn].compareTo(array2[columnToSortOn]);
}
}

Categories