if i store a numbers in stack , and i want to print it in queue , should i store the same numbers in queue again to print it , or there is another way to do it ?
import java.util.Stack;
import java.util.PriorityQueue;
import java.util.Scanner ;
public class Qa {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Stack<Integer> A =new Stack<Integer>();
System.out.println(" the numbers should be less than 99 ");
int x = input.nextInt() ;
while(x> 0 && x < 99){
A.push(x);
}
PriorityQueue<String> B =new PriorityQueue<String>();
}
Queue is basically FIFO. First store the elements in a Stack. Pop the elements and store it again in another Stack. Now pop the elements you will get it as FIFO(Queue).
You can initialize a List with the contents of the stack and then print from the List? You can print from last element in List till first
i don't know what you specific want to do, but if you have the numbers stored, you don't need to re-store again. You can just reed them in from the [first-->last] or [last-->first].
An example with code is here:
CodeExample
with that you save memory and time. :)
Is suppose that you utilizes the stack structure for some reason, but the results could be the same, storing data in a simple list, and then depending in what you wanna do, uses that list. You could save space and time, because doesn't be necessary duplicate data or make unnecessary loops on complex data structures.
Hope this helps.
java.util.Stack it is an ordered Iterable like a List. you can get the elements in order of insertion by iterating over the stack with a for loop (or .forEach in Java 8).
I'm pasting the example code and output below:
public class MyApp {
public static void main(String[] args) {
Stack<Integer> myInts = new Stack<>();
for (int i = 0; i < 5; i++) {
myInts.push(i);
}
System.out.println("ITERATING:");
myInts.forEach(System.out::println);
System.out.println("\nPOPPING:");
while(!myInts.isEmpty()) {
System.out.println(myInts.pop());
}
}
}
The output is:
ITERATING:
0
1
2
3
4
POPPING:
4
3
2
1
0
You see that if you iterate over the Stack it returns the numbers in order of insertion. If your intent is just print the contents of the stack this approach has the additional benefit of not having to mutate the stack by calling pop().
Related
for(int i = 0; i < points.size(); i = i+lines) {
points.remove(i);
}
The idea here is that a user can either remove every other space or every third space or every fourth space .. And so forth, of an array list by entering an int "line" that will skip the spaces. However, I realize the list gets smaller each time messing with the skip value. How do I account for this? I'm using the ArrayList library from java so don't have the option of just adding a method in the array list class. Any help would be greatly appreciated.
I've perfomed a benchmark of all the answers proposed to this question so far.
For an ArrayList with ~100K elements (each a string), the results are as follows:
removeUsingRemoveAll took 15018 milliseconds (sleepToken)
removeUsingIter took 216 milliseconds (Arvind Kumar Avinash)
removeFromEnd took 94 milliseconds (WJS)
Removing an element from an ArrayList is an Θ(n) operation, as it has to shift all remaining elements in the array to the left (i.e. it's slow!). WJS's suggestion of removing elements from the end of the list first, appears to be the fastest (inplace) method proposed so far.
However, for this problem, I'd highly suggest considering alternative data structures such as a LinkedList, which is designed to make removing (or adding) elements in the middle of the list fast. Another alternative, if you have sufficient memory, is to build up the results in a separate list rather than trying to modify the list inplace:
removeUsingIterLinked took 12 milliseconds
removeUsingSecondList took 3 milliseconds (sleepToken with WJS's comment)
Use an Iterator with a counter e.g. the following code will remove every other (i.e. every 2nd) element (starting with index, 0):
Iterator<Point> itr = points.iterator();
int i = 0;
while(itr.hasNext()) {
itr.next();
if(i % 2 == 0) {
itr.remove();
}
i++;
}
Here, I've used i as a counter.
Similarly, you can use the condition, i % 3 == 0 to remove every 3rd element (starting with index, 0).
Here is a different approach. Simply start from the end and remove in reverse. That way you won't mess up the index synchronization. To guarantee that removal starts with the second item from the front, ensure you start with the last odd index to begin with. That would be list.size()&~1 - 1. If size is 10, you will start with 9. If size is 11 you will start with 9
List<Integer> list = IntStream.rangeClosed(1,11)
.boxed().collect(Collectors.toList());
for(int i = (list.size()&~1)-1; i>=0; i-=2) {
list.remove(i);
}
System.out.println(list);
Prints
[1, 3, 5, 7, 9, 11]
You could add them to a new ArrayList and then remove all elements after iterating.
You could set count to remove every countth element.
import java.util.ArrayList;
public class Test {
static ArrayList<String> test = new ArrayList<String>();
public static void main(String[] args) {
test.add("a");
test.add("b");
test.add("c");
test.add("d");
test.add("e");
ArrayList<String> toRemove = new ArrayList<String>();
int count = 2;
for (int i = 0; i < test.size(); i++) {
if (i % count == 0) {
toRemove.add(test.get(i));
}
}
test.removeAll(toRemove);
System.out.print(test);
}
}
sorry for limited code, as i have quite no idea how to do it, and parts of the code are not a code, just an explanation what i need. The base is:
arrayList<double> resultTopTen = new arrayList<double();
arrayList<double> conditions = new arrayList<double(); // this arrayList can be of a very large size milion+, gets filled by different code
double result = 0;
for (int i = 0, i < conditions.size(), i++){ //multithread this
loopResult = conditions.get(i) + 5;
if (result.size() < 10){
resultTopTen.add(loopResult);
}
else{
//this part i don't know, if this loopResult belongs to the TOP 10 loopResults so far, just by size, replace the smallest one with current, so that i will get updated resultTopTen in this point of loop.
}
}
loopResult = conditions.get(i) + 5; part is just an example, calculation is different, in fact it is not even double, so it is not possible simply to sort conditions and go from there.
for (int i = 0, i < conditions.size(), i++) part means i have to iterate through input condition list, and execute the calculation and get result for every condition in conditionlist, Don't have to be in order at all.
The multithreading part is the thing i have really no idea how to do, but as the conditions arrayList is really large, i would like to calculate it somehow in parallel, as if i do it just as it is in the code in a simple loop in 1 thread, i wont get my computing resources utilized fully. The trick here is how to split the conditions, and then collect result. For simplicity if i would like to do it in 2 threads, i would split conditions in half, make 1 thread do the same loop for 1st half and second for second, i would get 2 resultTopTen, which i can put together afterwards, But much better would be to split the thing in to as many threads as system resources provide(for example until cpu ut <90%, ram <90%). Is that possible?
Use parallel stream of Java 8.
static class TopN<T> {
final TreeSet<T> max;
final int size;
TopN(int size, Comparator<T> comparator) {
this.max = new TreeSet<>(comparator);
this.size = size;
}
void add(T n) {
max.add(n);
if (max.size() > size)
max.remove(max.last());
}
void combine(TopN<T> o) {
for (T e : o.max)
add(e);
}
}
public static void main(String[] args) {
List<Double> conditions = new ArrayList<>();
// add elements to conditions
TopN<Double> maxN = conditions.parallelStream()
.map(d -> d + 5) // some calculation
.collect(() -> new TopN<Double>(10, (a, b) -> Double.compare(a, b)),
TopN::add, TopN::combine);
System.out.println(maxN.max);
}
Class TopN holds top n items of T.
This code prints minimum top 10 in conditions (add 5 to each element).
Let me simplify your question, from what I understand, please confirm or add:
Requirement: You want to find top10 results from list called conditions.
Procedure: You want multiple threads to process your logic of finding the top10 results and accumulate the results to give top10.
Please also share the logic you want to implement to get top10 elements or it is just a descending order of list and it's top 10 elements.
I have an array that has the following numbers
int[] arr = {2,4,3,1,5,6,0,7,8,9,10,11,12,13,14,15};
Or any other order for that matter.
I need to make all the possible combinations for the numbers using a recursion but satisfying a condition that the next number clubbed with the present one can only be from specific numbers given by a hashmap:
ex When the recursion takes 1 the next number can be from {0,4,5,2,6} (from the HaspMap),and then if i make 10,the next number can be from {1,4,5} and so on
static HashMap<Integer,Integer[]> possibleSeq = new HashMap<Integer,Integer[] >();
private static void initialize(HashMap<Integer,Integer[]> possibleSeq) {
possibleSeq.put(0,new Integer[]{1,4,5});
possibleSeq.put(1,new Integer[]{0,4,5,2,6});
possibleSeq.put(2,new Integer[]{1,3,5,6,7});
possibleSeq.put(3,new Integer[]{2,6,7});
possibleSeq.put(4,new Integer[]{0,1,5,8,9});
possibleSeq.put(5,new Integer[]{0,1,2,4,6,8,9,10});
possibleSeq.put(6,new Integer[]{1,2,3,5,7,9,10,11});
possibleSeq.put(7,new Integer[]{2,3,6,10,11});
possibleSeq.put(8,new Integer[]{9,4,5,12,13});
possibleSeq.put(9,new Integer[]{10,4,5,8,6,12,13,14});
possibleSeq.put(10,new Integer[]{7,6,5,9,11,15,13,14});
possibleSeq.put(11,new Integer[]{6,7,10,14,15});
possibleSeq.put(12,new Integer[]{8,9,13});
possibleSeq.put(13,new Integer[]{8,9,10,12,14});
possibleSeq.put(14,new Integer[]{9,10,11,13,15});
possibleSeq.put(15,new Integer[]{10,11,14});
}
Note: I am required to make all the possible numbers beginning from digit length 1 to 10.
Help!
Try with something like this, for starters:
void findPath(Set paths, Stack path, int[] nextSteps, Set numbersLeft) {
if (numbersLeft.isEmpty()) {
//Done
paths.add(new ArrayList(path));
return;
}
for (int step:nextSteps) {
if (numbersLeft.contains(step)) {
// We can move on
path.push(step);
numbersLeft.remove(step);
findPath(paths, path, possiblePaths.get(step), numbersLeft);
numbersLeft.add(path.pop());
}
}
}
Starting values should be an empty Set, and empty Stack, a nextSteps identical to you initial array, and a set created from your initial array. When this returns, the paths Set should be filled with the possible paths.
I haven't tested this, and there are bugs as well as more elegant solutions.
I want to make my own binary search algorithm to search ArrayList of 1 000 000 elements. I decided to do the search with do-while loop. I am aware I could use while() loop. But when I run it, it takes much time to find the number. I guess something is wrong with setting the value of first and last element of ArrayList. My code is
import java.util.*;
public class BinSearchAlg {
public static void main(String[]args){
int first;
int last;
int median;//middle element of arraylist
Long element;//element with median index
Scanner scan = new Scanner(System.in);
ArrayList<Long>list = new ArrayList();
for(long l=0;l<1000000;l++){
list.add(l);//list is sorted
}
first = 0;
last = list.size();
median = (last-first)/2;
element = list.get(median);
System.out.println("Choose the number: ");
long l = scan.nextLong();
do{
if(element<l){
first = median;
median=(last-first)/2;
element = list.get(median);
}else{ //if(element>l){
last = median;
median = (last-first)/2;
element = list.get(median);
}
}while(element!=l);
}
}
Thanks for you help.
The median calculation is problematic:
median=(last-first)/2;
You should rather do:
median=(last+first)/2;
In the current code you have, when you are searching in the range [10..16], your code will try to compare the goal with the median of list.get(3).
There could be another bug, but for now I'll leave you with this. Hint: try [0, 1], which should expose the bug in the code.
As Ziyao Wei answered, you'll need to fix the median. In addition, you'll probably need a different loop exit condition - right now you've got an infinite loop if l isn't in the list. Also, your if-else needs to be an if-elseif-else - at present if l == element then the loop will actually treat this as element > l and continue looping.
You can directly use Collection class's binary search method present java.util package :-
Collections.binarySearch(myList,key.get(i),new MyTransferObjectClass());
and
public class MyTransferObjectClass implements Comparator<MyTransferObjectClass>{
#Override
public int compare(MyTransferObjectClass o1, MyTransferObjectClass o2) {
//your logic for comparison
}
}
why to add redundant code when you can use available APIs.
Hi I have been working on a solution for days, and I've been trying to figure it out on my own but I just can't.
I have an ArrayList and I want to swap the elements in it. But I want to compare the list in halves. So say if the list had 8 elements in it, I would want to compare the first element in the first half of the list with the first element in the second half of the list.
So list[0] with list[4] and if 4 is bigger than 0, i want to swap them, then i want to increment 0 and by 1, and half the list by one, until i = 4.
I have to run it from the command line.
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class TennisTournament {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
while (input.hasNextInt()) {
nums.add(input.nextInt());
}
tournament(nums); }
public static void tournament(ArrayList <Integer> list) {
int midPoint = list.size()/2; // returns the index number of half of the lists size
for (int i = 0; i < midPoint; i++) { // while is bigger than mid point, increment by one
if (list.get(i) < list.get(midPoint)) {
Collections.swap(list, i, midPoint);
System.out.print(list);
}
}
System.out.println(list); }
}
This is what I have so far, but when I run it from the command line, it just returns an ordinary list, and I'm completely stumped. I would much rather use a loop than the collections method as it is not a style of programming i am particular familiar with.
Look at midPoint - it never changes inside the loop. You're continually exchanging the i-th element (provided that the "if" condition is true) with the midPoint. No element after midPoint is ever touched.