Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
Whenever I run this program it always showing the first element.
Given an array arr[] and an integer K where K is smaller than size of
array, the task is to find the Kth smallest element in the given
array. It is given that all array elements are distinct.
import java.util.PriorityQueue;
public class priorityQueue {
public static int kthSmallest(int[] arr, int l, int r, int k){
PriorityQueue<Integer> mh = new PriorityQueue<>();
int length = r;
for(int i=0; i<k;i++){
mh.add(arr[i]);
}
for(int i=k;i<=length;i++){
if(arr[i]<mh.peek()){
mh.remove();
mh.add(arr[i]);
}
}
return mh.peek();
}
public static void main(String[] args) {
int[] array = new int[]{2,3,5,6};
int r=array.length-1;
int k = 3;
int l = 0;
System.out.println(kthSmallest(array, l, r, k));
}
}
Some basic theory
In a PriorityQueue, whenever you call the peek() method, the smallest element will be the one returned. remove() will also remove the smallest element from the queue.
This being said, I see there's a problem at your second for() loop and I don't really understand the logic of that code section.
My solution
A much simpler thing to do is just eliminate the smallest element of the queue k-1 times, leading to the next element returned by peek() being the k-th smallest element of the array.
Fix for your second loop (the rest of the code seems okay):
for(int i=0;i<k-1;i++){
mh.remove();
}
The problem in your code logic
The reason your method always returns the first element is because of this condition:
for(int i = k; i <= length; i++)
What happens if length and k are the same?
Also, let's say you have an array of length 5:
int a[] = {1, 3, 2, 4, 5}
and want to get the 4-th smallest element of the array:
k = 4, length = 5.
Your for() loop is only going to do 2 eliminations, which is not okay. You should count 4-1=3 eliminations.
Related
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a java program in which we are given an array lets say {20 ,5 ,7 ,9} in this array we have to perform following operations:
(index do not matter here)
find max element in this array and delete that element in array.
then add the max element again by divided by 2(floor division).
we can add max element divided by 2 where ever we want.
Use ArrayList instead of arrays as in Java arrays are static so the size of the arrays cannot change once they are instantiated.Also cannot delete an element and reduce the array size.
int max = -Integer.MIN_VALUE;
int maxIndex = -1;
iterate over the array and and insert every element to the arraylist
ArrayList<Integer> list = new ArrayList<>();
for(int i : arr){
list.add(i);
}
Now the array is transformed to an ArrayList.Here we will find the max. Then store the max in the temp variable . Once we delete the max from the list we will use the temp to do floor division by 2 using Math.floorDiv(a,b) function.
for(int i = 0; i< list.size; i++){
max = temp;
list.remove(i);
list.add(Math.floorDiv(temp,2));
}
}
The complete code with the output is given below :
import java.util.*;
public class Main{
This is the function which will find the max number from the array and then do the floorDiv() by 2 and insert it back.
static ArrayList<Integer>solve(ArrayList<Integer>list){
int max = -Integer.MIN_VALUE;
int maxIndex = -1;
for(int i = 0; i< list.size(); i++){
if(list.get(i) > max){
int temp = list.get(i);
max = temp;
list.remove(i);
list.add(Math.floorDiv(temp,2));
}
}
return list;
}
public static void main(String[] args) {
int [] arr = new int[]{20 ,5 ,7 ,9};
ArrayList<Integer> list1= new ArrayList<>();
for(int a : arr){
list1.add(a);
}
Main obj = new Main();
System.out.println(obj.solve(list1));
}
}
The output is : [5, 7, 9, 10]
arrays in Java are static so the size of the arrays cannot change once they are instantiated. Thus we cannot delete an element and reduce the array size.
int max=-Integer.MIN_VALUE;
int maxIndex=-1;
Now iterate over the array and if element is greater than maxValue update maxValue and maxIndex.
for(int i=0;i<array.length;i++)
{
if(array[i]>max)
{
max= array[i];
maxIndex=i;
}
}
Now replace value at maxIndex with MaxValue/2 to solve this.Since position doesnt matter and delete operation has to be performed at the max index might as well place it there or you could use arrayLists to remove element at that index specifically and then using the ArrayList.add() method. Cheers!
I've been working on an algorithm that reverses the order of an array using a single for loop and then pushes each element of the reversed array onto the stack. I've been having a hard time getting this to work properly, but I may be interpreting the instructions incorrectly. The instructions are as follows:
Describe in pseudocode an efficient algorithm for reversing the order of the numbers in A using a single for-loop that indexes through the cells of A, to insert each element into a stack, and then another for-loop that removes the elements from the stack and puts them back into A in reverse order.
I can easily reverse the order of the array, but my stack does not fill before the for loop terminates. My code:
public static void reverseAndPush(int[] a, int start, int end)
{
for (int i = 0; i < end; i++)
{
int temp = a[start];
a[start] = a[end];
//only elements 5 and 4 get pushed to the stack
stack.push(a[start]);
a[end] = temp;
start++;
end--;
}
}
If I remove the stack portion, the array is reversed successfully. What changes would need to be made to make this code run successfully? I think it has something to do with my execution statement i < end but nothing I've tried works correctly (lots of index out of bound exceptions). The instructions say to do in pseudocode, but I wanted to actually try and write the algorithm anyway just to play around with it.
Edit
For the second for loop, I had thought of doing something like this:
for n to 1 do
stack.pop()
But this is assuming that I must push all the elements into the stack using the first for loop. I could be mistaken.
The trick here is to understand how stacks work, more specifically where items end up when you add/remove them from the stack. The stack data structure is a LIFO (last in, first out) data structure, therefore the last item you add is the first item you get when you call pop(). Here is a function to do what is being described by your question using the characteristics of a stack
public static int[] reverseArrayWithStack(int[] arrayToReverse)
{
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < arrayToReverse.length; i++)
stack.push(arrayToReverse[i]);
for(int j = 0; j < arrayToReverse.length; j++)
arrayToReverse[j] = stack.pop();
return arrayToReverse;
}
Example
given an array of arr = {1,2,3,4,5}
1st for-loop - stack = {1,2,3,4,5}, all values are pushed onto the stack
2nd for-loop - start with index 0 again because when we pop from stack we will get back 5 therefore arr[0] = stack.pop() = 5, arr[1] = statck.pop() = 4, arr[2] = statck.pop() = 3 etc. This allows us to use the behavior of the stack's pop() method to place the items in reverse order starting at index 0.
Loop the array from the end and push each element to the stack. This should have the first element in the array as first element. In the meantime you could use another array and populate it within the same loop, which would be in reverse order
2.In the second loop, pop elements from the stack and assign it to the array from the end. This way the array would be reversed.
public static void reverseAndPush(int[] a)
{
int sizeOfArray = a.length-1;
int[] tmp = new int[sizeOfArray];
for (int i = sizeOfArray; i <= 0; i--)
{
tmp[i] = a[i];
stack.push(a[i]);
}
for (int i = sizeOfArray; i <= 0; i--)
{
a[i] = stack.pop();
}
}
In Pseudocode:
FOR EACH INDEX I IN ARRAY A
PUSH A[I]
NEXT
FOR EACH INDEX I IN ARRAY A
POP A[I]
NEXT
This question already has answers here:
Finding the second highest number in array
(45 answers)
Closed 9 years ago.
How do you find second highest number in an integer array?
Is this a good implementation?
Is there a better way to do this?
public class Find2ndHighest {
public static void main(String[] args) {
int b[] = {2,3,1,0,5};
TreeMap<Integer,Integer> tree = new TreeMap<Integer,Integer>();
for(int i = 0; i<b.length;i++){
tree.put(b[i], 0);
}
System.out.println(tree.floorKey(tree.lastKey()-1));
}
}
You can sort the array and fetch second last element which executes in O(nlogn), but this works only if you are sure that there are no duplicates in the array else this method is unreliable.
You can iterate through the array maintain counters for highest and second highest and return 2nd highest. This executes in O(n)
Example:
int highest = Integer.MIN_VALUE+1;
int sec_highest = Integer.MIN_VALUE;
for(int i : b) //b is array of integers
{
if(i>highest)
{
sec_highest = highest; //make current highest to second highest
highest = i; //make current value to highest
}
else if(i>sec_highest && i != highest)
{
sec_highest = i;
}
}
Another solution is:
int b[] = {1, 2, 31,22,12,12};
Arrays.sort(b);
System.out.println(b[b.length-2]);
The easiest solution would be:
public static void main(String[] args) {
int b[] = {2,3,1,0,5};
int highest = Integer.MIN_VALUE;
int highest2nd = Integer.MIN_VALUE;
for(int i :b )
if (i>=highest) {
highest2nd = highest;
highest = i;
} else if (i>= highest2nd)
highest2nd = i;
System.out.println(highest2nd);
}
Then you walk through the list only once, which is the best you can do from a 'Big O' standpoint.
PS: depending on whether you want the second highest unique value, or the value that is stricly lower than the highest value, you could choose to put i>highest in the if-statement, instead of i>=highest.
There are multiple ways to find the second highest element in an unsorted array:
You can sort the array and take the second last element - runs in O(n log n).
You can store the elements in a TreeSet instead of an array, which is what you are doing - runs in O(n log n) as well.
Suppose for a while you want to get the highest element - all you have to do is to iterate over the whole aray once, while keeping the maximum in a variable.
This way you can achieve O(n) performance.
You can do the same thing for the second highest element, but instead of keeping the highest element, you will keep the two highest elements.
This way you can easily achieve O(n) performance.
The only problem with the last solution is that it does not scale well with the increasng k.
There is however a linear time algorithm to find the k-th highest element in an unsorted array - runs in O(n) for any k (http://en.wikipedia.org/wiki/Selection_algorithm)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
There was an online coding event yesterday on Codechef, and I can't figure out how to solve one of the questions from it. Briefly put:
Given a list of N numbers { a1, a2, …, aN }, find the range [L, R] (1 ≤ L ≤ R ≤ N) that maximizes the sum (a1 + … + aL−1) − (aL + … + aR) + (aR+1 + … + aN).
In other words, you get to multiply a subsection of the list by −1, and want to maximize the sum of the resulting list.
I looked at few of the solution like this but couldn't figure out what this guy is doing.
How would I go about this?
EXAMPLE
-2 3 -1 -4 -2
Now you can multiply the subsection 3 to 5 by -1 to get
-2 3 1 4 2
such that the sum(-2,3,1,4,2) = 8 which is the maximum possible for this case
if we can find the minimum sequence from the array than that part if we multiply with one will give you max sum.
For example in this example : -2 3 -1 -4 -2 the minimum sequence is -1, -4, -2. if we multiply this sequence with one it will maximise the sum. So the question is how to find minimum sum sequence.
Here come the O(N) solution:
negate every number
and run the kadane's algorithm
If the array contains all +ve than no subarray which needs to be multiplied by -1. Check the below question. minimum sum subarray in O(N) by Kadane's algorithm
The algorithm you have shown basically calculates the maximum sum and current sum up to any element.
Note: It builds the array with opposite sign of the original elements.
If the current sum is negative, then it rejects the original sum and starts a new sum with the new element.
If the current sum is positive, then that means including the previous entries is beneficial and it adds the current element to the sum.
If I understand your problem correctly, it sounds like you want to first find the minimum subarray and then multiply that by -1 and add the remaining non negated values.
The minimum subarray is essentially the opposite of maximum subarray problem:
public class MaxSumTest {
public static class MaxSumList{
int s=0, e=0;
List<Integer> maxList;
public MaxSumList(List<Integer> l){
//Calculate s and e indexes
minSubarray(l);
//Negate the minSubarray
for(int i=s; i < e; i++)
l.set(i, -l.get(i));
//Store list
maxList = l;
}
public int minSubarray(List<Integer> l){
int tmpStart = s;
int currMin = l.get(0);
int globalMin = l.get(0);
for(int i=1; i<l.size(); i++){
if(currMin + l.get(i) > 0){
currMin = l.get(i);
tmpStart = i;
}
else{
currMin += l.get(i);
}
if(currMin < globalMin){
globalMin = currMin;
s = tmpStart;
e = i+1;
}
}
return globalMin;
}
}
public static void main(String... args){
MaxSumList ms = new MaxSumList(Arrays.asList(new Integer[]{-2, 3, -1, -4, -2}));
//Prints [-2, 3, 1, 4, 2]
System.out.println(ms.maxList);
}
}