Array Equality Check Method - arrays

I have a method to check whether two arrays are equal.
private bool CheckArray(int[] ilk_dizi, int[] son_dizi)
{
for (int i = 0; i < 5; i++)
{
if (ilk_dizi[i]==son_dizi[i])
{
if (i==4)
{
return true;
}
else
{
continue;
}
}
else
{
return false;
}
}
}
but i have a "not all code returs value" error. Any Ideas?

you have the possibility of a "no return"
Be wary when using continue, alot of times it is not really necessary.
Try optimising your code as follows
private bool CheckArray(int[] ilk_dizi, int[] son_dizi)
{
for (int i = 0; i < 5; i++)
{
if (ilk_dizi[i]!=son_dizi[i])
{
return false;
}
}
return true;
}

You have continue inside one of the else blocks - and static analizer cannot infer arrays passed in are 5 long and that i=4 will eventually be reached.
Imagine you passed two equal arrays size 2 each - then you will hit continue twice and exit the for loop - what will be returned then? Thus the warning.
Either put return true; at the end of method's body, or revise your algorithm.

Related

CS50's Tideman: lock_pairs fails to skip the final pair if it creates a cycle (supposedly)

I'm stuck at the lock_pairs function of Tideman. I already wrote the code for it and it looks good. It also behaves as it should when running it through the debugger; however, every time I try it with check50 it gives me an error on "lock pair skips final pair if it creates a cycle".
In order to try it out, I've used examples where the final pair is the one which should be skipped and everything goes as planned when I watch the whole process step by step on the debugger, so I really don't know what I'm missing here.
Here's the explanation of the problem: https://cs50.harvard.edu/x/2022/psets/3/tideman/
void lock_pairs(void)
{
// TODO
// When no_cycle is 0, it indicates that there is no cycle and that locking the pair is safe
int no_cycle = 0;
for (int i = 0; i < pair_count; i++)
{
for (int j = 0; j < pair_count; j++)
{
// We check each pair, looking for a locked pair where the loser of the pair we're checking is the winner.
if (!locked[pairs[i].loser][pairs[j].loser])
{
no_cycle = 0;
continue;
}
else
{
// If the result is true, we check for a possible cycle using the cycle_check function
if (cycle_check(i, j) == false)
{
// If the result is false, we lock the pair and move on
no_cycle = 0;
break;
}
else
{
// If the result is true (indicating a cycle), we change the value of no_cycle to avoid locking the pair
no_cycle = 1;
break;
}
}
}
if (no_cycle == 0)
{
locked[pairs[i].winner][pairs[i].loser] = true;
}
else continue;
}
return;
}
bool cycle_check(i, j)
{
// We check if the loser of the locked pair is the same as our pair's winner or starting point (the end of the chain is also the begining)
if (pairs[j].loser == pairs[i].winner)
{
return true;
}
else
{
//If it isn't, we go through each locked pair, following the chain which could lead to the cycle
for (int h = 0; h < pair_count; h++)
{
if (locked[pairs[j].loser][pairs[h].loser])
{
// Once we find the next link in the chain, we start over
j = h;
if (cycle_check(i, j) == true)
{
// Once we find that there is indeed a cycle, we break recursion
return true;
}
}
}
// If we follow the chain but don't find a cycle, the function returns false and the pair is locked
return false;
}
}
Been stuck forever on this. Any help would be much appreciated.
Btw, english is not my primary language, so please excuse any grammar errors.

Given an array in which arr[i] = i-1 with the following method, what will be the output?

