Scrabble code in java - java

I have to write a scrabble code in java without the use of if/switch statements. this is what i have so far
public class Scrabble {
public static void main(String[] args) {
}
public static int computeScore(String word) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int[] values = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,3,3,10,1,1,1,1,4,4,8,4,10};
int sum = 0;
for(int i = 0; i <word.length();i++) {
????
}
return sum;
}
}
I need some help, I had the idea of finding the character inside the string and finding its value but not sure how to write it out. Any help will be great! Thanks!

Inside you for loop you would need to do the following:
sum += values[aplphabet.indexOf(word.charAt(i))];
So your loop should so something like:
for(int i = 0; i <word.length();i++) {
sum += values[aplphabet.indexOf(word.charAt(i))];
}
This will of course not handle any modifier tiles on the scrabble board.
Alternatively you can use a HashMap<char, int> to store your letters, so that accessing them is a bit easier:
public class Scrabble {
HashMap<char, int> alphabet;
public static void main(String[] args) {
//initialize the alphabet and store all the values
alphabet = new HashMap<char, int>();
alpahbet.put('A', 1);
alpahbet.put('B', 3);
alpahbet.put('C', 3);
//...
alpahbet.put('Z', 10);
}
public static int computeScore(String word) {
int sum = 0;
for(int i = 0; i <word.length();i++) {
//look up the current char in the alphabet and add it's value to sum
sum += alphabet.get(word.charAt(i));
}
return sum;
}
}

Related

Finding the Sum of a String of numbers seperated by operators

Given String = "128+16+8+2+1"
Answer should print out 155
The code is supposed to add all numbers in the string and the answer should be printed out as a string.
I attempted to write the code for this, however the last 2 numbers will not add and my current answer is printing out 153. Looking for help to lead me to the correct solution.
import java.util.stream.*;
public class add {
static void evalA(String s) {
int n = countChar(s,'+');
System.out.println(s);
int cnt = 0;
int[] data = new int[n];
for(int i=0;i<s.length();i++) {
if (s.charAt(i)=='+') {
System.out.println(s.substring(0,i));
data [cnt] = Integer.parseInt(s.substring(0,i));
cnt++;
s = s.substring(i+1,s.length()-1);
i=0;
}
}
String sum = ""+IntStream.of(data).sum();
System.out.println(sum);
}
}
You could do something like this:
public static void main(String[] args)
{
evaluate("128+16+8+2+1");
}
public static void evaluate(String equation)
{
String[] numbers = equation.split("\\+");
int sum = 0;
for (String number : numbers)
{
//could wrap this in a check incase of exception or errors
sum += Integer.parseInt(number);
}
System.out.println(sum);
}
It just splits the string up by the + to get the individual numbers as an array and then loop through the array and add each numbers value to a sum variable.

how to reverse a number using array in java?

