Labels

Wednesday, June 7, 2017

Wordament Boggle solver

Here is the code which will work on all unix systems and give all the words that can be formed in wordament game.

Few highlights for the code :

1) Code can be easily modified to give only big words for more points.
2) Also longer words are printed first. This feature can also be easily changed.
3) To compile the code just use g++ compiler. (g++ test.cpp).
4) and run it using ./a.out
5) input the wordament game in row first format.
6) This code was written using code from g4g site.
7) I combined the code given in "g4g boggle solver" and "g4g tries" and combined them to solve wordament.

Code :
 
#include<iostream>
#include<cstring>
#include <vector>
#include <fstream>
#include <algorithm>
#include <pthread.h>
using namespace std;

#define M 4
#define N 4
#define MAX 15
#define MIN 7

struct TrieNode *dictionary;//  = getNode();

#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])

// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)

// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')

string boggle[M][N];// = {{'G','I','Z'},
// trie node
vector<string> ans;

struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];

// isLeaf is true if the node represents
// end of a word
bool isLeaf;
};

// Returns new trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
struct TrieNode *pNode = NULL;

pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode));

if (pNode)
{
int i;

pNode->isLeaf = false;

for (i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}

return pNode;
}

// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
void insert(struct TrieNode *root, string key)
{
int level;
int length = key.size();
int index;

struct TrieNode *pCrawl = root;

for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();

pCrawl = pCrawl->children[index];
}

// mark last node as leaf
pCrawl->isLeaf = true;
}

// Returns true if key presents in trie, else false
bool search(struct TrieNode *root, string key)
{
int level;
int length = key.size();
int index;
struct TrieNode *pCrawl = root;

for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);

if (!pCrawl->children[index])
return false;

pCrawl = pCrawl->children[index];
}

return (pCrawl != NULL && pCrawl->isLeaf);
}




// A given function to check if a given string is present in
// dictionary. The implementation is naive for simplicity. As
// per the question dictionary is givem to us.
bool isWord(string &str)
{
if (search(dictionary, str) != 0)
return true;
return false;
}

// A recursive function to print all words present on boggle
void findWordsUtil(bool visited[M][N], int i,
int j, string &str, int size)
{
// Mark current cell as visited and append current character
// to str
//int size;
visited[i][j] = true;
str = str + boggle[i][j];
size = size+boggle[i][j].size();

// If str is present in dictionary, then print it
if (size<= MAX  && size>=MIN && isWord(str))
ans.push_back(str);//cout << str << endl;

// Traverse 8 adjacent cells of boggle[i][j]
for (int row=i-1; row<=i+1 && row<M; row++)
for (int col=j-1; col<=j+1 && col<N; col++)
if (row>=0 && col>=0 && !visited[row][col])
findWordsUtil(visited, row, col, str, size);

// Erase current character from string and mark visited
// of current cell as false
str.erase(str.length()-boggle[i][j].size());
size = size - boggle[i][j].size();
visited[i][j] = false;
}

// Prints all words present in dictionary.
void findWords() {
bool visited[M][N] = {{false}};
string str = "";
for (int i=0; i<M; i++)
      for (int j=0; j<N; j++)
findWordsUtil(visited, i, j, str, 0);

}

int all_chars(string s) {
int t = s.size();
for (int i  = 0; i<t; i++) {
if (!(s[i] >= 'a' && s[i] <= 'z'))
return 0;
}
return 1;
}

void load_dictionary() {
string line;
int n = 0;
ifstream myfile("/usr/share/dict/words");
dictionary = getNode();
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
//std::transform(line.begin(), line.end(), line.begin(), ::tolower);
//dictionary.push_back(line);
if (all_chars(line) && line.size()<=MAX && line.size()>=MIN) {
insert(dictionary, line);
n++;
}
}
myfile.close();
}
cout <<"words added = "<<n<<endl;
}


void enter_boog(string boggle[M][N]) {
int i,j;
for (i= 0; i<M; i++) {
for (j = 0; j<N; j++) {
cin>>boggle[i][j];
}
}
}

