Substring Algorithm

Hi, I have been given a practice problem involving dynamic programming and i would appreciate some help
If you are given 2 strings, str1 and str2, find the longest possible common substring.
So, for example, if given the strings 'rebublican' and 'democrat' (sans quotes), the longest common substring would be 'eca'
r[b]epubli[b]can
d[b]emo[b]cr[b]at
As you can see, the letters do not have to be adjacent but they must be in order
Can someone just give me a push in the right direction? Just ell me how to go about to solve this problem with dynamic programming (pseudocode, maybe)
Please do not just give me the answer (although you probably wont already)

Try to solve the following (imho easier) problem using dynamic programming. It might give you some ideas:
Given a sequence of n integers. Find the longest increasing subsequence.
Example:
6, 1, 3, 7, 4, 9, 5, 0, 44, 3

Similar Messages

  • Application registration algorithm

    I'm writing a small shareware app that I would ideally like people to register. This is the classic, if they send in the registration code 'xxxxxx', then I can send the unlock code 'YYYYY' situation.
    Three criteria:
    1) I would like the registrtaion code xxxxx to be unique. I am toying with the idea of storing the date in millisecs of when the app was first run on the system. If anyone has any better suggestions, I would love to hear them.
    2) I would really like to have the algorithm myself. i.e. I don't plan to make enough off of this to be worth purchasing a library.
    3) This does not need to be incredibly secure. Just enough to keep the casual person from
    Does anyone out there have an algorithm they are willing to share to accomplish this?
    Thanks all. This falls into the 'I know it has to be a known problem, but I'm not sure where to start' category.

    Unless I am misunderstanding, I think that I'm addressing what you mentioned. Let me recap and see if I can make it more clear.
    1) Client sends you an identifier and saves it to the client's disk.
    String start = "" + System.currentTimeMillis();
    start = start.substring( start.length() - 5, start.length() );
    //this pulls off the last 6 numbers from the first run time and converts to a string. 
    // this is written to a file on the client side and then sent to me for registration.
    2) You (the server) send back a hash of the identifier.
    //registration app
    String start = codeSentFromCustomer;
    String superSecretDecoderString = "Secret Code";
    start = start + superSecretDecoderString;
    String result = MD5.getHashString( start );
    result = result.substring( result.length() - 9, result.length() );
    //this takes the 6 digits provided and appends "Secret Code".
    //  i.e. if the customer's code is "333232", then "333232Secret Code" is fed into MD5.
    //  I then send the customer the last 10 digits from my MD5 hash, say "1234567890" for simplicity sake
    3) Clients types the unlock code ("1234567890") into the registration box, which is then saved to disk.
    // to check on the unlock code's validity, I...
    String superSecretDecoderString = "Secret Code";
    String start = originalCodeFromAbove; //i.e. "333232" in this example
    start = start + superSecretDecoderString;  //now start = "333232Secret Code"
    String result2 = MD5.getHashString( start );
    result2 = result2.substring( result2.length() - 9, result2.length());
    // I compare the result2 to the stored unlock code to make sure they are equal
    //  superSecretDecoderString is stored within the client and the registration prog's code.  i.e.
    //  the customer never sees that string.
    4) At each startup the client code checks the hash of sent ID against the return he has stored.
    // run through the validation code detailed in #3.I think it addresses what you were referring to, but if it doesn't please tell me. It's my first crack at this sort of code, and I'd much rather discover any gaping holes now than later. :)
    thanks again

  • I Need Java code for following Algorithm

    * I Need Java code for following algorithm. Kindly any one help.
    1. Read the contents (ideas and its corresponding scores) from two files named as 'a' and 'b'.
    2. Stored the file 'a' contents in array a[].
    3. Stored the file 'b' contents in array b[].
    4. compare both files like
    if(a.equals(b[j])
    Writing the common idea and add the score from file 'a' and 'b'.
    else
    write the uncommon idea and its score..
    For example :
    Form Agents.txt
    action,65
    architecture,85
    eco-,15
    essay,30
    form,85
    form,85
    link,40
    tangent,25
    Form Agents1.txt
    Black holes,69
    essay,78
    Herewith i have above mentioned two files named as Form Agents and Form Agents1.
    Form Agents has eight fields
    Form Agents1 has two fields
    --> 'essay' is common in two files, so store the idea 'essay' and add the score from Form Agents score is '30' and Form Agents1 has 78 (essay 108).
    Finally it stores idea in another file with uncommon fields also.
    Please help us.

    We have tried with following code.
    But we cant add the scores.
    For Example:
    Form Agents.txt --> has "essay,30"
    Form Agents1.txt --> has "essay,78"
    Result is: essay,108
    Finally it stores idea in another file with uncommon fields also.
    So Any one pls correct the following code.
    try
    DataOutputStream o1=new DataOutputStream(new
    FileOutputStream("C:\\Interfaces\\interfaces\\temp\\BlackBoard\\My Design
    World\\Project\\Material\\art\\System Agents\\Form Agents\\CandidateResponses\\Form
    Agents.txt"));
    //Reading the contents of the files
    BufferedReader br= new BufferedReader(new InputStreamReader(new
    FileInputStream("C:\\Interfaces\\interfaces\\temp\\BlackBoard\\My Design
    World\\Project\\Material\\art\\System Agents\\Form Agents\\Ideological\\Form
    Agents.txt")));
    BufferedReader br1= new BufferedReader(new InputStreamReader(new
    FileInputStream("C:\\Interfaces\\interfaces\\temp\\BlackBoard\\My Design
    World\\Project\\Material\\art\\System Agents\\Form Agents\\Related\\Form
    Agents.txt")));
    while((s=br.readLine())!=null)
    s1+=s+"\n";
    while((s2=br1.readLine())!=null)
    s3+=s2+"\n";
    int numTokens = 0;
    StringTokenizer st = new StringTokenizer(s1);
    String[] a = new String[10000];
    String[] br_n=new String[10000];
    int i=0;
    while (st.hasMoreTokens())
    s2 = st.nextToken();
    a=s2.substring(0,s2.length()-3);
    s6=s2.substring(s2.length()-2);
    br_n[i]=s6;
    i++;
    numTokens++;
    int numTokens1 = 0;
    StringTokenizer st1 = new StringTokenizer (s3);
    String[] b = new String[10000];
    String[] br1_n=new String[1000];
    int j=0;
    while (st1.hasMoreTokens())
    s4 = st1.nextToken();
    b[j]=s4.substring(0,s4.length()-3);
    s7=s4.substring(s4.length()-2);
    br1_n[j]=s7;
    j++;
    numTokens1++;
    int x=0;
    for(int m=0;m<a.length;m++)
    for(int n=0;n<b.length;n++)
    if(a[m].equalsIgnoreCase(b[n])){
    int sc=Integer.parseInt(br_n[m]);
         int sc1=Integer.parseInt(br1_n[n]);
    int score=sc+sc1;
         o.writeBytes(a[m]+","+score+"\n");
    break;
    else
    o.writeBytes(a[m]+","+br_n[m]+"\n");
    break;
    }catch(Exception e){}

  • Need algorithm help

    I need some help with my 3 class hangman program.
    whenever the program is run, it doesn't function as intended when a letter is entered. Any advice is greatly appreciated.
    Here's what I have so far:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    //<applet code="Hangman.class" width=400 height=400>
    //</applet>
    public class Hangman extends JApplet implements ActionListener
         private final int WIDTH = 400;
         private final int HEIGHT = 400;
         private JPanel panel,tools;
         private JLabel inputLabel;
         private Hang drawing;
         private JTextField guess;
         RandomWord t = new RandomWord();
         public String answer = t.getWord();
         public void init()
              tools = new JPanel();
              tools.setLayout(new BoxLayout(tools,BoxLayout.X_AXIS));
              tools.setBackground(Color.yellow);
              tools.setOpaque(true);
              guess = new JTextField(1);
              guess.addActionListener(this);
              inputLabel = new JLabel("Enter Guess:");
              tools.add(inputLabel);
              tools.add(guess);
              drawing = new Hang();
              panel = new JPanel();
              panel.add(tools);
              panel.add(drawing);
              getContentPane().add(panel);
              setSize(WIDTH,HEIGHT);
         public void actionPerformed(ActionEvent event)
              String g = guess.getText();
              int incorr = 0;
              int c = 0;
              int i;
              for(i = 0;i<answer.length();i++)
                   if((answer.substring(i,i+1)).equals(g))
                        c++;
                        drawing.setLetter(i,g);
              if(c == 0)
                   incorr++;
                   drawing.setIndex(incorr);
              repaint();
    // class number 2:
    import java.awt.*;
    import javax.swing.JPanel;
    public class Hang extends JPanel
         private final int PAN_HEI = 400;
         private final int PAN_WID = 400;
         private int index;
         private int posNum,corr = 0;
         private String print;
         public Hang()
              setBackground(Color.black);
              setPreferredSize(new Dimension(PAN_WID,PAN_HEI));
         public void setIndex(int v)
              index = v;
         public void setLetter(int y,String s)
              print = s;
              posNum = y + 1;
         public void drawBase(Graphics page)
              setBackground(Color.white);
              page.setColor(Color.black);
              page.fillRect(0,350,150,50);// base
              page.fillRect(0,150,25,200);
              page.fillRect(0,125,100,25);
              page.setColor(Color.gray);
              page.fillRect(84,125,7,50);// rope
              page.setColor(Color.black);
              page.drawOval(75,175,24,25);// head
              page.drawLine(250,55,255,55);
              page.drawLine(260,55,265,55);
              page.drawLine(270,55,275,55);
              page.drawLine(280,55,285,55);     
              page.drawLine(290,55,295,55);
              page.drawLine(300,55,305,55);
              page.drawLine(310,55,315,55);
         public void paintComponent(Graphics page)
              super.paintComponent(page);
              this.drawBase(page);
              if(index == 1)
                   page.drawLine(84,200,84,250);
              if(index == 2)
                   page.drawLine(84,215,34,175);
              if(index == 3)
                   page.drawLine(84,215,116,175);
              if(index == 4)
                   page.drawLine(84,250,50,300);
              if(index == 5)
                   page.drawLine(84,250,100,300);
                   page.drawString("You Lose",250,75);
              if(posNum == 1)
                   corr++;
                   page.drawString(print,250,50);
              if(posNum == 2)
                   corr++;
                   page.drawString(print,260,50);
              if(posNum == 3)
                   corr++;
                   page.drawString(print,270,50);
              if(posNum == 4)
                   corr++;
                   page.drawString(print,280,50);
              if(posNum == 5)
                   corr++;
                   page.drawString(print,290,50);
              if(posNum == 6)
                   corr++;
                   page.drawString(print,300,50);
              if(posNum == 7)
                   corr++;
                   page.drawString(print,310,50);
              if(corr == 7)
                   page.drawString("You Win",250,75);
    //last class :
    import java.util.Random;
    public class RandomWord
         Random g = new Random();
         String w1;
         String w2;
         String w3;
         String w4;
         String w5;
         String w6;
         String w7;
         String w8;
         public RandomWord()
              w1 = "freedom";
              w2 = "justice";
              w3 = "impulse";
              w4 = "destiny";
              w5 = "celsius";
              w6 = "ignited";
              w7 = "believe";
              w8 = "realize";
         public String getWord()
              String x = " ";
              int a = g.nextInt(6);
              if(a == 0) x = w1;
              if(a == 1) x =  w2;
              if(a == 2) x =  w3;
              if(a == 3) x = w4;
              if(a == 4) x = w5;
              if(a == 5) x = w6;
              if(a == 6) x = w7;
              if(a == 7) x = w8;
              return x;
    }I'm a very inexperiencd programmer as you can see.

    Darn, I thought you actually needed algorithm help. But instead all I see is:
    "Here's all my code. It doesn't work right. Let me plop it onto your virtual desk and ask that you just fix it for me. I'm going shopping (or whatever) and will be back soon."

  • Suffix tree clustering algorithm?

    I am studying in my final year of computer science and i need to get hold of a suffix tree clustering algorithm that can be used in javascript. I have searched all over the net but have come up with nothing and was wondering if anybody could help!

    In the section, "Longest Repeated Substring", it says, "the longest repeated substring of txt[1..n] is indicated by the deepest fork node in the suffix tree, where depth is measured by the number of characters traversed from the root".
    However, it doesn't seem to be always true(hmm...probably I interpret it incorrectly).
    Consider the original string = abb$
    (with index 1234)
    the suffix tries looks like
    bb$
    root--------------
    |
    | abb$
    |----------
    the suffix tree looks like
    (2,4)
    root-------------
    |
    | (1,4)$
    |---------
    However, there isn't even a fork node.
    But obviously, b is the longest repeated string.
    Another example
    Consider the original string = abc$
    (with index 1234)
    the suffix tries looks like
    c$
    root--------------
    |
    | bc$
    |----------
    |
    |
    | abc$
    |----------
    the suffix tree looks like
    (3,4)
    root--------------
    |
    | (2,4)
    |----------
    |
    |
    | (1,4)
    |----------
    However, there isn't even a fork node either. But in this case, there is no repated string.
    Hope anyone can answer this. Thanks.

  • How to list the available algorithms ?

    Hi,
    I would like to get all the available algorithms so that the user can choose the one he wants.
    Is it possible to write a generic function that can encryt/decrypt a file with an algorithm as parameter
    Because I've got the following problem : I use this code to list the available algorithms :
    public static String[] getCryptoImpls(String serviceType) {       
            Set result = new HashSet();                
            Provider[] providers = Security.getProviders();
            for (int i=0; i<providers.length; i++) {           
                Set keys = providers[ i].keySet();
                for (Iterator it=keys.iterator(); it.hasNext(); ) {
                    String key = (String)it.next();
                    key = key.split(" ")[0];   
                    if (key.startsWith(serviceType+".")) {
                        result.add(key.substring(serviceType.length()+1));
                    } else if (key.startsWith("Alg.Alias."+serviceType+".")) {                   
                        result.add(key.substring(serviceType.length()+11));
            return (String[])result.toArray(new String[result.size()]);
        }    I call it as : getCryptoImpls("Cipher");
    But some elements of the list are not available !
    Other problem :
    I encrypt/decrypt files using a password, and when I use different algorithms when encrypting and
    decrypting, it works ! Strange ...
    I create a key like this :
    SecretKey key = SecretKeyFactory.getInstance(algo).generateSecret(keySpec);here is the whole code for you to understand better :
        /*  CLASSE                  : CryptoUtils                                 */
        /*  PACKAGE                 : crypto.utils                                */   
        /*  AUTEUR                  : Guillaume YVON                              */
        /*  CREATION                : 15-07-2005                                  */
        /*  DERNIERE MODIFICATION   : 17-07-2005                                  */
        /*  DESCRIPTION             : gestion du cryptage / d�cryptage            */
    package crypto.utils;
    import crypto.component.*;
    import java.io.*;
    import java.util.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.security.spec.*;
    public class CryptoUtils {   
        public static final int ENCRYPT_MODE = 1;
        public static final int DECRYPT_MODE = 2;
        /* ----- D�claration de variables ----- */
        private static Cipher ecipher;
        private static Cipher dcipher;      
        /* Cr�ation d'un vecteur d'initialisation de 8 octets */
        private static byte[] salt = {
            (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
            (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
        /* Compteur pour l'it�ration */
        private static int iterationCount = 19;
        /* Buffer utilis� pour transporter les octets entre les flux */
        private static byte[] buf = new byte[1024];
        /*            PROCEDURE D'INITIALISATION DES CLES DE CRYPTAGE             */
        /* PARAMETRES D'ENTREE                                                    */
        /*      - password => mot de passe pour le cryptage : String              */
        /* PARAMETRES DE SORTIE                                                   */
        /*      - aucun                                                           */
        private static void init(String password,String algo) {
            try {
                /* G�n�ration de la cl� de cryptage � partir du mot de passe */
                KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount);            
                SecretKey key = SecretKeyFactory.getInstance(algo).generateSecret(keySpec);
                ecipher = Cipher.getInstance(key.getAlgorithm());
                dcipher = Cipher.getInstance(key.getAlgorithm());
                /* Pr�paration des param�tres pour les ciphers */
                AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
                /* Cr�ation des ciphers */
                ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
                dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
            } catch (Exception e){ System.err.println(e); }
        /*                   PROCEDURE DE CRYPTAGE / DECRYPTAGE                   */
        /* PARAMETRES D'ENTREE                                                    */
        /*      - mode        => mode de cryptage/decryptage : int                */
        /*      - in          => flux d'entr�e (lecture) : InputStream            */
        /*      - out         => flux de sortie (�criture) : OutputStream         */
        /*      - srcSize     => taille du fichier source : long                  */
        /*      - progressBar => barre de progression                             */
        /* PARAMETRES DE SORTIE                                                   */
        /*      - aucun                                                           */
        private static void crypt(int mode, InputStream in, OutputStream out, long srcSize,
    JProgressBarWindow progressBar){
            try {           
                if(mode == ENCRYPT_MODE){
                    /* Les octets �crits dans out seront crypt�s */
                    out = new CipherOutputStream(out, ecipher);
                }else if(mode == DECRYPT_MODE){
                    /* Les octets lus dans in seront d�crypt�s */           
                    in = new CipherInputStream(in, dcipher);
                /* Lit dans le texte clair les octets et �crit dans out pour le cryptage */
                int sum = 0;
                int numRead = 0;           
                while ((numRead = in.read(buf)) >= 0) {               
                    out.write(buf, 0, numRead);
                    sum += numRead;
                    Float percent = sum / (new Float(srcSize)) * 100;
                    if(progressBar!=null) progressBar.setValue(percent.intValue());               
                out.close();
            } catch (java.io.IOException e) { System.out.println(e); }
        /*             PROCEDURE DE LANCEMENT DU CRYPTAGE/DECRYPTAGE              */
        /* PARAMETRES D'ENTREE                                                    */
        /*      - mode        => mode de cryptage/decryptage : int                */
        /*      - algo        => algorythme � utiliser : String                   */
        /*      - srcFile     => flux d'entr�e (lecture) : String                 */
        /*      - tgtFile     => flux de sortie (�criture) : String               */
        /*      - password    => taille du fichier source : String                */
        /*      - progressBar => barre de progression : JProgressBarWindow        */
        /*      - text        => texte � afficher : String                        */
        /* PARAMETRES DE SORTIE                                                   */
        /*      - aucun                                                           */
        public static void launch(int mode,String algo,String srcFile,String tgtFile,String password,
                                    JProgressBarWindow progressBar,String text){
            try {           
                init(password,algo);                                  
                if(progressBar!=null && text!=null) progressBar.setLabelText(text);
                crypt(mode,new FileInputStream(srcFile),new
    FileOutputStream(tgtFile),FileUtils.getFileSize(srcFile), progressBar);                           
            } catch (Exception e) {}
        /*      FONCTION QUI RENVOIE LES IMPLEMENTATIONS DISPONIBLES POUR         */
        /*                          UN TYPE DE SERVICE                            */
        /* PARAMETRES D'ENTREE                                                    */
        /*      - serviceType => nom du service                                   */   
        /* PARAMETRES DE SORTIE                                                   */
        /*      - liste des impl�mentations : String[]                            */
        public static String[] getCryptoImpls(String serviceType) {       
            Set result = new HashSet();                
            Provider[] providers = Security.getProviders();
            for (int i=0; i<providers.length; i++) {           
                Set keys = providers[ i].keySet();
                for (Iterator it=keys.iterator(); it.hasNext(); ) {
                    String key = (String)it.next();
                    key = key.split(" ")[0];   
                    if (key.startsWith(serviceType+".")) {
                        result.add(key.substring(serviceType.length()+1));
                    } else if (key.startsWith("Alg.Alias."+serviceType+".")) {                   
                        result.add(key.substring(serviceType.length()+11));
            return (String[])result.toArray(new String[result.size()]);
        /*     FONCTION QUI RENVOIE LA LISTE DES TYPES DE SERVICE DISPONIBLES     */   
        /* PARAMETRES D'ENTREE                                                    */
        /*      - aucun                                                           */   
        /* PARAMETRES DE SORTIE                                                   */
        /*      - liste des services : String[]                                   */
        public static String[] getServiceTypes() {
            Set result = new HashSet();           
            Provider[] providers = Security.getProviders();
            for (int i=0; i<providers.length; i++) {           
                Set keys = providers[ i].keySet();
                for (Iterator it=keys.iterator(); it.hasNext(); ) {
                    String key = (String)it.next();
                    key = key.split(" ")[0];   
                    if (key.startsWith("Alg.Alias.")) {                   
                        key = key.substring(10);
                    int ix = key.indexOf('.');
                    result.add(key.substring(0, ix));
            return (String[])result.toArray(new String[result.size()]);
    }Any tip is welcome !
    (sorry for the french comments...)

    From 11.1 onwards, the below two views are available to identify the jar files loaded into the Database.
    JAVAJAR$
    JAVAJAROBJECTS$
    By querying the JAVAJAR$ view you can know information about the JAR files loaded into the Database and using JAVAJAROBJECTS$ view you can find all the java objects associated with the given JAR file.
    These views are populated everytime you use LOADJAVA with "-jarsasdbobjects" option to load your custom java classes.
    But unfortunately this feature is available only from 11.1 onwards and there is no clear workaround for above in 10.2 or earlier.

  • Substring matching for lists

    Can anyone suggest efficient data structure or algorithm to get the "subset" or "superset" of a string. What I mean by subset/superset is this:
      "new york",
      "new york city",
      "new york state",
      "york city"
    superset("new york") = {"new york", "new york city", "new york state"}  // left side is substring of every string on right side
    subset("new york city") = {"new york", "new york city", "york city"}  // every string on right side is substring of the left side
    subset("new york state") = {"new york", "new york state"}The brute force way is use loop through each string and do string contains comparison but is there a more efficient method especially w/ith large string lists??

    So if string A is a substring of string B than the subset of B contains A and the superset of A contains B.
    A classical algorithm that is used sometime to speed substring searching works like this. You create an integer signature for each string. For example, you could set a bit in the integer to indicate the presence of each individual letter of the alphabet. (Since there are more letters than the 32 bit location, you would actually hash each individual letter to a number between 1 and 32 and set that bit). What the signatures do is let you do a very fast substring rejection. If the integer signature of A is NOT a subset of the signature of B it means that A has character that does not show up in B and thus A could NOT be a subset of B.
    Note integer subset testing is very fast. A is subset of B iff (A & B) == A
    More typically, this encoding is done not on letters themselves but rather on di-grams. So to encode "new york" you hash "ne", "ew", "w ", " y"...
    Now, this structure, only gives you a fast reject. If signature of A really is a subset of signature of B it does NOT tell you that A is a substring of B. You must do the substring comparison to check, but it can reject lots of strings that could not possibly match quickly.
    The use of 32 bits for the signature was arbitrary and may not be appropriate. If your strings are long, way more than 32 characters, you would find yourself in general setting most of the bits, and if most of the bits are set you will typically get no rejections. So you must choose the length of your signature to match the characteristics (average length) of the data you expect to be processing.
    Thus to find the superset of String A, you would rip through the entire list of strings using the fast signature comparison to do a fast reject and only do the slower substring comparison on the ones where the signatures were compatible.
    There is a sense in which this is still just the brute force method, in that you compare every string to every other string, but by preprocessing each string once to create a signature, you can potentially speed up all subsequent substring processing.
    BTW I think Jos was pulling your leg about Patricia trees. They are a very efficient method for storing a dictionary of words that allow you to quickly decide if a word is in the dictionary but they are used for matching full strings against full strings, or full strings against prefixes and are not useful for matching substrings. Of course I could be wrong about this. I'd be happy to let Jos teach me a new use for Patricia trees.

  • Tiny Encrytion Algorithm (TEA)

    Hi Guys!
    I am currently developing the Tiny Encrytion Algorithm
    Currenlty is takes in a number to encrytp and works fine but I want to ammend this so it takes in a string.
    My current "get" method is as follows:
    public void getNumber() {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int count = 0, idx = 0;
            try {
                String number = br.readLine();
                while (count <= 1) {
                    num_array[count++] = Integer.parseInt(number.substring(idx, idx + 2));
                    idx += 2;
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (NumberFormatException ex) {
                ex.printStackTrace();
                System.out.println("You have entered an invalid number");
        }How do I go about amending this to take in a String, but still cut it up and save it to an Integer array? (The integer array is required for the encrytion process at a later stage).
    So in other words, i need to get from String to Integer, while cutting it up!!
    I have played about with the charAt() and toBytes() method but i'm just going round in circles! :(
    Cheers!!!
    Edited by: smitty350z on Oct 31, 2007 4:49 AM

    HI Sabre,
    Thanks so much for the immediate reply. I can paste the entire equivalent TEA algorithm that i wrote in java script. That didnt work, then i tried the Java side, bcos eventually i can call it from java script. The main task is to embed the script in to my load test runner. For your reference, please see below the java script equivalent that was written, and debugiing this a big nightmare. Sorry for the format of the javascript codes, its a bit annoying.
    Thanks so much
    function encrypt(src, key, token) {
              if(src.length == 0) return "";
    alert("strToChars(src):" + strToChars(src));
    alert("charsToLongs(strToChars(src)):" + charsToLongs(strToChars(src)));
    alert("hexToChars(key):" + hexToChars(key));
    alert("charsToLongs(hexToChars(key)):" + charsToLongs(hexToChars(key)));
              var v = charsToLongs(strToChars(src));
              var k = charsToLongs(hexToChars(key));
              var n = v.length;
              if (n % 2==1) v[n++] = 0;
              tempv = new Array(2);
              newv = new Array(v.length);
              for (i=0; i<v.length; i=i+2){
                   tempv = tea_code(k,v,v[i+1]);
                   newv[i] = tempv[0];
                   newv[i+1] = tempv[1];
              var encStr = charsToHex(longsToChars(newv));
    alert("encStr"+ encStr);
              return [key,(token + encStr)];
    function strToChars(src) {
         var codes = [];
         var strArr = src.split("");
         strArr1 = new String(strArr);
         var sl = strArr.length;
         var cnt = 0;
         var schar="";
         var intStringLen=strArr1.length;
         for (var intCur = 0; intCur < intStringLen; intCur++) {
              codes[intCur] = strArr1.charCodeAt(intCur);
         return codes;
    function charsToLongs(chars) {
         var tlength = Math.ceil(chars.length/4);
         var temp = [];
         var ti = 0;
         for(var i = 0; i<tlength; i++){
              ti = i*4;
              temp[i] = (((chars[ti] << 24) + (chars[ti+1]<<16)) + (chars[ti+2]<<8)) + chars[ti+3];
         return temp;
    function hexToChars(hex) {
              var codes = [];
              var hexArr = hex.split("");
              var hl = hexArr.length/2;
              for(var i=0;i<hl;i++) {
    //               codes[i] = int("0x"+hexArr[i*2]+hexArr[(i*2)+1]);
                   codes[i] = Math.round("0x"+hexArr[i*2]+hexArr[(i*2)+1]);
              return codes;
    function tea_code (k,y,z) {
         sum = 0;n = 32;
         //while (sum != -957401312) {
         while (n-- >= 0) {
              y = Math.round(y + ((((z << 4) ^ (z >>> 5)) + z) ^ (sum + k[sum & 3]))); y = y|0 ;
              sum = Math.round(sum + 0x9E3779B9);
              sum = sum|0;
              z = Math.round(z + ((((y << 4) ^ (y >>> 5)) + y) ^ (sum + k[(sum >>> 11) & 3]))); z = z|0 ;
         return [y,z];

  • Porter Stemmer Algorithm

    I have been constructing a PHP search engine for my website
    that implements the Porter Stemmer Algorithm. The algorithm is
    causing me some problems.
    If I search for the word "angry", the search script will
    convert the term to "angri". So if there is a record that contains
    "angry", it will not show in the results.
    Is the algorithm supposed to do this, or am I doing something
    wrong?

    Hi,
    I guess you have looked at what is described under /common
    errors/...
    http://tartarus.org/martin/PorterStemmer/
    AngryCloud skrev:
    > I have been constructing a PHP search engine for my
    website that implements the
    > Porter Stemmer Algorithm. The algorithm is causing me
    some problems.
    >
    > If I search for the word "angry", the search script will
    convert the term to
    > "angri". So if there is a record that contains "angry",
    it will not show in the
    > results.
    >
    > Is the algorithm supposed to do this, or am I doing
    something wrong?
    >
    >
    >
    >
    > <?php
    >
    > if(isset($_POST['query'])) {
    >
    > //Connect to server
    > require_once('Connections/ShroomTown.php');
    >
    > //Select database
    > mysql_select_db($database_ShroomTown, $ShroomTown);
    >
    > //Include external functions
    > require_once('functions.php');
    >
    > //Include Porter Stemmer Algorithm
    > include('PorterStemmer.php');
    > $stemmer = new Stemmer;
    >
    > //Define search query varible
    > $query = $_POST['query'];
    >
    > //Create array
    > $query_array = split(" ",$query);
    >
    > //Check if search query array is empty
    > if(implode('',$query_array) == '')
    > {
    > echo "Search query was empty!";
    > }
    > else
    > {
    >
    > //Stem and escape array elements
    > foreach ($query_array as &$value)
    > {
    > $value =
    mysql_real_escape_string($stemmer->stem($value));
    > }
    >
    > //Define SQL variable
    > $sql = "SELECT DISTINCT(id), title FROM submission_data
    WHERE (";
    >
    > foreach ($query_array as $value)
    > {
    > if ($value != '')
    > {
    > $sql .= "(title LIKE '%$value%' OR keywords LIKE
    '%$value%') OR ";
    > }
    > }
    >
    > $sql = substr($sql,0,-4);
    >
    > $sql .= ") AND status = 'complete' GROUP BY id ORDER BY
    submission_date DESC";
    >
    > //Define search results query
    > $query_search_results = mysql_query("$sql") or
    die(mysql_error());
    > $row_search_results =
    mysql_fetch_assoc($query_search_results);
    >
    > //Display search results
    > if(mysql_num_rows($query_search_results) > 0)
    > {
    > echo ('<strong>Results:
    '.mysql_num_rows($query_search_results).'</strong><br
    > /><br />');
    > do
    > {
    > echo ($row_search_results['id'].':
    '.$row_search_results['title'].'<br />');
    > }
    > while ($row_search_results =
    mysql_fetch_assoc($query_search_results));
    > }
    > else
    > {
    > echo ("No results to display");
    > }
    > }
    > }
    >
    > ?>
    >
    >
    Kim
    http://www.geekministry.com

  • Getting Error while decrypt a file using Blowfish algorithm

    I am using blowfish algorithm for encrypt and decrypt my file. this is my code for encrypting decrypting .
    while i am running program i am getting an Exception
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA12275)
    at Blowfishexe.main(Blowfishexe.java:65)
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.io.*;
    import org.bouncycastle.crypto.CryptoException;
    import org.bouncycastle.crypto.KeyGenerationParameters;
    import org.bouncycastle.crypto.engines.DESedeEngine;
    import org.bouncycastle.crypto.generators.DESedeKeyGenerator;
    import org.bouncycastle.crypto.modes.CBCBlockCipher;
    import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
    import org.bouncycastle.crypto.params.DESedeParameters;
    import org.bouncycastle.crypto.params.KeyParameter;
    import org.bouncycastle.util.encoders.Hex;
    public class Blowfishexe {
    public static void main(String[] args) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
              kgen.init(128);
              String keyfile="C:\\Encryption\\BlowfishKey.dat";
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
              System.out.println("key"+raw);
                   byte[] keyBytes = skey.getEncoded();
                   byte[] keyhex = Hex.encode(keyBytes);
                   BufferedOutputStream keystream =
    new BufferedOutputStream(new FileOutputStream(keyfile));
                        keystream.write(keyhex, 0, keyhex.length);
    keystream.flush();
    keystream.close();
    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
              System.out.println("secretKey"+skeySpec);
    FileOutputStream fos=new FileOutputStream("C:\\Encryption\\credit11.txt");
              BufferedReader br=new BufferedReader(new FileReader("C:\\Encryption\\credit.txt"));
              String text=null;
              byte[] plainText=null;
              byte[] cipherText=null;
              while((text=br.readLine())!=null)
              System.out.println(text);
              plainText = text.getBytes();
              cipherText = cipher.doFinal(plainText);
              fos.write(cipherText);
              br.close();
              fos.close();
              cipher.init(Cipher.DECRYPT_MODE, skeySpec);
              FileOutputStream fos1=new FileOutputStream("C:\\Encryption\\BlowfishOutput.txt");
              BufferedReader br1=new BufferedReader(new FileReader("C:\\Encryption\\credit11.txt"));
              String text1=null;
              /*while((text1=br1.readLine())!=null)
                   System.out.println("text is"+text1);
                   plainText=text1.getBytes("UTF8");
                   cipherText=cipher.doFinal(plainText);
                   fos1.write(cipherText);
              br1.close();
              fos1.close();
    //byte[] encrypted = cipher.doFinal("This is just an example".getBytes());
              //System.out.println("encrypted value"+encrypted);*/
    Any one pls tell me how to slove my problem
    thanks in advance

    hi
    i got the solution. its working now
    but blowfish key ranges from 56 to448
    while i am writing the code as
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(448);
    this code is generating the key upto 448 bits
    but coming to encoding or decode section key length is not accepting
    cipher.init(Cipher.ENCRYPT_MODE, key);
    Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at Blowfish1.main(Blowfish1.java:46)
    i am getting this error
    what is the solution for this type of exception.
    thank you

  • SHA2 Algorithm support in Adobe Acrobat 9

    Hello,
    1) Does Acrobat 9 supports SHA2 Hash algorithms while signing PDF file?
    2) As per my understanding PDF is signed using below approach
        Step 1. Take the PDF contents
        Step 2. Calculate the Hash of the content
        Step 3. Then sign(Encrypt) the hash. (here again we calculate the hash)
      So we are hashing the content twice.
      If I use SHA1 algorithm in Step2 and SHA2 algorithm in Step3, Adobe 9 is able to verify the signature. But if i use SHA2 algorithm in Step1 & Step 2
      Adobe 9 is saying "Content altered....."
      Why so?
    Please help.
    Thanks in advance
    Priyanka

    SHA2 was only added in Acrobat 9.1.  Also, the Microsoft Base CSP is needed for SHA2 support - Base CSP is included in Vista and Windows 7, but in XP it needs to be downloaded as a seperate addon.
    How are you setting the values in your SecurityHandler?  Off the top of my head, I believe in order to use SHA2 to hash the content (your "Step 2") you need to use AES-256 as your encryption algorithm which required a different cryptVersion be set in your SecurityHandler structure.

  • IF and SUBSTR in XML Publisher

    Hi
    I am developing a XML RTF template for a report.
    All I am trying to do is, if first 4 letters of the data of xml tag ITEM = 'Summ'
    then print a constant word 'Notes'
    <?if: xdofx:substr(ITEM,1,4)=’Summ’?> Notes<?end if?>
    I have been trying hard. IF and SUBSTR is not at all going along. Always throwing some error. Can some one please help me to resolve this issue
    Thanks

    Hi,
    I have a similar requirement, however instead of static text in the example i.e ITEM I am trying to get a substring from a tag value directly. Ex - Tag Value <eod>23-10-2009<eod>. I am trying to pick up the value 10 in the particular example and trying to compare with 1, which would be false and hence I need to print as false. I cannot use a hardcoded value since the value between the tags <eod> is dynamic and I need to use that itself.
    Can you please provide me with the sytax which can achieve this?
    Regards,
    Praseed

  • Can we use Trunc,Substr in Excel templates

    Hi All,
    I have a date xml tag with value like "2012/04/01 00:00:00" i need to show this in excel output as "01-APR-2012".
    I am using Excel template, need your help to achieve the same.
    I tired to use Trunc,Substr,Format date but nothing is working.
    Please give me your valuable inputs to solve this issue.
    Thanks
    Rajehs

    Varma,
    Thanks for the reply, i have already checked the link but it doesn't have syntax to use Trunc,substr etc. functions.
    Also date in example is - "1996-02-03T00:00:00.000-07:00" , but in my case date format is different "2012/01/01 00:00:00".
    Thanks
    Rajesh

  • How to find a substring in XML-lookslike string?

    Hi,
    I have a question and wondering if anyone can help me with it.
    We have Java tool that does a string replacement inside another string (that is actually an XML request). It works fine when searching for a simple substring (that exists within 1 line of the XML string).
    But when I'm trying to find and replace a substring that covers more then 1 line of XML request - it does not work. And I'm not sure what is wrong or (more importantly) how to make it work.
    There is no return or new-line chars seen in the XML request.
    To make it more clear - here is what I have and trying to do:
    <a>
    <a>
    <b>
    <c>
    <d> </d>
    <c>
    <c>
    </c>
    </c>
    </c>
    </b>
    </a>
    </a>
    If I'll seach for either <c> OR </c> OR <d> </d> it all works fine ... BUT if Itry to find
    </c>
    </b>
    which will be copied directly from the XML request and past into field - thus it will look like this (horisontal line instead of vertical) </c> </b> - it does not work

    qavlad wrote:
    But when I'm trying to find and replace a substring that covers more then 1 line of XML request - it does not work. First statement - "more than 1 line"
    There is no return or new-line chars seen in the XML request.Second statement.
    There is no way that I can understand what you meant in your first statement in terms of your second.
    If there are no end of line characters at all then there is only one line. Period.
    If there are end of line characters, of any kind, then that would really suggest the source of the problem.

  • Fastest square root algorithm

    I was looking for a fast algorythm for integer square roots and I found this one http://medialab.freaknet.org/martin/src/sqrt/.
    The algorithm comes from a book by Mr C. Woo on how to do maths on an abacus.
    I post the javaized version here in case anyone finds it interesting.
    I believe this is the fastest square root function in existance for integers (and in game programming much of the time you aren't interested in fractions)
    /* Fast interger square root adapted from algorithm by Martin Guy @ UKC, June 1985.
        *   Origonally from a book on programming abaci by Mr C. Woo.
       public static int fastSqrt2(int n)
          int op, res, one;
          op = n;
          res = 0;
          /* "one" starts at the highest power of four <= than the argument. */
          one = 1 << 30;   /* second-to-top bit set */
          while (one > op) one >>= 2;
          while (one != 0)
             if (op >= res + one)
                op = op - (res + one);
                res = res +  (one<<1);
             res >>= 1;
             one >>= 2;
          return(res);
       }

    public static double sqrt(double a){
      if(a<0) throw new IllegalArgumentException("number<0");
      double precision=0.001;
      double x_nMinus1 = -1;
      double x_n = 1;
      while( Math.abs(x_n - x_nMinus1) > precision ) {
        x_nMinus1 = x_n;
        x_n = (x_nMinus1 * x_nMinus1 + a) / (2*x_nMinus1);          
      return x_n;           
    }

Maybe you are looking for

  • Windows 7 and Adobe 9.3.3 - an internal error occurred

    Have installed Windows 7 on a domain client PC.  Have downloaded the only version available (9.3.3) for Windows 7.  End user belongs to Administrator Group on the domain and is also an Administrator if logged into the computer itself.  Download and i

  • SQL 2012 Database Availability Group - Force Automatic Failover

    Hi All, I'd appreciate some help in understanding the following scenario in my test environment. I have created a DAG with 2 replica servers (both of which are HyperV VM's running W2012 Std). From a client PC in my test lab, I can connect to the virt

  • Data filter when migrating Oracle to SQL

    How can I use a data filter (via t-sql or ??) when using SSMA to migrate data from Oracle to SQL Server ?

  • I have a 32 bit windows 7 computer - itunes not installing

    recently i had to get a new hard drive, so when i got it i had to re instal itunes to my 32-bit windows 7 PC. As it had worked previously with my old and same type hard drive i was confused when it didnt work.  when i  would open itunes a message wou

  • What should i learn first

    hi, i am trying to learn dw but am frustrated as i feel limited in creating layouts. where should i start learning. i am experienced in ai and psd but have never integrated into web. would fireworks be the place to start learning?