How to compare values from persistentObject in blackberry - java

I am developing a blackberry app in jdp plugin for eclipse.I want to store some values froma na array in the flash memory of blackberry device,& also check whether dat value already exits in the memory or not.I am giving the code which i tried to do with persistent object,bt somehw i am nt able to get want i want,plz modify the code where reqd
package com.firstBooks.series7.db;
import java.util.Random;
import com.firstBooks.series7.AppMain;
import com.firstBooks.series7.db.parser.XMLParser;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
public class DBMain {
public static String answer = "";
public static String selectedAnswer = "";
public static Question curQuestion;
public static int currQuesNumber = 1;
public static int correctAnswerCount = 0;
public static int totalNumofQuestions = 50 ;
static int quesNum[] = new int[20];
static int quesNumNew[];
static int quesCount = -1;
static int randomPosition;
static PersistentObject store;
static {
store = PersistentStore.getPersistentObject( 0xf9f8c7a20bc35c51L);
}
static{
initialize();
}
private static void initialize(){
Random rgen = new Random(); // Random number generator
//--- Initialize the array
for (int i=0; i<quesNum.length; i++) {
quesNum[i] = i;
}
//--- Shuffle by exchanging each element randomly
for (int i=0; i< quesNum.length; i++) {
randomPosition = rgen.nextInt(quesNum.length);
int temp = quesNum[i];
quesNum[i] = quesNum[randomPosition];
quesNum[randomPosition] = temp;
synchronized(store) {
if(quesNum[randomPosition]!=quesNum[i]){
System.out.println("...........i can do it............ ");
store.setContents(quesNum);
store.commit();
}
}
}
}
/*Changed the code to get a unique random number
* #author: Venu
*/
public static int getQuestionNumber() {
quesCount++;
if(quesCount < quesNum.length){
synchronized(store) {
int [] quesNumNew = (int[])store.getContents();
return quesNumNew[quesCount];
}
}
else{
initialize();
quesCount = -1;
return getQuestionNumber();
}
}
}

What is the problem you are encountering? Did you try to wrap the array in an object that implements Persistable interface? It is like the Serializable interface in j2se.
also see:
http://www.blackberry.com/developers/docs/4.5.0api/net/rim/device/api/util/Persistable.html
"A class must explicitly implement this interface for the system to persistently store instances of the class."

Related

why parallelizing the code of this implementation's genetic algorithm for the resolution of the tsp is much slower?

I am working on a university project on genetic algorithms to solve the TSP Problem and the teacher asked us to parallelize the optimize function. I tried to implement the optimize function in parallel and it works but it is much slower.
Tips?
You can find the original code here: https://github.com/Mentathiel/StackAbuseGeneticTravelingSalesman
public SalesmanGenome optimizeP() throws InterruptedException {
//Setting all the constant attributes that will not change during the optimizations
addInP.setGenerationSize(generationSize);
addInP.setGenomeSize(genomeSize);
addInP.setMutationRate(mutationRate);
addInP.setNumberOfCities(numberOfCities);
addInP.setStartingCity(startingCity);
addInP.setTravelPrices(travelPrices);
addInP myThreads[]= new addInP[N_THREADS];
List<SalesmanGenome> population = initialPopulation();//RandomPopulation
SalesmanGenome globalBestGenome = population.get(0);
for (int i = 0; i < maxIterations; i++) {
addInP.setPopulation(selection(population));
addInP.setCurrentGenerationSize(0);
addInP.setGeneration(new ArrayList<>());
for (int j = 0; j < N_THREADS; j++) {
myThreads[j]= new addInP();
myThreads[j].start();
myThreads[j].join();
}
population = addInP.getGeneration();//population generated each step
addInP.setCurrentGenerationSize(0); //Resetting current Generation Size
globalBestGenome = Collections.min(population);
if (globalBestGenome.getFitness() < targetFitness)
break;
}
return globalBestGenome;
}
This is the run function of my addInP class that extends thread
public void run()
{
while( getCurrentGenerationSize() < generationSize){
List<SalesmanGenome> parents = pickNRandomElements(population,2);
List<SalesmanGenome> children = crossover(parents);
children.set(0, mutate(children.get(0)));
children.set(1, mutate(children.get(1)));
generation.addAll(children);
setCurrentGenerationSize( getCurrentGenerationSize()+2);
}
}
These are the attributes of my addInP class and the methods to use the shared variable currentGenerationSize
private static List<SalesmanGenome> population;
private static volatile int currentGenerationSize ;
private static int generationSize;
private static int[][] travelPrices;
private static int startingCity;
private static int numberOfCities;
private static int genomeSize;
private static float mutationRate;
private static List<SalesmanGenome> generation;
public synchronized int getCurrentGenerationSize() {
return currentGenerationSize;
}
public synchronized static void setCurrentGenerationSize(int currentGenerationSize) {
addInP.currentGenerationSize = currentGenerationSize;
}

