Strings - Number guessing game [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is a game that generates a random 4 digit number and then lets the user input 5 chances to guess the game and returns a hint as to how many numbers were in the correct place and how many matched but were in the wrong place.
I am having a problem comparing two strings. One of the strings holds the correct answer to the game, the other string holds the most recent 4 digit guess.
aCount needs to be the number of characters that are in correct position.
bCount needs to be the number of characters that are in the correct answer, but not in correct position.
bCount is the part I'm having trouble with (it's not working as I expect). I thought I might try a double for loop, but I'm not sure.
static String getHint(String guess, String answer){
int aCount=0;
int bCount=0;
String hintString="";
for (int i =0; i<answer.length(); i++){
char guessAChar = guess.charAt(i);
char ansAChar = answer.charAt(i);
if(guessAChar == ansAChar){
aCount++;
}
}
for (int indexOfGuess = 0; indexOfGuess < answer.length(); indexOfGuess++)
{
for (int indexOfActualNumber = 0; indexOfActualNumber < answer.length(); indexOfActualNumber++)
{
if (guess.charAt(indexOfGuess) == (answer.charAt(indexOfActualNumber)))
{
bCount++;
}
}
}
bCount = bCount - aCount;
hintString =("Your hint is: \n"+aCount+"A" + bCount + "B");
return hintString;
}
}
EDIT: This problem has been solved: This method now searches and outputs how many numbers in each string match, and how many in each position are the same!

Variable bCount is the amount of numbers in the final string, but not in the right spot. You need a double loop for this to check each character in each string to see if they match. This might point you in the right direction.
int outer_counter = 0;
for(char g : guess.toCharArray())
{
int inner_counter = 0;
for(char a : answer.toCharArray())
{
if(g == a && inner_counter != outer_counter)
{
bCount++;
}
inner_counter++;
}
outer_counter++;
}
The counters make sure these are NOT in the same position.

