I'm trying to compare the X value of two points in two different arrays. Problem is sometimes the value I'm comparing may not exist yet and I'm not entirely sure how to go about making this check before I call upon this variable.
My code looks like this
if (blueShipPositions[0].x == redShipPositions[0].x) {
trace("Match in" + blueShipPositions[0]);
}
The x value for any given point in this array tops out at 4 so the error I'm running into looks like this
if (blueShipPositions[0].x == redShipPositions[4].x) {
trace("true");
}
If redShipPositions[4].x does not exist yet I get an error.
I am aware of the IndexOf function, I just don't know how to apply it here.
Wrap it inside an IF statement that determines the size of an array:
if (redShipPositions.length >= 5) {
if (blueShipPositions[0].x == redShipPositions[4].x) {
trace("true");
}
}
Another way is to have an int local variable to indicate the size of the array:
myArraySize = redShipPositions.length;
then you can use it as an indicator/(stop point) to safely execute your code w/o the concern of IndexOutOfBound exception.
As answer to your question, take this example : (comments inside)
var array:Array = new Array(1, 5, 6, 55)
var index:Number = 3
// type of the elements of array, in this case is Number
var element_type:* = Number
// so to verify if the array[index] exists, we can use
if(array[index]) {
trace(array[index])
}
// or
if(array[index] != undefined) {
trace(array[index])
}
// or
if(array[index] != null) {
trace(array[index])
}
// or
if(typeof array[index] != 'undefined') {
trace(array[index])
}
// or
if(array[index] is element_type) {
trace(array[index])
}
// or
if(array[index] as element_type != null) {
trace(array[index])
}
// or
// here you have to put in the mind that arrays in ActionScript starts always from the index 0, thats why we use < and not <=
if(index < array.length) {
trace(array[index])
}
// we use array.indexOf to search an element and not an index
if(array.indexOf(55)){
trace('we have "55" in this array')
} else {
trace('we don\'t have "55" in this array')
}
For more details about AS3 Array object, take a look here : Adobe.com : AS3 Array.
Hope that helps you.
Related
I have a function who's body looks a lot like this:
if (contains(array, element1) > -1){
// do something
} else if (contains(array, element2) > -1) {
// do something
} else if (contains(array, element3) > -1) {
// do someting
}...
The function contains will loop through my array and check to see if it contains an element that I pass to it and return either its position if it exists, or -1 if it doesn't.
In my // do something portion, I need the position of this element in the array. There are a couple of different ways I can do this:
I can call my contains() function once more to get the position.
I can define several variables that are defined as the return of the contain function, and then check them in my if-else block. So something like:
int element1Loc = contains(array, element1);
int element2Loc = contains(array, element2);
int element3Loc = contains(array, element3);
if (element1Loc > -1){
// do something
} else if (element2Loc > -1) {
// do something
} else if (element3Loc > -1) {
// do someting
}...
I can perhaps modify contain to return an int array[2], with array[0] equal to 0 or 1 whether the element is in it or not, and then array[1] qwould equal the actual location, making the code look like thiss:
if (contains(array, element1)[0] > -1){
// do something
} else if (contains(array, element2)[0] > -1) {
// do something
} else if (contains(array, element3)[0] > -1) {
// do something
}...
I can say screw the if-else block, save the return of contains in a variable and run several if-statements.
Solution one will search through my array at least twice. Solution two will search at least as many times as there are elements I'm looking for. Solution 3 is perhaps the best, but maybe not the most elegant. Solution 4 will run each if statement...
What is the best way to search just once? Should I make a function that takes all the things I am looking for and returns an array with the position of each element? Am I overthinking it?
I would modify contains to only use the return value to indicate the error/success of the find, and, if the parameter was found, output the parameter by reference.
int contains(int *data, int value, int *loc)
{
for(int i = 0; i < SIZE; i++)
{
if(data[i]==value)
{
*loc = i;
return 1; // success
}
}
*loc = -1;
return 0; // failure
}
Now, you can just do:
int elem1loc, elem2loc, elem3loc;
if(contains(data, val1, &elem1loc))
// use elem1loc...
if(contains(data, val2, &elem2loc))
// use elem2loc...
You could pass a pointer to say int which would be populated when the contains function finds an element. Then inside your if block you would be assured that pos is the correct index.
Example:
int pos;
if (contains(array, element1, &pos) > -1) {
// Here you can check pos for the position
} else if (contains(array, element2, &pos) > -1) {
// Here you can check pos as well...
}
Here's a solution that doesn't require you to modify contains at all:
int pos;
if ((pos = contains(array, element1)) > -1) {
// do something with pos
} else if ((pos = contains(array, element2)) > -1) {
// do something with pos
} else if ((pos = contains(array, element3)) > -1) {
// do something with pos
}
This works because variable assignment in most imperative languages is an expression.
My code worked fine until I added the else block.
String getInputSearch = JOptionPane.showInputDialog("city")
for(int i=0; i < listArray.length; i++) {
if(getInputSearch == loadData()[i][0]) {
for(int j=0; j< loadData()[i].length; j++) {
println(loadData()[i][j])
}
println("")
}
else {
println( getInputSearch+ "not a valid city");
}
}
If I add a break within the else block, the loop only works once and if I don't it keeps printing "not a valid city," even if the city is valid until it reaches the the right index in the array. (data is read from a text file btw)
help would be appreciated.
The problem is there's a mismatch between what you're trying to achieve and your approach. You're trying to determine whether the city is valid or not, and if so, print out some data. However, what you're doing instead is checking if a particular row has a valid city, which leads to your if statement being executed for every iteration; hence the multiple "not a valid city" results. Your if statement is just too early.
Try something like this:
/* Grabs all the rows in loadData() with a matching city.
* Which means that if the list is empty, then the city is invalid.
*/
def cityData = loadData().findAll { it[0] == getInputSearch }
if(cityData) {
cityData.each { row ->
row[1].each { column ->
println column
}
println()
}
} else {
println "${getInputSearch} not a valid city"
}
And if you're feeling fancy, there's a more stream/pipe like approach:
loadData()
.findAll { it[0] == getInputSearch }
.with {
/* asBoolean() tries to coerce the List into a boolean.
* An empty list is False, while a non-empty list is True
*/
if(!delegate.asBoolean()) println "${getInputSearch} not a valid city"
delegate // Return the list itself so that if it's not empty the process will continue.
}.each { row ->
row[1].each { column ->
println column
}
println()
}
I am trying to get out of a while loop using C, but using breaks, returns or changing the while condition are not working.
Basically, I want to know why in the last else if, when I state back = true my code keeps entering the for.
I would expect an output like: enter1, enter1, enter1, enter1, enter2.
Instead, the output is something like enter1, enter1, enter1, enter2, enter2, enter2, enter1, enter1, enter1....
This is my code work:
void SolveMap8(Core* core_building, Building* new, Stack* solve, bool goingBack){
Core* coreBuilding = core_building;
Building* first = new -> linked[0];
Building* next = NULL;
bool back = goingBack;
while (back == false) {
for (int i = 0; i < (first -> zone -> building_count); i++) {
if (first -> zone -> buildings[i] != NULL) {
if (first != first -> zone -> buildings[i]) {
next = first -> zone -> buildings[i];
if(next -> color == coreBuilding -> buildings[0] -> color && !city_client_is_taken(next)) {
puts("enter0");
Building_Pair* newPair = Building_Tuple_Create(first, next);
stack_push(solve, newPair);
city_client_link(first, next);
break;
}
else if(!city_client_is_taken(next)) {
if (city_client_is_blank(next)) {
if (!(next -> cored)) {
puts("enter1");
Building_Pair* newPair = Building_Tuple_Create(first, next);
stack_push(solve, newPair);
city_client_link(first, next);
SolveMap8(coreBuilding, next, solve, false);
}
}
}
else if (city_client_is_taken(next)) {
if (i == first -> zone -> building_count - 1) {
puts("enter2");
back = true;
}
}
}
}
}
}
}
Update Sorry, missed the recursion. In that case your problem has nothing to do with a missing break statement, but that you are trying to escape from a for loop at a different scope than you are currently in. You will need special logic to handle a global "done" condition. Perhaps something like this:
void process(Core* core, bool& done) {
for (int i = 0; i < core->size() && !done; ++i) {
if (!core[i]->is_taken()) {
process(core[i], done);
} else if (core[i]->is_taken() {
// done procesing
done = true;
}
}
}
// use via
bool done = false;
process(myCore, done);
In the version you have, the goingBack flag is passed by value, so every function gets its own copy and there is no way to pass the value of back to the parent in the recursive call chain. In my code above, done is passed as a reference, so changing the value at some point in the recursion chain will make it visible at parent scope (because the scope of the variable is outside the function itself). Hope this is more helpful.
I have an array of objects, each object has a function that returns a Boolean value. What I need to do, is have a loop continuously running until each object returns a true value when the function is called on each object.
EDIT: Sorry I wasn't clear enough, I meant that I want the loop to break, when ALL of the objects functions return true.
Any ideas?
Java style syntax:
boolean good;
while (true) {
good = true;
foreach (MyObject o : myArray) {
if (!o.someFunction()) {
good = false;
break;
}
}
if (good) break;
}
I interpreted it as meaning that every object needed to have its function evaluated to true each time, and once they all evaluate to true break out of the loop.
If I got your question, you can do like this...
do
{
test = 0;
for(all functions)
{
char test_array[] = function_call();
}
int i = 0;
for(test_array.length)
{
if(test_array[i] == true)
{
count_no_true = i++;
}
}
if(count_no_true == no of function)
{test == 1;}
else
{test == 0;}
}while(test == 1)
I need to write a function that will return true if it has found a difference between members of an array.
My code is:
int func1(int *str)
{
int i;
for(i=0;i<*(str+i);i++) {
if(*(str+i) == *(str+i+1))
{
return 1;
}
}
return 0;
}
I have to implement it with pointers.
The code above does not work(logically).
Can anybody help?
UPDATE:
I have changed my code to the following:
int func1(int *str)
{
int i,temp=0;
for(i=0;i<10-1;i++) {
if(*(str+i) == *(str+i+1))
{
temp++;
if( temp == 10 )
{
return 1;
}
}
}
return 0;
}
What is the problem with the new code?
This looks like homework to me, so I don't want to spoil the fun but one thing about C I'd like to mention: having a pointer to some array doesn't tell you anything about the size of the array. So your function will need to take a pointer and a second size_t argument (or maybe a pointer to the last element of the array).
Your function only takes in a single array pointer, that seems like one too few for a comparison.
You must add an argument that specifies the lengths of the arrays, or implement some kind of "policy" that e.g. terminates the arrays using a specific value.
You should also look into using the standard memcmp() function.
I don't understand the question (It's unclear what you're trying to achieve)...
As others have already said, there's no boundary checking on your array, which is wrong...
Here's some other feedback on your code:
// func1 - consider giving functions a meaningful name, it helps people to
// understand what the function is supposed to be doing....
// In this instance, it might have been helpful to identify what the expected
// return values / inputs of the function are...
int func1(int *str)
{
int i;
// Start a counter at 0, loop (adding 1) while
// the current value of the counter is less than, the value held in the
// array so, {1,2,3,4,0,7} Would terminate on the 0
// This: {1,20,7,14,0,7} Would also terminate on the 0
// This seems wrong, but again, it's unclear what you're trying to do here.
for(i=0;i<*(str+i);i++) {
// If the current element of the array
// is the same as the next element of the array
if(*(str+i) == *(str+i+1))
{
// return 1 - two numbers next to each other in the
// array are the same?
return 1;
}
}
// Either: The array contained a digit less than the counter,
// Or: It didn't contain two numbers that were the same next to each other.
// This seems a bit wrong?!?
return 0;
}
Your question could be improved (to get a more useful answer), if you showed what inputs you were expecting to return what return values.
Based on this 'I will need to write a function that will return true if its found diffrence between members of array.'
In pseudo code, it seems like you would want:
// Loop, checking we don't overflow. No point checking the last element as
// there's nothing after it to check...
for (count = 0 to arraysize -1) {
// If the current element != the next element, we've found a difference?!?
if(arrayElement[count] != arrayElement[count+1) {
return true
}
}
return false
UPDATE:
In your new code...
// You're still assuming the size of 'str'
int func1(int *str)
{
int i,temp=0;
// Loop while i < 9, i.e. 9 times.
for(i=0;i<10-1;i++) {
if(*(str+i) == *(str+i+1))
{
temp++;
// Temp can never == 10, you're only going round the loop 9 times...
// Maybe it should be (temp == 10-1), but I don't know where the
// 10 comes from...
if( temp == 10 )
{
return 1;
}
}
}
return 0;
}
This:
if(*(str+i) == *(str+i+1))
{
temp++;
// Temp can never == 10, you're only going round the loop 9 times...
if( temp == 10 )
{
return 1;
}
}
Could be:
// return 0 (FALSE) on first difference
if(*(str+i) != *(str+i+1))
{
return 0;
}
If you changed the return 0 at the end of your function to return 1