I made a method that remove any duplicate in the Stack and return the resulting stack sorted in ascending order. For example, look at the main function, it should output as 1, 3, 4, 7. But it outputs the original stack data instead, which is incorrect. Any suggestions?
import java.util.ListIterator;
import java.util.Stack;
public class removeDoubleInStack {
public static Stack<Integer> removeDouble(Stack<Integer> s) {
Stack<Integer> tempStack = new Stack<Integer>();
ListIterator<Integer> iter = s.listIterator();
while(iter.hasNext()) {
int tempNext = iter.next();
if(tempNext != iter.next())
tempStack.add(tempNext);
}
return tempStack;
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.add(1);
s.add(3);
s.add(3);
s.add(4);
s.add(7);
s.add(7);
removeDouble(s);
System.out.println(s);
}
}
As you can see in the Doc, there is nothing similar to remove duplicates
https://docs.oracle.com/javase/6/docs/api/java/util/Stack.html
but you can do it when:
1- get elements of the stack as Enumeration
2- turn Enumeration into List
3- add list to Set
4- clear stack
5- add set to stack
Example:
final Stack<Integer> ms = new Stack<Integer>();
ms.add(0);
ms.add(0);
ms.add(0);
ms.add(1);
ms.add(1);
ms.add(1);
ms.add(3);
ms.add(56);
System.out.println("Before clean:\n" + ms);
final Set<Integer> s = new HashSet<Integer>(Collections.list(ms.elements()));
ms.clear();
ms.addAll(s);
System.out.println("After clean:\n" + ms);
System.out.println(s) only prints s object that initialized before. removeDouble(s) doesn't have any impact unless you create new object of Stack or reinitialized...
public static void main(String[] args){
Stack<Integer> s = new Stack<Integer>();
s.add(1);
s.add(3);
s.add(3);
s.add(4);
s.add(7);
s.add(7);
Stack<Integer> tempStack = removeDouble(s); // create new object
System.out.println(tempStack);
}
Related
I create a game in Unity. And I got this error:
System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource)
Here is my short code:
public class OnlineGame : MonoBehaviour
{
private List<GameObject> domino = new List<GameObject>(7);
public void Start()
{
StartGame();
}
private void StartGame()
{
for (int i = 0; i < 7; i++)
{
domino[i] = Instantiate(dominoPrefab, new Vector3(11, 0, 0), Quaternion.identity) as GameObject;
}
}
}
If you need more details, write a comment. Thanks for help
private List<GameObject> domino = new List<GameObject>(7)
new List<T>(int capacity) constructor doesn't mean the resulting list will have hold capacity objects at beginning. The Count of elements in the list will still be 0.
When you use List class in c#, it will have capacity memory reserved for the list. When you add some elements to the list and its Count reaches capacity(or close to it, I'm not exactly sure), the list will automatically increase capacity by allocating additional memory so that you can add additional element to the list.
Usually when you use new List<T>() the list will have initial capacity of 0 where program doesn't know how many Count the list can possibly have and will dynamically adjust capacity to match your need.
Using new List<T>(int capacity) is like telling the program that the list will have at most capacity number of elements and list should have that capacity ready to avoid overhead of allocating more memory. Of course, when list's Count reach capacity it will increase as well.
To fix your problem, use Add method instead of assigning to array slot.
public class OnlineGame : MonoBehaviour
{
private List<GameObject> domino = new List<GameObject>(7);
public void Start()
{
StartGame();
}
private void StartGame()
{
for (int i = 0; i < 7; i++)
{
// domino[i] = Instantiate(dominoPrefab, new Vector3(11, 0, 0), Quaternion.identity) as GameObject;
domino.Add(Instantiate(dominoPrefab, new Vector3(11, 0, 0), Quaternion.identity) as GameObject);
}
}
}
I am trying to run below simple Flink job to count words using TableAPI. Used DataStream API to read a stream of data and used StreamTableEnvironment API to create a Table environment. I am getting below exception. Can someone please help me what is wrong in code? I am using Flink 1.8 version.
Exception:
**Exception in thread "main" org.apache.flink.table.api.TableException: Only the first field can reference an atomic type.**
at org.apache.flink.table.api.TableEnvironment$$anonfun$5.apply(TableEnvironment.scala:1117)
at org.apache.flink.table.api.TableEnvironment$$anonfun$5.apply(TableEnvironment.scala:1112)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
at scala.collection.mutable.ArrayOps$ofRef.flatMap(ArrayOps.scala:186)
at org.apache.flink.table.api.TableEnvironment.getFieldInfo(TableEnvironment.scala:1112)
at org.apache.flink.table.api.StreamTableEnvironment.registerDataStreamInternal(StreamTableEnvironment.scala:546)
at org.apache.flink.table.api.java.StreamTableEnvironment.fromDataStream(StreamTableEnvironment.scala:91)
at Udemy_Course.TableAPIExample.CountWordExample.main(CountWordExample.java:30)
Code
public class CountWordExample {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment environment=StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment streamTableEnvironment=StreamTableEnvironment.create(environment);
DataStream<WC> streamOfWords =
environment.fromElements(
new WC("Hello",1L),
new WC("Howdy",1L),
new WC("Hello",1L),
new WC("Hello",1L));
Table t1 = streamTableEnvironment.fromDataStream(streamOfWords, "word, count");
Table result = streamTableEnvironment.sqlQuery("select word, count(word) as wordcount
from " + t1 + " group by word");
streamTableEnvironment.toRetractStream(result, CountWordExample.class ).print();
environment.execute();
}
public static class WC {
private String word;
private Long count;
public WC() {}
public WC(String word,Long count) {
this.word=word;
this.count=count;
}
}
}
All that's needed to get this running is to change the private word and count fields in WC so that they are public, and to use Row.class rather than CountWordExample.class in toRetractStream.
Those fields either have to be public, or have publicly accessible getters and setters in order for the SQL engine to work with them.
public class CountWordExample {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment environment=StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment streamTableEnvironment=StreamTableEnvironment.create(environment);
DataStream<WC> streamOfWords =
environment.fromElements(
new WC("Hello",1L),
new WC("Howdy",1L),
new WC("Hello",1L),
new WC("Hello",1L));
Table t1 = streamTableEnvironment.fromDataStream(streamOfWords, "word, count");
Table result = streamTableEnvironment.sqlQuery("select word, count(word) as wordcount from " + t1 + " group by word");
streamTableEnvironment.toRetractStream(result, Row.class).print();
environment.execute();
}
public static class WC {
public String word;
public Long count;
public WC() {}
public WC(String word,Long count) {
this.word=word;
this.count=count;
}
}
}
I am having a very little problem in my Unity project but can't find a proper help or way to do. I am stuck at point where I have an array of prefab GameObjects and I am trying to instantiate index 1 GameObject and when it destroyed instantiate the next index. Here is how I am doing it. I have two scripts: One to instantiate and other one to destroy it.
Scripts 1:
public class GameObjectsArray : MonoBehaviour {
public static GameObjectsArray Instance { get; set; }
public GameObject[] Objects;
public int i=0;
// Use this for initialization
void Start()
{
InstiatingMethod();
//Instantiate(Objects[i]);
}
public void InstiatingMethod()
{
Instantiate(Objects[i]);
}
}
Scripts 2:
public class CheckDestroy : MonoBehaviour {
//public GameObject[] Objects;
//int i;
// Use this for initialization
void Start () {
Debug.Log("executed");
//Objects = GameObject.FindGameObjectsWithTag("Player");
//OnMouseDown();
//Instantiate(Objects[i], transform.position, transform.rotation);
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
BoxCollider boxCollider = hit.collider as BoxCollider;
if (boxCollider != null)
{
GameObjectsArray.Instance.i++;
GameObjectsArray.Instance.InstiatingMethod();
Destroy(boxCollider.gameObject);
}
}
}
}
}
So I created a very quick project to make a good response:
Scene Image
In the scene, we will have an empty game object that will contain our script that I called "GameManager", basically this script will do everything, it's more logic to put your logic in one script.
public GameObject[] GameObjects;
private int _targetIndex = -1;
private RaycastHit _hit;
private void Start()
{
InstantiateNextGameObject();
}
public void InstantiateNextGameObject()
{
//if the index is pointing at the last game object in the array, init the index to -1
if (_targetIndex == GameObjects.Length - 1)
_targetIndex = -1;
Instantiate(GameObjects[++_targetIndex]);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out _hit))
{
BoxCollider boxCollider = _hit.collider as BoxCollider;
if (boxCollider != null)
{
InstantiateNextGameObject();
Destroy(boxCollider.gameObject);
}
}
}
}
we will have an array of gameobjects following with the targetIndex which will start from -1.
The function InstantiateNextGameObject() will simply increment targetIndex and then instantiate a gameobject from the array (++targetIndex the first time will be 0, second time 1 etc). We have to check also if the targetIndex reaches the end of the array, put it back to -1.
Then basically what you did in the update, when you click on a gameobject, instantiate the next one and destroy the current.
At the end, you will get something like that:
https://ayoub-gharbi.org/youba_docs/stackoverflow/stackoverflow01.mp4
Feel free to ask me if you didn't understand anything:)
Happy coding!
I have to execute many(more than 10) batch jobs one after other to make sure it doesn't exceeds governor limits.
I want to implements something like below but it doesn't work because stateful doesn't work for static.
public class MyBatch implements Database.Batchable<SObject>,
Database.Stateful
{
private String a;
private Static List<String> aList = new List<String>();
private static Integer currentIndex = 0;
static
{
aList = getAllAList();
}
public MyBatch(String a)
{
this.a = a;
}
public Database.QueryLocator start(Database.BatchableContext bc)
{
return Database.getQueryLocator('some query which may get 30k
records');
}
public void execute(Database.BatchableContext BC, List<sObject>
recordList)
{
System.debug('execute');
System.debug(recordList);
}
public void finish(Database.BatchableContext BC)
{
System.debug('finish');
//do I have another A.
if(currentIndex < aList.size())
{
cuurentIndex++;
System.debug('Starting another batch: '+ anotherA);
Database.executeBatch(new MyBatch(aList.get(currentIndex));
}
}
}
So here in finish method, currentIndex is always zero and because of that it always get first value in aList.
I also tried with some other static variables from other class as well but that also doesn't work.
Is there any way to achieve this thing without using database transactions?
You can't call it like this because the finish method is just called once at the end of (all) batches.
So the start and the execute method are important. Depending on the batchsize the query result will be devided into x chunks and the execute method will do the rest.
And since the finish method is just called once your index will be increment at the most once. If you increment it in the excute method it will increment each time a new batch(chunk) run
I have implemented through keeping currentIndex in batch class and passing it when calling next batch.
public class MyBatch implements Database.Batchable<SObject>,
Database.Stateful
{
private List<String> aList = null;
private Integer currentIndex;
public MyBatch(List<String> aList, Integer index)
{
this.aList = aList;
this.index = index;
}
public Database.QueryLocator start(Database.BatchableContext bc)
{
return Database.getQueryLocator('some query which may get 30k
records');
}
public void execute(Database.BatchableContext BC, List<sObject>
recordList)
{
System.debug('execute');
System.debug(recordList);
}
public void finish(Database.BatchableContext BC)
{
System.debug('finish');
//do I have another A.
currentIndex++;
if(currentIndex < aList.size())
{
System.debug('Starting another batch: ');
Database.executeBatch(new MyBatch(aList, currentIndex);
}
}
}
So idea here is to keep index to batch as private member not as static and check if size doesn't exceed then trigger next batch.
I am developing a game and having problem in the following code.
for(intReps = 0; intReps <=9; intReps++)
{
final Path path = new Path(2).to(sprBalls[intReps].getX(), sprBalls[intReps].getY()).to(sprBalls[intReps].getX(), -50);
// sprBalls[intReps].registerEntityModifier(new LoopEntityModifier(new PathModifier(10, path, null, new IPathModifierListener() {
final Path path1 = new Path(2).to(fly[intReps].getX(), fly[intReps].getY()+10).to(fly[intReps].getX(), -50);
sprBalls[intReps].registerEntityModifier(new PathModifier(10, path, null, new IPathModifierListener() {
#Override
public void onPathStarted(PathModifier pPathModifier,
IEntity pEntity) {
// TODO Auto-generated method stub
}
#Override
public void onPathWaypointStarted(PathModifier pPathModifier,
IEntity pEntity, int pWaypointIndex) {
// TODO Auto-generated method stub
}
#Override
public void onPathWaypointFinished(PathModifier pPathModifier,
IEntity pEntity, int pWaypointIndex) {
// TODO Auto-generated method stub
}
#Override
public void onPathFinished(PathModifier pPathModifier,
IEntity pEntity) {
Log.e("Msg","intReps : "+intReps); // Output is 10
// TODO Auto-generated method stub
// mScene.detachChild(pEntity);
sprBalls[intReps].detachSelf(); // Error on this line.
// pEntity.detachSelf();
// sprBalls[intReps].dispose();
}
}, EaseSineInOut.getInstance()));
}
Array's length is 10. I get IndexOutOfBoundException on the line with error (sprBalls[intReps].detachSelf();)
I am running the loop from 0 to 9 but on printing the value of intReps it shows 10 that is why it generates the error. I don't understand how to clear this problem. I wan't to create an array of sprites with 10 sprites in it and want to move them from one end to other and upon path finished I want them to get cleared from memory.
You should remove your entities, using update thread:
/* Removing entities can only be done safely on the UpdateThread.
* Doing it while updating/drawing can
* cause an exception with a suddenly missing entity.
* Alternatively, there is a possibility to run the TouchEvents on the UpdateThread by default, by doing:
* engineOptions.getTouchOptions().setRunOnUpdateThread(true);
* when creating the Engine in onLoadEngine(); */
this.runOnUpdateThread(new Runnable() {
#Override
public void run() {
/* Now it is save to remove the entity! */
yourEntity.detachSelf()
}
});