In: Computer Science
using Java;
In Scrabble, each player has a set of tiles with letters on them. The object of the game is to use those letters to spell words. The scoring system is complex, but longer words are usually worth more than shorter words. Imagine you are given your set of tiles as a string, like "quijibo", and you are given another string to test, like "jib". Write a method called canSpell that takes two strings and checks whether the set of tiles can spell the word. You might have more than one tile with the same letter, but you can use each tile only once.
/**
* Java method that takes as input 2 strings,
representing the tiles and word and returns if the word can be
spelled using the tiles
* (each tile can be used only one)
* @param tiles, letters currently the user have
* @param word, letters of the word to check
* @return, boolean, if word can be spelled using the
tiles then return true else return false
*/
public boolean canSpell(String tiles, String
word)
{
// create an array of same size as
number of letters in tiles, with all entries initialized to
false
boolean[] used = new
boolean[tiles.length()];
for(int
i=0;i<used.length;i++)
used[i] =
false;
boolean found;
// loop over the word, character by
character
for(int
i=0;i<word.length();i++)
{
found = false;
// set found to false, as ith letter of word has not been found yet
in tiles
// loop over the
tiles, to search for ith character of word in tiles
for(int
j=0;j<tiles.length();j++)
{
// jth letter of tiles = ith letter of word and
jth letter has not been used
if((word.toLowerCase().charAt(i) ==
tiles.toLowerCase().charAt(j)) && (!used[j]))
{
// set jth letter used to
true and set found to true and exit the loop
used[j] = true;
found = true;
break;
}
}
if(!found) // if
ith letter of word has not been found, return false as word cannot
be spelled using the tiles
return false;
}
return true; // all letters of word
found in tiles, return true as word can be spelled using the
tiles
}