unable to check all elements in array - java

private void clear() {
for (int i = 0; i<9; i++){
for (int j = 0; j<9; j++){
if(iseditable(i,j)){
bord[i][j].setText("");
}
}
}
}
private boolean iseditable(int i, int j) {
for (String s : generatedXY) {
char[] m = s.toCharArray();
char x = (char) (i + '0');
char y = (char) (j + '0');
return m[1] != x || m[3] != y;
}
return false;
}
I have used the following code in my app here generatedXY array contains all the points in the formate (i,j) as strings I want to extract i & j from the string and compare them with index of board but it is only checking the first element of generatedXY it is not all elements

First your for loops go from 0 to 8, I assume you wanted to write
i<=9 instead.
Second: For iterate over all elements of generatedXY, but you exit loop already in the first iteration by the return statement. You possibly wanted to write something like
if (m[1] != x || m[3] != y)
{
return true;
}
, then the return statement is only executed if the condition is true.

Related

in Valid Anagram program not passing all test cases

Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
example 3
"aad"
"cab"
Output
true
Expected
false
my 3 test case is giving output true why?
class Solution {
public boolean isAnagram(String s, String t) {
if (s.isEmpty() && t.isEmpty()) {
return true;
}
if (s.length() != t.length()) {
return false;
}
char[] a = s.toCharArray();
char[] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
for (int i = 0; i <= a.length; i++) {
for (int j = 0; j <= b.length; j++) {
if (a[i] == b[j]) {
return true;
}
}
}
return false;
}
}
By using a nested for loop, you will iterate over every possible pair (i, j) with i and j an in idex in a and b respectively. Furthermore you use i++ and j++ twice, and thus you will skip the even indices. You can not return true from the moment a[i++] == b[j++] matches. In order to know if something is an anagram, you need to iterate over all elements. You can return false from the moment a[i] != b[i] however. Finally the bound should be i < a.length, not i <= a.length.
You thus need one for loop where you make a single increment and compare a[i] with b[i]:
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()){
return false;
}
char[] a = s.toCharArray();
char[] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
for(int i = 0; i < a.length; i++) {
if(a[i] != b[i]) {
return false;
}
}
return true;
}
You are just comparing the first letter of cab and rat which is a, and returning True, actually you need to check all letters.
Hence make the condition negative and swap the returns.
if(a[i++] !=b[j++]){
return false;
}
return true;
The above code will return false, when characters aren’t equal, hence the last line is reached only when all chars are equal.

How to compare a char to array when the array is not full

So I'm trying to compare a char to an array of chars, the problems is when the array isn't full yet. I'm making a java program for advanced tic-tac-toe.
I've thought about using an ArrayList, but I need the type to char not a primitive type.
char players = new char[numPlayers] // ex: numPlayers == 4
getPlayers(numPlayers, players)
private static void getPlayers(int numPlayers, char players[]){
char temp;
for(int i = 0; i < numPlayers; i++){
System.out.println("Enter the character to represent player " + (i + 1));
temp = in.next().charAt(0);
char upper = Character.toUpperCase(temp);
players[i] = upper;
if(!validatePlayer(upper, players)){
System.out.println("Each character must be unique");
getPlayers(numPlayers, players);
}
}
}
private static boolean validatePlayer(char upper, char players[]){
for(int i = 0; i < players.length; i ++){
if(upper != players[i]){
return true;
}
}
return false;
}
The caller knows the length that has been filled so far, and can pass it.
if (!validatePlayer(upper, players, i ))
The method can use this length, rather than the full length of the array.
private static boolean validatePlayer(char upper, char players[], int len ){
for (int i = 0; i < len; i++) {
...
}
return false;
}
The way to initialize a char array is
char[] players = new char[numPlayers];
The problem is here:
private static boolean validatePlayer(char upper, char players[]){
for(int i = 0; i < players.length; i ++){
if(upper != players[i]){
return true;
}
}
return false;
}
When players.length == 0, for loop will never be executed. And you get always false.
Also imagine if your players contains 'a' and 'b' and you call validatePlayer('b', players):
1. for loop will get first element. `players[0]` -> 'a'
2. Compare 'b' != 'a' -> true
3. Return true.
validatePlayer('b', players) returns true, even if he has 'b'.
I recommand you to change method like this:
private static boolean validatePlayer(char upper, char players[]){
for(int i = 0; i < players.length; i ++){
if(upper == players[i]){ //equal
return false; //false
}
}
return true; //true
}
Check if contains char, otherwise return true.

