views:

79

answers:

2

i want to generate numbers frm an array randomly,& every number should be unique as well,i am giving the piece of code.Kindly help me out,& plz dnt suggest for arraylist,bcoz i am building for blackberry app,& blackberry api doesnt support arraylist or collection or hashset,so kindly suggest me with array only in dis piece of code.

 Random rgen = new Random();  // Random number generator

    //--- Initialize the array 
    for (int i=0; i<20; i++) {
        quesNum[i] = i;
    }

//--- Shuffle by exchanging each element randomly

   for (int i=0; i< 20; i++) {
        int randomPosition = rgen.nextInt(20);

        int temp = quesNum[i];

        quesNum[i] = quesNum[randomPosition];

        quesNum[randomPosition] = temp;


    }
+4  A: 

Your code is nearly okay as it is, but you should use a modified Fisher-Yates shuffle instead:

for (int i=0; i < 20; i++) {
    // Partition the array into "shuffled" at the start
    // and "unshuffled" at the end. Select a random
    // unshuffled one, and swap it with the one at the
    // border of shuffled/unshuffled
    int randomPosition = i + rgen.nextInt(20 - i);
    int temp = quesNum[i];
    quesNum[i] = quesNum[randomPosition];
    quesNum[randomPosition] = temp;
}

It wasn't really clear from your question what you were asking for - validation that you were thinking along the right lines? If this answer doesn't help you, please clarify the question (ideally without text-speak abbreviations).

Jon Skeet
A: 

Sir i am developing a balckberry app,there r two version full & lite,with two xml databases.Full database contain 350 question,& in each test dere r 50 questions displayed.Whereas in lite version only 20 questions are there & each test comprises of 10 questions.i want to store the question for each version in persitentobject,so dat after appearing for a particular test,if the user exits the app,den later he comes back,at that time the values which r stored will verify that the questions generated this time for the next test is nt same as the earlier one,i want to exhaust all the qustion in the database untill all the test hav ben taken,for full version 7 test(350/50) & for lite version 2 test (20/10).I am giving the sample codes,kindly tell me in which page i hav 2 use persistantobject to persistantly store the question into the flash memory of balckberry,& what should be the logic to verify whether the questions generated for each test is unique & random.I hav used persistentobject in Dmain page,bt i am nt sure whether it is the correct place,kindly help me

AppMain Page

//#preprocess package com.firstBooks.series7;

import net.rim.device.api.ui.UiApplication;

import com.firstBooks.series7.ui.screens.HomeScreen;

public class AppMain extends UiApplication implements AppConfig{

public static String _xmlFileName;  
public static boolean _Lite;    
public static int _totalNumofQuestions;

public static void initialize(){
     //#ifndef FULL  
       /* 
       //#endif 
          _xmlFileName = "/res/Series7_FULL.xml";
          _totalNumofQuestions = 50;
          _Lite = false;
       //#ifndef FULL 
       */  
    //#endif 

    //#ifndef LITE  
       /* 
       //#endif 
         _xmlFileName = "/res/Series7_LITE.xml";
         _totalNumofQuestions = 10;
         _Lite = true;
       //#ifndef LITE 
       */  
     //#endif 
}

private AppMain() {
    initialize();
    pushScreen(new HomeScreen());
}

public static void main(String args[]) {
    new AppMain().enterEventDispatcher();
}

}

XMLParser Page

package com.firstBooks.series7.db.parser;

import java.io.IOException; import java.io.InputStream; import java.util.Vector;

import net.rim.device.api.xml.parsers.DocumentBuilder; import net.rim.device.api.xml.parsers.DocumentBuilderFactory; import net.rim.device.api.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;

import com.firstBooks.series7.AppMain; import com.firstBooks.series7.db.Question;

public class XMLParser {

private Document document;
public static Vector questionList;

public XMLParser() {                 
    questionList = new Vector();
}

public void parseXMl() throws SAXException, IOException,
        ParserConfigurationException {

    // Build a document based on the XML file.
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = getClass().getResourceAsStream(AppMain._xmlFileName);

    document = builder.parse(inputStream);
}

public void parseDocument() {
    Element element = document.getDocumentElement();

    NodeList nl = element.getElementsByTagName("question");

    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element ele = (Element) nl.item(i);
            Question question = getQuestions(ele);
            questionList.addElement(question);
        }
    }
}

