Sudoku Algorithm

Hi, i was venturing out to design an algorithm to generate sudoku puzzles, I was thinking of emplying 2D Matrix arrays. The idea I have is filling up the whole grid first with a solution then taking away a few numbers. I don't really know how to do this, though I have an idea, getting it to check the rows and columns add up to 45 and each 3x3 grid adds up to 45, 45 being the sum of all the numbers in a 3x3 grid. Would anyone be able to tell me if this would work and how would I be able to program this in JAVA. Many thanks in advance.

And I need an algorithm to solve sudokupuzzles.
That's the hard part, at least if you want to solve
it without brute force.Indeed, I thought that only with brute force Sudoku can be solved.
Indeed, I don�t think that there is a "magic intelligent" algorithm that can solve it . Well, Sudoku is cool exactly because it can just be solved by brute force. LOL!!!!
Maybe some math genius person knows how to write an algorithm to solve Sudoku easily, or how to explain and prove mathematically that an algorithm to solve that is not possible.

Similar Messages

  • Sudoku algorithm for available numbers

    Hi guys!
    I want to create a java sudoku but I'm stuck with the backtracking algorithm to get the available numbers to insert in the current cell. Can someone point me to a method that gives me an int[] with all available numbers for the current cell?
    Thanks!

    Do you think that this simple algorithm will find
    its way to a solution in the vast space of possible
    states, or will it end up in a local optimum?You can not count on this to work. Your intuition is that since you are swapping elements that were duplicates either in a row or column, that you are "fixing that problem" and thus getting closer to a solution. But the mere fact that A was a duplicate in row 1 and thus has to be removed does not mean that when you swap it with B that B does not now also confilit with something Both in row1 and also with something in the column that A used to be in. You could make things worse by your operation.
    On the other hand as long as you randomly choose among elements that are known to be out of order,the probability that your algorithm will find the solution is of course 1 because as long as you are randomly swapping things that are known to be wrong you will eventually by chance alone trip over the proper sequence of swaps that solve the problem.
    Of course, the same could be said for the algorithm that ignores looking at the elements and just swaps elements at random. That algorithm will also eventually solve the problem.

  • Reading in serialized objects in MIDP

    I have a sudoku algorithm which generates a puzzle and then serializes the result and writes it out to a file using FileOutputStream and ObjectOutputStream. My question is how do i get this file read in J2ME, because i have another game which is on a mobile phone, programmed using J2ME, and as MIDP doesn't support serialization I am having problems getting it read in. And as we are here let me say this I am also havin problems understanding the RMS in terms of reading in a sudoku puzzle, could anyone please help me with the above issues, especially how record store system works when reading in a sudoku puzzle.

    This has come up many times already:
    Check this one:
    http://java.sun.com/developer/J2METechTips/2002/tt0226.html#tip2
    You should rewrite the server side like this as well, though.

  • Threaded Sudoku solver - Assignment question (NOT LOOKING FOR ANSWERS  )

    Hi All,
    I'm going to be upfront and point out this is an assignment that i'm currently working on and i'm not receiving much in the way of feedback from the class forums.
    This is currently a 4th year OO assignment for UNSW Australia.
    What I am having trouble doing is figuring out where my program is deadlocking or dying. There have been a number of requirements set out by the assignment, basically no synchronization, no locking. We are able to use volatile, atomic, immutable and thread-local objects. The task is to find all solution for a given N x N sudoku problem using X number of threads. I have successfully built the solver (X = 0) without too much trouble and I thought i had managed to modify the recursive algorithm to suit but unfortunately I think I have come unstuck.
    Any generalized tips would be appreciated when implementing threads that utilise checking flags to determine when the thread is finished processing.
    Kind Regards,
    Chris Gibbs

    Honestly, I think that recursion (as you stated) would be the easiest way to have solved this problem. But as you stated, threads must be used to solve this problem as a requirement of the project...
    You could easily launch a Thread each time instead of calling your recursive method... that could possibly result in a crap load of threads, but the idea would work.
    Definitely take a look at the SwingWorker class here if you're able to use J2SE 6: [http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html|http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html]
    I currently use it while gathering data from several websites at the same time. What I did was create and execute() X number of MySwingWorker objects to collect the data, while they are not complete (i.e. MySwingWorker.isDone() is false) I just Thread.sleep(...).
    Give it a try. It may suit your needs.

  • Sudoku Pluzzle

    I'm looking for Algorithms that will solve sudoku puzzles. Im trying to write my own program for this to get ready for a compition. Would anyone know where to find these algorithms or ways to slove sudoku puzzles using a system every time? Any suggestions are helpfull thank you,
    Cobbweb

    I think you are going to have to write your own algorythm for this.
    The math is beyond me, but off the bat I am going to guess that a brute-force-from-zero approach is not going to work anytime this century. However, if you make an initial elimination pass and then start trying possibilities with recursive elimination passes from there I bet it would chop things down enough that you could just do it that way without any really clever algorythm.
      A B C
    A 1 ? ?
    B ? ? 3
    C ? 2 ?With coordinates given as X,Y - so that the 3 is at C,B.
    The number at A,B could be 1, 2, or 3, given only the rules of the game. Your "initial pass" is where you just run through the colum (A) and the row (B) and eliminate possibilities. So we know it cannot be 1 because there is a 1 at A,A and it cannot be 3 because there is a 3 at C,B. In a puzzle this simple that already tells us the answer (since only 1 is left) but obviously this will not be the case in a real puzzle. However, we will still have chopped out a LOT of possibilities.
    Next we just pick an order for empty spaces - say left to right, top to bottom. The first one is B,A, so we go there. Then we just pick a number (moving from 1 up) to try out. That number gives us more information, so we make another pass over the entire grid eliminating stuff again. Then we just walk down the grid in a binary search tree type of dealy.
    I bet that even a big puzzle would be no problem for a modern computer this way.
    Drake

  • SUDOKU (résolutio​n avec LV)

    Résolution des Sudoku avec LV.
    Ce VI utilise un algorithme de réflexion associé à un algorithme de backtraking. (100% home made)
    Il agit comme nous le ferions nous mêmes, par déductions, éliminations, recoupements
    et ... retour arrière en cas de "cul de sac".
    Les Sudoku "faciles" utilisent peu le backtraking. (pas du tout pour certains)
    Plus un Sudoku est difficile, plus il possède de solutions différentes.
    Celui que j'ai placé en "valeur par défaut d'entrée" est un exemple de Sudoku très difficile.
    Une horreur à résoudre, pour reprendre les termes de certains (je l'ai trouvé sur le Net)
    Ce Sudoku possèdent 2756 solutions différentes.
    Ce VI trouve la 1ere solution en 23 ms ... et les 2756 en un peu plus de 9 sec (Q6600 - 2.6Ghz)
    Possibilités:
    input - votre sudoku à résoudre.
    trouver une solution (la 1ere)
    trouver toutes les solutions.
    Faire pause (une fois que vous avez appuyé sur Pause, le petit bouton blanc permet de visualiser les solutions une par une)
    Le VI principal est : SUDOKU.vi
    Pour le tester rapidement ... lancer le vi et run
    1) start : il vous trouve la 1ere solution
    2) basculer l'interrupteur sur "all solutions" ... start ... il trouvera les 2756 solutions.
    voilou.
    Sur ce coup là ... me suis encore bien amusé
    Résolu !
    Accéder à la solution.
    Pièces jointes :
    main = SUDOKU.vi.zip ‏194 KB

    Il y a une règle pour interdire les groupes non anglophone?
    1) mon dieu ... que cela est bien difficle d'exprimer quelque chose ... de simple et de simplement dit.
    Je comprends que ceux qui travaillent sous LabVIEW tout ou partie de la journée aient envie de faire autre chose une fois chez eux.
    2) Je comprends parfaitement également, Il s'agissait d'un simple constat. (voir point 1)
    https://decibel.ni.com/content/docs/DOC-6108
    J'ai trouvé ceci sur le Net ... joli morceau de code ! très jolie cette solution récursive ...
    Mais ... mon algo va 5 fois plus vite. Résolution de la 1ere solution : 138ms contre 27ms.
    Cet algo récursif utilise également le backtraking, mais devant une impasse, il essaye "simplement" le nombre suivant.
    De mon côté, je calcule les possibilités pour chaque cases et à chaque instant,
    et quand je reviens en arrière, je ne passe pas "simplement" au nombre suivant ... mais au nombre suivant "possible" !

  • Solving Sudoku in SQL?

    Hi. I'm wondering if one could solve a Sudoku puzzle with a SQL query given the initial configuration of the Sudoku is stored in a database table. Suppose I have a database table named InitSudoku storing the initial configuration of a 5x5 Sudoku. Each row in the table indicates which number (1 to 25) is initially placed in which square of the puzzle. For example, the row (15,3,9) means the number 15 is initially placed in the square at the 3rd row and the 9th column of the puzzle. What I would like to get is a result set that would give me a completion of the Sudoku. Does anyone think that is doable strictly within SQL with one or more queries (without using a procedural language like C or Java, which would require coding up an algorithm of solving Sudoku)?
    Thanks.

    The same guru has improved on this solution in 11gr2:
    [http://technology.amis.nl/blog/6404/oracle-rdbms-11gr2-solving-a-sudoku-using-recursive-subquery-factoring|http://technology.amis.nl/blog/6404/oracle-rdbms-11gr2-solving-a-sudoku-using-recursive-subquery-factoring]
    [http://tonyhasler.wordpress.com]

  • How to Design a Sudoku Grid

    I'm designing a Sudoku Solver program and I need to represent the grid. How would you suggest I design it? Using buttons, labels, Table? What would you suggest?

    Custom components in a GridLayout. When I solve a sudoku by hand, I notate the cell with the numbers I've eliminated, so if I jot:
    ..This means I've eliminated 1, 3, 5, 6, 7 and 8. You can define a custom component to draw these dots.
    (This is assuming you want your GUI to be interactive -- allow a user to try to solve the puzzle, or show how your algorithm solves it, step by step.)

  • My sudoku program, any comments, improvements appreciated

    Hi all,
    So I've been refining my amateur-ish programming skills for around a month, and have been writing a C++ program that solves sudoku. (My background is in physics.) I realize there are a lot of mathematical sides in sudoku, but I'm concentrating on the programming side and not too much on the math/brain side. Now the program is basically finished (I hope!) and I just thought the hackers here can have a look and see if there are any things I can improve.
    The link is here: http://ifile.it/jkr56v8/Sudoku.tar
    Basically, a sudoku is an instance of Board, an abstract base class with the pure abstract function Go(). Any concrete class derived from it is essentially a strategy. I think this design pattern is called strategy?
    I've implemented two basic strategies, BruteForce and Priority. BruteForce does the good old sudoku brute force algorithm, which use trial-and-error from the top left box to the bottom right box all possibilitiies until the correct one is found. Priority does basically the same as BruteForce, except instead of trying from top left to bottom right, it plugs numbers in the box that has the most filled "associated" boxes.
    To accommodate "composite strategies," I implemented the prototype pattern, so for example, I can write
    void HyperBF::Go(void)
    BruteForce::Go();
    When a solution is found, I throw an exception to notify the main program, am I correct in that this is a clear and elegant use? Or is it a misuse and an alternative should be considered?
    To actually choose a strategy, I created an abstract factory, a singleton. I'm aware there are all the advice out there that says don't use a singleton unless absolutely necessary? So, should I use a singleton in this case? Also, I think my implementation of the singleton leads to a bug, which is the only known bug: when I put a completed sudoku as input, it gives the output as usual, but gives a segmentation fault afterwards:
    ./Sudoku Puzzle/test_1_Basic.psv BruteForce | tail -n 12 | head -n9 | tee completed
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    ./Sudoku completed BruteForce
    Starting configuration:
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    Final configuration:
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    Number of attempts: 0.
    Time elapsed: 0.00 s.
    Segmentation fault
    So what's wrong here?
    Having implemented the basic functionalities, I tried to play around and gain some simple experience in some optimization. I looked at the Go() function and saw probably the expensive operation is IsConsistent(), so I optimized it by only checking the consistency of changed boxes. By doing so, I reduced the computational time to around 1/3 the original time. Is this the right move, or bad move, or are there better moves?
    As a last question, I defined the number of attempts as a global variable. My reason is that, although it is possible to put it in class Board, I just think it doesn't "naturally belong" there, and putting it in a restricted scope would mean a lot of passing of parameters, slowing the program down unnecessarily. So, is this global variable fine?
    Lastly, please have a look at my Makefile. This is the first Makefile I wrote, and it took me 3 solid days to get all the .o files in Release/ ! Are there things I've left out?
    I realize the Generator is a joke, but at this moment I don't care too much about that, unless anyone has some good ideas.
    Any comments would be greatly appreciated! Thanks in advance!

    Grazz256 wrote:
    Just looking over your code a little I have a couple of comments about your coding style. Please keep in mind that these are just comments...
    I think you need to comment your code more. I know its a pain and I'm horrible about it as well but it really does help when/if you go back to read your code in a couple of years.
    I try to avoid lines like these:
      fprintf( stdout, "Starting configuration:\n" ); a->Write(stdout);
      start = clock(); a->Go();
    by putting two commands on one line it makes the code harder to read. with one command on each line I can quickly scan through and know
    generally what each line does, with two I have to actually read each line fully so that I don't miss anything.
    Descriptive variable names can also help with readability, I've always been taught the convention of using the first character to indicate type then
    using a short descriptive name. For instance you have a function that returns a long value, the value would be decalred like this:
    long lRetVal;
    so looking through the code I would know thats a long value that represents a return value.
    This is an area I'm all over the place with, I always try to stick to one convention but never seem manage it...
    As far as your problem goes, where are the boards normally deleted? ie if an incomplete sudoku is inputed?
    One possible solution is to run an IsComplete check before you start processing the board. so you would have...
    if (a->IsConsistent()) {
    if (a->IsComplete()) {
    a->Go()
    I'll be honest in that I don't really understand the flow of your code, but instead of having the board deleted within strategy or within win why not just delete it on the next line... eg:
    start = clock(); a->Go();
    delete a;
    the downside to this approach is that you would have to delete it within each exception as well but this is relatively minor.
    Cheers
    Thanks for your comments. At my present level of programming skills, any comments will help.
    I thought all my code was basically concise and self-explanatory, and each function is small enough that a quick skim through the definition and declaration would be enough to understand. As the project grew, however, things got slightly more complicated. I have added more comments in my source files, trying to comment why rather than how. I thought the flow of the code was fairly obvious though, by inspecting the main loop. It takes care of the input, bark if anything's wrong, trigger a.Go(), and try to catch a Win. Do you mean the flow within Go()? Anyway, it is very true I need clearer coding style.
    Yeah I now solved the segfault problem. The reason a completed sudoku was deleted twice is because the original sudoku is meant to be deleted by the abstract factory, while the solved sudoku is meant to be deleted by Win. When a solved sudoku is inputted it would be deleted twice. Due to lack of programming experience, I failed to see the obvious way is to, as Grazz256 said, check in the beginning whether the inputted sudoku is already solved. If it is, then I duplicate the inputted sudoku and throw the win exception.
    By the way, I think I'm beginning to understand why some people are obsessed wtih optimization. I did 3 optimization techniques in my program. First, I thought the most expensive procedure is the IsConsistent() method. By evaluating it lazily I reduced the time to 1/3 the original time. Then following http://www.acm.org/crossroads/xrds1-4/ovp.html, I used initialized the 2D vector within each sudoku via constructor rather than as statements. Doing so gave a 20% time boost. Using a friend procedure while copying sudokus boost another 5%. Doing a right move and getting positive feedback through better performance can be so satisfying.
    EDIT:
    I found out there was memory leak after all, which I finally solved.
    What happens is with all my brute force algorithms I keep creating new Board's and call the Board's Go() recursively. To delete all Board's in the heap I need to have, within each Board::Go(), instead of
    Board* a = Clone(); // return new derived Board(*this);
    a->Put(x,y,'0'+k);
    a->Go();
    delete a; // if an exception is thrown this line never gets executed
    this
    Board* a = Clone();
    a->Put(x,y,'0'+k);
    try {a->Go(); }
    catch( const Win& e) {
    delete a;
    throw(e);
    delete a;
    But this deletes the winning sudoku too. This means I have to keep the result in Win, either by duplicating the winning sudoku or storing the string. In the end I overloaded Board::Write(File* f) to also have Board::Write(std::string& p) to sprintf on the reference of a string, so Win just stores the solution in string format. Finally, no memory leak, no need to do a first check to see if the inputted sudoku is already solved, and no pointer deleted twice.
    So in the end, to manage pointers I recursively threw exceptions. That made me ask, is using exceptions worth it, or should I stick to the more conventional methods, such as have Go() return a boolean value, then deleting pointers which would give an implementation that is essentially the same as recursive exceptions?
    I still think exceptions is the way to go, the reasons being:
    1) Exception mechanism provide a natural place to hold the result. Throwing exceptions recursively and the traditional way is essentially the same, but where should the result be stored in the latter case?
    2) Arguing over the dictionary, an exception is not necessarily an "error." Winning is an exception in this algorithm, because failure is the norm (as in life).
    3) Exception arguably gives better presentation in the main loop, to my "unbiased" eyes at least. Board* a->Go() is triggered in the try block in the main(), with all (foreseeable) possible results caught as exceptions. It is true that this might be a bit unconventional, but given proper comments I still think it is at least as good as the conventional way, in terms of presentation.
    So what do you think?
    Last edited by dumas (2009-12-21 12:37:47)

  • Looking for All-In-One Sudoku Game App for iPad?

    Bare with me...  I'm going to learn now if this is an appropriate question here and if not where to go that would be appropriate?
    I'm looking for a great iPad Sudoku game app that offers a variety of different format variations using numbers 1-9, different colors, and different shapes--that sort of thing...instead of just the common numbers.  I'm not concerned about scoring the game or tracking time or the leaderboard stuff.
    I've looked and found a gillion to consider including Google and looked at some for more detail but so far have found none...and maybe none exist or maybe I'll have to settle for two or three separate Sudoku games to fullfill what I'm after?
    So maybe someone in the community knows of just the Sudoku app I'm looking for?
    Thank you.

    A quick Google search provided the following:  http://itunes.apple.com/us/app/sudoku-hd-for-ipad/id364909963?mt=8
    I don't know if it offers exactly what you want, but you can check the App Store, or you can go to Google and type the following in your search bar:  apple sodoku app ipad
    Several options will come up.

  • 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.

  • 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

  • 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;           
    }

  • Square root algorithm?

    Okay, two things...I've always kinda wondered what the algorithm for the square-root function is...where would I find that?
    but the main thing is, I was making a class to store/deal with a complex/mixed number (a + b*i), and I was trying to make a square-root method for that. But I fiddled around with the variables in the equation, and I can't quite get any further.
    This is what I got (algebraically: this isn't actual code):
    ( the variables a, b, c, d are all real numbers )
    ( the constant i is the imaginary unit, sqrt(-1) )
    sqrt(a + b*i) == c + d*i
    a + b*i == (c + di)^2
    a + b*i == c*c - d*d + 2*c*d*i
    a == c*c - d*d
    b == 2*c*d
    c == sqrt( a + d*d )
    c == b / (2* d)
    d == sqrt( c*c - a )
    d == b / (2*c)
    right now the only thing i can conclude from that, is that if you know (a or b) and (c or d) you can determine the other variables. but I can't figure out how to define c or d purely in terms of a and b, as the method would need to. so I'm stuck.

    Okay, two things...I've always kinda wondered what the
    algorithm for the square-root function is...where
    would I find that?
    Math.sqrt()It's an extremely important skill to learn to read the API and become familiar with the tools you will use to program Java. Java has an extensive set of documentation that you can even download for your convenience. These "javadocs" are indexed and categorized so you can quickly look up any class or method. Take the time to consult this resource whenever you have a question - you'll find they typically contain very detailed descriptions and possibly some code examples.
    http://java.sun.com/reference/api/index.html
    http://java.sun.com/j2se/1.4.2/docs/api/

Maybe you are looking for