CodingBat commonTwo method, help examine the output?

Question Summary:
Given two String arrays, return an integer representing how many matches are between them (ignore duplicates).
Real Answer:
http://www.javaproblems.com/2013/11/java-ap-1-commontwo-codingbat-solution.html
My Code
public int commonTwo(String[] a, String[] b) {
int count = 0;
boolean done = false;
for (int i = 0; i<a.length-1; i++){
if(a[i].equals(a[i+1])){
i++;
for (String j:b)
if (a[i].equals(j) && !done){
done = true;
count++;
}
}
else{
for (String j:b)
if(a[i].equals(j) && !done){
done = true;
count++;
}
}
done = false;
if(i == a.length-2)
for (String j:b)
if (a[i+1].equals(j) && !done){
done = true;
count++;
}
}
return count;
}
Image of output: [1]: http://i.stack.imgur.com/0esjC.png
So what it was intended to do was to go through all of the array a,if it equals the next one then go to that index, then add to count if there's a match between the arrays. The done boolean was used to make it so it doesn't add to count if there're duplicates of b that matches a and to end it once a match is found.
Lastly,
if(i == a.length-2)
was intended to make it so if it's the second before the last index number (as the last index number won't be checked in some cases), and not the same as the last index number, then it would check for matches for the last index number after checking the one before the last essentially. I understand why both errors occur and was wondering what could be done to fix it, particularly for the second one/comments on the code. Also, a third issue I notice would be (["a"], ["a"]) → 1 but the code will result in 0.
This question can be done is linear time O(N) that is a single traversal of both arrays a and b.
You should increment i as long as same string appears.So
if(a[i].equals(a[i+1]))
i++;
should be replaced by
while(i+1<a.length&&a[i].equals(a[i+1])){
i++;}
Also you do not need to go through entire array b for a single string of array a since both are in alphabetical order.You should only compare the string from the array b as long there is no match.Once a match is found then you should remember that index and next time matching should continue from that index onwards for the array b
Also you don't need the boolean variable done.
Keeping these things in mind the correct code is:
public static int commonTwo(String[] a, String[] b) {
int count = 0;
int j=0,i;
for (i = 0; i<a.length-1&&j<b.length-1;){
//SKIP DUPLICATES FOR ARRAY a
while(i+1<a.length&&a[i].equals(a[i+1])){
i++;}
//SKIP DUPLICATES FOR ARRAY b
while(j+1<b.length&&b[j].equals(b[j+1])){
j++;}
//MATCH THE STRINGS FROM ARRAY a AND ARRAY b
while(i<a.length&&j<b.length&&a[i].compareTo(b[j])!=0)
{
//INCREMENT I IF STRING IN ARRAY a IS LESS THAN STRING IN ARRAY b
if(a[i].compareTo(b[j])<0)
++i;
//INCREMENT J IF STRING IN ARRAY b IS LESS THAN STRING IN ARRAY a
else ++j;
}
//IF ABOVE LOOP BREAKS BECAUSE OF MATCH
if(i<a.length&&j<b.length)
{count++; ++j; ++i;}
}
//IF THE LAST ELEMENT OF ARRAY a IS LEFT FOR COMPARISON
if(i==a.length-1)
{
while(j<b.length)
{
//SKIP DUPLICATES OF ARRAY b
while(j+1<b.length&&b[j].equals(b[j+1]))
++j;
if(a[i].equals(b[j]))
{++count;}
++j;
}
}
//IF THE LAST ELEMENT OF ARRAY b IS LEFT FOR COMPARISON
if(j==b.length-1)
{
while(i<a.length)
{
//SKIP DUPLICATES OF ARRAY a
while(i+1<a.length&&a[i].equals(a[i+1]))
++j;
if(a[i].equals(b[j]))
++count;
++i;
}
}
return count;
}
This is the simplest solution i could come up with that uses only one loop.
public int commonTwo(String[] a, String[] b) {
int count = 0;
int i = 0;
int j = 0;
String s = "";
while (i < a.length && j < b.length) {
if (a[i].compareTo(b[j]) < 0)
i++;
else if (a[i].equals(b[j]) && a[i] != s) {
s = a[i];
count++;
i++;
j++;
}
else j++;
}
return count;
}
public int commonTwo(String[] a, String[] b) {
int ctr = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (i > 0 && a[i] == b[j] && a[i] != a[i - 1]) {
ctr++;
break;
} else if (i == 0 && a[i] == b[j]) {
ctr++;
break;
}
}
}
return ctr;
}