So bCount is determining the number of digits that are in the answer, but not in the right place. So let's try this:
public string bCount()
{
for (int indexOfGuess = 0; indexOfGuess < answer.length(); indexOfGuess++)
{
for (int indexOfActualNumber = 0; indexOfActualNumber < answer.length(); indexOfActualNumber++)
{
if (guess.charAt(indexOfGuess).equals(answer.charAt(indexOfActualNumber))
{
bCount++;
}
}
}
}
This method does:
Creates an outer loop that loops through each index of the "guess" array
Creates an inner loop that, while the "guess" array is at an index, the inner loop will loop through each index (so while "guess" is at index 0, "answer" will go through all indexes before "guess" goes to 1, and then the inner loop runs again)
Check to see if the number at the guess index = number at the actual index.
If it is, increment bCount.
The only issue which I haven't taken care of for you is if the number is entered twice. Example: if the number is 1900, and you guess 1909, you number for bCount will be higher than it should be. However, I'll leave that to you as this is a homework assignment after all.

Related

Not understanding the issue with my solution to a palindrome problem

I'm trying to solve a question where your code is supposed to determine if a given number is a palindrome or not, and I don't understand why it isn't working.
(You can skip this and just read the code if you want) The idea was that I create a string with the value of the integer, and create a for loop using the length of said string that uses % 10 to reverse the integer and store it in a separate string. I would then compare the 2 strings to determine if the number is a palindrome or not
public static boolean isPalindrome(int x) {
String s = String.valueOf(x);
int count = s.length();
String palindrome = "";
for(int i = 0; i < count; i++){
palindrome += x % 10;
}
System.out.print(palindrome);
if(palindrome == s){
return true;
}
else{
return false;
}
}
The problem is that the code only returns false, and when I added a print statement to check what the reversed number (String palindrome) is, I got a different number.
For ex. I used 121 to test it and after the for loop the print statement outputted 111.
I'm not really looking for a solution, I just want to understand why it's behaving like this. Thanks in advance.
for(int i = 0; i < count; i++){
palindrome += x % 10;
}
Since x does not change in that loop (or indeed anywhere in the code), each execution yields the same thing, the least significant digit of x.
Thus palindrome has some number of copies of the same digit, and will almost never equal s
You need to divide x by 10 each time around the loop.

Outputting specific values from an two dimensional array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Problem with output from a two dimensional array, basically 8 rows and 5 columns, each row represents one athlete, the five colums represent the points they have gained in each task. I have to find out If an athlete went beyond 250 points in a single task. Firstly, I made an integer which counts the number of times the Array has been look at, If the number can be divided by 5 it means the next number is going to be the next row and thus a new athlete, next I created another loop to check all the previous numbers and if any of them goes beyond 250, I add one number to the total + break the cycle. The result I have been getting back is 0, or before I got nothing.
for (i=0; i<8; i++) {
for (j=0; j<5; j++)
if(rezultati[i][j]>0) {
skaits = skaits + 1;
}
else if(skaits % 5==0) {
for (int a=0; a<5; a++) {
if(rezultati[i-a][j-a]>250) {
daudzums = daudzums + 1;
break;
}
}
}
}
realised that the row index should be just i if(rezultati[i][j-a]>250), didnt fix the issue tho
You already have an outer loop that will move to the next row/athlete for you. Simply look at the current value and if it exceeds 250, increment your counter and move to the next athlete with break:
int daudzums = 0;
int[][] rezultati = new int[8][5];
// ... populate zezultati somehow ...
for (int i=0; i<rezultati.length; i++) {
for (int j=0; j<rezultati[i].length; j++) {
if (rezultati[i][j]>250) {
daduzums++;
break; // move to next athlete
}
}
}
System.out.println("daudzums = " + daudzums);
After the loops, daudzums will tell you how many athletes had at least one task over 250.

How to find missing numbers in an integer array in Java? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I couldn't find a solution for this in Java. I need to write code that will take an integer n, and an array of integers that has numbers up to n(some may be missing), and the method will print out which numbers are missing
ex: {2; 3; 5; 1; 2; 3} should print out 4, 6
Edit: Here is what I got from the comments suggestion, but it doesn't seem to work. What did I do wrong?
public static void findMissingNum(int n, int[]a) {
boolean A[] = new boolean[n];
for(int i = 0; i < a.length; i++) {
A[a[i]] = true;
}
for(int j = 0; j < A.length; j++) {
if (A[j] = false) {System.out.print(A[j]);}
}
}
I've seen this used as a homework or quiz problem before, the question is begging you to use a hash table. Create an empty Boolean array of size n and for each number in the list set array[num] to True. Loop over the new array, and record all the instances of False, you know ahead of time how many there should be.
The following ought to work:
public void find() {
Scanner s = new Scanner(System.in);
int[] nums = {2, 3, 5, 1, 2, 3};
int n = s.nextInt();
boolean[] included = new boolean[n+1];
for(int i = 0; i < nums.length; i++) included[nums[i]] = true;
for(int z = 0; z < included.length; z++) {
if(included[z] == false) System.out.print(z+ ",");
}
}
This will print out all missing numbers including n (if it is missing). If n is not included then do new boolean[n]
The way it works is by first using Scanner to read in your int n. It has two arrays, an int array which has your numbers, and a boolean array which serves as a set of flags. The boolean array is initalized to the size of n. Then it loops through the nums array and sees what numbers are included in the array. If the number is included, its element in the boolean arary is flagged as true. Finally, it loops through the flags/boolean array, if the element at that flag is true, do nothing since its already there, otherwise if its false (meaning the # wasn't included) then print it.
Try to implement this solution in Java:
Create second array A = [0,..,n] of booleans. Initialize it with false values.
Iterate through input array: for i = 0 to length(inputArray): A[inputArray[i]] := true.
Check which indexes in array have value false, those are the values that You want to return.
List< Integer > list = Arrays.asList(yourArray);
Then you can just create an array from 1 up to n with all numbers in order, and iterate through its elements checking for each one if your list contains it or not, adding it to another missingValues list if not.

What is wrong with my Java solution to Codility MissingInteger? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to solve the codility MissingInteger problem link:
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A.
For example, given:
A[0] = 1
A[1] = 3
A[2] = 6
A[3] = 4
A[4] = 1
A[5] = 2
the function should return 5.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
My solution is:
class Solution {
TreeMap<Integer,Object> all = new TreeMap<Integer,Object>();
public int solution(int[] A) {
for(int i=0; i<A.length; i++)
all.put(i+1,new Object());
for(int i=0; i<A.length; i++)
if(all.containsKey(A[i]))
all.remove(A[i]);
Iterator notOccur = all.keySet().iterator();
if(notOccur.hasNext())
return (int)notOccur.next();
return 1;
}
}
The test result is:
Can anyone explain me why I got this two wrong answers? Especially the first one, if there is only one element in the array, shouldn't the only right answer be 1?
Here is my answer, got 100/100.
import java.util.HashSet;
class Solution {
public int solution(int[] A) {
int num = 1;
HashSet<Integer> hset = new HashSet<Integer>();
for (int i = 0 ; i < A.length; i++) {
hset.add(A[i]);
}
while (hset.contains(num)) {
num++;
}
return num;
}
}
returns the minimal positive integer that does not occur in A.
So in an array with only one element, if that number is 1, you should return 2. If not, you should return 1.
I think you're probably misunderstanding the requirements a little. Your code is creating keys in a map based on the indexes of the given array, and then removing keys based on the values it finds there. This problem shouldn't have anything to do with the array's indexes: it should simply return the lowest possible positive integer that isn't a value in the given array.
So, for example, if you iterate from 1 to Integer.MAX_VALUE, inclusive, and return the first value that isn't in the given array, that would produce the correct answers. You'll need to figure out what data structures to use, to ensure that your solution scales at O(n).
I have done the answer inspired by the answer of Denes but a simpler one.
int counter[] = new int[A.length];
// Count the items, only the positive numbers
for (int i = 0; i < A.length; i++)
if (A[i] > 0 && A[i] <= A.length)
counter[A[i] - 1]++;
// Return the first number that has count 0
for (int i = 0; i < counter.length; i++)
if (counter[i] == 0)
return i + 1;
// If no number has count 0, then that means all number in the sequence
// appears so the next number not appearing is in next number after the
// sequence.
return A.length + 1;
returns the minimal positive integer that does not occur in A
The key here is that zero is not included in the above (as it is not positive integer). So the function should never return 0. I believe this covers both of your failed cases above.
edit: due to the fact that question has been changed since this was written this answer isn't really relevant anymore
Very little wrong.
Just the last line
return 1;
should read
return A.length + 1;
because at this point you've found & removed ALL KEYS from 1 to A.length since you have array entries matching each of them. The test demands that in this situation you must return the next integer above the greatest value found in array A.
All other eventualities (e.g. negative entries, missing 1, missing number between 1 and A.length) are covered by returning the first unremoved key found under iteration. Iteration here is done by "natural ordering", i.e. 1 .. max, by default for a TreeMap. The first unremoved key will therefore be the smallest missing integer.
This change should make the 2 incorrect tests okay again. So 50/50 for correctness.
Efficiency, of course, is another matter and one that carries another 50 points.
Your use of the TreeMap data structure here brings a time penalty when evaluating the test results. Simpler data structures (that essentially use your algorithm) would be faster.
This more primitive algorithm avoids sorting and copies all entries > 1 onto a new array of length 100001 so that index x holds value x. It actually runs faster than Serdar's code with medium and large input arrays.
public int solution(int[] A)
{
int i = 0,
count = 0,
N = A.length;
int[] B = new int[100001]; // Initially all entries are zero
for (i = 0; i < N; i++) // Copy all entries > 0 into array B ...
{
if (A[i] > 0 && A[i] < 100001)
{
B[A[i]] = A[i]; // ... putting value x at index x in B ...
count++; // ... and keep a count of positives
}
}
for (i = 1; i < count + 1; i++) // Find first empty element in B
{
if (B[i] == 0)
{
return i; // Index of empty element = missing int
}
}
// No unfilled B elements above index 0 ?
return count + 1; // => return int above highest filled element
}

String Switch Statement Not Working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This program's purpose is to translate Morse code into English. I've divided the program's execution logic into three cases: the translation of one Morse code character, two characters and three+ characters. This program tries to translate characters that fall under case three. If you can help, and decide to test the program, please input at least four morse code characters (between a and d)! Otherwise, expect some outofbounds exceptions!
What's wrong with the switch I used? I've read that, up until a few years ago, Java did not support switch statements that used Strings. Java now supports String switch statements and, if I'm not mistaken, my syntax agrees with the not-very-complex conventions of these statements. To determine whether the compiler first recognizes the switch's subject (i.e. switch (aReferenceThatPointsToaString), I printed the reference in the line preceding the switch. No problem there. I also looked at whether cases could be executed if the switch's subject were explicitly stated. Instead of saying switch (array3[i]), I wrote in switch ("._") This test did result in a working switch, leaving me with the impression that switch(array3[i]) isn't quite the same as switch(aStringexpression)
import java.util.Scanner;
public class MorseToEnglish1 {
public static void main (String[]args){
System.out.println("enter morse here");
Scanner input = new Scanner (System.in);
String container = input.nextLine();
char [] array = container.toCharArray();
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ')
count++ ;
}
// count counts the number of times a space appears
System.out.println(count);
int [] array2 = new int [count];
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == ' '){
array2[counter] = i;
counter ++ ;
}
}
// array2 assigns the indexes of spaces to its members
System.out.println(counter);
String [] array3 = new String [array2.length - 1];
for (int i = 0; i < array3.length ; i ++)
array3[i] = container.substring(array2[i], array2[i+1]);
// array3 creates substrings based on these spaces
System.out.print (array3[1]);
System.out.print(array3[0]);
// tests above
for (int i = 0; i < array3.length; i ++){
switch (array3[i]){
case ("._"):
{ System.out.println("a");
break; }
case "_...":
{ System.out.println("b");
break; }
case "_._.":
{ System.out.println("c");
break;}
case "_..":
{ System.out.println("d ");
break;}
}
}
input.close();
}
}
There's nothing wrong with your switch statement, there is a lot wrong with the rest of the program...
The problem is, your custom "split" process is leaving spaces within the text, so, if were to enter ._ _... _._. _.., the array would be split into...
" _...", " _._."
Which is wrong on two accounts, one, it's missing stuff I entered and two, it's leaving the leading space character in the String, so when you try and compare the Strings in the switch statement, you are actually trying to do something like...
"_...".equals(" _...")
Which will fail...
To start with, this "manual" splitting code...
char[] array = container.toCharArray();
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ') {
count++;
}
}
// count counts the number of times a space appears
System.out.println(count);
int[] array2 = new int[count];
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ') {
array2[counter] = i;
counter++;
}
}
// array2 assigns the indexes of spaces to its members
System.out.println(counter);
String[] array3 = new String[array2.length - 1];
for (int i = 0; i < array3.length; i++) {
array3[i] = container.substring(array2[i], array2[i + 1]);
}
// array3 creates substrings based on these spaces
System.out.println(array3[1]);
System.out.println(array3[0]);
Should be replaced with...
String[] array3 = container.split(" ");
As I, frankly, have no idea what it's trying to achieve and it breaks if there is less than 4 "codes" on the input String and doesn't correctly parse the input anyway (throwing away values)
Your splitting code is leaving leading space characters which cause them to not correctly match. You should instead be using a version of String.split in order to produce your array3. This will create the correct substrings with a lot less work.
Edit:
Your splitting code also appears to leave off the first and last morse codes which is why you get ArrayIndexOutOfBoundsExceptions when you input less than 4.
From looking at the code you've got too many } curly braces. You only need one of those at the end of the switch statement.
case ("._"):
{System.out.println("a");
break;
case "_...":
{System.out.println("b");
break;
case "_._.":
{System.out.println("c");
break;
case "_..":
{System.out.println("d ");
break;
}
It should work. My assumption is of course that your problem is that your code doesn't compile. Which I'm pretty sure that the code you posted won't do.

Categories