• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Or is it, b = 20 seconds
c = 100 seconds
d = 40 seconds. hm

these should really all be solved in the same fashion.

c * f(x) = y

c = y/f(x)

then

y' = c * f(x')

so using a
we get c = 10/log 1000
b we get c = 10 / 1000 and so on and so forth. then you plug in your calculated c and 2000 to solve for the new amount of time.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Code:
public static void method2(int[] array, int n)
{
   for (int index = 1; index <= n - 1; index++)
      privateMethod2(array[index], array, 0, index - 1); 
} 

public static void privateMethod2(int entry, int[] array, int begin, int end)
{
   int index;
   for (index = end; (index >= begin) && (entry < array[index]); index--) 
      array[index + 1] = array[index];
   array[index + 1] = entry;
}
The first method loops from the second element in the array to the nth element, so this is obviously O(n). It passes every entry it loops over into privateMethod2().

The second algorithm loops backwards from Index - 1 to the start of the array. It terminates when it hits an element that is bigger than the entry that was passed in. While it's looping, it shifts the data one index to the right. When the loop ends, it sets replaces whatever was in array[index] with entry.

So this is just Insertion Sort. Which is O(n^2). The best case is when the array is already sorted, and it never performs any swaps while looping to the end. The worst case is when the array is sorted in descending order, at which point it'll perform O(n^2) comparisons and swaps.
 
In C++11 you can do this more sanely, and if you must use heap allocation I would definitely do it this way:

Code:
    std::vector<std::unique_ptr<Foo>> fooList;
    for (int i = 0; i < 10; ++i) {
        // Create a unique pointer to Foo.
        // This is an affine type that can only be destroyed or moved, never copied.
        std::unique_ptr<Foo> foo(new Foo(i));
        // Now we move it into the vector--it can no longer be referenced anywhere else
        fooList.push_back(std::move(foo));
        // if you try to dereference foo here, you'll get a segmentation fault (the internal pointer
        // has been set to nullptr).
    }

    // do stuff with them Foos
    // They get deterministically freed when the block ends; it is safe to do this since
    // there is only ever one valid reference to them.
This is all good, but I'd like to add something...

If Foo isn't abstract or a base class, I'd just do this:
Code:
    std::vector<Foo> fooList;
    for (int i = 0; i < 10; ++i) {
        fooList.push_back(Foo(i));
    }

    // do stuff with them Foos
    // vector handles all memory allocation and deallocation

Inexperienced C++ programmers explicitly use dynamic memory way, way too much. Probably because that's how it's taught, but even so: You have the stack! You have the STL! They are your friends!
 

tokkun

Member
This is all good, but I'd like to add something...

If Foo isn't abstract or a base class, I'd just do this:
Code:
    std::vector<Foo> fooList;
    for (int i = 0; i < 10; ++i) {
        fooList.push_back(Foo(i));
    }

    // do stuff with them Foos
    // vector handles all memory allocation and deallocation

Inexperienced C++ programmers explicitly use dynamic memory way, way too much. Probably because that's how it's taught, but even so: You have the stack! You have the STL! They are your friends!

Big caveat here is that it only works if Foo has copy or move semantics defined. I've worked for companies that encouraged disabling copy/assign in all classes unless necessary.

You also have to be careful about how expensive a move/copy is, because it could make reallocation of the backing array very costly.
 

Sharp

Member
This is all good, but I'd like to add something...

If Foo isn't abstract or a base class, I'd just do this:
Code:
    std::vector<Foo> fooList;
    for (int i = 0; i < 10; ++i) {
        fooList.push_back(Foo(i));
    }

    // do stuff with them Foos
    // vector handles all memory allocation and deallocation

