How to create an Anagram Generator

Posted: September 20, 2012 in Programming
Tags: , , , ,

Anagram generator is the tool which generates all possible meaningful combination of the words from the given input word. This application is created using HTML,CSS,PHP,JQUERY,MYSQL.

Working example of this code : Anagram Working Example
Download Source Code : Anagram Code
The source code has 7 files. Lets walk through it.

File 1 : Connect.php
Purpose : This file is used to created a database connection and selection of the database.

<?php
//setting the paramters
$hostname="";
$username="";
$password="";
$dbname="";
$con=mysql_connect($hostname,$username,$password); //creating the connection
if(!$con)
{
  //what if the connection fails
	die('couldnt connect to db');
}

mysql_select_db($dbname",$con); //selecting the db

?>

File 2 : index.php
Purpose : This is the design file and it holds the input

<?php // creation of session 
session_start();
$_SESSION['value']=1;
?>
<!-- Designing of the index page --!>
<html>
	<head>
		<link rel="stylesheet" type="text/css" href="mystyle.css" />
		<title>Anagram Finder</title>
	</head>
	<body>
		<div id="header">
			ANAGRAM FINDER
		</div>
		<br>
		<hr />
		<br>
		<br>
		<div id="main_container">
		<table id="table1" width="100%" border="1">
			<tr>
				<td width="30%">
							<div id="leftpane">
			<P id="ul_head">Rules for Giving Input</p>
			
			
				
					The input must only be alphabets<br>
				
				
					The input must atleast by 3 characters long<br>
				
				
				
					The input can be maximum of 15 characters<br>
				
					
				
					The input must contain atleast one vowel<br>
				
				
					The input may contain repetition of letters<br>
					
		</div>					
				</td>
				<td>
					<div id="content">
						<P id="ul_head">Enter the input word and hit generate</p>
						<form action="result.php" method="post">
						<input type="text" name="word" maxlength="15" class="tbox">
						<p class="error"></p>
						<br><br>
						<input type="submit" name="submit" value="Generate Now" id="submit">
						
						</form>			
						<br><br>
					</div>		
				</td>
			</tr>
		</table>
		</div>
		<script type="text/javascript" src="jquery.js"></script>  <!-- Inclusion of JQuery Library --!>
		<script type="text/javascript" src="validate.js"></script>  <!-- Validating user input using jquery --!>
	</body>
</html>


File 3 : result.php
Purpose : This file holds the logic to find the anagram

<?php 
	require_once('connect.php'); //connect to the database
	session_start(); //start the session 
	
?>
<html>
	<head>
		<link rel="stylesheet" type="text/css" href="mystyle.css" /> 
		<title>Anagram Finder</title>
	</head>
	<body>
		<div id="header">
			ANAGRAM FINDER
		</div>
		<br>
		<hr />
		<br>
		<br>
		<div id="result">
		
		
<?php

if(isset($_SESSION['value']))
{
$word=strtolower($_POST['word']); // get the input word
$len=strlen($word);
$alpha = array(
"a" => 0,
"b" => 1,
"c" => 2,
"d" => 3,
"e" => 4,
"f" => 5,
"g" => 6,
"h" => 7,
"i" => 8,
"j" => 9,
"k" => 10,
"l" => 11,
"m" => 12,
"n" => 13,
"o" => 14,
"p" => 15,
"q" => 16,
"r" => 17,
"s" => 18,
"t" => 19,
"u" => 20,
"v" => 21,
"w" => 22,
"x" => 23,
"y" => 24,
"z" => 25
); // An array which holds the character value


function generate($input_word,$array,&$num)
{
	$len_input_word = strlen($input_word);
	for( $i=0 ; $i<$len_input_word ; $i++) //run the loop till wordlength
	{
 		$array_index = $array[$input_word[$i]]; //compare with alpha array and find the index of the letter
 		$num[$array_index] = $num[$array_index] + 1; // store the index value in $num array
	}

	return $num;
}



$result = array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); //output array
$result=generate($word,$alpha,$result); //passing arrays to function 
$input_bin=implode("",$result); //now, $input_bin contains the input string in numbers format
$result = array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); // re-initialize the array 
$init=array();
for($i=0;$i<$len;$i++)
{
	array_push($init,$alpha[$word[$i]]); //create number format for input word and store it in init array
}

