Incremental score calculator Optaplanner - java

I am trying to implement an IncrementalScoreCalculator for the current Kaggle TSP challenge. So, I have been looking at the docs and I have succesfully implemented an EasyScoreCalacultor that returns a HardSoftScore where the hardscore is the number of locations for which every 10th step is not a prime.
what I have looks as follows
#Override
public void beforeVariableChanged(Object o, String s) {
if (o instanceof Domicile) {
return;
}
switch (s) {
case "previousStandstill":
retract((Visit) o);
break;
case "position":
retractPosition((Visit) o);
break;
default:
throw new IllegalArgumentException("Unrecognized variable change " + s);
}
}
#Override
public void afterVariableChanged(Object o, String s) {
if (o instanceof Domicile) {
return;
}
switch (s) {
case "previousStandstill":
insert((Visit) o);
break;
case "position":
insertPosition((Visit) o);
break;
default:
throw new IllegalArgumentException("Unrecognized variable change " + s);
}
where position is a shadow variable.
retractPosition and insertPosition look as follows:
private void retractPosition(Visit visit) {
Integer position = visit.getPosition();
if (position != null) {
if (visit.getLocation().getId() % 10 == 0) {
if (isPrime(position)) {
hardscore--;
}
}
}
}
private void insertPosition(Visit visit) {
Integer position = visit.getPosition();
if (position!= null) {
if (visit.getLocation().getId() % 10 == 0) {
if (isPrime(position)) {
hardscore++;
}
}
}
}
But this somehow does not seem to work correctly and I cannot seem to wrap my head around it. Any help is deeply appreciated.

Related

Java - Error Cannot cast from HashBasedTable<Object,Object,Object> to Table<UUID,PotionEffectType,PotionEffect>

I'm having this errors:
1) Cannot cast from HashBasedTable to Table .
This is the code in error: In the line:
this.restores = **(Table<UUID, PotionEffectType, PotionEffect>)HashBasedTable.create()**;
2) The method put(UUID, PotionEffectType, PotionEffect) in the type Table is not applicable for the arguments (Object, Object, Object)
This is the code in error: In the line:
this.restores.**put**((Object)player.getUniqueId(), (Object)active.getType(), (Object)active);
public class MageRestorer implements Listener
{
private final Table<UUID, PotionEffectType, PotionEffect> restores;
public MageRestorer(final HCF plugin) {
this.restores = (Table<UUID, PotionEffectType, PotionEffect>)HashBasedTable.create();
plugin.getServer().getPluginManager().registerEvents((Listener)this, (Plugin)plugin);
}
#EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPvpClassUnequip(final PvpClassUnequipEvent event) {
this.restores.rowKeySet().remove(event.getPlayer().getUniqueId());
}
public void setRestoreEffect(final Player player, final PotionEffect effect) {
boolean shouldCancel = true;
final Collection<PotionEffect> activeList = (Collection<PotionEffect>)player.getActivePotionEffects();
for (final PotionEffect active : activeList) {
if (active.getType().equals((Object)effect.getType())) {
if (effect.getAmplifier() < active.getAmplifier()) {
return;
}
if (effect.getAmplifier() == active.getAmplifier() && effect.getDuration() < active.getDuration()) {
return;
}
this.restores.put((Object)player.getUniqueId(), (Object)active.getType(), (Object)active);
shouldCancel = false;
}
}
player.addPotionEffect(effect, true);
if (shouldCancel && effect.getDuration() > 100 && effect.getDuration() < MageClass.DEFAULT_MAX_DURATION) {
this.restores.remove((Object)player.getUniqueId(), (Object)effect.getType());
}
}
#EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPotionEffectExpire(final PotionEffectExpiresEvent event) {
final LivingEntity livingEntity = event.getEntity();
if (livingEntity instanceof Player) {
final Player player = (Player)livingEntity;
final PotionEffect previous = (PotionEffect)this.restores.remove((Object)player.getUniqueId(), (Object)event.getEffect().getType());
if (previous != null) {
new BukkitRunnable() {
public void run() {
player.addPotionEffect(previous, true);
}
}.runTask((Plugin)HCF.getPlugin());
}
}
}
}
I dont know fix this. This is a clase of bukkit
For the first error, can we see the stack trace? Also, why do you need to cast it? You can store it as a Table; a cast is unnecessary.
For the second error, remove the casts to Object. Simply leave them as their actual types. this.restores.put(player.getUniqueId(), active.getType(), active);
This should help you get through the issue.

