Array Processing
Hi! I need to create a boolean method that processes two strings and returns if one is a subset of another. Example
if AAC is a subset of AAABBCK return true/
I currently have
for (int i = 0; i < shorterArray.length; i++) {
for (int j = 0; j < longerArray.length; j++) {
if longerArray[j] == shorterArray[i] {
count++
}
}
if (count == shorterArray.length) {
return true
) else {
return fasle;
}
}
However this doesn't take into account the repetitions
return longerString.indexOf(shorterString) > -1;
Never mind, thanks to Joachim for correcting me on the definition of subset. Now I have to provide the correct answer.
public boolean isSubset(String subset, String superset)
{
boolean[] used = new boolean[superset.length()];
iLoop:
for (int i = 0; i < subset.length(); i++) {
for (int j = 0; j < superset.length(); j++) {
if (!used[j] && subset.charAt(i) == superset.charAt(j)) {
used[j] = true;
continue iLoop;
}
}
return false;
}
return true;
}
If you can use the built in methods within the String class :
String input="your input string with substring";
CharSequence findMe="substring";
boolean retval = input.contains(findMe);
Related
I write this code but I don't know why doesn't work.
static boolean findeText(String text1, String text2) {
char c1[] = text1.toCharArray();
char c2[] = text2.toCharArray();
boolean b = false;
for (int i = 0; i <= c1.length - c2.length; i++) {
for (int j = 0, h = i; j <= c2.length; j++, h++) {
if (i == c2.length) {
return true;
}
if (c1[h] != c2[j]) {
b = false;
break;
}
}
}
return b;
}
I want find text 2 in text 1 and after that return true or false.
if you want to check if some string contains any other string, just use contains() method.
In your case that would be
return text1.contains(text2);
Plus you should always write your code in defensive way. That means you should always make sure there will be no NullPointerException etc. So in your particular case if someone pass either null text1 or null text2, your program will crash.
Above you had NPE in line
if (c1[h] != c2[j])
I have modified your code slightly to get output as requirement.
static boolean findeText(String text1, String text2) {
if ((text1== null) ||(text2==null) || (text1.isEmpty()) || (text2.isEmpty())) {
System.out.println("Invalid input");
return false;
}
char c1[] = text1.toCharArray();
char c2[] = text2.toCharArray();
for (int i = 0; i <= c1.length - c2.length; i++) {
int count = 0;
for (int j = 0; j < c2.length; j++) {
if (c1[i + j] == c2[j]) {
count = count + 1;
}
if (count == c2.length) {
return true;
}
}
}
return false;
}
I have next method
public Event findEvent(Date date){
for (int i = 0; i < events.length ; i++) {
if(events[i].getDate() == date){
return events[i];
}
}
return null;
}
It returns me link from object in array.
Then I want to delete this element, but don't know how to correct code it.
public void deleteEvent(Date date){
findEvent(date) = null; //???????????
Event[] list = new Event[events.length - 1];
int j = 0;
for (int i = 0; i < events.length ; i++) {
if(events[i] != null){
list[j] = events[i];
j++;
}
}
}
Use the found event to compare against, if no event was found for the date then just return with nothing changed.
public void deleteEvent(Date date){
Event foundEvent = findEvent(date);
if (foundEvent == null) {
return;
}
Event[] list = new Event[events.length - 1];
int j = 0;
for (int i = 0; i < events.length ; i++) {
if(!events[i].getDate().equals(foundEvent.getDate())) {
list[j] = events[I];
j++;
}
}
events = list;
}
You can't assign a value to a method return value.
While, yes, you logically want to "set the found date to null", you will need to actually do that within the loop
And instead of setting it to null, you could skip over its index and not copy it into the new list
public void deleteEvent(Date date){
Event[] list = new Event[events.length - 1];
int j = 0;
for (int i = 0; i < events.length ; i++) {
if(events[i] != null){
if (events[i].getDate().equals(date)) continue; // skip the event to delete
list[j] = events[i];
j++;
}
}
events = list; // reassign the new events
}
Note: this doesn't work if multiple events are on the same date
Alternatively, make the find method return an index
public int findEvent(Date date){
for (int i = 0; i < events.length ; i++) {
if(events[i].getDate().equals(date)){
return i;
}
}
return -1;
}
From which you can delete
int indexToRemove = findEvent(date);
if (indexToRemove > 0) {
events[indexToRemove] = null;
// copy these events to new list to remove nulls
}
If you're not required to use arrays, you should be using an Arraylist and making your Event objects as Comparable types
In interview I got question to sort the array first in LNAME and then FNAME without using any in-built function like(compare, compareTo, Collections.sort).
String NAMES[][]={{"Abse","Blase"},{"Gua","Tysg"},{"Hysdt","Tyser"}};
Unfortunately, I compared the String like below
String fname;
String lname;
for (int i = 0; i < NAMES.length; i++) {
lname = NAMES[i][0];
for (int j = i + 1; j < NAMES.length; j++) {
if (NAMES[j][1] < lname) { // showing compilation error :(
}
}
}
And, I came to know that, It was wrong. Then, how can I compare them without using any in-built function ?
Note: I haven't added full snippet. Just wanted to know, how can we compare String.
According to the String.class compareTo(String s) method states the following. You can probably refer the below snippet but again it will not fulfil your requirement as the compareTo method uses Math function. But I believe this is what the interviewer was looking for.
public int compareTo(String s)
{
int i = value.length;
int j = s.value.length;
int k = Math.min(i, j);
char ac[] = value;
char ac1[] = s.value;
for(int l = 0; l < k; l++)
{
char c = ac[l];
char c1 = ac1[l];
if(c != c1)
return c - c1;
}
return i - j;
}
Pretty hard inteview question. It's more like a school assignment ;)
public void sort() {
String NAMES[][] = {{"Abse", "Blase"}, {"Gua", "Blase"}, {"Gua", "Tysg"}, {"Hysdt", "Tyser"}};
List<String[]> result = new ArrayList<>(3);
for (String[] name : NAMES) {
if (result.isEmpty()) {
result.add(name);
continue;
}
int addAt = 0;
for (String[] sortedName : result) {
if (isBefore(name, sortedName)) {
break;
}
addAt++;
}
result.add(addAt, name);
}
}
private boolean isBefore(String[] name, String[] name2) {
//last name
int position = 0;
char[] lastName1 = name[1].toLowerCase().toCharArray();
char[] lastName2 = name2[1].toLowerCase().toCharArray();
while (lastName1.length > position && lastName2.length > position) {
if (lastName1[position] < lastName2[position]) {
return true;
} else if (lastName1[position] > lastName2[position]) {
return false;
}
position++;
}
position = 0;
char[] firstName1 = name[0].toLowerCase().toCharArray();
char[] firstName2 = name2[0].toLowerCase().toCharArray();
while (firstName1.length > position && firstName2.length > position) {
if (firstName1[position] < firstName2[position]) {
return true;
} else if (firstName1[position] > firstName2[position]) {
return false;
}
position++;
}
//equal so whatever
return false;
}
I have a feeling you would be able to do this with lambdas a lot easier, but I don't really know
< or > operator cannot compare Strings, so we can use it to compare characters.
Maybe implement your own string comparision method. Which checks character by character and returns the String with the highest value.
public String compare(String s1, String s2)
{
for(int i = 0; i < Math.min(s1.length(), s2.length()); i++)
{
if(s1.charAt(i) > s2.charAt(i))
return s1;
}
return s2;
}
To complete the answer to your question.
public class GreatString {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String NAMES[][] = { { "Abse", "Blase" }, { "Gua", "Tysg" },
{ "Hysdt", "Tyser" } };
int n = NAMES.length;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (NAMES[i][0].equals(NAMES[j][0])) {
if (compare(NAMES[i][1], NAMES[j][1])) {
String[] temp = NAMES[i];
NAMES[i] = NAMES[j];
NAMES[j] = temp;
} else {
if (compare(NAMES[i][0], NAMES[j][0])) {
String[] temp = NAMES[i];
NAMES[i] = NAMES[j];
NAMES[j] = temp;
}
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < NAMES[i].length; j++) {
System.out.println(NAMES[i][j]);}}
}
private static boolean compare(String str1, String str2) {
// TODO Auto-generated method stub
int len = str1.length() < str2.length() ? str1.length() : str2.length();
for (int i = 0; i < len; i++) {
if (str1.charAt(i) > str2.charAt(i))
return true;
}
return false;
}
}
I'm trying to do this:
User inputs a number for example 2013 or 2012 and it checks if the number has any reoccurring digits like in 2012 there is 2 but I don't know where to go from here.
public static boolean hasDuplicates(String text){
for(int i = 0; i < text.length() - 1; i++){
for(int j = i + 1; j < text.length(); j ++){
if(text.charAt(i) == text.charAt(j)){
return true;
}
}
}
return false;
}
You can make it this way:
public static boolean containsDuplicate(int number) {
String strNum = number.toString();
for(int i=0; i < strNum.length() -1 ; i++){
if( containsDuplicatedValue(strNum, strNum.charAt(i) )
return true;
}
return false;
}
private static boolean containsDuplicatedValue(String str, char searchFor) {
return str.indexOf(searchFor) != str.lastIndexOf(searchFor);
}
Here is a way to check for duplicates. If the first occurrence of number has a different index than the last occurrence, then number must occur more than once.
public static boolean containsDuplicate(String str, int number) {
return str.indexOf(number) != str.lastIndexOf(number);
}
public boolean isNumber(String t) {
for (int i = 0, i<= 9, i++) {
if t.equals(i) {
return true;
}
}
return false;
}
Copypastad the wrong method originally -_-
I have this inside a class compiling with this error:
data_structures/ExpressionEvaluator.java:40: illegal start of type for (int i = 0, i< 10, i++) {
Use semi-colons instead of commas.
for(int i = 0; i < 10; i++) {
//do stuff
}
You should use semi-colon and your if should be surrounded with brackets.
public boolean isNumber(String t) {
for (int i = 0; i <= 9; i++) {
if (t.equals(i)) {
return true;
}
}
return false;
}
I would suggest reading Language Basics
Semicolons separate the qualities of a for loop. Also, the condition of your if block must be surrounded by parentheses.
public boolean isNumber(String t) {
for (int i = 0; i <= 9; i++) {
if (t.equals(i)) {
return true;
}
}
return false;
}
public boolean isNumber(String t) {
for (int i = 0; i<= 9; i++) {
if( t.equals(i) ){
return true;
}
}
return false;
}
1 . use ";" replace of ","
2 .
if(boolean) {
//do stuff
}
Your method only verifies if the String that you passed is a digit, not a number (a number can have more than one digit). You could verifiy it only using a char and calling the ,Character.isDigit
char c = '1';
boolean isDigit = Character.isDigit(c);
If you really want to create your own method, passing a String param, I suggest you to modify like this:
public boolean isDigit(String t) {
return t.length() == 1 && Character.isDigit(t.charAt(0));
}