I am writing a code to reverse a number entered by a user using java. I am using an array for this purpose. The problem that I am facing is in returning the array when I call my method in the main function.
I understand that you want to reverse an array... so, for that you can use ArrayUtils.reverse
ArrayUtils.reverse(int[] array)
For example, you can do:
public static void main(String[] arg){
int[] arr = { 1,2,3,4,5,6};
ArrayUtils.reverse(arr);
System.out.println(Arrays.toString(arr));
// Prints: [6, 5, 4, 3, 2, 1]
}
However, if you want to code the reverse by yourself, if you check the source code of ArrayUtils.reverse, you can find how Apache guys did it. Here the implementation:
public static void reverse(int[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
int tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
There are many ways of doing it. Depends if you want to use Java Builtin methods or not. Here is my part:
Reverse a int array using ListIterator:
public class ReverseAListWithoutInbuiltMethods {
public static void main(String[] args) {
int[] arr={12, 4, 34, 7, 78,33, 20};
display(arr);
int[] rev=reverse(arr);
display(rev);
}
private static void display(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(" "+arr[i]);
}
System.out.println("");
}
private static int[] reverse(int[] arr){
List<Integer> list=new ArrayList<Integer>();
for(int a:arr){
list.add(a);
}
int[] rev=new int[arr.length];
int j=0;
ListIterator<Integer> listI=list.listIterator(arr.length);
while(listI.hasPrevious()){
rev[j]=listI.previous();
j++;
}
return rev;
}
}
Reverse by for loop only:
public static void main(String[] args) {
/* create a new string */
StringBuilder s = new StringBuilder("GeeksQuiz");
System.out.println(" ************* REVERSED STRING IS **************");
char[] c2=reverseForLoop(s);
for (int i = 0; i < c2.length; i++) {
System.out.print(c2[i]);
}
}
private static char[] reverseForLoop(StringBuilder sb) {
char[] str = sb.toString().toCharArray();
int n = str.length;
char[] charNew = new char[n];
int j = 0;
for (int i = n - 1; i >= 0; i--) {
charNew[j] = str[i];
j++;
}
return charNew;
}
Reverse using swap method:
private static char[] reverse2(StringBuffer sb) {
char[] str=sb.toString().toCharArray();
int n = str.length;
for (int i = 0; i < n / 2; i++) {
swap(str, i, n - 1 - i);
}
return str;
}
private static void swap(char[] charA, int a, int b) {
char temp = charA[a];
charA[a] = charA[b];
charA[b] = temp;
}
Reverse String using Stack implementation:
public class StackForStringReverse {
public static void main(String[] args) {
/*create a new string */
StringBuffer s= new StringBuffer("GeeksQuiz");
/*call reverse method*/
reverse(s);
/*print the reversed string*/
System.out.println("Reversed string is " + s);
}
private static void reverse(StringBuffer str) {
int n=str.length();
MyStack obj=new MyStack(n);
// Push all characters of string
// to stack
int i;
for (i = 0; i < n; i++)
obj.push(str.charAt(i));
// Pop all characters of string and put them back to str
for (i = 0; i < n; i++)
{
char ch = obj.pop();
str.setCharAt(i,ch);
}
}
}
class MyStack{
int size;
char[] a;
int top;
public MyStack(int n) {
top=-1;
size=n;
a=new char[size];//{'1','f','f','f'};
}
public boolean isEmpty() {
return top<0;
}
/**
* Insert data into Stack if it's not full*/
public void push(char c) throws IllegalArgumentException{
if(top>=size) {
throw new IllegalArgumentException("Stack overflow.");
}
a[++top]=c;
}
public char pop() {
if(top<0) {
throw new IllegalArgumentException("Stack underflow.");
}
char x=a[top--];
return x;
}
public void clear() {
while(top>0) {
top--;
size=top;
}
}
/**
* Display the data inserted */
public void display() {
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]);
}
System.out.println("");
}
}
You can do that using StringBuilder :
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println(getReverse(s.nextInt()));
}
public static int getReverse(int a){
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(a));
sb = sb.reverse();
return Integer.parseInt(sb.reverse().toString());
}
}
StringBuilder can do reversals.
String reverseNumber(Number n) {
String numStr = n.toString();
StringBuilder reverser = new StringBuilder(numStr);
reverser.reverse();
return reverser.toString();
}
Obviously there are some gaps here for particular cases (e.g. negative numbers) but I'll leave that for you to solve. This should serve as a good starting point.
Java is powerful, but complicated.
Here is a oneliner for it.
public static void main(String[] args) {
int n = 123;
int reversed_n = (int) Integer.valueOf( // 5.) cast back to an int.
new StringBuilder(
Integer.toString(n) // 1.) Make the integer a String.
) // 2.) load that string to a String builder.
.reverse() // 3.) reverse the string.
.toString())); // 4.) go back to a string.
}
Tried my hand at a relatively well-documented, external library and array-free solution. Hope it helps!
int reverseNumber(int inputNum)
{
String numString = Integer.toString(inputNum);
int numLength = numString.length();
int finalReversedNumber = 0;
/*
* Goes through the input number backwards, and adds the digit (with it's new value) to the final number.
* This is accomplished by multiplying the current number by 10 to the power of the index i, which corresponds
* to the current digit value of the number.
* i the index counter, goes from the length of the input number (not inclusive) to 0 (inclusive)
*/
for(int i=numLength-1; i>=0; i--)
{
int currentNum = Integer.parseInt(String.valueOf(numString.charAt(i)));
int valueInFinalNum = currentNum * (int)Math.pow(10, i); // i.e. a 5 in the thousands digit is actually 5000
finalReversedNumber += valueInFinalNum;
}
return finalReversedNumber;
}