Linkedlist remove method erroe [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 4 years ago.
when i try to remove element there is an error, i have uploaded the error in the image section. any help to fix? of any other way to get the code fixed and working smoothly and it it works while deleting the middle element not the first or second
duplication issue ,fixed using iterator. hatsooff to stack overflow .
all good
import java.util.*;
public class EarthquakeList {
private ArrayList<EarthquakeNode> records;
public EarthquakeList() {
records = new ArrayList<EarthquakeNode>();
}
public boolean isempty() {
return true;
}
public void add(String EarthquakeLo,String EarthquakeDt, double EarthquakeSgth, int EarthquakeDu) {
EarthquakeNode en = new EarthquakeNode(EarthquakeLo, EarthquakeDt, EarthquakeSgth, EarthquakeDu);
records.add(en);
}
public boolean remove(String EarthquakeLo,String EarthquakeDt) {
boolean flag= false;
for(EarthquakeNode earthquake: records)
{
if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
{
if(earthquake.getDate().equals(EarthquakeDt))
{
records.remove(earthquake);
flag=true;
}
}
}
return flag;
}
public EarthquakeNode search(String EarthquakeLo,String EarthquakeDt) {
EarthquakeNode node= null;
for(EarthquakeNode earthquake: records)
{
if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
{
if(earthquake.getDate().equals(EarthquakeDt))
{
node=earthquake;
}
}
}
return node;
}
public boolean clear() {
int count=records.size();
for(EarthquakeNode earthquake: records)
{
count=count-1;
records.remove(earthquake);
}
if(count==0)
{
System.out.println("already empty");
return false;}
else
System.out.println("every thing is removed");
return true;
}
public boolean isempty(String EarthquakeLo,String EarthquakeDt) {
boolean flag= false;
for(EarthquakeNode earthquake: records)
{
if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
{
if(earthquake.getDate().equals(EarthquakeDt))
{
flag=true;
}
}
}
return flag;
}
public void print() {
for(EarthquakeNode earthquake: records)
{
System.out.println( earthquake.getLocation() +" - "
+ earthquake.getDate()+ " - "
+ earthquake.getStrength() + " on rector scale"+
"-" + earthquake.getDuration() + "mins");
}
}
}
You need to use an Iterator to safely remove from a collection while iterating over it.
public boolean remove(String earthquakeLo, String earthquakeDt) {
boolean flag= false;
Iterator<EarthquakeNode> iterator = records.iterator();
while(iterator.hasNext()) {
EarthquakeNode earthquake = iterator.next();
if(earthquake.getLocation().equalsIgnoreCase(earthquakeLo)) {
if(earthquake.getDate().equals(earthquakeDt)) {
iterator.remove();
flag=true;
}
}
}
return flag;
}

Making string as switch case

In switch case there is an error -> RUNNING, ABORTED and READY cannot be resolved to a variables. What can i do to make it work? Tried enum but it really isn't working.
Main class which i cannot edit:
public class Main {
public static void main(String[] args) throws InterruptedException {
StringTask task = new StringTask("A", 70000);
System.out.println("Task " + task.getState());
task.start();
if (args.length > 0 && args[0].equals("abort")) {
/*<- code that interrupts task after 1 sec and start a new thread
*/
}
while (!task.isDone()) {
Thread.sleep(500);
switch(task.getState()) {
//error case RUNNING: System.out.print("R."); break;
//error case ABORTED: System.out.println(" ... aborted."); break;
//error case READY: System.out.println(" ... ready."); break;
default: System.out.println("unknown state");
}
}
System.out.println("Task " + task.getState());
System.out.println(task.getResult().length());
}
}
StringTask class:
public class StringTask implements Runnable {
String string;
String result = "";
String status = "";
int x;
boolean end = false;
boolean done = false;
public StringTask(String string, int x) {
this.string = string;
this.x = x;
this.status = "CREATED";
}
public void start() {
Thread thread = new Thread(this);
thread.start();
}
public void run() {
this.status = "RUNNING";
synchronized (this.result) {
try {
for (int i = 0; i < x; i++) {
result += string;
}
this.status = "READY";
this.done = true;
} catch (Exception ex) {
this.status = "ABORTED";
this.done = false;
}
}
}
public void abort() {
this.end = true;
this.done = true;
this.status = "ABORTED";
Thread.interrupted();
}
public StringTask() {
this.status = "ABORTED";
}
public String getState() {
return this.status;
}
public boolean isDone() {
return this.done;
}
public String getResult() {
return this.result;
}
}
I just noticed that you're not allowed to edit the main class. To ameliorate your issue, you'll have to make an enum to store the status:
public enum Status {
RUNNING, ABORTED, READY
}
After changing StringTask#getState to return Status, you can use your switch statement:
switch (task.getState()) {
case RUNNING:
System.out.print("R.");
break;
case ABORTED:
System.out.println(" ... aborted.");
break;
case READY:
System.out.println(" ... ready.");
break;
default:
System.out.println("unknown state");
}
Have you tried to use Strings in switch case?
"RUNNING" instead of RUNNING etc?
It seems your assignment is to get the main class to work with Enum, to do this you have to change the StringTask class. Change the type of status to State
State status;
public StringTask(String string, int x) {
this.string = string;
this.x = x;
this.status = State.CREATED;
}
...
public State getState() {
return this.status;
}
...
enum State {
RUNNING, ABORTED, READY
}
Then your switch should work fine
switch(task.getState()) {
case RUNNING:
System.out.print("R.");
break;
case ABORTED:
System.out.println(" ... aborted.");
break;
case READY:
System.out.println(" ... ready.");
break;
default:
System.out.println("unknown state");
}

Are expected values for Eclipse RCP property testers always String?

In the eclipse documentation I've seen the following snippet (http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fcore%2Fexpressions%2FPropertyTester.html):
<propertyTester
namespace="org.eclipse.jdt.core"
id="org.eclipse.jdt.core.IPackageFragmentTester"
properties="isDefaultPackage"
type="org.eclipse.jdt.core.IPackageFragment"
class="org.eclipse.demo.MyPackageFragmentTester">
</propertyTester>
with the following property tester implementation:
public class MyPackageFragmentTester extends PropertyTester {
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
IPackageFragment fragment= (IPackageFragment)receiver;
if ("isDefaultPackage".equals(property)) {
return expectedValue == null
? fragment.isDefaultPackage()
: fragment.isDefaultPackage() == ((Boolean)expectedValue).booleanValue();
}
Assert.isTrue(false);
return false;
}
}
I'm a bit wondering about the ((Boolean)expectedValue) part - because the expected value is give in the <test property="..."/> tag as string:
<test property="org.eclipse.jdt.core.isDefaultPackage" value="true" />
And whenever I implemented a property tester the value was given as a String.
So my question is: Is it possible to have an expected value that is not a String? According to the Eclipse RCP documentation it should be... but how!?
It is not made very clear but the expected value can be a String or a Boolean, Float (!) or Integer.
The code that works out which is in org.eclipse.core.internal.expressions.Expressions:
public static Object convertArgument(String arg) throws CoreException {
if (arg == null) {
return null;
} else if (arg.length() == 0) {
return arg;
} else if (arg.charAt(0) == '\'' && arg.charAt(arg.length() - 1) == '\'') {
return unEscapeString(arg.substring(1, arg.length() - 1));
} else if ("true".equals(arg)) { //$NON-NLS-1$
return Boolean.TRUE;
} else if ("false".equals(arg)) { //$NON-NLS-1$
return Boolean.FALSE;
} else if (arg.indexOf('.') != -1) {
try {
return Float.valueOf(arg);
} catch (NumberFormatException e) {
return arg;
}
} else {
try {
return Integer.valueOf(arg);
} catch (NumberFormatException e) {
return arg;
}
}
}
So it is a String unless it is true, false or a number.

