In 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 only use each tile once.
CODE:
package com.company; //main driver class class Main{ //main method public static void main(String[] args) { String tile = "quijibo"; String word = "jib"; //testing the function if(canSpell(tile,word)){ System.out.println(tile+" can spell "+word); }else System.out.println(tile+" cannot spell "+word); } //can spell method returns true if the word string is possible //to extract from the tiles String otherwise false public static boolean canSpell(String tiles, String word){ StringBuilder tileString = new StringBuilder(tiles.toLowerCase()); word = word.toLowerCase(); //extracting char by char from word String boolean found; for(int i=0;i<word.length();i++){ found = false; for(int j=0;j<tileString.length();j++){ if(word.charAt(i) == tileString.toString().charAt(j)){ //if the current letter is found in the tile that letter is removed from the tiles String //and found is set to true tileString.deleteCharAt(j); found = true; break; } } //if in any iteration found remains false that means the word cannot be //spelt using the given String tiles hence the function returns false if(!found) return false; } //if all the letters of the String word are present in the String tiles the //function returns true return true; } }
_________________________________________
CODE IMAGES:
_________________________________________
OUTPUT:
___________________________________________________
Feel free to ask any questions in the comments section
Thank You!
Get Answers For Free
Most questions answered within 1 hours.