import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Print output to STDOUT. Your class should be named Solution. */
Scanner sc= new Scanner(System.in);
int siz= sc.nextInt();
int max= sc.nextInt();
CircularQueue<Long> queue = new CircularQueue<>(max);
while(siz-->0){
queue.add(sc.nextLong());
}
System.out.println(queue.size());
for(int i=queue.size();i>0;i--){
System.out.print(queue.get(i-1)+" ");
}
}
public static class CircularQueue<E> extends LinkedList<E> {
private int capacity = 10;
public CircularQueue(int capacity){
this.capacity = capacity;
}
#Override
public boolean add(E e) {
if(contains(e)){
return true;
}
if(size() >= capacity)
removeFirst();
return super.add(e);
}
}
}
In this Program I have created fixed size Linked List in which while adding values greater than the size of list then it removes old value and adds new value at Last.
Suggest some changes in code without changing the logic. Thanks in Advance
contains() of LinkedList has O(n) time at the worst case.
Construct an auxiliary HashSet for this purpose, or invent another way to trace elements which had appeared already.
Scanner class is slow for large inputs, so try to avoid it. you can use BufferedReader class which is faster than Scanner class.
Scanner is a much more powerful utility than BufferedReader but BuffredReader has a significantly large buffer (8KB) than Scanner (1KB) and also Scanner uses regular expression to read and parse text input which makes it slow.
The call to queue.size in main method.
You can save one calculation if you call it once and save its value then reuse in sysout statement and in for loop.
Avoid generalizing imports. Ex. import java.io.*
Put exactly the packages you want specifically to access.
That may save also little bit of time.
Related
I want to create a program which would be like a home budget, so I have a class AmountModel
(I know that Integer is not so good for id, but it's not a problem now):
import java.time.LocalDate;
public class AmountModel {
private Integer id;
private Double amount;
private CategoryModel categoryModel;
private LocalDate localDate;
// getters/setters etc.
}
And in another class I built this deleteAmount method:
static Scanner sc = new Scanner(System.in);
public List<amountModel> deleteAmount() {
Iterator<AmountModel> it = amountList.iterator();
while (it.hasNext()) {
System.out.println("Choose index to delete ");
AmountModel am = it.next();
if (am.getId().equals(sc.nextInt())) {
it.remove();
}
break;
}
return amountList;
}
Adding object works good, but when I try to use the delete method I have to put first index.
Example:
I have three objects (with index 0, 1, 2).
When I choose 1 or 2 program do nothing.
When I choose 0 program deletes first index, remains index 1 and 2.
When I choose 2, program do nothing.
When I choose 1, program deletes index 1, remains index 2... etc.
What is wrong with this method?
You should separate your input logic from your delete logic and accept the list as a parameter.
Note: this only works with a mutable list. If you use something like Arrays.asList() it will throw an exception.
public void deleteAmount(List<AmountModel> list, int key) {
list.removeIf(a -> a.getId().equals(key));
}
Welcome to Stack Overflow!
As others have mentioned, there are a few ways to tackle this. But I think you can make this even simpler by changing the data structure used to access your AmountModel collection: if you're frequently accessing an item by ID, a Map is a great fit.
No more worrying about iterator state; you could just do something like:
// Map "amounts" by ID for easy O(1) lookup.
static Map<Integer, AmountModel> amountMap
public void deleteAmount(Integer id) {
if (!amountMap.containsKey(id)) {
// (TODO: Handle invalid input)
throw new Exception()
}
amountMap.remove(id)
return
}
Hope this helps! I threw together a working example in a gist here if you're interested. (In Groovy, but should be enough to give you the idea)
Your break statement is breaking the while loop in the first iteration only. So, it will work only if the first am.getId() matches with your fist input.
Also, your sc.nextInt() will keep on scanning for next available input, Remove it from while loop.
static Scanner sc = new Scanner(System.in);
public List<AmoutModel> deleteAmount() {
Iterator<AmoutModel> it = amountList.iterator();
Integer scId = sc.nextInt();
while (it.hasNext()) {
System.out.println("Choose index to delete ");
AmoutModel am = it.next();
if (am.getId().equals(scId)) {
it.remove();
break;
}
}
return amountList;
}
call your sc.nextInt() outside of the loop, otherwise it will get run everytime the loop returns, as the condition gets reevaluated every time the loop ends.
also you could use the remove method of list
static Scanner sc = new Scanner(System.in);
public List<AmoutModel> deleteAmount() {
System.out.println("Choose index to delete ");
int index = sc.nextInt();
amountList.remove(index);
return amountList;
}
I am reading in data from a text file into an ArrayList and then trying to search for a particular string in that ArrayList (the second method).
I believe that I am correctly reading in the data however am struggling to write methods to implement on the ArrayList once it has been filled. For instance, in the checking method below, it is returning a false when I am certain the input String is in the data structure.
I recognize this is likely a problem with my variable scope or how my methods are interacting with each other (i.e, the arraylist is not actually filled with the data when I am checking it).
Any help would be much appreciated - thanks
import java.util.*;
import java.io.*;
public class Word {
ArrayList<String> diclist = new ArrayList<String>();
private void readIn() throws FileNotFoundException {
File file = new File("filepath");
Scanner s = new Scanner(file);
s.useDelimiter("\n");
while (s.hasNextLine()) {
diclist.add(s.nextLine());
}
s.close();
}
public boolean checkIn(String z) {//Check if input string z is in diclist
for (int i = 0; i < diclist.size(); i++) {
if (diclist.get(i).equals(z)) {return true;}
}
return false;
}
}
There are no obvious problems in the code you posted so far. After calling readIn, if the file exists, readable and not empty, the list should get populated. I suggest running it through a debugger.
Note that the checkIn method can be vastly simplified to this:
return diclist.contains(z);
In a interview I was asked to wrtie a method which will generate unique 5 digit random number everytime when it is called.For ex: if I call the method and get 22222 then in next call i should not get 22222.
I wrote a code as below:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class RandomNumberGen {
private static ArrayList arr=new ArrayList();
private static int k=-1;
public RandomNumberGen(){
for (int i=10000;i<99999;i++){
arr.add(i);
}
Collections.shuffle(arr);
}
public static void main(String[] args) {
for(int m=0;m<10;m++){
try {
System.out.println(new RandomNumberGen().randomNumbermethod());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Integer randomNumbermethod() throws Exception{
k++;
if(k>=arr.size()){
throw new Exception("No more number available");
}else return (Integer) arr.get(k);
}
}
Answer got accepted but I was asked to avoid memory wastage now.
My question is here as you can see I am using only 10 numbers.So rest of the space occupied by arraylist is a memory-wastage.Is there a way I can achieve same thing without using extra memory.
What I mean is there someway using which unique number can be generated on each call so that this much memory do not get wasted.
private static int number = 10000;
public int getNextUniqueRandomNumber() {
return number++;
}
Implications:
In order to not to return the same value twice, you need to track which numbers you've already generated. This can be very memory consuming.
You eventually run out of numbers. Instead of keeping on searching for an unused random number, you can track how many numbers you've returned (or how many are still available) and recognize if you ran out of numbers.
The generated numbers could be tracked in a collection (Set). This means having an overhead of 32bit per number (when tracking available or generated numbers) plus the collection overhead. Another possibility is to use a boolean-array and mark which slots have been used. Again, this is an overhead, as booleans usually are stored as 32bit value.
But there's a cheaper way to store booleans: as packed bits in an integer. That's what java.util.BitSet does, so each boolean will occupy one bit.
Solution with BitSet and tracking how many numbers are available:
public class RandomNumbers {
private final Random random = new Random();
private final BitSet used = new BitSet();
private final int min = 10000;
private final int max = 99999;
private final int numbersAvailable = max - min + 1;
public static void main (String[] args) {
RandomNumbers randomNumbers = new RandomNumbers();
for (int i = 0; i < 100; i++) {
System.out.println(randomNumbers.nextRandom());
}
}
public int nextRandom () throws NoSuchElementException {
while (numbersAvailable > 0) {
int rnd = min + random.nextInt(max - min + 1);
if (!used.get(rnd)) {
used.set(rnd);
numbersAvailable--;
return rnd;
}
}
throw new NoSuchElementException();
}
}
Just
(int)(Math.random()*89999)+10000
After edit: (just not understood before edit) - you can put generated number in HashSet and after random just check if set contains new number (it will go very slow if you use it many times, but I think this is a good solution if you don't need a lot of numbers.
From my comment: After exceding about 50% of numbers I would create a collection of remaining numbers to pick, same as yours, but you should document in class, that it can freeze for a moment after 50% results usage and give ability to set this factor to client.
Maybe ther is a better way, depending of "how much randomness" must be in generated numbers (for example mathematical approach to sequence generator)
Seems pretty straightforward. A much simpler solution with less memory usage is to just create a set that will hold all the numbers you want like this:
Random random = new Random();
Set<Integer> randomNumbers = new HashSet<Integer>(10);
while(randomNumbers.size() < 10)
randomNumbers.add( new Integer(random.nextInt(89999) + 10000) );
And to view them all:
for(Integer randomNumber : randomNumbers){
System.out.println(randomNumber);
}
This will guarantee uniqueness to the properties of a set and greatly improve your memory usage.
Your method would indeed be ideal to create a large number of unique values, however if you are only creating a small number of unique values it can be more efficient to simply keep track of the used values to garantee uniqueness
import java.util.Collection;
import java.util.HashSet;
import java.util.Random;
public class UniqueRandom {
static Random rnd=new Random();
public static void main(String args[]){
Collection<Integer> alreadyChosen = new HashSet<Integer>();
for(int i=0;i<10;i++){
System.out.println(getNextUniqueRandom (alreadyChosen));
}
}
public static int getNextUniqueRandom(Collection<Integer> alreadyChosen){
if (alreadyChosen.size()==90000){ //hardcoded 5 figure numbers, consider making a variable
throw new RuntimeException("All 5 figure IDs used");
}
boolean unique=false;
int value=0;
while(unique==false){
value=rnd.nextInt(90000)+10000;
unique=!alreadyChosen.contains(value);
}
alreadyChosen.add(value);
return value;
}
}
This method is highly efficient when only a small proportion of the available range is required but becomes slower and slower as collisions become more common. The exact implementation you should choose is highly dependant upon how many values you need to get.
Notes to consider
As already stated this will get very very slow as more values are
chosen, should be made clear to end user, or even better; change algorithm after so many calls
So I have a null pointer exception when run. I am supposed to create a generic class that implements a list with chunks of arrays added as needed. Each time I add an element it is to check if there is space in the tail chunk array and if so add the element. Else it needs to add a chunk, adjust the pointers and add the element. My problem so far is that when I go to add the first element it is throwing a null pointer exception. I believe I have instantiated and object and assigned it where needed. If anyone has any insight please feel free to let me know what I am doing wrong or maybe its right in front of my face.
"myChunk.chunk_.add(element);////////////error" is where I am getting the error.
package ChunkList;
import java.util.*;
import java.io.*;
public class chunkList<T> {
public static void main(String[] args) {
chunkList<Integer> myList=new chunkList<Integer>();
for(int i=1; i<24; i++)
{
myList.add(i);//////////////////////////////////
System.out.println("Adding number: "+ i);
}
System.out.println("");
myList.display();
}
private chunk head;//changed T to chunk
private chunk tail;//changed T to chunk
private int array_size=8;
private int list_size;
public chunkList()//Default Constructor
{
head=null;
tail=null;
list_size=0;
}
//public chunkList(chunkList copy){}// a copy constructor.... don't think I need.
class chunk// added <T>
{
//T[] chunk_arr = new T[array_size];// illegal operation
//ArrayList<T> chunk_ = new ArrayList<T>(array_size);
ArrayList<T> chunk_;
private int chunk_size; //may need to change to public
chunk nextChunk;//changed T to chunk
chunk prevChunk;//changed T to chunk
public chunk()//default constructor
{
chunk_ = new ArrayList<T>(array_size);
chunk_size=0;
nextChunk=null;
prevChunk=null;
}
}
public void add(T element)
{
if(this.tail==null)//empty chunk list
{
chunk myChunk=new chunk();//instantiate
//myChunk.prevChunk=null;//changed from head to null
//myChunk.nextChunk=null;//changed from tail to null
head=myChunk;
tail=myChunk;
//head.nextChunk=null;
//head.prevChunk=null;
myChunk.chunk_.add(element);////////////error
list_size++;
myChunk.chunk_size=1;
}
else if (this.tail.chunk_size<array_size)//adds the element to the last chunk in list
{
this.tail.chunk_.add(element);//add element
list_size++;
this.tail.chunk_size++;//increase individual chunk array size
}
else// create new chunk, relink chunks, add element
{
chunk myChunk=new chunk();
myChunk.chunk_size=1;
list_size++;
myChunk.chunk_.add(element);
tail.nextChunk=myChunk;
myChunk.prevChunk=tail;
tail=myChunk;
}}
public int size()
{return list_size;}
public void display()
{
chunk my_chunk=head;
if(my_chunk==null)
{
System.out.print("Empty Chunk List");
return;
}
for(int i=0;i<list_size; )
{
for(int j=0; j<my_chunk.chunk_size; j++)
{
System.out.println(my_chunk.chunk_.get(j));
i++;
}
if(my_chunk.nextChunk!=null)
my_chunk=my_chunk.nextChunk;
}
}
}
So thanks Olivier Jacot-Descombes , I fixed one problem with the code and it now adds the first chunk BUT it is throwing NPE when it tries to create the next chunk. I will look at it and be back if i need more help. Thanks All.
P.S. The add method on this was incorrectly linked together in the last else statement.
Your code is very strange
There is a public static void main(String[] args) inside the class chunkList<T>. This makes no sense.
You declare a chunkList<Integer> instead of chunkList<int>.
You re-declare a chunk<T> head and chunk<T> tail in the constructor. The code should simply be head = null; without chunk<T>.
In the constructor of chunk you do the same thing again with ArrayList<T> chunk_ = ....
I could tell more things; however, I think that you should start by fixing these things to begin with.
NAMING STANDARDS PLEASE!
You will immediately benefit from adhering to industry naming standards, because your code will be more easily read by others when you ask for their help. Also, you'll be able to read other's code more easily too.
In java, convention is that:
all names are camelCase
all names start with a lowercase letter, except class names start with a capital letter
constants are all-capitals with underscore separation (eg MY_CONSTANT)
tend not to abbreviate names
don't use hungarian notation
To apply this to your code, make the following changes:
Rename chunkList to ChunkList
Rename array_size to arraySize
Rename my_chunk to myChunk
Rename chunk_ tochunk`
Now, to answer your question, just use a java.util.LinkedList and stop trying to reinvent the wheel!
I'm fairly confident that there's no way this could work, but I wanted to ask anyway just in case I'm wrong:
I've heard many times that whenever you have a certain number of lines of very similar code in one batch, you should always loop through them.
So say I have something like the following.
setPos1(getCard1());
setPos2(getCard2());
setPos3(getCard3());
setPos4(getCard4());
setPos5(getCard5());
setPos6(getCard6());
setPos7(getCard7());
setPos8(getCard8());
setPos9(getCard9());
setPos10(getCard10());
setPos11(getCard11());
setPos12(getCard12());
There is no way to cut down on lines of code as, e.g., below, right?
for (i = 0; i < 12; i++) {
setPos + i(getCard + i)());
}
I'm sure this will have been asked before somewhere, but neither Google nor SO Search turned up with a negative proof.
Thanks for quickly confirming this!
No way to do that specifically in Java without reflection, and I don't think it would be worth it. This looks more like a cue that you should refactor your getcard function to take an integer argument. Then you could loop.
This is a simple snippet that shows how to loop through the getters of a certain object to check if the returned values are null, using reflection:
for (Method m : myObj.getClass().getMethods()) {
// The getter should start with "get"
// I ignore getClass() method because it never returns null
if (m.getName().startsWith("get") && !m.getName().equals("getClass")) {
// These getters have no arguments
if (m.invoke(myObj) == null) {
// Do something
}
}
}
Like the others stated, probably it's not an elegant implementation. It's just for the sake of completeness.
You could do it via reflection, but it would be cumbersome. A better approach might be to make generic setPos() and getCard() methods into which you could pass the index of the current item.
You need to ditch the getter/setter pairs, and use a List to store your objects rather then trying to stuff everything into one God object.
Here's a contrived example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Foo {
public static class Card {
int val;
public Card(int val) {
this.val = val;
}
public int getVal() {
return val;
}
}
public static class Position {
int value;
public Position(Card card) {
this.value = card.getVal();
}
}
public static void main(String[] args) {
List<Card> cards = new ArrayList<Card>(Arrays.asList(new Card(1), new Card(2), new Card(3)));
List<Position> positions = new ArrayList<Position>();
for (Card card : cards) {
positions.add(new Position(card));
}
}
}
You can't dynamically construct a method name and then invoke it (without reflection). Even with reflection it would be a bit brittle.
One option is to lump all those operations into one method like setAllPositions and just call that method.
Alternatively, you could have an array of positions, and then just loop over the array, setting the value at each index.
Card[] cardsAtPosition = new Card[12];
and then something like
public void setCardsAtEachPosition(Card[] valuesToSet) {
// check to make sure valuesToSet has the required number of cards
for (i = 0; i < cardsAtPosition.length; i++) {
cardsAtPosition[i] = valuesToSet[i];
}
}
Reflection would be your only option for your example case.