I'm given the following method written in pseudo-code
for i=1 to floor(n/2)
if arr[i] != 0 then
for(j=2 to floor(n/i)
arr[i*j] = 0
I need to find the output and to prove that it's indeed the output.
So far I tried to write the code in Java and to try different inputs and array sizes but to no avail.
Putting it here if it's of any help:
public class Checking
{
private static int method(int[] A,int n)
{
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
if(A[i] != 0)
{
for(int j=2;j<=java.lang.Math.floor(n/i);j++)
{
A[i*j]=0;
System.out.println("The index ofA["+i*j+"] became "+A[i*j]);
}
}
//System.out.print(", "+A[i]);
}
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
System.out.print(", "+A[i]);
}
return 0;
}
public static void main(String[] args)
{
int[] A = {-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
System.out.println(method(A,20));
}
}
Thank you.
You can change the following:
In your main method remove
System.out.println(method(A,20));
as it will always print 0 as you return 0; from the method().
As you print everything in your method() change the following (as it does not print the full array but from index 1 (missing index 0) to floor n/2)
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
System.out.print(", "+A[i]);
}
to
for (int i=0;i<A.length; i++)
{
System.out.print(", "+A[i]);
}
So you can print the whole array.
For simplicity you can use Array's print method to print the array without a for loop
System.out.println(Arrays.toString(A));

The reset of one array affecting a different array

I'm not entirely sure whats going on here. When you shoot all three bullets and the last one leaves the screen the "asteroids" array also resets.
EDIT:
Is it because the bullets array ends up being spliced to an undefined when they all leave the screen? Or will it return the base empty array? Even then, it doesn't explain why the asteroids array is voided as well. I also found that the asteroids don't even start falling unless I've shot at least once.
Code on p5web editor
What is it causing this to happen? This is the first time I've coded something this large, code amount wise, but I made sure to use obvious variable names for the most part.
The problem is in your asteroids class:
check(bullets) {
for (let i = 0; i < bullets.length; i++) {
if (dist(bullets[i].x, bullets[i].y, this.pos.x, this.pos.y) < this.r) {
return false;
} else {
return true;
}
}
}
If there are no bullets to check, this function returns undefined implicitly, which is taken as falsey by the calling code, which promptly destroys the asteroid as if it had collided with a bullet.
Also, if there are bullets to check and the first one happens to not collide, the loop breaks prematurely with else { return true; }, possibly missing collisions.
Change it to:
check(bullets) {
for (let i = 0; i < bullets.length; i++) {
if (dist(bullets[i].x, bullets[i].y, this.pos.x, this.pos.y) < this.r) {
return false;
}
}
return true; // no collisions (or bullets.length === 0)
}
Having said this, the function name check is pretty unclear. I'd rename it as collidesWith(bullets) and invert the boolean--it makes more sense to say "true, yes, we did collide with a bullet" than "false, yes, we did collide with a bullet". We can also make use of the for ... of loop construct. This gives us:
collidesWith(bullets) {
for (const bullet of bullets) {
if (dist(bullet.x, bullet.y, this.pos.x, this.pos.y) < this.r) {
return true;
}
}
return false;
}
You could shorten this further to:
collidesWith(bullets) {
return bullets.some(e => dist(e.x, e.y, this.pos.x, this.pos.y) < this.r);
}
Similarly, I'd change bullet.check() to bullet.outOfBounds() or similar.
Another tip: iterate in reverse over any arrays you plan to slice the current element from:
for (let j = asteroids.length - 1; j >= 0; j--) {
// code that could call `.splice(j, 1)`
}
Otherwise, after splicing, your loop will skip an element and you might miss a collision.
A minor design point, but player.controls() seems strange--why should the player be responsible for listening for keypresses? I'd listen in the keyPressed() function and send the changes to update the player position from there. I'd also break up draw into smaller functions. But these are minor design decisions so the above is enough to get you rolling.
Here's a first revision for the draw function, adjusted to match the modified booleans:
function draw() {
background(0);
scene();
if (tick <= 0) {
if (asteroids.length < asteroidsLimit) {
asteroids.push(new Asteroid());
}
tick = 60;
}
for (let i = asteroids.length - 1; i >= 0; i--) {
if (asteroids[i].collidesWith(bullets)) {
asteroids.splice(i, 1);
}
else {
asteroids[i].update();
asteroids[i].display();
}
}
for (let i = bullets.length - 1; i >= 0; i--) {
if (bullets[i].outOfBounds()) {
bullets.splice(i, 1);
}
else {
bullets[i].update();
bullets[i].display();
}
}
image(ship, player.x, player.y);
player.controls();
tick--;
}

File not loading properly in C

