I have a char array of a length n, which I don't know the value. I need to write a condition to check if all elements of my array are one by one equal to a given char 'a'.
For example, with n = 4, I convert the array to a string by doing :
String str = new String(myArray);
and then I do my condition like :
if (str.equals("aaaa")) {}
but my problem is that the value of n is unknown.
I tried to do :
for (int i = 0; i < n; i++) {
if (myArray[i].equals('a')) {
??
}
}
But i don't know to do in '??' after the if, as I need to wait the for loop to be finished, because i want that all the elements of my array to be equal to 'a'.
A process of checking all items usually goes as follows:
Check an individual item
If it matches the condition, continue
Otherwise, declare the match unsuccessful, and end the loop
If the loop ends without declaring the match unsuccessful, you have a successful match
In terms of Java, declaring the match unsuccessful could mean setting a boolean variable to false:
boolean successfulMatch = true;
for (int i = 0; i < myArray.length ; i++) {
// ^^^^^^^^^^^^^^
// Note how we check array length
if (myArray[i] != 'a') {
// ^^
// Note != here
successfulMatch = false;
break;
}
}
if (successfulMatch) {
...
}
In Java-8 you can do it using Stream#allMatch. It will reduce ceremonial code. You don't need to worry about the Array Length and setting the flag and breaking the loop.
String[] strs = {"a","a","a"};
boolean isAllEqual = Arrays.stream(strs).allMatch(e->e.equals("a"));
System.out.println(isAllEqual);
You can simply use regular expression. For example:
String s = "aaaaaaaa";
if(s.matches("[a]*"))
System.out.println("s only contains a");
else if(s.matches("[A]*"))
System.out.println("s only contains A");
else if(s.matches("[aA]*"))
System.out.println("s only contains A and a");
else
System.out.println("s not match a*");
try this
private static void n(){
char[] n = {'a', 'b'};
String[] myArray = {"a", "a", "a"};
for(char c : n){
int i = 0;
int j = 0;
for(String s : myArray){
if((s.equals(String.valueOf(c)))){
i++;
}
if(++j == n.length){
System.out.println(i + "->" + n.length);
if(n.length == i){
System.out.println("All the elemntes in your array are the same to char array");
}else{
System.out.println("Not the same");
}
}
}
}
}
What about:
boolean matched = true;
for(int i = 0, n=myArray.length; i<n; i++){
if(!myArray[i].equals("a")){
matched = false;
}
}
Then all you have to do is check matched boolean.
Related
Question:
Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Code:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0)
return "";
for(int i=0;i<strs[0].length();i++) {
char x = strs[0].charAt(i);
for(int j=0;j<strs.length;j++) {
if((strs[j].length()==i)||(strs[j].charAt(i)!=x)) {
return strs[0].substring(0,i);
}
}
}
return strs[0];
}
}
This is the second solution, but I don't understand the inner loop.
I think if the second element in strs returns a string and ends the for loop, the third element will not have a chance to be compared.
You have to check same position in all of the words and just compare it.
positions
word 0 1 2 3 4 5
=====================
w[0] F L O W E R
w[1] F L O W
w[2] F L I G H T
In Java:
class Main {
public static void main(String[] args) {
String[] words = {"dog","racecar","car"};
String prefix = commonPrefix(words);
System.out.println(prefix);
// return empty string
String[] words2 = {"dog","racecar","car"};
String prefix2 = commonPrefix(words2);
System.out.println(prefix2);
// Return "fl" (2 letters)
}
private static String commonPrefix(String[] words) {
// Common letter counter
int counter = 0;
external:
for (int i = 0; i < words[0].length(); i++) {
// Get letter from first word
char letter = words[0].charAt(i);
// Check rest of the words on that same positions
for (int j = 1; j < words.length; j++) {
// Break when word is shorter or letter is different
if (words[j].length() <= i || letter != words[j].charAt(i)) {
break external;
}
}
// Increase counter, because all of words
// has the same letter (e.g. "E") on the same position (e.g. position "5")
counter++;
}
// Return proper substring
return words[0].substring(0, counter);
}
}
Your first loop is itterating over all chars in the first string of array. Second loop is checking char at i posistion of all strings of array. If characters do not match, or length of string is the same as i it returns substring result.
I think the best way to understand is debug this example.
If the char in the second string is different than the char in the first one, then it is correct to return, since it means that the common prefix ends there. Checking the third and following strings is not necessary.
Basically it returns as soon as it finds a mismatch char.
If we first sort them then it would be very easy we have to only go and compare the first and the last element in the vector present there so,
the code would be like,This is C++ code for the implementation.
class Solution {
public:
string longestCommonPrefix(vector<string>& str) {
int n = str.size();
if(n==0) return "";
string ans = "";
sort(begin(str), end(str));
string a = str[0];
string b = str[n-1];
for(int i=0; i<a.size(); i++){
if(a[i]==b[i]){
ans = ans + a[i];
}
else{
break;
}
}
return ans;
}
};
public class Solution {
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0)
{
return string.Empty;
}
var prefix = strs[0];
for(int i=1; i<strs.Length; i++) //always start from 1.index
{
while(!strs[i].StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length-1);
}
}
return prefix;
}
}
I'm trying to create a string array program that looks for the last match. For example, when asked for the last word of length 3, the code should locate “was” at index 7. This is what I have so far, but I'm not sure how to make sure the code returns the position of the last match:
public static void main(String[] args)
{
String[] words = { "Mary", "had", "a", "little", "lamb",
"it's", "fleece", "was", "white", "as",
"snow" };
Scanner in = new Scanner(System.in);
System.out.print("Word length: ");
int wordLength = in.nextInt();
boolean found = false;
int pos = 0;
while (!found)
{
if (wordLength == words[pos].length())
{
pos++;
}
else
{
found = true;
}
}
if (pos > 0)
{
System.out.println("Found " + words[pos] + " at position " + pos);
}
else
{
System.out.println("No word of length " + wordLength);
}
}
public static void main(String[] args)
{
String[] words = { "Mary", "had", "a", "little", "lamb",
"it's", "fleece", "was", "white", "as",
"snow" };
Scanner in = new Scanner(System.in);
System.out.print("Word length: ");
int wordLength = in.nextInt();
boolean found = false;
int pos;
for(int i = words.length-1 ; i >= 0 ; i--)
{
if (wordLength == words[i].length())
{
pos =i;
found = true;
break;
}
}
if (found)
{
System.out.println("Found " + words[pos] + " at position " + pos);
}
else
{
System.out.println("No word of length " + wordLength);
}
}
Try this:
for(int i=(words.length)-1;i>=0;i--){
if(words[i].length()==3){
System.out.println("Position:"+i);
break;
}
}
The problem with your code is that after the length of the first word is not the one you are looking for your if statement is evaluated as false then you set found = true and the while loop ends. as #Shubham Agrawa pointed out you could use a reverse loop. Also exchange the contents of the if statements and set pos-- insted of pos++. You will also need to check that pos is greater or equal to 0 so it doesn't go out of bounds
int pos = words.length - 1;
while (!found && pos >= 0)
{
if (wordLength == words[pos].length())
{
found = true;
}
else
{
pos--;
}
}
Hope this helps
I'll prefer using for loop instead of while. start from last index and break when you found a match and print that index number.
for(int i=words.length-1;i>-1;i--) {
if (wordLength == words[i].length()) {
pos=i;
found = true;
break;
}
}
I guess this the most efficient and shortest method to get what you
requires.
It takes an int as an input parameter and then search from last to
first for the element with size equal to input lenght.
Code:-
public static void main(String[] args) {
String[] words = { "Mary", "had", "a", "little", "lamb",
"it's", "fleece", "was", "white", "as",
"snow" };
Scanner in = new Scanner(System.in);
System.out.print("Word length: ");
int wordLength = in.nextInt();
System.out.println("word lenght ="+wordLength);
int size=words.length;
System.out.println("Lenght of array ="+size);
for(int i=size-1;i>=0;i--){
if(words[i].length()==wordLength){
System.out.println(words[i]);
break;
}
}
}
Output:-
Word length: 5
word lenght =5
Lenght of array =11
white
Java 8 has a good way to do this with Streams. After collecting the word length (assume it is stored in the variable wordLength, and that the array is called words):
Optional<String> lastMatchingWord = Arrays.stream(words).filter(word -> word.length() == wordLength).reduce((a, b) -> b);
if (lastMatchingWord.isPresent())
{
String word = lastMatchingWord.get();
int index = Arrays.asList(words).lastIndexOf(word);
//Use these values as you wish.
}
else
{
//Handle no match found procedure however you want.
}
The first bit makes a Stream from the array (Arrays.stream), and then filters it down to only the elements with the desired length (the name filter is self-explanatory, the actual procedure uses a Java 8 lambda to check for equality, and only values for word which cause this function to return true are left in the Stream), then gets the last element (reduce is designed to reduce a Stream of element down to a single instance of that element type. It is frequently used to fold all elements into a single element (think adding together a bunch of Integers, for example). In this case, we're simply plucking out the last value, because our accumulator always discards the accumulated value and sets the new value to whatever the next element is).
The reduce operation returns an Optional, which will be empty if the result of the filter operation returned an empty Stream (read: the Optional will be empty if no words are the desired length). Thus, if lastMatchingWord.isPresent(), you can grab the word out of the Optional as a String, an find its index in the original array. If it isn't there, you can deal with that as appropriate. Overall, you end up with less code than manual loops.
I am having difficulties with my method returning true. It is a boolean method that takes two words and tries to see if one can be turned into the other by transposing two neighboring letters. I have had no troubles getting the false boolean. When the code gets to the for loop with an if statement in it it runs fine but does not return true when the if statement is satisfied. For some reason it continues through the for loop. For example, when comparing "teh" and "the" when the loop hits 1 the if statement is satisfied but does not return true, the for lo
public static boolean transposable(String word1, String word2)
{
ArrayList<Character> word1char = new ArrayList<Character>();
ArrayList<Character> word2char = new ArrayList<Character>();
int word1length = word1.length();
int word2length = word2.length();
int count = 0;
String w1 = word1.toUpperCase();
String w2 = word2.toUpperCase();
if(word1length != word2length)
{
return false;
}
for(int i = 0; i < word1length; i++)
{
char letter1 = w1.charAt(i);
word1char.add(letter1);
char letter2 = w2.charAt(i);
word2char.add(letter2);
}
for(int i = 0; i < word1length; i++)
{
char w1c = word1char.get(i);
char w2c = word2char.get(i);
if(w1c == w2c)
{
count++;
}
}
if(count < word1length - 2)
{
return false;
}
for(int i = 0; i < word1length; i++)
{
char w1c = word1char.get(i);
char w2c = word2char.get(i+1);
if(w1c == w2c)
{
return true;
}
}
return false;
}
op just keeps running. What am I doing wrong?
As pointed out in the comments this doesn't seem to be the easiest way around this problem. Here is a solution which tries to follow your logic and includes the use of toUpperCase() and ArrayLists.
Going over your code it looks like you were getting a bit lost in your logic. This is because you had one method trying to do everything. Break things down into smaller methods and you also will benefit by not having to repeat code and it keeps things much cleaner. The code below is tested with Java8 (although there is no reason why this should not work with Java 7).
public static void main(String args[]) {
String word1 = "Hello";
String word2 = "Hlelo";
transposable(word1, word2);
}
private static boolean transposable(String word1, String word2) {
// Get an ArrayList of characters for both words.
ArrayList<Character> word1CharacterList = listOfCharacters(word1);
ArrayList<Character> word2CharacterList = listOfCharacters(word2);
boolean areWordsEqual;
// Check that the size of the CharacterLists is the same
if (word1CharacterList.size() != word2CharacterList.size()) {
return false;
}
// check to see if words are equal to start with
areWordsEqual = checkIfTwoWordsAreTheSame(word1CharacterList, word2CharacterList);
System.out.print("\n" + "Words are equal to be begin with = " + areWordsEqual);
if (!areWordsEqual) {
/*
This loop i must start at 1 because you can't shift an ArrayList index of 0 to the left!
Loops through all the possible combinations and checks if there is a match.
*/
for (int i = 1; i < word1CharacterList.size(); i++) {
ArrayList<Character> adjustedArrayList = shiftNeighbouringCharacter(word2CharacterList, i);
areWordsEqual = checkIfTwoWordsAreTheSame(word1CharacterList, adjustedArrayList);
System.out.print("\n" + "Loop count " + i + " words are equal " + areWordsEqual + word1CharacterList + adjustedArrayList.toString());
if (areWordsEqual) {
break;
}
}
}
return areWordsEqual;
}
// takes in a String as a parameter and returns an ArrayList of Characters in the order of the String parameter.
private static ArrayList<Character> listOfCharacters(String word) {
ArrayList<Character> wordCharacters = new ArrayList<Character>();
String tempWord = word.toUpperCase();
for (int wordLength = 0; wordLength < tempWord.length(); wordLength++) {
Character currentCharacter = tempWord.charAt(wordLength);
wordCharacters.add(currentCharacter);
}
return wordCharacters;
}
// takes in two character arrayLists, and compares each index character.
private static boolean checkIfTwoWordsAreTheSame(ArrayList<Character> characterList1, ArrayList<Character> characterList2) {
// compare list1 against list two
for (int i = 0; i < characterList1.size(); i++) {
Character currentCharacterList1 = characterList1.get(i);
Character currentCharacterList2 = characterList2.get(i);
if (!currentCharacterList1.equals(currentCharacterList2)) {
return false;
}
}
return true;
}
// this method takes in an ArrayList of characters and the initial index that we want to shift one place to the left.
private static ArrayList<Character> shiftNeighbouringCharacter(ArrayList<Character> characterListToShift, int indexToShiftLeft) {
ArrayList<Character> tempCharacterList = new ArrayList<Character>();
int indexAtLeft = indexToShiftLeft - 1;
// fill the new arrayList full of nulls. We will have to remove these nulls later before we can add proper values in their place.
for (int i = 0; i < characterListToShift.size(); i++) {
tempCharacterList.add(null);
}
//get the current index of indexToShift
Character characterOfIndexToShift = characterListToShift.get(indexToShiftLeft);
Character currentCharacterInThePositionToShiftTo = characterListToShift.get(indexAtLeft);
tempCharacterList.remove(indexAtLeft);
tempCharacterList.add(indexAtLeft, characterOfIndexToShift);
tempCharacterList.remove(indexToShiftLeft);
tempCharacterList.add(indexToShiftLeft, currentCharacterInThePositionToShiftTo);
for (int i = 0; i < characterListToShift.size(); i++) {
if (tempCharacterList.get(i) == null) {
Character character = characterListToShift.get(i);
tempCharacterList.remove(i);
tempCharacterList.add(i, character);
}
}
return tempCharacterList;
}
Hope this helps. If you are still struggling then follow along in your debugger. :)
So I have the following String: dog "and" cat
I split it up into an array named: array1 with,
{'d','o','g',' ','"','c','a',t','"'}
boolean works = false;
for (int i=0; i < array1.length;i++){
if (array1[i].equals("d"){
if (array1[i+1].equals("o"){
if(array1[i+2].equals("g"){
if (array1[i+3].equals(" "){
if (array1[i+4].equals("""){ //does work here
if (array1[i+5].equals("c"){
if (array1[i+6].equals("a"){
if (array1[i+7].equals("t"){
works = true;
}
}
}
}
}
}
}
}
}
System.out.println(works);
It doesnt work at the equals with quotations. Does anyone have any ideas?
I would try to simplify your code, for example you could write
String s = "dog \"and\" cat";
boolean works = s.contains("dog \"cat");
This makes it much more obvious that works will always be false.
You have ambiguous data types.
I assume that your array1 is of type char[]. If it is, then you should have == comparators in your code (note the single quotes 'x' where x is the char you are testing):
if (array1[i] == 'd'){
....
}
if the arrays are of type String[], then you need to escape the " character using a backslash in the comparison:
if (array1[i+4].equals("\""){ //does work here
....
}
{'d','o','g',' ','"','c','a',t','"'} this is a char array
you need below code
You can no equal Char with String.
boolean works = false;
for (int i=0; i < array1.length;i++){
if (array1[i]=='d'){
if (array1[i+1]=='o'){
if(array1[i+2]=='g'){
if (array1[i+3]==' '){
if (array1[i+4]=='"'){ //does work here
if (array1[i+5]=='c'){
if (array1[i+6]=='a'){
if (array1[i+7]=='t'){
works = true;`
}
}
}
}
}
}
}
}
boolean works = false;
String[] pattern = { "d","o","g"," ","\"","c","a","t","\"" };
for (int i = 0; i < array1.length; i++) {
// Loop over the items in the pattern array, and check if they match array1
boolean inner = true;
for (int j = 0; j < pattern.length; j++) {
if (i + j >= array1.length) {
// Don't go beyond the end of array1
break;
}
if (!pattern[j].equals(array1[i+j])) {
// We found an item that doesn't match.
inner = false;
break;
}
}
if (inner) {
// All items matched
works = true;
break;
}
}
System.out.println(works);
You need to escape the " character inside the "". Like this:
(array1[i+4].equals("\"")
I'm making this method remove() which takes a String word as argument, to delete from a global Array "words", but I keep getting a NullPointerException for some reason I cannot find, been stuck for hours.
Basically I check for if the word is in the first position, else if is in the last position, or else if it is in neither so I check all the array, and add the first half before the position of the word, and then add the second half after the position of the word in the array, as to skip it and "delete it". But I'm getting a NullPointerException in the for loop looking for the position of the word in the array. Code for the method is here:
public void remove(String a){
String[] temp_arr = new String[words.length-1]; // make array with 1 less length for deleted
if(words[0].equals(a)){ // if the word is the first in the array
for(int x=0, z=1; x<temp_arr.length; x++,z++)
temp_arr[x]=words[z];
words = temp_arr;
} else if(words[words.length-1].equals(a)){ // if the word is in the last position of the array
for(int x=0, z=0; x<temp_arr.length; x++,z++)
temp_arr[x] = words[z];
words = temp_arr;
} else{ // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop, in the if(words[k].equals(a))
int k=0;
for (; k<words.length; k++){ // find the position of the word to delete
if (words[k].equals(a)) {
break;
}
}
for (int i = 0; i < k-1; i++){ // add first part of array before the word
temp_arr[i] = words[i];
}
for(int c = k, b = k+1; c< temp_arr.length; c++,b++){
temp_arr[c] = words[b];
}
words = temp_arr; // assign the new values to global array
}
}
Also, if theres any suggestions for good coding practice would be appreciated, thanks!
** I can only use Arrays as my data structure for this method.
Modify the condition like this
a.equals(words[0])
because you know the string value a. But dont know what value will come from array. So even null value comes from the array it does allow the null pointer exception.
I run your code and find a few errors, I correct somethings without changing the core idea:
} else { // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop.
int k = -1;
for (int i = 0; i < words.length; i++) { // find the position of the word to delete
if (words[i].equals(a)) {
k=i;
break;
}
}
if(k<0)//if not exists
return;
for (int i = 0; i < k /*- 1*/; i++) { // add first part of array before the word
temp_arr[i] = words[i];
}
for (int i = k; i < temp_arr.length; i++) {
temp_arr[i] = words[i+1];
}
words = temp_arr; // assign the new values to global array
}
If the original array could't have null elements I would do like this:
public static String[] remove(String words[] , String a) {
int counter = 0;
for (int i = 0; i < words.length; i++) {
if( a.equals(words[i]) ){
words[i] = null;
counter++;
}
}
if(counter==0){
return words;
}
String[] words2 = new String[words.length - counter];
int i=0;
for (String string : words) {
if(string!=null){
words2[i++]=string;
}
}
return words2;
}
I would do that like this:
public void remove(String a) {
List<String> tmp = new ArrayList<String>();
for (String word : words) {
if ((word != null) && (word.equals(a))) {
continue;
}
tmp.add(word);
}
words = tmp.toArray(new String[]);
}
I have a question for you:
Why oh why are you using an array? You should always use a collection (eg a List) unless you absolutely have to use an array (which is rare indeed).
If it were a List, you wouldn't even need this method, because List has the remove() method that does all this for you!