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()));
}
Related
I am pretty new in this world, and I must say sometimes things that looks easy are pretty harsh.
I am stuck with a task that entails dealing with an array and for-loops.
I should iterate over the array and for every iteration step print a different random string. My current code is not working correctly, the only thing I'm getting a random item and the same index printed multiple times.
My output right now:
relax
2
2
2
2
How can I fix that and get a correct randomized output?
My code:
public static void main(String[] args) {
int i;
String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
java.util.Random randomGenerator = new java.util.Random();
int x = Cofee.length;
int y = randomGenerator.nextInt(x);
String frase = Cofee[y] ;
System.out.println(frase);
for(i = 0; i < Cofee.length; i++)
System.out.println(y);
}
You assign a value to y once, and you print y repeatedly. The value of y doesn't change. To do that, you would need to call randomGenerator.nextInt(x) for each iteration of the loop!
However, if you want to randomize and print the array, use:
public static void main(String[] args)
{
String[] coffee = {"pick it","drink it","relax","put it in a cup",};
// this wraps the array,
// so modifications to the list are also applied to the array
List<String> coffeeList = Arrays.asList(coffee);
Collections.shuffle(coffeeList);
for(String value : coffee)
System.out.println(value);
}
As an aside, don't use String coffee[], but use String[] coffee. Although Java allows putting the array type after the variable name, it is considered bad form.
Or use a list directly:
public static void main(String[] args)
{
List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
Collections.shuffle(coffeeList);
for(String value : coffeeList)
System.out.println(value);
}
For that, you can implement a shuffling algorithm.
It's not so scaring as it might sound at first. One of the famous classic shuffling algorithms, Fisher–Yates shuffle is relatively easy to grasp.
The core idea: iterate over the given array from 0 to the very last index, and for each index swap the element that corresponds to the randomly generated index between 0 and the current index (i) with the element under the current index.
Also, I would advise creating a separate array representing indices and shuffle it in order to preserve the array of string its initial state (you can omit this part and change the code accordingly if you don't need this).
That's how it might be implemented:
public static final Random RANDOM = new Random(); // we need an instance for random to generate indices
A Fisher–Yates shuffle implementation:
public static void shuffle(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
swap(arr, i, j); // swapping elements `i` and `j`
}
}
Helper-method for swapping elements:
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Usage-example:
String[] coffee = {"pick it","drink it","relax","put it in a cup"};
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
shuffle(indices);
for (int i = 0; i < coffee.length; i++) {
String next = coffee[indices[i]];
System.out.println(next);
}
Output:
drink it
pick it
put it in a cup
relax
I am trying to get pass a coding challenge. The goal is to remove duplicate (after a defined 'n-th' time) from the array.
For example,
int[] arr;
arr = new int[] {1, 2, 2, 3, 3, 3, 4, 5, 5};
arr = tester(arr,1);//return 1,4. anything having more then 1 occurrence is removed from the //array
I have 2 questions here.
I understand that although java is mainly call by value,
more detail: https://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java#:~:text=Longer%20answer%3A,object%20that%20the%20caller%20sees.
and
Is Java "pass-by-reference" or "pass-by-value"?
.
so am I not able to modify/return the value of arr without re-assigning it as I need to use the "new" keyword later on.
example:
I am not able to do the following:
tester(arr,1) //return the original value, as the method has a "new" when converting the
//arraylist into array. There seems to be no work around for this as well..
I am also only passing 2 out of 10 test case in the coding challenge, I am not very sure why. I have also attempted to error handle with string inputs, or length=0 or null, to no success. (or implemented it in hashmap for sake of time complexity)
It does not seem like my logic has an issue, I am just not sure what are the test case as it is hidden.
I believe part of the challenge requires me to return it in the original array, meaning changing the value of arr itself, but i cant find a way to do it without using the new keyword.
Any ideas anyone?
public static int[] tester(int[] data, int n)
{
ArrayList<Integer> storeNon_dup = new ArrayList<Integer>();
//nested for loop to run through the array
//store in arrayList if criteria valid
for(int i = 0; i < data.length; i++)
{
int counter = 0;
for(int j = 0; j< data.length; j++)
{
if(data[i] == data[j])
{
counter++;
}
}
//if not duplicate in n-th occurence, add to list
if(counter<=n)
{
storeNon_dup.add(data[i]);
}
}
//convert arraylist to array
int[] container = new int[storeNon_dup.size()];
for(int i = 0; i<storeNon_dup.size(); i++)
{
container[i] = storeNon_dup.get(i);
}
return container;
}
Alternate solution by using HashMap.
public static List tester(int[] data, int n) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<data.length; i++) {
if(map.containsKey(data[i])) {
map.put(data[i], map.get(data[i])+1);
}else {
map.put(data[i], 1);
}
}
List lst = new ArrayList<Integer>();
for(Integer key : map.keySet()) {
if(map.get(key)<=n) {
lst.add(key);
}
}
return lst;
}
I have a problem comparing the numbers inside a list so that it does not repeat using Random. I wanted the numbers to be random, but only those that are not on the list can be added.
Here is my code:
private void addToListNumber() {
int randomPosition = new Random().nextInt(5);
int maxPosition = 5;
if (list.size() < 1) {
list.add(1);
addToListNumber();
} else if (list.size() < maxPosition) {
for (Integer integer : list) {
if (integer == randomPosition) {
addToListNumber();
}
}
list.add(randomPosition);
addToListNumber();
} else {
for (Integer integer : list) {
System.out.println(integer);
}
}
}
The numbers are repeated.
If I understand correctly your question, you're trying to build a list of 5 integers, in a random order.
A simple way to get there is to generate a list of ordered numbers and then randomly swap them.
First create your list of ordered numbers.
public List<Integer> createOrderedList(int size) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(i);
}
return list;
}
Then create a method that swaps two elements in the list, given their indexes.
public void swap(List<Integer> list, int i, int j) {
Integer hold = list.get(i);
list.set(i, list.get(j));
list.set(j, hold);
}
Last, create a method that mixes all of them.
public void mix(List<Integer> list) {
Random random = new Random();
for (int i = 0; i < list.size(); i++) {
swap(list, i, random.nextInt(list.size()));
}
}
Call the methods in this order:
List<Integer> list = createOrderedList(5);
mix(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
This is happening because of the recursive call addToListNumber(). To make it simple and short let me assume maxPosition = 3
At first you add 1 to the list. Then suppose randomPosition = 2 and you add 2 to the list and call addToListNumber(). Now suppose randomPosition = 1, then you call addToListNumber() again on comparing integer == randomPosition (you have compared only the first element here and it matched)
Now let randomPosition = 3 and 3 be inserted. Since, this is a recursive call, on returning to addToListNumber() which was invoked for randomPosition = 1 (in the previous case), the list is not over (the list has {1,2,3}) here and only the first element has been compared. At the end of the loop it inserts 1 again and your list becomes {1,2,3,1} hence duplicates.
public class AccumulatedData {
public static void main(String args[]) {
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(145.0);
weights.add(146.5);
weights.add(146.5);
weights.add(147.0);
weights.add(146.0);
weights.add(148.0);
weights.add(148.5);
ArrayList<Double> printWeightChanges = getWeightChanges(weights);
System.out.println(weights);
}
public static ArrayList<Double> getWeightChanges(ArrayList<Double> weights) {
for (int i = 0; i < weights.size() - 1; i++) {
weights.set(i, (weights.get(i + 1) - weights.get(i)));
}
return weights;
}
}
I have attempted above to traverse all the elements of the array list and print out their respective consecutive differences (Taking index one of the array list and subtracting index zero) however, my for loop seems to traverse all elements printing their respective differences but then adds the last number of my initial array to the end of my new array list with all of the differences. How do I fix this?
ublic class PartA {
public static void main(String args[]) {
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(145.0);
weights.add(146.5);
weights.add(146.5);
weights.add(147.0);
weights.add(146.0);
weights.add(148.0);
weights.add(148.5);
ArrayList<Double> printWeightChanges = getWeightChanges(weights);
NEW ATTEMPT:
}
/**
* Part a
*/
public static ArrayList<Double> getWeightChanges(ArrayList<Double> weights) {
ArrayList<Double> weightDifferences = new ArrayList <Double>();
for (int i = 0; i < weights.size() - 1; i++) {
weightDifferences.add(i, weights.get(i + 1) - weights.get(i));
}
System.out.println(weightDifferences);
return weightDifferences;
}
}
This generates all sorts of errors :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 145 out of bounds for length 6
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:458)
at PartB.getWeights(PartB.java:37)
at PartB.main(PartB.java:25)
My attempt
Code output from my attempt
It's because of how you defined your loop limits:
for (int i = 0; i < weights.size() - 1; i++)
The loop changes one less element, than there is in an array (i < weights.size() - 1).
I would suggest creating another list for differences, something like this:
public static List<Double> getWeightChanges(ArrayList<Double> weights) {
List<Double> diffs = new ArrayList<>();
for (int i = 0; i < weights.size() - 1; i++) {
diffs.add(weights.get(i + 1) - weights.get(i));
}
return diffs;
}
What you're trying to output will be a different length (specifically, one data point less) than your original list. You either need to remove() the last element of your list, or create a new list to output with a different size.
Since your original list contains 7 doubles, and you changed the first 6, the last element of the list stays the same.
I have an algorithm to count each permutation of an int array. In this case - when I want to print these permutations - everything worked fine. But if I want to save the arrays to the arraylist, it saved the correct number of them, but it saved only the one same option. I know that the problem will be trivial, but I can't solve it. Thanks for your help.
I add to the method printArray, that it saved the printed Array to Arraylist afterwards.
Output of printArray is correct, but output of printList is like this:
1 2 3 4 5 6
(and this input is printed n!, which is correct but its only one permutation)
Here is my code:
public class Permute {
ArrayList<int[]> list;
public Permute() {
list=new ArrayList<>();
}
void printArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
list.add(a);
}
void printList(){
for(int[] arr:list){
for(int item:arr){
System.out.print(item+" ");
}
System.out.println("");
}
}
void permute(int[] a, int k) {
if (k == a.length)
printArray(a);
else {
for (int i = k; i < a.length; i++) {
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
public static void main(String[] args) {
Permute p = new Permute();
int a[] = {1, 2, 3, 4, 5, 6};
p.permute(a, 0);
p.printList();
}
}
You are using the same array over and over again. You rearrange the items inside it.
It's fine when you print it. But when you come to save it in a list, what gets saved is the array reference, not the array contents.
So you enter a reference to the same object n! times into the the list. At the end of the operation, all those references still refer to the same object - and printing the list will print that same array again and again, with the most recent contents it has.
If you want to save the different contents each time, you'll need to make a copy of the array, and save that copy.
So, for example, you can use
list.add( Arrays.copyOf(a, a.length) );