I'm trying to compare a string using a pointer to the array and the destination as defined.
string destination;
int flightcompare(Flights FDA[], String destination)
{
int j=0;
Flights founddestination[10];
for (int i=0;i<MAXARRAYSIZE;i++)
{
(strcmp(Flight *FDA[i]->destination,destination)==0);
founddestination[j]= FDA[i];
j++;
}
return 1;
}
I am not sure about the programming language but I am assuming it is one with stringas a data type.
In your code, there's a Semicolon at the end of
strcmp(Flight *FDA[i]->destination,destination)==0);
which makes use of strcmpredundant.
Remove that Semicolon.
Plus You don't need to pass Flight*to strcmp
So, With these modifications, Function should look like:
int flightcompare(Flights FDA[], String destination)
{
int j=0;
Flights founddestination[10];
for (int i=0;i<MAXARRAYSIZE;i++)
{
if(strcmp(FDA[i]->destination,destination)==0)
{
founddestination[j]= FDA[i];
j++;
if(j >= 10)
{
break; // Stop Looping as Array is full
}
}
}
return j; // Return Count of the Flights found.
}
your strcmp line doesn't make any sense, cause you're not checking the boolean value which is the result of your comparison.
In general, it should be put in an if statement.
There's another problem though since there's no need to compare string objects with strcmp.
You can just compare them with operator ==.
if (FDA[i].destination == destination) {
// they're equal -> do something
} else {
// they're not equal -> do something else
}
That's assuming Flights type has a 'destination' public member.
Moreover, why put them in the founddestination array if you're not using it? and what is the purpose of returning an int?
If you want to know if there's any mismatching destination you can return a boolean.
If you want to return the number of equal destinations / non equal destinations you can just count them in an int.
Assuming you aim for the boolean solution i'd write:
bool flightcompare(Flights FDA[], String destination) {
for (int i = 0; i < MAXARRAYSIZE; ++i) {
if (FDA[i].destination != destination) {
return false;
}
}
return true;
}
If you want to return the amount of matching flights i'd write:
int flightcompare(Flights FDA[], String destination) {
int count = 0;
for (int i = 0; i < MAXARRAYSIZE; ++i) {
if (FDA[i].destination == destination) {
++count;
}
}
return count;
}

error: control may reach end of non-void function

This error appeared to me when i was trying to compile a c file which contains a declaration of a linear search function
bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm
for(int d = 0;d<n;d++){
if(n<0){
return false;
}
else if(values[d]==value){
return true;
}
else{
return false;
}
}
}
What is wrong with my code? Please help.
Some problems with the code:
The method have a path that don't return anything, as commented, when parameter n = negative number or 0
The for-loop don't do anything, will only execute one time and exit for one of the conditions. It would only work correctly when the first element is the element searched, in any other case only check the first element and return (without correct info of present or not). Test with array int values[] = { 1, 2, 3, 4, 5 }; and search 3, your code would not found this value.
If you're searching for a specific value the code is:
bool search(int value, int values[], int n) {
for (int d = 0; d < n; d++) {
if (values[d] == value) {
return true;
}
}
return false;
}
The problem is the argument n passed to the function is n <= 0. The loop never executes and the function finishes without returning any value.
To fix it put the if(n <= 0) statement before the for loop.
If the 'for' loop doesn't get to do any iterations you won't be able to return anything from the function. Maybe add an edge case like
if(n <=0 )
return false;
before the loop.
d is incremented in the for loop until it equals the value of n. At that point, the code beyond the for loop is executed.
Being that there are no instructions beyond the for loop, the function returns to the caller. The error occurs due to there being no (boolean) value returned from the function in this case.
The error can be avoided by following Rule #1 of the Mahonri List Of Rules For Writing Maintainable C Code. Example:
bool search(int value, int values[], int n)
{
bool rCode=false;
// TODO: implement a searching algorithm
for(int d = 0;d<n;d++)
{
if(n<0)
{
goto CLEANUP;
}
else if(values[d]==value)
{
rCode=true;
goto CLEANUP;
}
else
{
goto CLEANUP;
}
}
CLEANUP:
return(rCode);
}

Resources