Java void into an int array

how do I store a void in to an array?
for my example:
count (String text) into int[] letter.
is there a quick and easy opportunity to do it or should I rewrite it completely?
I really appreciate your help
my code:
public static void main (String [] args){
String text="E";
String[] words = split(text);
int[] letter = count(text);
someWords(words, letter);
}
public static int[] count(String text){
int count;
for (char letter=(char)65;letter<=90;letter++){
count=0;
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(I) || (letter+32)==text.charAt(I)){
count++;
}
}
if (count>0){
System.out.println(letter+" = "+count);
}
}
}
I could be wrong, because your question is not very clear, but it seems that what you're trying to do is:
public static int[] count(String text){
int[] counts = new int[26];
// iterate over each letter:
for (char letter='A';letter<='Z';letter++){
int currentIndex = (int) letter - 'A';
// count the occurrences of the current letter:
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(i) || (letter+32)==text.charAt(i)){
counts[currentIndex]++;
}
}
// print the count for the current letter if non-zero
if (counts[currentIndex]>0){
System.out.println(letter+" = " + counts[currentIndex]);
}
}
return counts;
}
There's surely a more efficient way to do this (iterating over the characters in text and incrementing the count index accordingly would be faster than checking all the chars in text 26 times), but the approach works.
I don't really understand why you want to do it like this, but you can just pass the int[] as a paramter.
...
int[] count = new int[1];
count(text, count);
...
public static void count(String text, int[] count){
...
count[0] = ..
}
Reading your code it seems like you just want to return and integer and not an integer array (the number of letters in a String as it seems)
public static int count(String text){
int count;
for (char letter=(char)65;letter<=90;letter++){
count=0; // are you sure you want to set the value of count to 0 every time you loop?
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(i) || (letter+32)==text.charAt(i)){
count++;
}
}
if (count>0){
System.out.println(letter+" = "+count);
}
}
return count;
}
In your main method you write:
String[] words = split(text);
int letter = count(text);
public int count()
{
count = 0;
for ...
...
...
return count;
}
you should use RETURN word at the end of your function, and declare the return type (int, string, ...etc) next to the function name.
You only need to spin through the string once:
public static int[] count(String text) {
int[] totals = new int[26];
for (char c : text.toUpperCase().toCharArray()) {
int idx = (int)c - (int)'A';
if ((idx >= 0) && (idx <= 26)) {
totals[idx]++;
}
}
return totals;
}

How to print the string without duplicate?