$init_str=implode($init,','); // create a string by imploding array with comma as parameter
$extract=array();
$query= mysql_query("select id,word,bin from anagram where len<=$len and init in ($init_str) and last in ($init_str) order by len");
// query to fetch words from db which has the length less than or equal to our input word
while($row=mysql_fetch_assoc($query))
{
	$db_id=$row['id'];
	$db_title=$row['word'];
	$db_bin=$row['bin'];
	$count=0;
	for($i=0;$i<26;$i++)
	{
		if($db_bin[$i]<=$input_bin[$i])
		{
		  //if the value of db word is less than or equal to value of input word increase the count
			$count++;
		}
		else
		{
		  // even if one condition fails, break the loop
			break;
		}
	}
	
	if($count==26)
	{
	   // if all the letters meets the condition , it is an anagram
		$extract[]=$db_title; //store the word in output array
	}
}


?>


<?php //printing array in table format if(count($extract)) { ?>
<table id="output_table">
<th><a href='index.php'>Try Again</a></th>
<?php for($i = 0; $i < count($extract); ++$i) { ?>
<?php if(!$i) { ?>
  <tr>
<?php } else if(!($i %10)) { ?>
  </tr>
  <tr>
<?php } ?>
    <td><?php echo $extract[$i]; ?></td>
<?php } ?>
  </tr>
</table>
<?php }
else
{
//if input word has no combinations
	echo '
	<table id="output_table">
	<th><a href="index.php">Try Again</a></th>
	<tr><td> No Combinations Found For The Given Input </td></tr>
	<table>
	';
	
}

mysql_close($con); //close db connection

}
 ?>

</div>
				
	</body>
</html>

<?php
session_destroy(); //destroy the session 
?>

<?php
if(!isset($_SESSION['value']))
{
//handle if session is not set
	echo '
	<table id="output_table">
	<th><a href="index.php">Go Back</a></th>
	<table>
	';
}

?>

File 4 : mystyle.css
Purpose : Design using CSS

body
{
	background-color:#b0c4de;
}

#header
{
	font-family:"Comic Sans MS", Times, serif;
	font-size:30px;
	text-align:center;
}

hr
{
	
	background-color: #FFFFFF;
	height: 5px;
}

#leftpane{
	color:#000000;
	font-family:"Comic Sans MS", cursive, sans-serif;
	margin : 10px;
	text-align: left;
}

#ul_head
{
	color: #463325;
	font-size: 30px;	
}

#content
{
	vertical-align:top;
}

.table
{
	border-style: solid;
		
}

#content
{
	text-align:center;
}

.tbox
{
	width:300px;
	height: 30px;
	font-size : 25px;
	font-family:"Comic Sans MS", Times, serif;	
}


table#output_table
{
	border-style: solid;
	width:100%;
	font-family:"Comic Sans MS", Times, serif;
	font-size:20px;
	color:#3E210C;
	border-collapse:collapse;
}

td
{
	text-align:center;
	height: 50px;
	padding: 15px;
	border-style :solid;
	
}


a
{
	text-decoration:none;
}

.error
{
	color:red;
}

File 5 : validate.js
Purpose : Validate the input and throw error if necessary

var $input = $('.tbox');
var $error = $('.error');
var $submit = $('#submit');
var Filters = {
	min: {
		re: /.{3,}/,
		error: '*Must be at least 3 characters.'
	},
	char: {
		re: /^[a-z]+$/i,
		error: '*Must be only letters.'
	},
	vowel: {
		re: /[aeiou]/i,
		error: '*Must have at least one vowel.'
	}
};

function test(value, filters) {
	var isValid = false;
	for (var i in filters) {
		isValid = filters[i].re.test(value);
		$error.hide();
		$submit.prop('disabled', false);
		if (!isValid) {
			$error.show().text(filters[i].error);
			$submit.prop('disabled', true);
			break;
		}
	}
	return isValid;
}

test($input.val(), Filters);
$input.on('keyup blur', function() {
	test(this.value, Filters);
});

And the last one is Database which contains all the dictionary words in the number format. YOu can download that dictionary from the above link.

Advertisements
Comments
  1. Elango says:

    Do you have the scripts to create the DB? What is the logic behind the bin column in the sql dump. Can you please explain

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s