Inexperienced C++ programmers explicitly use dynamic memory way, way too much. Probably because that's how it's taught, but even so: You have the stack! You have the STL! They are your friends!
What you wrote was already in the post I was quoting (I just didn't quote the entire thing), and I mentioned at the end of the post that you should usually do it that way. But I suppose it's an important enough message that it's worth reiterating :)
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
That feel when creating and implementing a linked list data structure manually.

it's frustration
 

Water

Member
Big caveat here is that it only works if Foo has copy or move semantics defined. I've worked for companies that encouraged disabling copy/assign in all classes unless necessary.

You also have to be careful about how expensive a move/copy is, because it could make reallocation of the backing array very costly.
You could use a non-reallocating container, manually reserve enough space ahead of time and/or use emplace functions for insert to get through some of those situations without pointers.
 
In my database class, our major project is basically a lite version of Amazon's system with the need for multiple databases using SQL and a front end for accessing and mutating the data. We get bonus points if we build a web-interface as opposed to a CLI for our front end.

How difficult would it be build a simple web-interface to interact with a system written in Python (potentially C++) if I have no prior web development experience (i.e. very little HTML, CSS, no Javascript)?
 

phoenixyz

Member
How difficult would it be build a simple web-interface to interact with a system written in Python (potentially C++) if I have no prior web development experience (i.e. very little HTML, CSS, no Javascript)?

Using a library like Bottle or Flask it wouldn't be too hard, assuming the front-end and design is rather simple.
 

Vire

Member
Hey GAF, I'm just starting to learn Java and I could use a bit of help if you don't mind.

I'm trying to end this for loop when the user inputs 10 into the array to complete the order, but I don't think I have the syntax correct and it keeps going on infinitely.

Code:
        // Print out menu 
        System.out.println("BEST PURCHASE PRODUCTS");
        System.out.println("1. Smartphone       $249");
        System.out.println("2. Smartphone case  $39");
        System.out.println("3. PC Laptop        $1149");
        System.out.println("4. Tablet           $349");
        System.out.println("5. Tablet case      $49");
        System.out.println("6. eReader          $119");
        System.out.println("7. PC Desktop       $899");
        System.out.println("8. LED Monitor      $299");
        System.out.println("9. Laser Printer    $399");
        System.out.println("10. Complete my order");
   
    
    for (nIndex=0; nIndex < naItemSelection.length || naItemSelection[nIndex] !=10;  nIndex++){
        
        if(nIndex==0){
            System.out.print("Please select an item from the menu above: ");
            naItemSelection[nIndex] = input.nextInt();
        }//end if
        
        else if(nIndex<10){
        System.out.print("Please select another item from the menu above: ");
        
        naItemSelection[nIndex] = input.nextInt();
        
        }// end else if
  
    }//end for
 

Saprol

Member
I'm trying to end this for loop when the user inputs 10 into the array to complete the order, but I don't think I have the syntax correct and it keeps going on infinitely.

Code:
    for (nIndex=0; nIndex < naItemSelection.length || naItemSelection[nIndex] !=10;  nIndex++){

Somebody inputs 10 as the first item. naItemSelection[0] is 10. Start the next iteration of the loop and it's going to check naItemSelection[1] instead of the index that was just changed.

You could do naItemSelection[nIndex-1] but that seems weird to me to include early exit conditions in that line because it would start getting a bit crowded there if you later wanted to add additional cases to exit out. The break keyword would be useful here.
 

emb

Member
Hey GAF, I'm just starting to learn Java and I could use a bit of help if you don't mind.

I'm trying to end this for loop when the user inputs 10 into the array to complete the order, but I don't think I have the syntax correct and it keeps going on infinitely.
I'm not totally sure I'm following correctly, but I think that the issues are:

The condition in the loop is || for OR. So even if the user enters '10' after the first order, the loop will continue because the index is less than itemSelection.length.

So I think it's going to ask for 10 items regardless. But then you need to enter 10 on the tenth prompt. If you enter anything else at the tenth prompt, then it goes back, checks the loop condition, sees that the selection isn't ten, and repeats. Now that nIndex isn't 0 and isn't less than 10, the input doesn't get requested? If that's the case, you should probably include an 'else' at the end of the conditional to set item selection to 10.

If it's asking for input forever, then I'm not sure. That bug's not jumping out at me.

Edit: Oh, nevermind then. Good catch Saprol.
 
Beaten like a red headed step child.

Apart from the index issue that Saprol mentioned, the OR condition there isn't quite what you intend either. Remember that OR is true if either one or both sides are true.
 

Vire

Member
EDIT: We haven't learned the break method in class yet so I don't think the professor wants us to use that.


When I try && it waits until it reaches the array length AND has the the last inputted number = 10

Code:
    for (nIndex=0; nIndex < naItemSelection.length && naItemSelection[nIndex] !=10;  nIndex++){
        
        if(nIndex==0){
            System.out.print("Please select an item from the menu above: ");
            naItemSelection[nIndex] = input.nextInt();
        }//end if
        
        else {
        System.out.print("Please select another item from the menu above: ");
        
        naItemSelection[nIndex] = input.nextInt();
        
        }// end else if


Code:
output:

Please select an item from the menu above: 1
Second Index:1
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10
Please select another item from the menu above: 10
Second Index:10

Done

What is the logical operator I need to use so that one or the other condition triggers it to stop?

Thank you all so much for the help!
 

BreakyBoy

o_O @_@ O_o
Ok, so as long as the left side is true, it will continue? Let me retry this.

Yep, it's an optimization since it knows that if the first test is true, then the remaining tests don't matter. The inverse also happens with && (i.e. first test evaluates to false, then the entire thing evaluates to false).

See: Short-circuit evaluation

It's a useful thing to know, and a very common thing to see in the wild. Some languages even have things like an ||= operator, which only assigns the given value to the variable if the variable is undefined or nil/null.
 

Saprol

Member
What is the logical operator I need to use so that one or the other condition triggers it to stop?
The for-loop ends when the expression evaluates to false.

Logical OR (||) returns true when either expression is true, so flip the result by wrapping the entire thing with a logical NOT (!).
 
EDIT: We haven't learned the break method in class yet so I don't think the professor wants us to use that.

You fixed the && correctly which is good but the index issue is still there. That is, on iteration 1 of the loop, nIndex = 0, if you assign naItemPosition[0] to 10, then on iteration 2 of the loop, nIndex = 1 and it will check the value at naItemSelection[1], which is not 10, it's 0. You can't check the value at naItemSelection[i - 1], because on the first iteration that will go out of bounds. You basically have 2 ways to solve this problem:

1) Add a dummy entry to naItemPosition and iterate from position 1. e.g.
Code:
int[] naItemPosition = new int[size + 1];
for (int i = 1; i < naItemPosition.length && naItemPosition[i - 1] != 10; ++i) {
    // do loop here with 1 as the first index
}

2) Explicitly check for the end condition in the loop and terminate early
Code:
for (int i = 0; i < naItemPosition.length; ++i) {
    // normal readint
    if (naItemPosition[i] == 10) { 
        // you can terminate here in 1 of 2 ways
        // either set the loop variable to the end manually (not recommended)
        i = naItemPosition.length;
        // or explicitly break (preferred)
        break;
    }
}

break; is just a single statement that terminates the most recent layer of iteration you are in. The reason break is preferred is that it makes it very clear what you are doing, you are terminating the loop, whereas if you manipulate i it is not immediately obvious the effect that will have, the reader needs to recheck the condition themselves to verify.

Personally I prefer option 1 as it reduces the amount of nesting and makes it easier to read the condition on which the loop terminates, but you do have to remember that there is that empty slot in the area in that case at position 0.

Edit: I'm tired
 
The for-loop ends when the expression evaluates to false.

Logical OR (||) returns true when either expression is true, so flip the result by wrapping the entire thing with a logical NOT (!).

You need to be careful with this, typically if you wrap an expression containing a NOT with a NOT it's a sign that you are doing something non optimal in terms of what you are trying to express. Here you would just be doing a ~(A+~B) which is equivalent to ~(A.B).

Both are wrong for this situation but I just wanted to point out that everyone should be familiar with De Morgan's Laws and avoid inverting expressions for the sake of it :p.
 

Vire

Member
The for-loop ends when the expression evaluates to false.

Logical OR (||) returns true when either expression is true, so flip the result by wrapping the entire thing with a logical NOT (!).

You fixed the && correctly which is good but the index issue is still there. That is, on iteration 1 of the loop, nIndex = 0, if you assign naItemPosition[0] to 10, then on iteration 2 of the loop, nIndex = 1 and it will check the value at naItemSelection[1], which is not 10, it's 0. You can't check the value at naItemSelection[i - 1], because on the first iteration that will go out of bounds. You basically have 2 ways to solve this problem:

1) Add a dummy entry to naItemPosition and iterate from position 1. e.g.
Code:
int[] naItemPosition = new int[size + 1];
for (int i = 1; i < naItemPosition.length && naItemPosition[i - 1] != 10; ++i) {
    // do loop here with 1 as the first index
}

