distributing a number among an array in java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Given a number N and an array ? How to distribute N among the array as the following example:
N = 5 and array of size 4;
[5,0,0,0]
[0,5,0,0]
[0,0,5,0]
[0,0,0,5]
[4,1,0,0]
[4,0,1,0]
[4,0,0,1]
[1,4,0,0]
[0,4,1,0]
[0,4,0,1]
[1,0,4,0]
[0,1,4,0]
[0,0,4,1]
.
..
..
[2,1,2,0]
..
..
...
and so on
The important thing is that the sum of whole array is N!
I want to implement a hill climbing algorithm so I want to generate all successors, then hill climbing can choose from the list.

Use recursion or don't if you hate it or have long arrays. You want to fill in arr. You have filled beginning (0..index-1) and you want to fill the end of array with the rest N.
Call (arr has length 5): fill(arr, 5, 0);
private static void fill(int[] arr, int N, int index) {
if (arr == null) {
return;
}
if (N == 0) {
for (; index < arr.length; index++) {
arr[index] = 0;
}
} else if (index == arr.length - 1) {
arr[index] = N;
} else {
for (int j = N; j >= 0; j--) {
arr[index] = j;
fill(arr, N - j, index + 1);
}
}
if (index >= arr.length - 1) {
// use your array
System.out.println(Arrays.toString(arr));
}
}

Related

Why does insertion sort work only if we use while as an inner loop and doesn’t work for ” for loop”? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I was trying to attempt a insertion algorithm question. However, I had the following question.
I wanted to nderstand why most solutions online use a nested while loop instead of a nested for loop? I thought it might have to do something with time complexity, however, both have a O(n^2) complexity.
Below I have attached the two different solutions
public class InsertionSort {
// MY method
/*Function to sort array using insertion sort*/
// void sort(int arr[])
// {
// int n = arr.length;
// for (int i = 1; i < n; ++i) {
// if(arr[i] < arr[i-1]){
// for(int j = 0; j < i; j++){
// if(arr[i] < arr[j]){
// int temp = arr[j];
// arr[j] = arr[i];
// arr[i] = temp;
// }
// }
// }
// }
// }
// Online Solution
void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
Usually, when developing algorithms, you choose a loop based on this:
If the number of iterations is known, use a for-loop.
If the number of iterations is not known, use a while-loop.
In Java, and other languages, you can implement the same thing using both loops. It doesn't matter if the number of iterations is known. However, it makes sense, it's more readable/logical:
... for a known starting value to a known limit do ...
... while a condition is true do ...
In pseudocode, which is a way to describe an algorithm independently of implementation-details, it's often done just like that (or similar):
for i = 0 to n do
...
while condition do
...
When you look at sort, you can see two loops: the outer for-loop and the inner while-loop.
The outer loop is a for-loop because i and n are known. Value n is known because it's given by the size of the array, which is a constant in this algorithm.
The inner loop is a while-loop because it's not known when the condition will fail, as it depends on an array-access. You don't know the values; if you would, then you could sort the array by hardcoding some swaps.

Find longest squential streak in arraylist java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to write a code in java where suppose i have an arraylist of (1,3,4,5,8,9,11,12,13,14,15)
i need the code to analyze the longest streak of consecutive numbers in the arraylist. From the above arraylist 11,12,13,14,15 is the longest streak so the code should give this in the output in form of another arraylist.
the code should be executed on any ArrayList consisting of different numbers
actually, i have made the code where i have come up to the point of extracting index of postive values from a bigger arraylist and stored it in another arraylist. Now, im stuck at finding the longest streak of consecutive numbers in the newly made arraylist.
Here is my code:
List<Integer> mega = new ArrayList<Integer>();
for (int i = 0; i <= data.size() - 1; i++) {
double a = (data.get(i).adjClose) - (data.get(i).open); //calculating a value
if (a > 0) { // if value is bigger than zero, then store the index of that element in a new arraylist
mega.add(i);
}
}
ArrayList<Integer> bigger = new ArrayList<>();
for (int x = 0; x < numbers.size(); x++) {
int current = numbers.get(x);
ArrayList<Integer> temp = new ArrayList<>();
temp.add(current);
for (int y = x + 1; y < numbers.size(); y++) {
int nextValue = numbers.get(y);
if (nextValue == current + 1) {
temp.add(nextValue);
current = nextValue;
}
else {
break;
}
}
if (temp.size() > bigger.size()) {
bigger.clear();
bigger.addAll(temp);
}
}
numbers is the ArraList of your numbers and
Inside bigger is your sequence.

Find palindromes in list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Assume we have a list of integers, for example:
L = [13,13,4,13,4,2]
I want to find the set of all palindromes, where each palindrome is a sub-list of L containing contiguous integers. For the above list that would be:
S = {[13], [4], [2], [13,13], [13,4,13], [4,13,4]}
Because the inverse of L would be L' = [2,4,13,4,13,13], and every element of S appears in L' in the correct order.
How can I find the set of all palindromes in general? My naive approach would be to check if each element of the power set of L appears in L', but this is inefficient and I am sure that there is a better solution.
I think my solution is pretty similar to solution from MC Emperor, but I focused on not creating temporary objects like lists.
I select sub-arrays of given array using left and right indices and check it for palindrome.
public static Set<List<Integer>> findAllPalindromes(int[] arr) {
Set<List<Integer>> res = new LinkedHashSet<>();
for (int length = 1; length < arr.length; length++)
for (int left = 0, right = left + length - 1; right < arr.length; left++, right++)
if (isPalindrome(arr, left, right))
res.add(sublist(arr, left, right));
return res;
}
This method check is given sub-array palindrome or not:
private static boolean isPalindrome(int[] arr, int left, int right) {
for (; left < right; left++, right--)
if (arr[left] != arr[right])
return false;
return true;
}
This method create separate list for given sub-array:
private static List<Integer> sublist(int[] arr, int left, int right) {
List<Integer> res = new ArrayList<>(right - left);
for (; left <= right; left++)
res.add(arr[left]);
return res;
}
You need two steps to do that.
First, you'll need to find all sublists within the list:
List<Integer> input = Arrays.asList(13, 13, 4, 13, 4, 2);
List<List<Integer>> subLists = new ArrayList<>();
for (int subListSize = 1; subListSize < input.size(); subListSize++) {
for (int startIndex = 0; startIndex < input.size() - subListSize + 1; startIndex++) {
List<Integer> subList = input.subList(startIndex, startIndex + subListSize);
subLists.add(subList);
}
}
// Also test the whole list:
subLists.add(input);
Then you need to check for each element if the list is a palindrome. To test if a list is a palindrome, element n must be compared to element listSize - 1 - n.
We only need to check half of the elements.
static boolean isPalindrome(List<Integer> subList) {
for (int i = 0; i < subList.size() / 2; i++) {
if (!Objects.equals(subList.get(i), subList.get(subList.size() - 1 - i))) {
return false;
}
}
return true;
}
If you want to remove duplicates, then you can put the elements into a Set.

Insertion sort array java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So I have to write code for an insertion sort that will sort an array of random ints, the array is already set up and working okay and everything but my sort is not, heres what i have:
for(int i =1; i< numberSort.length-1;i++){
int temp = numberSort[i];
int j = i-1;
while((j >= 0) && (numberSort[j]>temp)){
numberSort[j+1] = numberSort[j];
j = j-1;
}
numberSort[j+1] = temp;
}
}
It seems to me that that should work, however it does not, it moves the numbers around from their original position but does not order them in ascending order. Thanks for any help you may be able to offer.
This code works for me:
public static void main(String[] args) {
int[] numberSort = {22,7,2, 5, 7, 1, 2, 9,33,55,12,1,0};
for (int i = 1; i < numberSort.length; i++) {
int temp = numberSort[i];
int j = i - 1;
while ((j >= 0) && (numberSort[j] > temp)) {
numberSort[j + 1] = numberSort[j];
j = j - 1;
}
numberSort[j + 1] = temp;
}
for (int i = 0; i < numberSort.length; i++) {
System.out.println(numberSort[i]);
}
}
Gives output:
0
1
1
2
2
5
7
7
9
12
22
33
55