private Question getQuestions(Element element) {

    String title = getTextValue(element, "title");
    String choice1 = getTextValue(element, "choice1");
    String choice2 = getTextValue(element, "choice2");
    String choice3 = getTextValue(element, "choice3");
    String choice4 = getTextValue(element, "choice4");
    String answer = getTextValue(element, "answer");
    String rationale = getTextValue(element, "rationale");

    Question Questions = new Question(title, choice1,
            choice2, choice3, choice4, answer, rationale);

    return Questions;
}

private String getTextValue(Element ele, String tagName) {
    String textVal = null;
    NodeList nl = ele.getElementsByTagName(tagName);
    if (nl != null && nl.getLength() > 0) {
        Element el = (Element) nl.item(0);
        textVal = el.getFirstChild().getNodeValue();
    }

    return textVal;
}

}

DBmain Page

package com.firstBooks.series7.db;

import java.util.Random; import net.rim.device.api.system.PersistentObject; import net.rim.device.api.system.PersistentStore;

import com.firstBooks.series7.AppMain; import com.firstBooks.series7.db.parser.XMLParser;

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 = AppMain._totalNumofQuestions ;

static int quesNum[] = new int[XMLParser.questionList.size()];
static int quesCount = -1;
static int quesNumNew[];
static PersistentObject store;
//static {
//store = PersistentStore.getPersistentObject( 0x827e7fde7a825309L );

//synchronized(store) {
    //store.setContents(quesNum);
    //store.commit();
    //}
//}
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;
    }

    store = PersistentStore.getPersistentObject( 0x827e7fde7a825309L );

    //--- Shuffle by exchanging each element randomly
    for (int i=0; i< quesNum.length; i++) {
        int randomPosition = i + rgen.nextInt(quesNum.length-i);
        //System.out.println("The value of RANDOMPOSITION is:"+randomPosition);
        int temp = quesNum[i];
        //System.out.println("The value of TEMP is:"+temp);
        quesNum[i] = quesNum[randomPosition];
        System.out.println("The value of QUESNUM is:"+quesNum[i]);
        quesNum[randomPosition] = temp;
        System.out.println("The value of NEWQUESNUM is:"+quesNum[randomPosition]);
        synchronized(store) {
            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){

        return quesNum[quesCount];

     }
    else{ 
       initialize();
       quesCount = -1;
       return getQuestionNumber();
    }
}

}

TestScreen Page

package com.firstBooks.series7.ui.screens;

import net.rim.device.api.ui.Field; import net.rim.device.api.ui.FieldChangeListener; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.Menu; import net.rim.device.api.ui.component.NullField; import net.rim.device.api.ui.container.HorizontalFieldManager; import net.rim.device.api.ui.container.VerticalFieldManager;

import com.firstBooks.series7.AppConfig; import com.firstBooks.series7.db.DBMain; import com.firstBooks.series7.db.Question; import com.firstBooks.series7.db.parser.XMLParser; import com.firstBooks.series7.ui.UIinitialize; import com.firstBooks.series7.ui.managers.TopManager; import com.vensi.api.ImgButtonField;