I tried to print the string without duplicate but i not getting the proper output and here I exposed my code snippets.
class Duplicatestring
{
public static void main(String [] args)
{
String word = "";
String[] ip ={"mani" ," manivannan","raghv ","mani"};
for(int i =0; i<ip.length; i++)
{
for(int j = i+1; j<=ip.length; j++)
{
if(ip[i].equals(ip[j])){
word = word+ip[i];
}
}
System.out.println(word);
}
}
}
And one more thing is I don't want use the collections that is my task and pleas give any proper solution for this.
Example:
Input -> {mani, manivanna,raghv, mani};
output -> {mani, manivanna,raghv}
If you don't want to use collections then I assume it's a homework, so I don't want to provide you a full solution, but I'll guide you.
You can have a helper array of the size of the original array. Now you write two nested loops and for each word, if you find a duplicate, you mark the helper array with 1.
After this procedure you'll have something like this in the helper array:
[0,0,0,1]
Now you iterate on the arrays in parallel and print the element only if the corresponding index in the helper array is 0.
Solution is O(n2).
Your loop is incorrect.
To solve the problem, you can use a Set to eliminate duplicated words.
If the problem must be solved by O(n^2) loops, the following code will work:
public class Duplicatestring {
public static void main(String[] args) {
String[] ip = { "mani", " manivannan", "raghv ", "mani" };
for (int i = 0; i < ip.length; i++) {
boolean duplicated = false;
//search back to check if a same word already exists
for (int j = i - 1; j >= 0; j--) {
if(ip[i].equals(ip[j])) {
duplicated = true;
break;
}
}
if(!duplicated) {
System.out.println(ip[i]);
}
}
}
}
if you want to remove the duplicate from the array call the below method and pass the array has the duplicate values.. it will return you the array with non-duplicate values..
call method here
ip = removeDuplicates(ip);
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}
it will return you the non duplicates values array..!!
u may try this:
public class HelloWorld{
public static void main(String []args){
String[] names = {"john", "adam", "will", "lee", "john", "seon", "lee"};
String s;
for (int i = 0; names.length > i; i ++) {
s = names[i];
if (!isDuplicate(s, i, names)) {
System.out.println(s);
}
}
}
private static boolean isDuplicate(String item, int j, String[] items) {
boolean duplicate = Boolean.FALSE;
for (int i = 0; j > i; i++) {
if (items[i].equals(item)) {
duplicate = Boolean.TRUE;
break;
}
}
return duplicate;
}
}
output
john
adam
will
lee
seon
if string order does not matter for you, you can also use the TreeSet.. check the below code.. simple and sweet.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class MyArrayDuplicates {
public static void main(String a[]){
String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
System.out.println();
Iterator<Integer> iterator = unique.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
it will print as -
[five, four, one, three, two]
five
four
one
three
two

charAt(i) is not giving expecting Behaviour with arrays

Below is my simple program which converts a string into elements of array, charAt(i) is not returning what it is supposed to according to documentation. My code is
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
int puz[] = new int[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (int c : puz) {
System.out.println(c);
}
}
}
Expected output: 1 2 3 4 5
Real output: 49 50 51 52 53
but when i use puz[i] = puzzle.charAt(i)-"O";
its working Fine..!
That's because a character's value is not the same as the int used to represent it. Declaring puz as a char[] should resolve the issue and print the numbers as expected.
You are displaying the character's unicode point values. Instead, you could use
System.out.println(Character.getNumericValue(c));
try
char puz[] = new char[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (char c : puz) {
System.out.println(c);
}
Its normal.
You take the string "1" not the number 1.
To get the number, prefer use Integer.paserInt(yourString);
then you'l lget your number.
As example:
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
int puz[] = new int[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = Integer.parseInt(puzzle.charAt(i));
}
for (int c : puz) {
System.out.println(c);
}
}
You're casting the char you get to an int, thus Java will print its integer representation. Store the result as an array of Strings, and loop over that array to print.
You implicitly convert char to int,a char '1' is not equals to 1,You can cast them to char like:
System.out.println((char)c);
You are using the int array so it prints the ascii values.You can do the following :
public static void fromPuzzleString(String puzzle) {
for (int i = 0; i < puzzle.length(); i++) {
System.out.println( puzzle.charAt(i));
}
}
You need not use 2 for loops and an array unnecessarily.
"charAt(i) is not returning what it is supposed to according to documentation"
You cannot put a char inside an int. Or else it will return its unicode value.
The values returned Real output: 49 50 51 52 53 are the unicode ASCII Characters codes
This will solve your issue:
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
char[] puz = new char[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (char c : puz) {
System.out.println(c);
}
}
}
However, to save memory I would suggest that you do not declare an array, display the values immediately like this:
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
for (int i = 0; i < puzzle.length(); i++) {
System.out.println(puzzle.charAt(i));
}
}
}

Categories

Resources