Tuple Java like tuple in OPL

I have coded and run my model in OPL, and I am trying to run code it in JAVA and run it again. As part of my Code (in OPL), I have defined a Tuple as follows:
int Y = asSet(1..7);
int k = asSet(1..42);
int G = asSet(1..2);
tuple SL {
int i;
int j;
float l;
}
{SL} SLs with i,j in Y=...; /* e.g. {<1,2,502>, <2,5,309>, <5,7,401>, <2,3,350>} */
Then, I have defined other arrays of:
int u[SLs][G]=...; /* e.g. u[<1,2,502>][1] = 50; u[<1,2,502>][2] = 83; u[<2,5,309>][1] = 75;*/
Now that I wanted to code it in Java, I have done it as follows, but I am not sure if I am right. I would appreciate if you could share your ideas.
import java.io.*;
import java.util.*;
public class Model {
public static int Y = 7;
public static int K = 42;
public static int G = 3;
public static int R = 2;
public class SL {
public int i; /* how say i is in Y*/
public int j; /* how say j is in Y*/
public int l;
List<SL> sl = new ArrayList<SL>();
Object[] SL1 = Sl.toArray();
int [][] u = new int [sL.length][G];
}
public static void Solve() {
/* How to instantiate SL1 and u[<i,j,l> in SL1][g in G] here and printout SL1:*/
}
}
and another class to run the solve() method:
public class SolverMethod {
public static void main(String[] args) {
Model.Solve();
}
}
I would appreciate if you help me out to fix and run the code.
Regards,
Bornay
You may make Map so that with tuple or object of SL you can generate unique number which can be used as a index in u var. say,
Map<SL,Integer> m;
int key=m.get(sl);
u[key][g]
and to instatiate SL1 you need to make object of SL since SL1 is not static.
SL sl=new SL();
sl.SL1 or sl.u
First create object of SL and point it's variables or methods.
Here is my implemented code below. I have made some changes.
import java.io.*;
import java.util.*;
public class Model {
public static int Y = 7;
public static int K = 42;
public static int G = 3;
public static int R = 2;
static Map<SL,Integer> m=new HashMap<>();
static List<SL> sL = new ArrayList<SL>();
static int[][] u;
static int index=0;
static public class SL {
public int i;
/* how say i is in Y*/
public int j;
/* how say j is in Y*/
public int l;
}
public static void Solve() {
/* How to instantiate SL1 and u[<i,j,l> in SL1][g in G] here and printout SL1:*/
for(int i=0;i<5;i++){
SL sl=new SL();
sl.i=i;sl.j=i+1;sl.l=i+2;
sL.add(sl);
m.put(sl, index++);
}
u=new int[m.size()][G];
for(SL s:sL){
for(int i=0;i<G;i++){
u[m.get(s)][i]=i+10;
}
}
for(SL s:sL){
for(int i=0;i<G;i++){
System.out.println(u[m.get(s)][i]);
}
}
}
public static void main(String[] arg){
Model.Solve();
}
}
Here I have made sL,m and u static because we need only single instance of it.

Problems with Static Internal Threads When Accessing Static Variables in External Classes