ArrayList emptying itself?

Follow the path of eventList please. While it stores the proper objects as it's supposed to initially, it empties itself as soon as it enters MouseClicked(). There is a driver used to run initialize() in another class. I just can't seem to get eventList to hold its information.
public class Adventure_Chapter1 implements MouseListener
{
boolean success = true;
ArrayList<StoryEvent> eventList = new ArrayList<StoryEvent>();
public void initiliaze() throws FontFormatException, IOException
{
load(); // loads StoryEvents
play(0);
System.out.println("Init() eventList size: " + eventList.size());
}
private void load()
{
int x = 0;
switch(x)
{
case 0:
StoryEvent txt0 = new StoryEvent(parameters);
eventList.add(txt0);
case 1:
StoryEvent assassinStart = new StoryEvent(parameters);
eventList.add(assassinStart);
}
}
public void updatePlayer()
{
System.out.println("Player Updated ");
}
public void play(int c) // to be implemented
{
storyLineDisplay.setText("testing");
System.out.println("Play() eventList size:" + eventList.size());
//int c would typically change my buttons' options next to them. but for now it
is irrelevant.
}
public void mouseClicked(MouseEvent e)
{
if (e.getSource().equals(buttonOne));
{
if (success == true)
{
updatePlayer();
System.out.println("MouseClicked eventList size: " + eventList.size());
play(1);
}
else
{
updatePlayer();
currentCharacter.add(eventList.get(choice));
choice = currentCharacter.get(currentCharacter.size() -1).getFail1();
play(1);
}
}
}
Output is here:
Play() eventList size:2
Init() eventList size: 2
Player Updated
MouseClicked eventList size: 0
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Adventure_Chapter1.mouseClicked(Adventure_Chapter1.java:277)
insert further lines of errors here.
You should break your switch statements.
if (success == true)
can be replaced by
if (success)
if (e.getSource().equals(buttonOne));
must be replaced by
if (e.getSource().equals(buttonOne))
put all of the involved code if you want help with debugging, we are not mind readers and guessers. Obviously there are missing code.
Edited
Can we see the code for StoryEvent. Are you touching the evenList list there
? Otherwise I don't understand how you get two elements in your
evenList, to begin with.
public void mouseClicked(MouseEvent e)
{
if (e.getSource().equals(buttonOne));
{
if (success == true)
{
updatePlayer();
System.out.println("MouseClicked eventList size: " + eventList.size());
play(choice);
}
else
{
updatePlayer();
currentCharacter.add(eventList.get(choice));
choice = currentCharacter.get(currentCharacter.size() -1).getFail1();
}
}
}
but what is "choice" ?

Categories