What happens to a nested if statement in a for-loop if the conditions are not met and there is no else statement?

This is the code my prof gave on a practice exam. Since the first if statement has no else statement, does it exit the for-loop all together and move onto the next if statement? Then, if the second if-statement evaluates to true I'm assuming it's going to go through the first for-loop again and then the second. Once it starts goes through the second for-loop again does the loop begin at j=1 again or another value?
I'm also a little confused with what happens in the second if statement. Does it mean the value at what the currentMaxIndex is becomes the s[i] value and then the currentMax value?
Thanks!
public class Cards {
public static String[] sortCards(String[] s){ // SELECT SORT
for (int i = s.length - 1; i >= 1; i--){
// Find the maximum in the list[0..i]
String currentMax = s[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (cardLessThan(currentMax,s[j])){
currentMax = s[j];
currentMaxIndex = j;
}
}
// Swap list[i] with s[currentMaxIndex] if necessary;
if (currentMaxIndex != i) {
s[currentMaxIndex] = s[i];
s[i] = currentMax;
}
}
return s;
}
static boolean cardLessThan(String s1, String s2){
char s1s = s1.charAt(s1.length()-1); //suites
char s2s = s2.charAt(s2.length()-1);
if(s1s < s2s)
return true;
else if(s1s > s2s)
return false;
// Same suite cards - order determined by card number
String n1 = s1.substring(0,s1.length()-1);
String n2 = s2.substring(0,s2.length()-1);
if(n1.equals("A") && !n2.equals("A")) return true;
if(n1.equals("2") && !n2.equals("A") && !n2.equals("2")) return true;
…
return false;
}
If the condition isn't met the loop continues onto the next iteration, and the condition is tested again. That inner loop could also have been written like,
for (int j = 1; j <= i; j++) {
if (!cardLessThan(currentMax,s[j])){
continue;
}
currentMax = s[j];
currentMaxIndex = j;
}

Testing string for ascending order

I have written a piece of code here to generate a random PIN number of a specified length. The code works fine but I want to add an exception where a PIN would be invalid if it ends up in ascending order. For example if a PIN ended up being 1234, 3456, 4567 they would be invalid PINs.
public static String generatePin(int nmrPinDigits)
{
String pin = new String();
NUMBER_PIN_DIGITS = nmrPinDigits;
for(int i = 0; i < NUMBER_PIN_DIGITS; i += 1)
{
double rnd = Math.random();
rnd *= 9;
rnd += 1;
byte rndByte = (byte)rnd;
String rndStr = Byte.toString(rndByte);
pin += rndStr;
}
return pin;
}
Edit
Actually the question of the OP is probably more to know if the pin is a sequence. In which case:
char prev = pin.charAt(0);
for (char ch : pin.substring(1).toCharArray()) {
if (chr - prev != 1) {
// Not a sequence
return false;
}
prev = chr;
}
// Is a sequence !
return true;
Same goes for descending order, just with -1 as a test value.
The simplest solution would be to compare each random digit generated in your loop to the previous one. If the difference is +1, discard the digit and generate another one.
This is the method to detect ascending or descending string..
public static boolean checkForAscendingOrDescendingPart(String txt, int l)
{
for (int i = 0; i <= txt.length() - l; ++i)
{
boolean success = true;
char c = txt.charAt(i);
for (int j = 1; j < l; ++j)
{
if (((char) c + j) != txt.charAt(i + j))
{
success = false;
break;
}
}
if (success) return true;
success = true;
for (int j = 1; j < l; ++j)
{
if (((char) c - j) != txt.charAt(i + j))
{
success = false;
break;
}
}
if (success) return true;
}
return false;
}
Call this method before returning pin..and throw exception there..like..
checkForAscendingOrDescendingPart(pin, pin.length());

Categories

Resources