www.webdeveloper.com
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 32

Thread: Who fancies a code challenge just for fun?

  1. #16
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    Ok, the script has been modified to return the "Top 5" best words to use from the available letters:
    ( I think this should level the playing fields a little with your file based indexing bokeh )

    index.php?letters=czta
    Array
    (
    [0] => act
    [1] => cat
    [2] => ta
    [3] => cz
    [4] => ct
    )
    0.19173002243042
    index.php?letters=test
    Array
    (
    [0] => stet
    [1] => test
    [2] => set
    [3] => est
    [4] => tt
    )
    0.17785286903381
    index.php?letters=poixaenohb
    Array
    (
    [0] => xenophobia
    [1] => neophobia
    [2] => hipbone
    [3] => phoenix
    [4] => phobia
    )
    0.34027099609375
    index.php
    PHP Code:
    <?php

        $timer   
    microtime(true);
        
    $letters strtolower(isset($_GET['letters']) ? $_GET['letters'] : 'test');
        
    $length  strlen($letters);
        
    $words   = array();

        
    $handle fopen('en.txt''rb');
        while (!
    feof($handle)) {
            
    $word trim(fgets($handle));
            
    $wlen strlen($word);
            if (
    $word && $wlen <= $length) {
                for (
    $i 0$a strtolower($word), $b $letters$i $wlen; ++$i) {
                    if ((
    $j strpos($b$a[$i])) !== false) {$b[$j] = '*';} else {break;}
                }
                if (
    $i >= $wlen) {
                    
    $words[$wlen '.' $word] = $word;
                }
            }
        }
        
    fclose($handle);

        
    krsort($wordsSORT_NUMERIC);
        
    $words array_slice(array_values($words), 05);

        echo 
    '<pre>';
        
    print_r($words);
        echo (
    microtime(true) - $timer);
        echo 
    '</pre>';

    ?>
    JavaScript: Learn | Validate | Compact | bionoid

  2. #17
    Join Date
    Feb 2005
    Location
    Indianapolis, IN
    Posts
    142
    Cool thread guys.... Anyone want to write an article around the code they created? If so, I'll see about posting it to one of our other sites (PHPBuilder or Developer.com).

    Brad!
    WebDeveloper Admin

  3. #18
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    http://charles-reace.com/scrabble.php

    scrabble.php:
    PHP Code:
    <!DOCTYPE html>
    <html>
        <head><title>Scrabble word-finder</title></head>
        <body>
            <form action='' method='get'>
                <div>
                    <label>Enter your letters:
                        <input type='text' size='7' maxlength='7' name='letters'<?php
                            
    if(!empty($_GET['letters'])) {
                                echo 
    " value='".$_GET['letters']."'";
                            }
                        
    ?> />
                    </label>
                    <input type='submit' value='Get Words' />
                </div>
            </form>
        </body>
    </html>
    <?php
    if(!empty($_GET['letters'])) {
        
    $counts count_chars(strtolower($_GET['letters']), 1);
        try {
            
    $pdo = new PDO('mysql:host=*****;dbname=*****''*****''*****');
            
    $pdo->setAttribute(PDO::ERRMODE_EXCEPTIONtrue);
            
    $sql "SELECT `word`, LENGTH(`word`) AS `word_length` FROM `words` WHERE\n";
            foreach(
    range('a''z') as $letter) {
                if(isset(
    $counts[ord($letter)])) {
                    
    $where[] = "`$letter` <= ".$counts[ord($letter)];
                }
                else {
                    
    $where[] = "`$letter` = 0";
                }
            }
            
    $sql .= implode(" AND\n"$where)."\nORDER BY `word_length` DESC, `word`";
            
    //echo "<pre>$sql</pre>";
            
    $stmt $pdo->query($sql);
            if(
    $stmt == false) {
                die(
    "<pre>".print_r($pdo->errorInfo(),1)."\n$sql</pre>");
            }
            echo 
    "<h3>Result:</h3>\n<ul>\n";
            while((
    $row $stmt->fetch(PDO::FETCH_ASSOC)) != false) {
                echo 
    "<li>".$row['word']."</li>\n";
            }
            echo 
    "</ul>\n";
        }
        catch(
    PDOException $e) {
            die(
    "<pre>DB ERROR:\n".print_r($etrue)."</pre>");
        }
        catch(
    Exception $e) {
            die(
    "<pre>OTHER ERROR:\n".print_r($etrue)."</pre>");
        }
    }
    words table:
    Code:
    CREATE TABLE IF NOT EXISTS `words` (
      `word` varchar(20) NOT NULL,
      `a` int(2) unsigned NOT NULL,
      `b` int(2) unsigned NOT NULL,
      `c` int(2) unsigned NOT NULL,
      `d` int(2) unsigned NOT NULL,
      `e` int(2) unsigned NOT NULL,
      `f` int(2) unsigned NOT NULL,
      `g` int(2) unsigned NOT NULL,
      `h` int(2) unsigned NOT NULL,
      `i` int(2) unsigned NOT NULL,
      `j` int(2) unsigned NOT NULL,
      `k` int(2) unsigned NOT NULL,
      `l` int(2) unsigned NOT NULL,
      `m` int(2) unsigned NOT NULL,
      `n` int(2) unsigned NOT NULL,
      `o` int(2) unsigned NOT NULL,
      `p` int(2) unsigned NOT NULL,
      `q` int(2) unsigned NOT NULL,
      `r` int(2) unsigned NOT NULL,
      `s` int(2) unsigned NOT NULL,
      `t` int(2) unsigned NOT NULL,
      `u` int(2) unsigned NOT NULL,
      `v` int(2) unsigned NOT NULL,
      `w` int(2) unsigned NOT NULL,
      `x` int(2) unsigned NOT NULL,
      `y` int(2) unsigned NOT NULL,
      `z` int(2) unsigned NOT NULL,
      PRIMARY KEY (`word`),
      KEY `a` (`a`),
      KEY `b` (`b`),
      KEY `c` (`c`),
      KEY `d` (`d`),
      KEY `e` (`e`),
      KEY `f` (`f`),
      KEY `g` (`g`),
      KEY `h` (`h`),
      KEY `i` (`i`),
      KEY `j` (`j`),
      KEY `k` (`k`),
      KEY `l` (`l`),
      KEY `m` (`m`),
      KEY `n` (`n`),
      KEY `o` (`o`),
      KEY `p` (`p`),
      KEY `q` (`q`),
      KEY `r` (`r`),
      KEY `s` (`s`),
      KEY `t` (`t`),
      KEY `u` (`u`),
      KEY `v` (`v`),
      KEY `w` (`w`),
      KEY `x` (`x`),
      KEY `y` (`y`),
      KEY `z` (`z`)
    ) ENGINE=MyISAM DEFAULT CHARSET=ascii;
    script that populated the table:
    PHP Code:
    <?php
    $fh 
    fopen('en.txt''r');
    $db = new PDO('mysql:host=*****;dbname=*****''*****''*****');
    $sql = <<<EOD
    INSERT INTO `words` VALUES (
        :word, :a, :b, :c, :d, :e, :f, :g, :h, :i, :j, :k,
        :l, :m, :n, :o, :p, :q, :r, :s, :t, :u, :v, :w, :x, :y, :z
    )
    EOD;
    $stmt $db->prepare($sql);
    while((
    $word fgets($fh20)) != false) {
        
    $word trim($word);
        
    $letters count_chars($word);
        
    $data = array(':word' => $word);
        foreach(
    range('a''z') as $letter) {
            
    $data[$letter] = $letters[ord($letter)];
        }
        
    $stmt->execute($data);
        echo 
    ".";
    }
    echo 
    PHP_EOL;
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  4. #19
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    I guess the next enhancement would be to add the Scrabble point value for each letter in the DB, then have the query also calculate the total points for each word.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  5. #20
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    Ha! Interesting method

    Have you ever tried the "count_chars" PHP function before NogDog? It could possibly replace your ranged query builder.
    JavaScript: Learn | Validate | Compact | bionoid

  6. #21
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    Quote Originally Posted by bionoid View Post
    Ha! Interesting method

    Have you ever tried the "count_chars" PHP function before NogDog? It could possibly replace your ranged query builder.
    I used it for populating the table and building the query, but decided to then let the database do the brute force work while being able to make use of all the indexes to optimize it. However, a few years ago I made an anagram solver that actually stored a serialized version of the count_chars() result in the database, then all I had to do was apply count_chars() to the input word, serialize() it, and look for that in the DB: http://charles-reace.com/PHP_and_MySQL/Anagram_Finder/ (don't laugh too much when you look at it: I haven't updated that site in a lonnngggg time).
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  7. #22
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    I apologies, busy reading your code on my iPhone and overlooked you using it. Your site looks fine too BTW

    I'm also interested to know how the profiles look using your method.
    JavaScript: Learn | Validate | Compact | bionoid

  8. #23
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    Fixed some HTML formatting issues, and added a timer so you can see how long it took PHP/MySQL to process the output.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  9. #24
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,739
    Quote Originally Posted by NogDog View Post
    I guess the next enhancement would be to add the Scrabble point value for each letter in the DB, then have the query also calculate the total points for each word.
    Bit difficult that because you don't know what squares intersect with your word and what multiplication values they may have.

    Anyway If I had to judge I'd probably say you are the winner as your code is the most readable.

  10. #25
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    Quote Originally Posted by bokeh View Post
    Bit difficult that because you don't know what squares intersect with your word and what multiplication values they may have.
    Yeah, location is at least as important as tile values. Makes me appreciate the AI more when I play Scrabble on my Kindle.

    Anyway If I had to judge I'd probably say you are the winner as your code is the most readable.
    w00t! What's my prize?
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  11. #26
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,739
    BTW, what is the point converting 'a-z' to integer value, then building an array with integer keys, only to convert them back to chars. Why not just use an array with string keys?

  12. #27
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    Quote Originally Posted by bokeh View Post
    BTW, what is the point converting 'a-z' to integer value, then building an array with integer keys, only to convert them back to chars. Why not just use an array with string keys?
    As to why, because count_chars() creates its resulting array with the numeric byte-values as the keys. Now, whether or not it would have made more sense at that point to immediate covert them to the corresponding characters would have made more sense, you might have a point -- or not: I've obviously not thought it through completely.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  13. #28
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,739
    Well one thing you can be sure of is the key order. With an associative array the keys could be in any order. If you were going to serialize and compare (like the acronym finder) the key order is important.

  14. #29
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,739
    Quote Originally Posted by NogDog View Post
    a few years ago I made an anagram solver that actually stored a serialized version of the count_chars() result in the database, then all I had to do was apply count_chars() to the input word, serialize() it, and look for that in the DB
    Wouldn't it have been a lot easier to just sort the letters of your word into alphabetical order and use that as the DB index?

    For example: xenophobia.

    Either: abehinoopx
    or: a:9:{i:97;i:1;i:98;i:1;i:101;i:1;i:104;i:1;i:105;i:1;i:110;i:1;i:111;i:2;i:112;i:1;i:120;i:1;}

    Or am I missing the plot?
    Last edited by bokeh; 10-11-2013 at 10:44 PM.

  15. #30
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    I think the anagram-solver was the result of a solution looking for a problem. I had run across the count_chars() function for some reason or other, and I realized that its results would be the same for any two combinations of the same letters, which led to the idea of an anagram-solver. If I had started out simply with the requirement to create an anagram-solver, who knows?

    As to simpler, while your alternative supplies a more compact result that might qualify as "simpler", it's a bit more subjective as to which is simpler to achieve:
    PHP Code:
    $result serialize(count_chars($word1));

    // versus

    $letters str_split($word);
    sort($letters);
    $result implode(''$letters); 
    Not really a big difference, and once you've indexed it in the DB, probably not any difference in performance (okay, if we're counting micro- or even nanoseconds, a few less bytes to exchange between the app and the DB might matter ), so I certainly have no argument against your proposal, but would be reasonably satisfied with either, I think.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles