Move non repeating numbers from 2 arrays in new array - java

I want the numbers in the first array that do not repeat with the numbers in the second array to go to the third array
This is what I have done till now and it doesn`t work...please help
for(int i = 0; i < isir.length; i++)
{
for(int j = 0 ; j < isir2.length; j++)
{
if(isir[i] != isir[j])
{
for(int k = 0; k < sirdif1.length; k++)
{
sirdif1[k] = isir[i];
}
}
}
}
I am entering the numbers from console with Scanner function...

With using lists and steams:
Integer a1[] = {1,2,5,6,8};
Integer a2[] = {1,3,5,7,8};
List<Integer> result = new ArrayList<>();
// Add elements from first array which ist not in the second
Arrays.stream(a1).filter(_a -> !Arrays.asList(a2).contains(_a)).forEach(result::add);
// Add elements from second array which ist not in the first
Arrays.stream(a2).filter(_a -> !Arrays.asList(a1).contains(_a)).forEach(result::add);
result.forEach(System.out::println);
Output will be:
2
6
3
7

I'd probably use Sets for clarity.
public void test() {
Integer[] a1 = {1,2,3,4,5};
Integer[] a2 = {2,3,4};
// Treat them as Sets.
Set<Integer> s1 = new HashSet<>(Arrays.asList(a1));
Set<Integer> s2 = new HashSet<>(Arrays.asList(a2));
// Get the union of both.
Set<Integer> all = new HashSet<>(s1);
all.addAll(s2);
// Find the repeating ones.
Set<Integer> common = new HashSet<>(s1);
common.retainAll(s2);
// Non-repeating is.
Set<Integer> nonRepeats = new HashSet<>(all);
nonRepeats.removeAll(common);
System.out.println(nonRepeats);
}

I would suggest good naming conventions first..variables like sirdif1(i cant even imagine how this name was decided..) really make it hard for others to read/help
int a1[] ; // Initialize array1
int a2[] ; // Initialize array2
List<Integer> tempList = new ArrayList<Integer>();
for(int i = 0; i < a2.length; i++)
{
boolean found = false; // To be able to track if the int was found in both arrays
for(int j = 0; j < a1.length; j++)
{
if(a1[j].equals(a2[i]))
{
found = true;
break; // If it exist in both arrays there is no need to look further
}
}
if(!found ) // If the same is not found in both..
tempList.add(a2[i]); // .. add to temporary list
}

//Temporary array to combine both arrays;
int[] merged= new int[isir1.length + isir1.length];
//Copy isir1 into new temporary "merged" array;
System.arraycopy(isir1, 0, merged, 0, isir1.length);
//Copy isir2 into new temporary "merged" array;
System.arraycopy(isir2, 0, merged, isir1.length, isir2.length);
//Get the unique values of array "merged" and assign them to new array;
int[] sirdif1= IntStream.of(merged).distinct().toArray();

Related

Changing 2D ArrayList code to 2D array code

I found this code online and it works well to permute through the given array and return all possible combinations of the numbers given. Does anyone know how to change this code to incorporate a 2D array instead?
public static ArrayList<ArrayList<Integer>> permute(int[] numbers) {
ArrayList<ArrayList<Integer>> permutations = new ArrayList<ArrayList<Integer>>();
permutations.add(new ArrayList<Integer>());
for ( int i = 0; i < numbers.length; i++ ) {
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for ( ArrayList<Integer> p : permutations ) {
for ( int j = 0, n = p.size() + 1; j < n; j++ ) {
ArrayList<Integer> temp = new ArrayList<Integer>(p);
temp.add(j, numbers[i]);
current.add(temp);
}
}
permutations = new ArrayList<ArrayList<Integer>>(current);
}
return permutations;
}
This is what I have attempted:
public static int[][] permute(int[] numbers){
int[][] permutations = new int[24][4];
permutations[0] = new int[4];
for ( int i = 0; i < numbers.length; i++ ) {
int[][] current = new int[24][4];
for ( int[] permutation : permutations ) {
for ( int j = 0; j < permutation.length; j++ ) {
permutation[j] = numbers[i];
int[] temp = new int[4];
current[i] = temp;
}
}
permutations = current;
}
return permutations;
}
However this returns all zeroes. I chose 24 and 4 because that is the size of the 2D array that I need.
Thanks
It’s not really that easy. The original code exploits the more dynamic behaviour of ArrayList, so a bit of hand coding will be necessary. There are many correct thoughts in your code. I tried to write an explanation of the issues I saw, but it became too long, so I decided to modify your code instead.
The original temp.add(j, numbers[i]); is the hardest part to do with arrays since it invloves pushing the elements to the right of position j one position to the right. In my version I create a temp array just once in the middle loop and shuffle one element at a time in the innermost loop.
public static int[][] permute(int[] numbers) {
// Follow the original here and create an array of just 1 array of length 0
int[][] permutations = new int[1][0];
for (int i = 0; i < numbers.length; i++) {
// insert numbers[i] into each possible position in each array already in permutations.
// create array with enough room: when before we had permutations.length arrays, we will now need:
int[][] current = new int[(permutations[0].length + 1) * permutations.length][];
int count = 0; // number of new permutations in current
for (int[] permutation : permutations) {
// insert numbers[i] into each of the permutation.length + 1 possible positions of permutation.
// to avoid too much shuffling, create a temp array
// and use it for all new permutations made from permutation.
int[] temp = Arrays.copyOf(permutation, permutation.length + 1);
for (int j = permutation.length; j > 0; j--) {
temp[j] = numbers[i];
// remember to make a copy of the temp array
current[count] = temp.clone();
count++;
// move element to make room for numbers[i] at next position to the left
temp[j] = temp[j - 1];
}
temp[0] = numbers[i];
current[count] = temp.clone();
count++;
}
assert count == current.length : "" + count + " != " + current.length;
permutations = current;
}
return permutations;
}
My trick with the temp array means I don’t get the permutations in the same order as in the origianl code. If this is a requirement, you may copy permutation into temp starting at index 1 and shuffle the opposite way in the loop. System.arraycopy() may do the initial copying.
The problem here is that you really need to implement properly the array version of the ArrayList.add(int,value) command. Which is to say you do an System.arraycopy() and push all the values after j, down one and then insert the value at j. You currently set the value. But, that overwrites the value of permutation[j], which should actually have been moved to permutations[j+1] already.
So where you do:
permutation[j] = numbers[i];
It should be:
System.arraycopy(permutation,j, permutations, j+1, permutations.length -j);
permutation[j] = numbers[i];
As the ArrayList.add(int,value) does that. You basically wrongly implemented it as .set().
Though personally I would scrap the code and go with something to dynamically make those values on the fly. A few more values and you're talking something prohibitive with regard to memory. It isn't hard to find the nth index of a permutation. Even without allocating any memory at all. (though you need a copy of the array if you're going to fiddle with such things without incurring oddities).
public static int[] permute(int[] values, long index) {
int[] returnvalues = Arrays.copyOf(values,values.length);
if (permutation(returnvalues, index)) return returnvalues;
else return null;
}
public static boolean permutation(int[] values, long index) {
return permutation(values, values.length, index);
}
private static boolean permutation(int[] values, int n, long index) {
if ((index == 0) || (n == 0)) return (index == 0);
int v = n-(int)(index % n);
int temp = values[n];
values[n] = values[v];
values[v] = temp;
return permutation(values,n-1,index/n);
}

How can you form unique sets of integers by combining integer arrays with variable sizes in Java?

I have any amount of arrays of integers like:
[1,9]
[5]
[7]
And I want to combine them in such a way that I get sets of numbers like:
[1,5,7]
[9,5,7]
Another Example INPUT:
[1,9]
[3,5]
[7]
[10]
OUTPUT:
[1,3,7,10]
[9,3,7,10]
[1,5,7,10]
[9,5,7,10]
I have tried nesting "for" loops but I always seem to get lost and can't get the right iterators I need to pull the right numbers when building the final array. There can be any number of integers in each array, and any number of arrays.
I have tried something like this, but it seems like a deadend:
int[][] allIndexes = {{1, 9},{5},{7}};
List<Integer> dataset1 = new ArrayList<Integer>();
//int[] dataset2 = {};
int i = 0;
for (int[] indexSet : allIndexes){
if(indexSet.length > i){
dataset1.add(indexSet[i]);
}else{
dataset1.add(indexSet[0]);
}
i++;
}
System.out.println(dataset1.toString());
//System.out.println(dataset2);
Any help would be greatly appreciated. I tried searching for others, but I really am not sure if I am defining this correctly.
You need a variable number of nested loops to enumerate all cases. Thus, recursion is your friend here. The code below will do what you're asking.
public static void main(String[] args)
{
int[][] allIndexes = {{1, 9},{3,5},{7},{10}};
List<Integer> dataset1;
if( allIndexes.length > 0)
{
int[] firstIndexes = allIndexes[0];
for( int i = 0; i < firstIndexes.length; i++)
{
dataset1 = new ArrayList<Integer>();
dataset1.add( firstIndexes[i]);
foo( dataset1, allIndexes, 1);
}
}
}
public static void foo( List<Integer> dataset1, int[][] allIndexes, int index)
{
if( index < allIndexes.length)
{
int[] indexes = allIndexes[index];
for( int i = 0; i < indexes.length; i++)
{
List<Integer> dataset = new ArrayList<Integer>();
for( Integer integer : dataset1)
dataset.add( integer);
dataset.add( indexes[i]);
foo( dataset, allIndexes, index+1);
}
}
else
{
StringBuilder sb = new StringBuilder();
sb.append( "[");
for( int i = 0; i < dataset1.size() - 1; i++)
sb.append( dataset1.get( i) + ",");
sb.append( dataset1.get( dataset1.size()-1));
sb.append( "]");
System.out.println( sb.toString());
}
}
Edit seems uoyilmaz was faster with his answer
Edit2 fixed a typo
I think a recursive approach might be worth a try.
You have your first input array and all following input arrays.
You want to get all combinations of your following input arrays and combine each of them with every element from your first input array
[1,9] // first input array
[5] // following input arrays
[7] // following input arrays
.
void GetCombinations(int[][] arrays, int startIndex, LinkedList<LinkedList<Integer>> outLists) {
// startIndex to high
if (startIndex >= arrays.length) return;
int[] firstArray = arrays[startIndex]
LinkedList<LinkedList<Integer>> subLists = new LinkedList<LinkedList<Integer>>();
// get sub-results
GetCombinations(arrays, startIndex + 1, subLists);
// combine with firstArray
if (subLists.size() == 0) {
subLists.add(new LinkedList<Integer>());
}
for (int i = 0; i < subLists.size(); ++i) {
for (int j = 0; j < firstArray.length; ++j) {
LinkedList<Integer> temp = new LinkedList<Integer>(subLists.get(i));
temp.addFirst(firstArray[j]);
outLists.add(temp);
}
}
}
You then call the function with
int[][] yourInputArrays = { ... };
LinkedList<LinkedList<Integer>> outputLists = new LinkedList<LinkedList<Integer>>();
GetCombinations(yourInputArrays, 0, outputLists);
If you are new to programming, the recursive approach might not be intuitive at first, but it is definitely worth looking into it.

How to convert double[] to List<double[]> in Java?

I have a Double[] array that contains about 400k double values. I want to create a List<Double[3]> array out of it.
For example: we have a list of doubles [0.00332, 1.23112, 0.241321, 2.0001 ...]
We need to transform it into another structure like: [[0.00332, 1.23112, 0.241321], [2.0001, ..., ...], [...]]
I tried to come up with something but eventually understood that I have no idea how to do this in Java in more or less concise way. Can somebody help me?
public List<double[]> toListTuple(double [] array){
List<double []> ret = new ArrayList<double[]>() ;
double [] sublist = null;
for(int i = 0;i<array.length;i++){
if(sublist == null)
sublist = new double[3];
sublist[i%3] = array[i];
if(i%3==2) {
ret.add(sublist);
sublist = null;
}
}
if(sublist!=null){
ret.add(sublist); // This means some of the last elements weren't initialized
}
return ret;
}
double[] source = getValues();
List<Double[]> dest = new List<Double[]>;
for (int i = 0; i < source.length; i += 3)
{
dest.add(new double[] {source[i], source[i + 1], source[i + 2]});
}
If you can guarantee that 3 | source.length .
There's various methods, this one will pad the last element in the array with zeroes if the original length isn't divisible by 3
List<double[]> list = new ArrayList<double[]>();
for (int i=0; i<original.length; i+=3) {
list.add( Arrays.copyOfRange(original, i, i+3) );
}
Maybe something like this:
// Create a new list (in this example, an ArrayList) to hold the values
ArrayList<double[]> myList = new ArrayList<double[]>();
// Create a temporary subArray to hold the entries you'll store
// on each entry of the list
double[] subArray;
// Traverse your original array (in this example: "myOriginalArray"
for(int i = 0; i < myOriginalArray.length; i++) {
// If the entry of the original array is the first of each three,
// initialize the temporary array
if(i % 3 == 0)
subArray = new double[3];
// Store the entry of the original array in the temp array
subArray[i % 3] = myOriginalArray[i];
// If the entry you've just stored is the last of each three
// OR if the entry of the original array is the last one,
// add the temporary array to your list
if(i % 3 == 2 || i == myOriginalArray.length - 1)
myList.add(subArray);
}
You may try Google Guava:
Double[] doubles = {3.0, 9.1, -1.1, 0.5};
List<List<Double>> doubleLists = Lists.partition(Arrays.asList(doubles), 3);
This will get you [[3.0, 9.1, -1.1], [0.5]]
I think something like this should do it:
double[] values = ....
List<double[]> list = new ArrayList<>();
for(int i = 0; i < values.length; i += 3) {
double[] d = new double[3];
d[0] = values[i];
d[1] = values[i+1];
d[2] = values[i+2];
list.add(d);
}
public static void main(String [] args){
double[] doubleArray = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
ArrayList<double[]> doublelist = new ArrayList<double[]>();
double[] innerArray = {};
for(int i=0; i<doubleArray.length; i++){
if(i%3 == 0){
innerArray = new double[3];
}
innerArray[i%3] = doubleArray[i];
if(i%3 == 2 || i == doubleArray.length-1){
doublelist.add(innerArray);
}
}
}

Substitution in an Array List

I have to list out 10 unique numbers between 1 and 20, but before storing the numbers, the program should check whether the number is in the list or not. If the number is already in the list, it should generate a new number. Also, the amount of numbers replaced must be counted.
This is what I have so far:
public static void main(String[] args)
{
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
System.out.print("List: ");
for(int w = 0; w < arrayA.length; w++)
{
System.out.print(arrayA[w] + " ");
}
}
As you can see, there are two "3"s on the list, I have to output the same list but change one of the "3"s. Plus it has to be counted.
This is not hard to do, but what do you mean by change one of the threes?
You can add a boolean flag outside of your for loop that can tell if you've encountered a 3 or not and what the index of that 3 is.
Try something like this:
boolean changedThree = false;
int threeIndex = -1;
for(int i = 0; i < arrayA.length; i++){
if(arrayA[i] == 3 && !changedThree){
arrayA[i] = 4;
threeIndex = i;
changedThree = true;
}
System.out.println(arrayA[i] + " ");
}
I don't know for sure if that captures the information you need, but hopefully can give you a push in the right direction. Let me know if you have questions.
EDIT
To avoid any duplicate values, I recommend you create an array list, and add the unique values to it. Then, you can use the ArrayList.contains() method to see if a value exists already. So, I would recommend changing your code to this:
ArrayList<int> usedCharacters = new ArrayList<int>();
int changedCounter = 0;
Random rand = new Random();
for(int i = 0; i < arrayA.length; i++){
if(!usedCharacters.contains(arrayA[i])){ // If we haven't used this number yet
usedCharacters.add(arrayA[i]);
} else{
// Generate a new number - make sure we aren't creating a duplicate
int temp = rand.nextInt(20) + 1;
while(usedCharacters.contains(temp)){
temp = rand.nextInt(20) + 1;
}
// Assign new variable, increment counter
arrayA[i] = temp;
changedCounter++;
}
}
If you're not familiar with the random.nextInt() method, read this.
so if I understand you correctly you have to save the arrayA, right?
If that is the case, you can just make a new array, targetArray where you can save to numbers to, and then check using a for-loop if you already added it, and if so you can generate a new, random number.
The result would look something like this:
public static void main(String[] args) {
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
int[] targetArray = new int[10];
int numbersReplaced = 0;
System.out.print("List: ");
for (int i = 0; i < arrayA.length; i++) {
for (int j = 0; j < targetArray.length; j++) {
if (arrayA[i] == targetArray[j]) {
targetArray[j] = (int)(Math.random() * 100);
numbersReplaced++;
} else {
targetArray[j] = arrayA[i];
}
}
}
System.out.println("Numbers replaced: " + numbersReplaced);
}
Hope that helped
You could use recursion to achieve your result.
This will keep looping until all values are unique
private void removeDoubles(int[] arr) {
for(int i = 0; i < arr.length; i++)
{
// iterate over the same list
for(int j = 0; j < arr.length; j++) {
// Now if both indexes are different, but the values are the same, you generate a new random and repeat the process
if(j != i && arr[i] == arr[j]) {
// Generate new random
arr[j] = random.nextInt(20);
// Repeat
removeDoubles(arr);
}
}
}
}
Note: This is the sort of question I prefer to give guidance answers rather than just paste in code.
You could walk the array backward looking at the preceding sublist. If it contain the current number you replace with a new one.
Get the sublist with something like Arrays.asList(array).subList(0, i) and then use .contains().
You logic for finding what number to add depends on lots of stuff, but at it simplest, you might need to walk the array once first to find the "available" numbers--and store them in a new list. Pull a new number from that list each time you need to replace.
EDIT: As suggested in the comments you can make use of Java Set here as well. See the Set docs.

Iteratively reading specific elements within an ArrayList

I am trying to read specific elements within lines of an ArrayList. For example, an array list called Combinations of size 3 with the following lines is being produced by my code:
Combinations =
[0, 1]
[0, 2]
[1, 2]
I would like to create a loop that will read each line of the array, each element of that line, and add strings to a new array depending on the values of that array line. What should I use in order to accomplish the following pseudocode in java?
Pseudocode would be as follows
For (int i = 0; i < Combinations.size(); i++)
If Combinations(Line i, First Element) = "0"
Then NewArray(i).add("Vial1,")
If Combinations(Line i, First Element) = "1"
Then NewArray(i).add("Vial2,")
If Combinations(Line i, First Element) = "2"
Then NewArray(i).add("Vial3,")
If Combinations(Line i, Second Element)= "0"
Then NewArray(i).add(+"Vial1")
If Combinations(Line i, Second Element)= "1"
Then NewArray(i).add(+"Vial2")
If Combinations(Line i, Second Element)= "2"
Then NewArray(i).add(+"Vial3")
The resulting ArrayList would then be:
NewArray =
[Vial1,Vial2]
[Vial1,Vial3]
[Vial2,Vial3]
Below is the code which I am using to generate my Arraylist
import java.util.*;
import org.apache.commons.math3.util.CombinatoricsUtils;
public class Combinations1 {
public static void main (String[] args){
ArrayList<Integer[]> combinations = new ArrayList();
Iterator<int[]> iter = CombinatoricsUtils.combinationsIterator(3, 2);
while (iter.hasNext()) {
int[] resultint = iter.next();
Integer[] resultInteger = new Integer[2];
for (int i = 0; i < 2; i++) {
resultInteger[i] = Integer.valueOf(resultint[i]);
}
combinations.add(resultInteger);
}
for (int i = 0; i < combinations.size(); i++) {
System.out.println(Arrays.deepToString(combinations.get(i)));
}}}
Your pseudocode is a bit of a mess. You seem to be wanting to turn what is currently an array of Integers into an array of Strings.
I think you want something like this:
ArrayList<String[]> NewArray = new ArrayList<String[]>();
for (Integer[] combination : combinations) {
String[] newCombination = new String[2];
if (combination[0].intValue() == 0) {
newCombination[0] = "Vial1";
}
... etc for other possible values
if (combination[1].intValue() == 0) {
newCombination[1] = "Vial1";
}
.. etc for other values
NewArray.add(newCombination);
}
Of course if your rule is exactly 0 -> Vial1, 1 -> Vial2 etc, you don't need to handle each case separately, but instead:
newCombination[0] = "Vial" + (combination[0].intValue() + 1);
and the same for the second element. If the rule is the same for both you could just iterate over the elements of the array too. Hopefully you can figure that out for yourself.
Do you mean something like this?
String[][] newArray = new String[combinations.size()][2];
for (int i = 0; i < combinations.size(); i++) {
Integer[] eachArray = combinations.get(i);
for (int j = 0; j < eachArray.length; j++){
int elem = eachArray[j];
if (elem==0 || elem==1 || elem==2){
newArray[i][j]="Vial"+(elem+1);
}
}
}

Categories

Resources