Suitable Shuffling algorithm [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
Just checking that this shuffling algorithm is suitable. Or maybe there could be improvements?
public static void shuffleArray(Object[] arr, Random rnd){
int lastIndex = arr.length - 1;
for (int i=0; i<=lastIndex; i++){
int k = rnd.nextInt(lastIndex+1);
Object a = arr[i];
Object b = arr[k];
arr[i] = b;
arr[k] = a;
}
}
Your random number should be chosen in the range i..lastIndex+1 rather than the range 0..lastIndex+1. Google for Fisher-Yates shuffle for an explanation.
You could also save one assignment during the swap by copying directly from one array location to the other without an intermediary: x = arr[i], arr[i] = arr[k], arr[k] = x.
If by suitable you are saying uniformly distributed, then no, it is not. Considering the fact that for each iteration, with each of the possible configurations, you generate N possible next configurations with equal probability. In the end, you have N ^ N equal possibilities, while there's just N! permutations, and the former in the normal case cannot be divided by the latter, thus impossible to be uniformly distributed.
In fact, I think Jeff Attwood has a explanation here:
Coding Horror - The danger of naivete
I need this to shuffle an array of char(s)
You can adapt the shuffle code like this for primitives
public static void shuffle(char[] chars, Random rnd) {
int size = chars.length;
for (int i = size; i > 1; i--) {
int idx = rnd.nextInt(i);
char tmp = chars[idx];
chars[idx] = chars[i-1];
chars[i-1] = tmp;
}
}
You could just do
Collections.shuffle(Arrays.asList(array), random);
Or you could look at this code. It is slightly more efficient to use one temporary variable and reduce the size of the random as you go. See Collections.shuffle for how to do this.
public static void shuffle(List<?> list, Random rnd) {
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i=size; i>1; i--)
swap(list, i-1, rnd.nextInt(i));
} else {
public static void swap(List<?> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
Note: you are doing (lastIndex+1) but lastIndex is arr.length - 1 so really this is just arr.length

Categories

Resources