public class TestScreen extends ScreenManager implements AppConfig {

TopManager topManager = null;
VerticalFieldManager middleManager = null;
HorizontalFieldManager manager = null;
ImgButtonField A, B, C, D;
int quesNumber;
LabelField question1, blank, choice1Label, choice2Label, choice3Label,
        choice4Label;
FieldChangeListener checkAnswerListenerA, checkAnswerListenerB,
        checkAnswerListenerC, checkAnswerListenerD;

public TestScreen() {
    super();
    drawScreen();
}

public void drawScreen() {

    topManager = new TopManager(newTestButton, 0);

    middleManager = new VerticalFieldManager(
            VerticalFieldManager.VERTICAL_SCROLL
                    | VerticalFieldManager.VERTICAL_SCROLLBAR
                    | VerticalFieldManager.USE_ALL_WIDTH
                    | Field.FIELD_HCENTER) {
        protected void sublayout(int maxWidth, int maxHeight) {
            // maxwidth reduced by 15 to get padding along the edges
            super.sublayout(maxWidth - 15, maxHeight - 10);

            if (UIinitialize.displayType == Device_Storm) {
                setExtent(maxWidth - 15, 347);
            } else if (UIinitialize.displayType == Device_Tour) {
                setExtent(maxWidth - 15, 263);
            } else if (UIinitialize.displayType == Device_Curve) {
                setExtent(maxWidth - 10, 165);
            }

        }
    };

    A = new ImgButtonField(buttonABkGrndDown, buttonABkGrnd,
            Field.FOCUSABLE | Field.FIELD_HCENTER);
    B = new ImgButtonField(buttonBBkGrndDown, buttonBBkGrnd,
            Field.FOCUSABLE | Field.FIELD_HCENTER);
    C = new ImgButtonField(buttonCBkGrndDown, buttonCBkGrnd,
            Field.FOCUSABLE | Field.FIELD_HCENTER);
    D = new ImgButtonField(buttonDBkGrndDown, buttonDBkGrnd,
            Field.FOCUSABLE | Field.FIELD_HCENTER);


        manager = new HorizontalFieldManager(Manager.NO_HORIZONTAL_SCROLL
            | Manager.NO_VERTICAL_SCROLL | Field.USE_ALL_WIDTH
            | Field.USE_ALL_HEIGHT) {
        protected void sublayout(int maxWidth, int maxHeight) {

             if (UIinitialize.displayType == Device_Storm) {
                layoutChild(A, buttonABkGrnd.getWidth(), buttonABkGrnd
                        .getHeight());
                setPositionChild(A, 25, 9);

                layoutChild(B, buttonBBkGrnd.getWidth(), buttonBBkGrnd
                        .getHeight());
                setPositionChild(B, 115, 9);

                layoutChild(C, buttonCBkGrnd.getWidth(), buttonCBkGrnd
                        .getHeight());
                setPositionChild(C, 205, 9);

                layoutChild(D, buttonDBkGrnd.getWidth(), buttonDBkGrnd
                        .getHeight());
                setPositionChild(D, 295, 9);

            } else if (UIinitialize.displayType == Device_Tour) {
                layoutChild(A, buttonABkGrnd.getWidth(), buttonABkGrnd
                        .getHeight());
                setPositionChild(A, 41, 9);

                layoutChild(B, buttonBBkGrnd.getWidth(), buttonBBkGrnd
                        .getHeight());
                setPositionChild(B, 161, 9);

                layoutChild(C, buttonCBkGrnd.getWidth(), buttonCBkGrnd
                        .getHeight());
                setPositionChild(C, 281, 9);

                layoutChild(D, buttonDBkGrnd.getWidth(), buttonDBkGrnd
                        .getHeight());
                setPositionChild(D, 401, 9);
            } else if (UIinitialize.displayType == Device_Curve) {
                layoutChild(A, buttonABkGrnd.getWidth(), buttonABkGrnd
                        .getHeight());
                setPositionChild(A, 33, 19);

                layoutChild(B, buttonBBkGrnd.getWidth(), buttonBBkGrnd
                        .getHeight());
                setPositionChild(B, 107, 19);

                layoutChild(C, buttonCBkGrnd.getWidth(), buttonCBkGrnd
                        .getHeight());
                setPositionChild(C, 182, 19);

                layoutChild(D, buttonDBkGrnd.getWidth(), buttonDBkGrnd
                        .getHeight());
                setPositionChild(D, 257, 19);
            }

            setExtent(maxWidth, maxHeight);
        }

        protected void paint(Graphics g) {
            super.paint(g);
        }
    };

    String title = "";

    quesNumber = DBMain.getQuestionNumber();
    System.out.println("the value of QUESNUMBER IS:"+quesNumber);
    DBMain.curQuestion = (Question) XMLParser.questionList
            .elementAt(quesNumber);
    title = DBMain.curQuestion.getTitle();
    System.out.println("the value of TITLE IS:"+title);
    String BlankSpace = "  ";
    String choice1 = "A.  " + DBMain.curQuestion.getChoice1() + "\n" + "  ";
    String choice2 = "B.  " + DBMain.curQuestion.getChoice2() + "\n" + "  ";
    String choice3 = "C.  " + DBMain.curQuestion.getChoice3() + "\n" + "  ";
    String choice4 = "D.  " + DBMain.curQuestion.getChoice4() + "\n" + "  ";

    question1 = new LabelField(title);
    question1.setFont(myFontBoldSmall());

    blank = new LabelField(BlankSpace);
    blank.setFont(myFontBoldSmall());

    choice1Label = new LabelField(choice1);
    choice1Label.setFont(myFontPlainSmall());
    choice2Label = new LabelField(choice2);
    choice2Label.setFont(myFontPlainSmall());
    choice3Label = new LabelField(choice3);
    choice3Label.setFont(myFontPlainSmall());
    choice4Label = new LabelField(choice4);
    choice4Label.setFont(myFontPlainSmall());

    DBMain.answer = DBMain.curQuestion.getAnswer();

    checkAnswerListenerA = new FieldChangeListener() {

        public void fieldChanged(Field field, int context) {
            DBMain.selectedAnswer = "A";
            UiApplication.getUiApplication().pushScreen(new AnswerScreen());
            UiApplication.getUiApplication().popScreen(getScreen());

        }
    };
    A.setChangeListener(checkAnswerListenerA);
    checkAnswerListenerB = new FieldChangeListener() {

        public void fieldChanged(Field field, int context) {
            DBMain.selectedAnswer = "B";
            UiApplication.getUiApplication().pushScreen(new AnswerScreen());
            UiApplication.getUiApplication().popScreen(getScreen());
        }
    };
    B.setChangeListener(checkAnswerListenerB);

    checkAnswerListenerC = new FieldChangeListener() {

        public void fieldChanged(Field field, int context) {
            DBMain.selectedAnswer = "C";
            UiApplication.getUiApplication().pushScreen(new AnswerScreen());
            UiApplication.getUiApplication().popScreen(getScreen());
        }
    };
    C.setChangeListener(checkAnswerListenerC);

    checkAnswerListenerD = new FieldChangeListener() {

        public void fieldChanged(Field field, int context) {
            DBMain.selectedAnswer = "D";
            UiApplication.getUiApplication().pushScreen(new AnswerScreen());
            UiApplication.getUiApplication().popScreen(getScreen());
        }
    };
    D.setChangeListener(checkAnswerListenerD);
    /*A.setChangeListener(checkAnswerListenerA);
    B.setChangeListener(checkAnswerListenerB);
    C.setChangeListener(checkAnswerListenerC);
    D.setChangeListener(checkAnswerListenerD);*/

    manager.add(new NullField(Field.FOCUSABLE));
    manager.add(A);
    manager.add(B);
    manager.add(C);
    manager.add(D);
    manager.add(new NullField(Field.FOCUSABLE));

    middleManager.add(question1);
    middleManager.add(new NullField(Field.FOCUSABLE));
    middleManager.add(blank);
    middleManager.add(choice1Label);
    middleManager.add(new NullField(Field.FOCUSABLE));
    middleManager.add(choice2Label);
    middleManager.add(new NullField(Field.FOCUSABLE));
    middleManager.add(choice3Label);
    middleManager.add(new NullField(Field.FOCUSABLE));
    middleManager.add(choice4Label);

    add(topManager);
    add(middleManager);
    add(manager);
}

protected void makeMenu(Menu menu, int instance) {
    menu.add(new MenuItem("A", 20, 10) {
        public void run() {
            answerMenu("A");
        }
    });
    menu.add(new MenuItem("B", 30, 20) {
        public void run() {
            answerMenu("B");
        }
    });
    menu.add(new MenuItem("C", 40, 30) {
        public void run() {
            answerMenu("C");
        }
    });
    menu.add(new MenuItem("D", 50, 40) {
        public void run() {
            answerMenu("D");
        }
    });
    super.makeMenu(menu, instance);
}

private void answerMenu(String answer) {
    DBMain.selectedAnswer = answer;

    UiApplication.getUiApplication().pushScreen(new AnswerScreen());
    UiApplication.getUiApplication().popScreen(getScreen());

}

protected boolean keyChar(char character, int status, int time) {
    if (character == 'A' || character == 'a')
        DBMain.selectedAnswer = "A";
    else if (character == 'B' || character == 'b')
        DBMain.selectedAnswer = "B";
    else if (character == 'C' || character == 'c')
        DBMain.selectedAnswer = "C";
    else if (character == 'D' || character == 'd')
        DBMain.selectedAnswer = "D";
    else
        return super.keyChar(character, status, time);

    UiApplication.getUiApplication().pushScreen(new AnswerScreen());
    UiApplication.getUiApplication().popScreen(getScreen());
    return true;
}

protected void paint(Graphics g) {
    g.drawBitmap(0, 0, UIinitialize.screenWidth, UIinitialize.screenHeight,
            backgroundBitmap, 0, 0);
    subpaint(g);
    TestScreen.this.invalidate();
}

}

Arunabha Dutta Choudhury
-1 - this is not an answer
Stephen C