This problem has puzzled me for a long time, please help me,thanks.
This is my java code.
package com.concurrent.example;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* P683
*/
class CircularSet {
private int[] array;
private int len;
private int index = 0;
public CircularSet (int size) {
array = new int[size];
len = size;
for (int i = 0; i < size; i++) {
array[i] = -1;
}
}
public synchronized void add(int i ) {
array[index] = i;
index = ++index % len;
}
public synchronized boolean contains(int val) {
for (int i = 0; i < len; i++) {
if(array[i] == val) {
return true;
}
}
return false;
}
}
public class SerialNumberChecker {
private static final int SIZE = 10;
private static CircularSet serials = new CircularSet(1000);
private static ExecutorService exec = Executors.newCachedThreadPool();
private static int serial;
static class SerialChecker implements Runnable {
#Override
public void run() {
while(true) {
//int serial;
synchronized (serials) {
serial = SerialNumberGenerator.nextSerialNumber();
}
if (serials.contains(serial)) {
System.out.println("Duplicate: " + serial);
System.exit(0);
}
System.out.println(serial);
serials.add(serial);
}
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < SIZE; i++) {
exec.execute(new SerialChecker());
if (args.length > 0) {
TimeUnit.SECONDS.sleep(new Integer(args[0]));
System.out.println("No duplicates detected");
System.exit(0);
}
}
}
}
It can stop, but when i uncomment //int serial;The result is different,it can't stop.Why does this temporary variable have a different result than the static variable of the external class. Is this the reason of using a thread?
The code of SerialNumberGenerator:
public class SerialNumberGenerator {
private static volatile int serialNumber = 0;
public static int nextSerialNumber() {
return serialNumber ++; //Not thread-safe
}
}
With private static int serial, all SerialNumberCheckers share the same serial. For example:
Thread1 set serial = 1
Thread2 set serial = 2
Thread1 put 2 into CircularSet.
Thread2 found it duplicate and exit.
However, if you declare another int serial in the run method, It will shadow the private static int serial, which means all threads has its own serial and they will assign & check it. Since the generation of serial is in the synchronized block, there will be no duplicates.

Dealing cards in Java

I'm super new to programming so excuse me if my code is hard to understand. I was assigned to program a game to deal a card to the user and being it is the top card. I already have my card class made. I just need to know if I'm doing this correctly. It says build successful, but doesn't show anything. Please help!
package deck;
import java.util.*;
/**
*
* #author useradmin
*/
// Write a description of class Deck here.
public class Deck {
private Card[] theCards;
private int deal;
public Deck() {
theCards = new Card[52];
deal = 52;
this.fill();
//fill();
}
public int deal() {
return deal;
}
public Card getCard() {
Card a = null;
a = theCards[deal-1];
deal--;
return a;
}
public String toString()
{
String deckString = "New deck shuffled\n";
for(int i = 1; i <= 1; i++)
{
deckString += theCards[i].toString() + "\n";
}
return deckString;
}
public void shuffleCards() {
Random random = new Random();
Card temp;
int topCard;
for(int i = 0; i<30; i++){
topCard = random.nextInt(deal);
}
}
private void fill() {
int i, j;
int index = 0;
for(i = 0; i <4; i++) {
for(j = 1; j < 14; j++){
theCards[index] = new Card(i, j);
index++;
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
{
}
}
The public static void main(String[] args) method is the entry point for your program. When you run your program, this is the first method that gets called. Yours is empty, so nothing will happen.
Solution
Make a new class and call it Application.
Cut the public static void main(String[] args){} method from your Deck class and paste it into your new Application class.
Inside the main() you will need to put some code! I suggest creating a Deck object and then printing the contents of the deck using your toString() method, just so that you can see that everything is working.
Your new class should look like this:
public class Application {
//Main method (Entry point for program)
public static void main(String[] args) {
Deck myDeck = new Deck(); //Create Deck
System.out.println(myDeck.toString()); //Print contents of Deck
}
}
Make sure that you have removed the main() method from your Deck class .
Hope that helps you out. :)

Using a method to add an object to a class

This feels like a very obvious question but I can't figure out how to do it. I have a class called Hive and I want to add a hive object to my Garden class using an addHive method. I know it is going to be something very simple but I can't figure it out =/
My Garden class:
import java.util.ArrayList;
import java.util.Random;
public class Garden {
ArrayList<Flower> flowerbed = new ArrayList<Flower>();
Hive hive = null;
public void anotherDay(){
int size = flowerbed.size();
for(int i = 0; i < size; i++) {
Flower flower = flowerbed.get(i);
flower.grow();
}
}
public void addHive(Hive hive){
}
public void addFlower(Flower flower){
flowerbed.add(flower);
}
public Flower getFlower(int fi){
if(fi < flowerbed.size()){
return flowerbed.get(fi);
}else{
return null;
}
}
public Integer getRandomInteger(Integer max)
{
Random rand = new Random();
int number;
number = rand.nextInt(max) + 1;
return new Integer(number);
}
public Flower findFlower(){
return getFlower(getRandomInteger(flowerbed.size()));
}
public int size(){
return flowerbed.size();
}
}
I have also used what I feel is a rather untidy roundabout method for getting a random flower from my arraylist of flowers- can anyone suggest a better method or is this as good as it gets?
if you need only one hive, use:
public void setHive(Hive hive){
this.hive = hive;
}
If you need multiple hive, do exact the same as with flower. Including creating the list.
ArrayList<Hive> hives = new ArrayList<Hive>();
public void addHive(Hive hive){
hives.add(hive);
}

Categories

Resources