Check for consecutive value in Map? - oop

I'm creating a chat app and don't want to display the user avatar over and over if a user sends multiple messages consecutively.
The user messages are stored in a Map, where the newest message has the index 0.
To check if a message at an index is sent by the same person as the message before, I use the following method:
bool _sameUser () {
if (index > 0 && map != null && map[index + 1] != null && map[index + 1]['fromUser’] == map[index][‘fromUser’]) {
return true;
} else {
return false;
}
}
However, this doesn't work for the newest message or if there are more than two messages from the same user.
How I can rewrite the conditional so it works as intended?
Thanks!
UPDATE:
After try #Marcel answer and test more I find another issue maybe cause this.
map[index + 1] != null is not true even when message 2 is send. Is only true after message 3 is send.
I test with conditional in function:
if (map[index + 1] != null) {
print('!=null');
}

There's no reason your code shouldn't work for the index 0 except you test index > 0.
By removing that, it should work fine:
bool _sameUser () {
assert(index >= 0);
assert(map != null);
return map[index + 1] != null && map[index + 1]['fromUser'] == map[index]['fromUser'];
}
Because I assumed, the index should never be smaller than 0 and the map should never be null, I moved some of the condition code to assert statements.
Also, because your if-expression is a boolean, you can just return it directly.

Related

how do i correctly use >= and <= in code?

I have tried many thing involving this, >=, >==, =>, ==>.i can not find one that works. hey all return either primary expression needed or expected initializer before '>'. I am creating a IR receiver latch switch and thus have to create parameters for the code because the receiver is not constant in all conditions. Full code below. Any suggestions to fix the code please reply and don't DM me. Thank you.
code:
int LEDState = 0;
int LEDPin = 8;
int dt = 100;
int recieverOld ==> 500 and recieverOld ==< 2000;
int recieverNew;
int recieverPin = 12;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
pinMode(recieverPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
recieverNew = digitalRead(recieverPin);
if((recieverOld >== 0 && recieverOld <== 10) && (recieverNew >== 500 && recieverNew <== 2000) {
if(LEDState == 0) {
digitalWrite(LEDPin, HIGH);
LEDState = 1;
}
}
recieverOld = recieverNew;
delay(dt);
}
error:
expected initializer before '==' token
if one = used line 4 and related, return error expected primary-expression before '>' token
if > before = line 4 and related, return error expected initializer before '>=' token
Any solutions or suggestions welcome.
TL;DR
Operators that do no exist, and that you should NOT use:
==>, ==<, >==, <==
Operators that works and you can use them:
>= - MORE THAN OR EQUAL, compare operator, for example X >= 5
<= - LESS THAN OR EQUAL, compare operator, for example X <= 5
> - MORE THAN, compare operator, for example X > 5
< - LESS THAN, compare operator, for example X < 5
== - compare operator, when you want to compare values of the variables if they have the same value, for example X == 5, Y == X, 10 == 7
=== - equality operator, similar to compare operator ==, but aditionally checks the type of a variable. for example X === Y, '10' === 10
= - assign operator, when you want to assign something to the variable, for example X = 5
<> OR != - NOT EQUAL, compare operator, for example X != 5, Y <> 10
!== - similar to != or <>, but also checks the type of a value. For example 10 !== '10', and will return opposite result of the equality operator ===

Check for boolean when null

If the field "size" is null, this will throw an exception:
if (p?.company?.industries?.size > 0)
job.industryName = p?.company?.industries!![0]
I tried using .size!! but this generated an exception as well. How do I check if size is greater than zero?
(p!!.company?.industries?.size ?: 0) > 0
will give you 0 if size (or more likely, another element of the chain) is null, so the comparison is 0 > 0 which is false.
But as a side note: why is everything nullable in the first place? And why do you have such a random mix of ?. and !!?
All the field members can be nullable as this data is imported from the web and there is no guarantee that any of the fields will be present.
Even then you can at least do
val industries = p?.company?.industries
if (industries != null && industries.size > 0) {
job.industryName = industries[0]
}
or
p?.company?.industries?.let {
if (it.size > 0) { job.industryName = it[0] }
}
if you don't want to make a variable for it.

Operator '==' cant be applied to 'Boolean' and 'Char'

So i want to compare three members of an array with as little code as possible. Heres what i did:
for(i in 0..2) {
if(board[i][0] == board[i][1] == board[i][2]) {
return true
} else if(board[0][i] == board[1][i] == board[2][i]) {
return true
}
}
(All of the values ar Char's FYI) But it didnt work. I get this error message "Operator '==' cant be applied to 'Boolean' and 'Char'". I also tried using .equals, but that just didnt work. Any ideas on what to do?
You can write a small function to keep it more readable and tidy, especially if You need to do that comparison often:
fun allEqual(vararg items: Any) : Boolean {
for(i in 1..(items.size-1)){
if(items[0] != items[i]) return false
}
return true
}
And invoke simply by comma separating values:
allEqual(board[i][0], board[i][1], board[i][2])
I don't know Kotlin specifically, but most* languages don't allow you to compare 3 values at the same time. What your error message is communicating is that your code ends up comparing
"Is board[i][0] equal to board[i][1]?" which is true/false (Boolean)
to
board[i][2], which is a Char.
*I don't know of any, but maybe there's one out there that does.
You have included this condition:
if(board[i][0] == board[i][1] == board[i][2])
Firstly, this one is compared: board[i][1] == board[i][2]
After comparing, it returns true. After that if logic converts to:
if(board[i][0] == true)
Now, board[i][0] is a char and you are trying to compare it to a boolean which is not possible. That's why you are getting this error.
You have to change the logic to:
if((board[i][0] == board[i][1]) && (board[i][1] == board[i][2]))
So, your code will be:
for(i in 0..2) {
if((board[i][0] == board[i][1]) && (board[i][1] == board[i][2])) {
return true
} else if((board[0][i] == board[1][i]) && (board[1][i] == board[2][i])) {
return true
}
}
Another approach:
for (i in 0..2) {
if (board[i].toSet().size == 1)
return true
else if (board.map { it[i] }.toSet().size == 1)
return true
}
As the others said, your first comparison returns Boolean, and the second compares Boolean to Char.
You can use an extension function, and transitivity to simplify things:
fun Any.equalsAll(vararg others: Any):Boolean
{
others.forEach {
if(it!=this)
return false
}
return true
}
and call:
if (board[0][i].equalsAll(board[1][i], board[2][i]))

Hit Detection Implementation in Processing.JS

I am having some trouble with programming hit detection in Processing.JS. I have tried to make a function that checks if something is touching an object and returns true and otherwise returns false. This is that here.
Snake.prototype.checkTouching = function(v){
if(v.position.x > this.position.x - this.width/2 && v.position < this.position.x + this.width/2 && v.position.y > this.positon.y - this.height/2 && v.position.y < this.position.y + this.height/2){
return true;
}else{
return false;
}
};
I am implementing it by creating a new variable "b" in my draw function that holds the value the function returned then using an if statement to check if the value "b" is holding is true. Like so
var b = snakey.checkTouching(mos);
var restarts = 0;
if(b === true){
restarts += 1;
Program.restart();
}
unfortunately even when the object the function is running on is touching the object that is running it nothing happens. I have already checked to see if the logic works and it is valid so I know it has to be my implementation I just can not seem to find out what is wrong with my implementation. Can anyone tell what I am doing wrong? Full program here.Full Program

GridWorld Actor - Calling toString() causes a NPE

I am writing a custom Rock in GridWorld. However when, I run the following code:
for(int i = 0;i<7;i++){
Grid<Actor> g = getGrid();
Location l = getLocation();
int x = l.getCol();
int y = l.getRow();
switch(i){
case 0:
Location l1 = new Location(x-1,y-1);
Actor a = g.get(l1);
if((a.toString()).equals("Infectious Rock")){
}else if((a.toString()).equals("Infectious Bug")){
}else{
a.removeSelfFromGrid();
}
break;
(This is repeated 7 more times with different variables and different coordinates)
Here is the NPE:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at infectiousRock.act(infectiousRock.java:18)
Does anyone know what is causing this?
You first have to check if the Actor you get from calling g.get(1l) exists or not. There is a simple fix to this, change your current if statement to:
if(a != null) {
if((a.toString()).equals("Infectious Rock")){
}else if((a.toString()).equals("Infectious Bug")){
}else{
a.removeSelfFromGrid();
}
} else
break;
Adding the extra !=null check should do the trick, and if not leave a comment and I'll do my best to update the answer.