How to make null knowing link - java

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

Related

How do i convert this forEach to forLoop

Hey im trying convert all my ForEachs into ForLoops as i am now using a Linked List.
I am having trouble with this one for some reason! Anyone able to covert the forEach into a forLoop
public String listCounty(String county) {
boolean matchFound = false;
int i = 0;
String displayPropertys = "All Propertys";
for (Property item : house) {
if (item.getGeneralLocation().equals(county)) {
displayPropertys += "\n" + i++ + item;
i++;
matchFound = true;
} else i++;
}
if (!matchFound)
return "No propertys for this County";
else
return displayPropertys;
}
}
Assuming house is a LinkedList<Property> you could use LinkedList.get(int) but it would be more efficient to use a traditional iterator (because accessing arbitrary indices of a LinkedList is potentially expensive). You could also use a StringJoiner. Something like,
public String listCounty(String county) {
boolean matchFound = false;
Iterator<Property> iter = house.iterator();
StringJoiner sj = new StringJoiner(System.lineSeparator());
sj.add("All Propertys");
for (int i = 0; iter.hasNext(); i++) {
Property item = iter.next();
if (item.getGeneralLocation().equals(county)) {
sj.add(String.format("%d%s", i + 1, item));
matchFound = true;
}
}
return !matchFound ? "No propertys for this County" : sj.toString();
}
You should be able to do it using the following.
for(int index = 0; index < house.size(); index++)
{
Property item = house.get(index);
// Your code goes here
}
There's also no need for the i variable now that we have the index from the for loop.
public String listCounty(String county) {
boolean matchFound = false;
String displayPropertys = "All Propertys";
for (int index = 0; index < house.length; index++) {
Property item = house.get(index)
if (item.getGeneralLocation().equals(county)) {
displayPropertys += "\n" + (index + 1) + item;
matchFound = true;
}
}
if (!matchFound)
return "No propertys for this County";
else
return displayPropertys;
}
You can also use an iterator like Elliot suggests. This will give you better performance but is a bit more difficult to read.
Iterator<Property> iterator = house.iterator();
for (int index = 0; iterator.hasNext(); index++) {
Property item = iterator.next();
// Your code goes here
}
As per your question, I am assuming house is a LinkedList
for (int k = 0; k < house.size(); k++) {
if (house.get(k).getGeneralLocation().equals(county)) {
displayPropertys += "\n" + i++ + house.get(k);
matchFound = true;
} else i++;
}

HugeInteger Class adding and subtracting taking into account negative values

I'm currently writing a HugeInteger class that can take in 40 digits, and I have a few comparison tests that are already written. The thing I'm having most trouble with is adding and subtraction methods. I was able to get two values to add, but don't know how to implement a negate function if one of the values are negative. My subtraction method doesn't seem to work either.
public void add(HugeInteger hi) {
if (digits[NUM_DIGITS] < 0) {
negate();
this.subtract(hi);
}
int carry = 0;
for(int i = digits.length-1; i >=0 ;i--) {
int cur = this.digits[i] + hi.digits[i] + carry;
if (cur >= 10){
cur= cur-10;
resultAdd[i] = cur;
carry = 1;
} else{
resultAdd[i] = cur;
carry = 0;
}
}
StringBuilder builder = new StringBuilder();
int j=0;
for (int i : resultAdd) {
builder.append(i);
this.digits[j] = i;
j++;
}
this.hi = builder.toString().replace("0", "");
}
public void subtract(HugeInteger hi) {
for(int i = digits.length-1; i >=0 ;i--) {
if (this.digits[i] - hi.digits[i] < 0){
this.digits[i-1]--;
this.digits[i]+=10;
}
int cur = this.digits[i] - hi.digits[i];
this.digits[i] = cur;
}
StringBuilder builder = new StringBuilder();
int j=0;
for (int i : resultAdd) {
builder.append(i);
this.digits[j] = i;
j++;
}
this.hi = builder.toString().replace("0", "");
}
public void negate() {
if(this.positive){
this.positive = false;
} else{
this.positive = true;
this.hi = this.hi.replace("-", "");
}
}

Creating all variations based on the differences of two Strings

I do have a function waiting two Strings. I would like to return with a list of words containing all of the possible variations, which can be created based on the differences.
getAllVersions('cso','cső'); //--> [cso, cső]
getAllVersions('eges','igis'); //--> [eges, igis, egis, iges]
So far I have created the function which counts the differences, and saves their locations. Do you have any idea how to continue?
public ArrayList<String> getAllVersions(String q, String qW) {
int differences = 0;
ArrayList<Integer> locations = new ArrayList<>();
ArrayList<String> toReturn = new ArrayList<>();
for (int i = 0; i < q.length(); i++) {
if (q.charAt(i) != q.charAt(i)) {
differences++;
locations.add(i);
}
}
toReturn.add(q);
toReturn.add(qW);
for (int i = 0; i < q.length(); i++) {
for (int j = 0; j < q.length(); j++) {
}
}
return toReturn;
}
}
Here is a recursive solution
Time Complexity : O(n)
public List<String> allVariants(String x, String y) {
if ((x == null || x.isEmpty()) && (y == null || y.isEmpty())) {
return new ArrayList<String>();
}
List<String> l = new ArrayList<String>();
if (x == null || x.isEmpty()) {
l.add(y);
return l;
}
if (y == null || y.isEmpty()) {
l.add(x);
return l;
}
char xc = x.charAt(0);
char yc = y.charAt(0);
List<String> next = allVariants(x.substring(1), y.substring(1));
if (next.isEmpty()) {
l.add(xc + "");
if (xc != yc) {
l.add(yc + "");
}
} else {
for (String e : next) {
l.add(xc + e);
if (xc != yc) {
l.add(yc + e);
}
}
}
return l;
}
Test Code:
public static void main(String[] args) {
List<String> l = new Test().allVariants("igis", "eges");
for (String x : l) {
System.out.println(x);
}
}
Output:
igis
egis
iges
eges
for (int i = 0; i < q.length(); i++) //as before, but a little simplified...
if (q.charAt(i) != q.charAt(i))
locations.add(i);
//Now we're going to create those variations.
toReturn.add(q); //Start with the first string
for each location we found
Additions = a new empty list of Strings
for each element in toReturn
create a new String which is a copy of that element
alter its location-th character to match the corresponding char in qW
append it to Additions
append Additions to toReturn
When this is done, toReturn should start with q and end with qW, and have all variations between.

How to compare string in Java

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;
}
}

Array Processing

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);

Categories

Resources