bool compare(string s1, string s2) {
int i = s1.size();
int j = s2.size();
if ( i != j)
return i > j;
else
return (s1[0] - s2[0] > 0);
}
void display_words() {
sort(ans.begin(), ans.end(), compare);
for (int i=0; i<ans.size(); i++) {
cout<<ans[i]<<endl;
}
}
// Driver program to test above function
int main()
{
load_dictionary();
while (1) {
cout<<"enter boggle matrix";
enter_boog(boggle);
for (int i= 0; i<M; i++) {
for (int j = 0; j<N; j++) {
cout<<boggle[i][j]<<" ";
}
cout<<endl;
}

cout << "Following words of dictionary are present\n";

findWords();
display_words();
ans.resize(0);
}
return 0;
}


Sunday, April 16, 2017

Minimum Path Sum in C++ using tabulation (Dynamic Programming)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int row = grid.size();
        int col = grid[0].size();
        vector<vector<int>> v(row, vector<int>(col,0));
        v[0][0] = grid[0][0];
        for (int i = 1; i< row; i++) 
            v[i][0] = grid[i][0] + v[i-1][0];
        for (int i = 1; i< col; i++) 
            v[0][i] = grid[0][i] + v[0][i-1];
        for (int i = 1; i<row; i++) {
            for (int j = 1; j < col; j++) {
                v[i][j] = grid[i][j] + min (v[i-1][j], v[i][j-1]);
            }
        }
        return v[row-1][col-1];    
    }
};

Coin Change problem in C++ using tabulation method dynamic programming

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int n = coins.size();
        vector<vector<int>> v(n+1, vector<int>(amount+1, 0));
        for (int i = 0; i<=n; i++)
            v[i][0] = 0;
        for (int i = 0; i<= amount; i++)
            v[0][i] = INT_MAX;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= amount; j++) {
                if (j>=coins[i-1] && v[i][j-coins[i-1]] < INT_MAX)
                    v[i][j] = min(v[i-1][j], v[i][j-coins[i-1]]+1);
                else
                    v[i][j] = v[i-1][j];
            }
        }
        return (v[n][amount]<INT_MAX)?v[n][amount]:-1;
    }
};

Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.size();
        int len2 = word2.size();
        vector<vector<int>> v (len1+1, vector<int>(len2+1, 0));
        if (len1 == 0) return len2;
        if (len2 == 0) return len1;
        for (int i = 0; i< len1+1; i++) {
            for (int j = 0; j< len2+1; j++) {
                if (i == 0) v[i][j] = j;
                else if (j == 0) v[i][j] = i;
                else if (word1[i-1] == word2[j-1]) v[i][j] = v[i-1][j-1];
                else v[i][j] = 1+ min(min(v[i-1][j], v[i][j-1]), v[i-1][j-1]);
            }
        }
        return v[len1][len2];
    }
};

Longest Consecutive Sequence c++

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int max = 0;
        int cnt = 0;
        if (nums.size() == 0 ) return 0;
        sort(nums.begin(), nums.end());
        for (int i = 0; i< nums.size(); i++) {
            if (nums[i]+1 == nums[i+1]) {
                cnt++;
            } else if (nums[i+1] > nums[i]){
                if (cnt>max) max = cnt;
                cnt = 0;
            }
        }
        if (cnt>max) max = cnt;
        return max+1;
    }
};

Longest Substring Without Repeating Characters C++

#include <iostream>
#include <string>
#include <vector>
using namespace std;

   void util (string &s, int & max, int start, int end) {
        vector<int> arr(256,-1);
        int cnt = 0;
        int i;
        if (start >= end) return;
       
        for (i = start; i<end; i++) {
            if (arr[s[i]] == -1) {
                cnt++;
                arr[s[i]] = i;
            } else {
                break;
            }
        }
       
        if (cnt>max) max = cnt;
        arr.clear();
        if (i<end)
        util (s, max, arr[s[i]]+1, end);
       
    }
    int lengthOfLongestSubstring(string s) {
        int max = 0;
        util(s, max, 0, s.size());
        return max;
    }
int main() {
string s = "";
cout <<lengthOfLongestSubstring(s);
return 0;
}

Longest increasing sub-sequence in C++

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len = 0, max = 0;
        int n = nums.size();
        vector<int> L(n,1);
        for (int i = 0; i< n; i++) {
            for (int j = i+1; j<n; j++) {
                if (nums[j]>nums[i] && L[j]<L[i]+1) {
                    L[j] = L[i]+1;
                }
            }
        }
        for (int i = 0; i<n; i++) {
            if (max<L[i]) max = L[i];
        }
        return max;
    }
};