2) Explicitly check for the end condition in the loop and terminate early
Code:
for (int i = 0; i < naItemPosition.length; ++i) {
    // normal readint
    if (naItemPosition[i] == 10) { 
        // you can terminate here in 1 of 2 ways
        // either set the loop variable to the end manually (not recommended)
        i = naItemPosition.length;
        // or explicitly break (preferred)
        break;
    }
}

break; is just a single statement that terminates the most recent layer of iteration you are in. The reason break is preferred is that it makes it very clear what you are doing, you are terminating the loop, whereas if you manipulate i it is not immediately obvious the effect that will have, the reader needs to recheck the condition themselves to verify.

Personally I prefer option 1 as it reduces the amount of conditionals and makes it easier to read the condition on which the loop terminates, but you do have to remember that there is that empty slot in the area in that case at position 0.

Hurray! Thanks again!

Here is what I ended up using - it's not pretty, but it works perfectly and is easy for me to understand.

Code:
    for (nIndex=0; (nIndex < naItemSelection.length && naItemSelection[nIndex] !=10);  nIndex++){
        
        if(nIndex==0){
            System.out.print("Please select an item from the menu above: ");
            naItemSelection[nIndex] = input.nextInt();
            
         
            if(naItemSelection[nIndex]==10){
                nIndex = 10;
                        }           
        }//end if
        
        else {
        System.out.print("Please select another item from the menu above: ");
        
        naItemSelection[nIndex] = input.nextInt();
        
        
            if(naItemSelection[nIndex]==10){
                nIndex = 10;
                        }           
        
        
        }// end else if
 

Saprol

Member
You need to be careful with this, typically if you wrap an expression containing a NOT with a NOT it's a sign that you are doing something non optimal in terms of what you are trying to express. Here you would just be doing a ~(A+~B) which is equivalent to ~(A.B).

Both are wrong for this situation but I just wanted to point out that everyone should be familiar with De Morgan's Laws and avoid inverting expressions for the sake of it :p.

I probably confused myself thinking of a way to do it with operators. It'd be less error-prone to just change the individual expressions within the || or &&.
 

RELAYER

Banned
A new question -

I'm making a game where two players see who has the fastest reaction time. 4 LEDs countdown, and when the final one comes on, whoever presses their switch first wins.

I'm using a while loop for the LED countdowns, and using interrupts for the player switches.

Right now it's set up something like this

Code:
while (!response) {
//led stuff
}

response is initialized to zero, and when a player-interrupt is activated, it turns to one, stopping the game.

When a a player interrupt is activated, I have a 5 second waiting period while I display some stuff on the computer screen, and then response is set back again to zero.

The problem is that this causes the while loop to pick up where it left off.
But the behavior I want is for the while loop to restart at the beginning of the countdown when 'response' is reset to zero.

How can I make it return back to the top of the while loop instead of returning to where it left off?
 

Sharp

Member
A new question -

I'm making a game where two players see who has the fastest reaction time. 4 LEDs countdown, and when the final one comes on, whoever presses their switch first wins.

I'm using a while loop for the LED countdowns, and using interrupts for the player switches.

Right now it's set up something like this

Code:
while (!response) {
//led stuff
}

response is initialized to zero, and when a player-interrupt is activated, it turns to one, stopping the game.

When a a player interrupt is activated, I have a 5 second waiting period while I display some stuff on the computer screen, and then response is set back again to zero.

The problem is that this causes the while loop to pick up where it left off.
But the behavior I want is for the while loop to restart at the beginning of the countdown when 'response' is reset to zero.

How can I make it return back to the top of the while loop instead of returning to where it left off?
There isn't really enough information to go on here, since what you're asking about necessarily occurs outside the context of that while loop. Can you give us the full program?
 

Onemic

Member
Can someone please tell me Im just a newbie to the language and I'll adjust in time, when I say that my experience with Javascript leads me to believe it's one of the worst languages out there. Every time I use this piece of shit it makes me want to pull my hair out with how completely unintuitive it is. It's almost like I can't even use logic to solve problems when working with this thing. Maybe it's because I'm too used to C/C++, but why the hell is nothing consistent with this language? I'm finding situations where certain methods can only be used when initialized to a variable, yet some don't have this restriction....and there doesnt seem to be a reason why. Things like subscript methods and split are needlessly complicated for no reason and don't even get me started on the atrocious debugging(or lack of) features. Every time I use this language it makes me question how anyone could enjoy using this thing on a daily basis.
 

Sharp

Member
Can someone please tell me Im just a newbie to the language and I'll adjust in time, when I say that my experience with Javascript leads me to believe it's one of the worst languages out there. Every time I use this piece of shit it makes me want to pull my hair out with how completely unintuitive it is. It's almost like I can't even use logic to solve problems when working with this thing. Maybe it's because I'm too used to C/C++, but why the hell is nothing consistent with this language? I'm finding situations where certain methods can only be used when initialized to a variable, yet some don't have this restriction....and there doesnt seem to be a reason why. Things like subscript methods and split are needlessly complicated for no reason and don't even get me started on the atrocious debugging(or lack of) features. Every time I use this language it makes me question how anyone could enjoy using this thing on a daily basis.
C++ is the poster boy for language inconsistency, up there with PHP and Perl. I think it's currently understood to be impossible to actually implement a conformant compiler. So yes, I'd say it's entirely a question of familiarity.
 

RELAYER

Banned
There isn't really enough information to go on here, since what you're asking about necessarily occurs outside the context of that while loop. Can you give us the full program?


I was trying to ask generally because the full program is kind of long and annoying and plus I don't want my instructor to google it and discover my sinister GAF alter-ego.
Can I PM it to you?
 

survivor

Banned
This is an slightly older post but I'll answer it now anyhow.

......
Yeah, after spending some time I'm seeing the usefulness of some of the libraries and frameworks. I was just really frustrated cause I wanted to get a basic understanding of Nodejs/Express project structure, but I was getting swamped with all these extra tools that I needed to understand first.
 

Ortix

Banned
Had my 4th java course today. Missed the 3rd one because I was sick, as a result I had some trouble following it all. We had to make a (very) basic program to convert °C to °F and °F to °C. So, the program had to give (someone) the choice to chose either, or to enter 0 to quit. Now the thing is, there needed to be a (while) loop, in order to return to the "menu" when a conversion was finished, and I don't know how to. Can anybody help me?

public class OefeningP1W2 {
public static void main(String[] args) {
int choice;
int numberlnCelsius;
int numberInF;


Scanner keyboard = new Scanner(System.in);

System.out.println("Which conversion do you wish to do?");
System.out.println("1) °C to °F");
System.out.println("2) °F to °C");
System.out.println("Your choice?");
choice = keyboard.nextInt();

if(choice == 1){
System.out.println("Your choice?1");
System.out.println("Give the value in °C:");
numberInCelsius = keyboard.nextInt();
System.out.println(numberincelsius * 9/5 + 32);}
if(choice == 2){
System.out.println("Your choice?2");
System.out.println("Give the value in °F:");
numberInF = keyboard.nextInt();
System.out.println((numberInF - 32) * 5/9);
}
if(choice == 0){
System.out.println("Your choice?0");
System.out.println("Goodbye!");
}




}
}

(translated this from dutch so there could be a mistake somewhere)
 
Had my 4th java course today. Missed the 3rd one because I was sick, as a result I had some trouble following it all. We had to make a (very) basic program to convert °C to °F and °F to °C. So, the program had to give (someone) the choice to chose either, or to enter 0 to quit. Now the thing is, there needed to be a (while) loop, in order to return to the "menu" when a conversion was finished, and I don't know how to. Can anybody help me?

Hm... Read this, run the examples given and see if you can figure out what to do?

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
 

RELAYER

Banned
This program is driving me crazy. I feel like the solution must be rather simple but I don't know the way in which to create the desired behavior. I guess I'll just post it.

Code:
#include "mbed.h"

Serial pc(USBTX, USBRX);

DigitalOut ledone (LED1);
DigitalOut ledtwo (LED2);
DigitalOut ledthree (LED3);
DigitalOut ledfour (LED4);
InterruptIn playerone(p14);
InterruptIn playertwo(p21);
Timer tim;
Timeout timeout;
float difference;
volatile int response = 0;
volatile int ignorerise;
volatile int playeronescore = 0;
volatile int playertwoscore = 0; 

void ignorerisetimeout (void) { //for button bounce
    ignorerise = 0;
}

void switchrelease (void) { //for bounce
    ignorerise = 1;
    timeout.attach(ignorerisetimeout, 0.01);
}

void playeroneinterrupt(void) { //player one buzzes in
    tim.stop();
    tim.read();
    response = 1;
    if (ignorerise) return;
    ignorerise = 1;
    timeout.attach(ignorerisetimeout, 0.01);
    if (tim.read() < 3) {
        playeronescore--;
        difference = 3 - tim.read();
        pc.printf("Player 1 was %f ms too early and lost.\n\r", difference);
        pc.printf("Player 1: %d points, Player 2: %d points.\n\r", playeronescore, playertwoscore);
    }
    if (tim.read() > 3) {
        playeronescore++;
        difference = tim.read() - 3;
        pc.printf("Player 1 won with a reaction time of only %f ms.\n\r", difference);
        pc.printf("Player 1: %d points, Player 2: %d points.\n\r", playeronescore, playertwoscore);
    }
    wait (5);
    tim.reset();
    response = 0;
}

void playertwointerrupt(void){ //player two buzzes in
    tim.stop();
    tim.read();
    response = 1;
    if (ignorerise) return;
    ignorerise = 1;
    timeout.attach(ignorerisetimeout, 0.01);
    if (tim.read() < 3) {
        playertwoscore--;
        difference = 3 - tim.read();
        pc.printf("Player 2 was %f ms too early and lost.\n\r", difference);
        pc.printf("Player 1: %d points, Player 2: %d points.\n\r", playeronescore, playertwoscore);
    }
    if(tim.read() > 3) {
        playertwoscore++;
        difference = tim.read() - 3;
        pc.printf("Player 2 won with a reaction time of only %f ms.\n\r", difference);
        pc.printf("Player 1: %d points, Player2: %d points.\n\r", playeronescore, playertwoscore);
    }
    wait(5);
    tim.reset();
    response = 0;
}

int main() {
    playerone.mode(PullUp);
    playerone.fall(playeroneinterrupt);
    playerone.rise(switchrelease);
    playertwo.rise(playertwointerrupt);
    playertwo.fall(switchrelease);
    pc.baud(9600);
    while(1) { //led countdown
    tim.start();
    ledfour = 1;
    wait(1);
    ledfour = 0;
    ledthree = 1;
    wait(1);
    ledthree = 0;
    ledtwo = 1;
    wait(1);
    ledtwo = 0;
    ledone = 1;
    wait(1);
    ledone = 0;
    wait(1);
    }
}

When a player buzzes in, the interrupt is called, the timer is checked, a message is displayed depending on when they buzzed, and everything is reset (besides the score).

Then there is a 5 second wait, and we return to the countdown.

Right now, the countdown picks up right where it left off.

What I want is for the countdown to begin anew. Is there any way to do this? I saw 'continue' recommended to me. That's a new one for me, I googled it but either didn't understand it or couldn't get it to work.

Also, this is a microcontroller the mbed. So I don't know if that affects what functions I can use.
 

Husker86

Member
This program is driving me crazy. I feel like the solution must be rather simple but I don't know the way in which to create the desired behavior. I guess I'll just post it.

When a player buzzes in, the interrupt is called, the timer is checked, a message is displayed depending on when they buzzed, and everything is reset (besides the score).

Then there is a 5 second wait, and we return to the countdown.

Right now, the countdown picks up right where it left off.

What I want is for the countdown to begin anew. Is there any way to do this? I saw 'continue' recommended to me. That's a new one for me, I googled it but either didn't understand it or couldn't get it to work.

Also, this is a microcontroller the mbed. So I don't know if that affects what functions I can use.

Can you adjust the LEDs in the while loop to trigger based on the timer?

if (tim < 1){ LED4 }
if (tim > 1 && tim < 2){ LED3 }

Since you're resetting the timer before starting the loop again, that should work, right?

Maybe not the most elegant solution, but...
 

tokkun

Member
This program is driving me crazy. I feel like the solution must be rather simple but I don't know the way in which to create the desired behavior. I guess I'll just post it.

Code:
#include "mbed.h"

Serial pc(USBTX, USBRX);

DigitalOut ledone (LED1);
DigitalOut ledtwo (LED2);
DigitalOut ledthree (LED3);
DigitalOut ledfour (LED4);
InterruptIn playerone(p14);
InterruptIn playertwo(p21);
Timer tim;
Timeout timeout;
float difference;
volatile int response = 0;
volatile int ignorerise;
volatile int playeronescore = 0;
volatile int playertwoscore = 0; 

void ignorerisetimeout (void) { //for button bounce
    ignorerise = 0;
}

void switchrelease (void) { //for bounce
    ignorerise = 1;
    timeout.attach(ignorerisetimeout, 0.01);
}

void playeroneinterrupt(void) { //player one buzzes in
    tim.stop();
    tim.read();
    response = 1;
    if (ignorerise) return;
    ignorerise = 1;
    timeout.attach(ignorerisetimeout, 0.01);
    if (tim.read() < 3) {
        playeronescore--;
        difference = 3 - tim.read();
        pc.printf("Player 1 was %f ms too early and lost.\n\r", difference);
        pc.printf("Player 1: %d points, Player 2: %d points.\n\r", playeronescore, playertwoscore);
    }
    if (tim.read() > 3) {
        playeronescore++;
        difference = tim.read() - 3;
        pc.printf("Player 1 won with a reaction time of only %f ms.\n\r", difference);
        pc.printf("Player 1: %d points, Player 2: %d points.\n\r", playeronescore, playertwoscore);
    }
    wait (5);
    tim.reset();
    response = 0;
}

void playertwointerrupt(void){ //player two buzzes in
    tim.stop();
    tim.read();
    response = 1;
    if (ignorerise) return;
    ignorerise = 1;
    timeout.attach(ignorerisetimeout, 0.01);
    if (tim.read() < 3) {
        playertwoscore--;
        difference = 3 - tim.read();
        pc.printf("Player 2 was %f ms too early and lost.\n\r", difference);
        pc.printf("Player 1: %d points, Player 2: %d points.\n\r", playeronescore, playertwoscore);
    }
    if(tim.read() > 3) {
        playertwoscore++;
        difference = tim.read() - 3;
        pc.printf("Player 2 won with a reaction time of only %f ms.\n\r", difference);
        pc.printf("Player 1: %d points, Player2: %d points.\n\r", playeronescore, playertwoscore);
    }
    wait(5);
    tim.reset();
    response = 0;
}

int main() {
    playerone.mode(PullUp);
    playerone.fall(playeroneinterrupt);
    playerone.rise(switchrelease);
    playertwo.rise(playertwointerrupt);
    playertwo.fall(switchrelease);
    pc.baud(9600);
    while(1) { //led countdown
    tim.start();
    ledfour = 1;
    wait(1);
    ledfour = 0;
    ledthree = 1;
    wait(1);
    ledthree = 0;
    ledtwo = 1;
    wait(1);
    ledtwo = 0;
    ledone = 1;
    wait(1);
    ledone = 0;
    wait(1);
    }
}

When a player buzzes in, the interrupt is called, the timer is checked, a message is displayed depending on when they buzzed, and everything is reset (besides the score).

Then there is a 5 second wait, and we return to the countdown.

Right now, the countdown picks up right where it left off.

What I want is for the countdown to begin anew. Is there any way to do this? I saw 'continue' recommended to me. That's a new one for me, I googled it but either didn't understand it or couldn't get it to work.

Also, this is a microcontroller the mbed. So I don't know if that affects what functions I can use.

It seems like the easiest way to modify your existing code to do that would be to add a global variable representing the current time to display with the LEDs.

Then control the LED logic using a switch statement.

Code:
while (1) {
  switch (led_display) {
    // Add your cases here
  }
  wait(1);
}

And you reset the led_display value in the interrupt.
 
This program is driving me crazy. I feel like the solution must be rather simple but I don't know the way in which to create the desired behavior. I guess I'll just post it.

Another method that jumps out at me is if you convert your loop to be data driven, you can change the state of the program by modifying the data. So then you just need to set the active LED inside the interrupt and it should work ok. Advantage here is less code repitition and you can turn off every light on each pass to prevent getting stuck in weird state.

e,g,

Code:
int const LED_COUNT;
//array of DigitalOuts
DigitalOut leds[LED_COUNT];
leds[0] = DigitalOut(LED1);
leds[1] = DigitalOut(LED2);
leds[2] = DigitalOut(LED3);
leds[3] = DigitalOut(LED4);

int activeLed = 0;

void playeroneinterrupt(void) { //player one buzzes in
    activeLed = 0;
   // rest of function
}

void playertwointerrupt(void){ //player two buzzes in
    activeLed = 0;
    // rest of function
}

int main() {
    // setup
    while(1) { //led countdown
        // turn off all leds
        (for int i = 0; i < LED_COUNT; ++i) {
            leds[i] = 0;
        }
        // turn on active
       leds[activeLed] = 1;
       activeLed = (activeLed + 1) % LED_COUNT; 
       wait(1);    
}

I think this array syntax will work unless it's pure C you're using? I'm a bit crap with C/C++.
 

Sharp

Member
This program is driving me crazy. I feel like the solution must be rather simple but I don't know the way in which to create the desired behavior. I guess I'll just post it.
Okay, as I suspected, you're using a long-running interrupt. There are actually a lot of problems with this code. While it may seem like that's the right way to do this, it actually usually is not what you want.

First off, please read the mbed article on ISRs. Some of the restrictions you are violating:
mbed documentation said:
No blocking code in ISR

In ISR you should avoid any call to wait, infinitive while loop, or blocking calls in general.

No printf, malloc, or new in ISR

In ISR you should avoid any call to bulky library functions. In particular, certain library functions (like printf, malloc and new) are non re-entrant and their behaviour could be corrupted when called from an ISR.

The problem with long-running interrupt handlers (well, one of the many problems) is that they are really hard to make safe. The provided rules are designed to help prevent some of the more common issues when using interrupts.

Once you take care of these issues, your program design should be clarified. It helps to realize that wait() in mbed is actually implemented as a busy loop. You aren't getting anything out of calling wait() as opposed to using a loop. So the way to redesign your program is to have the interrupt routines do very simple, quick operations (like just setting the active LED) and check in the loop for any changes. This is how most interrupt handlers work in practice, e.g. keyboard interrupt handlers for games will set an index into a key array when a key is depressed or released, but not handle actual game logic there.
 
I hate to ask for help, but I'm working on a mini android side project on my own for the fun of it(and I want to start developing apps that connect and interact with servers/websites so I figured this will be good practice). I'm trying to get an html source from a website and extract certain information from it and use it in the app. I have only extracted info from sites in javascript with the help of ajax so I'm still new to this. So after a few attempts, I tried searching it and found this:
http://stackoverflow.com/questions/...eb-and-use-the-data-in-my-app/4523525#4523525

I put that in a AsyncTask class, however it's just takes forever to load. I had something like this in the class:

Code:
private class AsyncTasker extends AsyncTask<Void, Void, Void>
{
//overide methods ...
@Override
protected Void doInBackground(Void... params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.google.com"); 
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
//do other stuff
}

Yet, logcat just says something like it's skipping and the app may be doing too much work. When I input an address that doesn't exists, then it timeouts.

Can someone point me to the right direction?
 
Anyone have any knowledge of Scheme/Racket?

I'm trying to create a list of variable length, with every item in the list being the same (in this case, a list of n strings that are "_")

I know that this will most likely involve recursion but I am wrapping my head around how it will work.

Code:
(define temp (list ""))

(define makeBlankWord n 
              (if (= (length n) 1)
              "_ "
              (define blankWord (makeBlankWord (cdr  (append temp (list "_ "))))))
Am I on the right track?
 

Sharp

Member
Anyone have any knowledge of Scheme/Racket?

I'm trying to create a list of variable length, with every item in the list being the same (in this case, a list of n strings that are "_")

I know that this will most likely involve recursion but I am wrapping my head around how it will work.

Code:
(define temp (list ""))

(define makeBlankWord n 
              (if (= (length n) 1)
              "_ "
              (define blankWord (makeBlankWord (cdr  (append temp (list "_ "))))))
Am I on the right track?
You're right that it will involve recursion, but I'd suggest scrapping your current solution and trying anew. Think about the API for makeBlankWord--what type is n? How would you write an inductive proof that your function is correct (which is the analogue for recursion)?
 
Anyone have any knowledge of Scheme/Racket?

I'm trying to create a list of variable length, with every item in the list being the same (in this case, a list of n strings that are "_")

I know that this will most likely involve recursion but I am wrapping my head around how it will work.

Am I on the right track?

Like Sharp said think about how to prove it. For a list of n items, what does a list of length 0 look like? What does a list of length 1 look like? What is the relation between a list of length n and a list of length n - 1?
 

Apt101

Member
Sorry if this has been asked before. I want to learn Java with an eye on moving to Android development. I was wondering if anyone knew of some good free coursework on-line, and what the best IDE is? Preferably Linux. Thanks.
 

maeh2k

Member
Sorry if this has been asked before. I want to learn Java with an eye on moving to Android development. I was wondering if anyone knew of some good free coursework on-line, and what the best IDE is? Preferably Linux. Thanks.

As for IDE, I'd recommend IntelliJ IDEA or the Android Studio (based on IntelliJ IDEA). If you have a .edu address, the full IDE is free, otherwise there's the free community edition that should work about as well for your purposes. It has integrated Android development tools. There's also Android Studio, which is basically a modified IntelliJ IDEA community edition that is a bit more geared towards Android development. It doesn't offer any more features, but supposedly makes some things a bit more straight-forward.

IntelliJ offers lot and lots of shortcuts and it might take a while to get used to it, but I think it's worth it. I love it.
 

Apt101

Member
As for IDE, I'd recommend IntelliJ IDEA or the Android Studio (based on IntelliJ IDEA). If you have a .edu address, the full IDE is free, otherwise there's the free community edition that should work about as well for your purposes. It has integrated Android development tools. There's also Android Studio, which is basically a modified IntelliJ IDEA community edition that is a bit more geared towards Android development. It doesn't offer any more features, but supposedly makes some things a bit more straight-forward.

IntelliJ offers lot and lots of shortcuts and it might take a while to get used to it, but I think it's worth it. I love it.

Thanks for the advice, I'll grab that community edition and get started.
 

PK Gaming

Member
Hi

Apologies in advance for such a basic question, but i'm at my wits end (regarding C programming)

To put it simply, I would like to do 2 things:

1) I'd like to populate every member of an array using the scanf function
2) I'd like to print out ever member of said array

For example, let's say I create an array of size 3. I want to set it up so that when I input say... "3" it prints out [3] [0] [0]. Inputing "5" afterward would print out [1] [5] [0] and inputing "7" would print out [1] [5] [7].

Not sure how to go about it. The array itself looks like this:

double my_array[10] = { '\0' };
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Hi

Apologies in advance for such a basic question, but i'm at my wits end (regarding C programming)

To put it simply, I would like to do 2 things:

1) I'd like to populate every member of an array using the scanf function
2) I'd like to print out ever member of said array

For example, let's say I create an array of size 3. I want to set it up so that when I input say... "3" it prints out [3] [0] [0]. Inputing "5" afterward would print out [1] [5] [0] and inputing "7" would print out [1] [5] [7].

Not sure how to go about it. The array itself looks like this:

double my_array[10] = { '\0' };

for loops.

Code:
for(i = 0; i < size of array - 1; i++)
{
    // use scanf to get use input
    // store user input in i position of array
    // print array contents here, or outside of loop. Use another for loop
    for (i = 0; i < size of array - 1; i++)
    {
         // print array contents at i
    }
}

Super simple way of doing it. I'm sure there's other ways out there that are probably more elegant.
 

Ape

Banned
I have a pivot table with 2 columns (Region & District) and about six calculated values (showing who completed the notifications-i.e. S, C Or U), with those values being the rows as well. I have inserted a pivot chart showing the calculated fields. I also have some slicers showing the status of the notification, the incident type, region, district, and the year the notification was created. Everything seems to work just fine, but when I use the slicer for notification status="pending" or "deleted", I notice that the data displayed on the pivot chart is not correct according to my data source. For example, according to my data source there are five valid, pending notifications completed by S and about thirty valid, pending notifications completed by U, but the chart shows all values as 0%. I have tried adding the status to the columns, values, rows and filters. Nothing seems to be working for me...any suggestions?
 
Top Bottom