esmith08734
Member
Or is it, b = 20 seconds
c = 100 seconds
d = 40 seconds. hm
c = 100 seconds
d = 40 seconds. hm
Or is it, b = 20 seconds
c = 100 seconds
d = 40 seconds. hm
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;
}
This is all good, but I'd like to add something...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.
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
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 reiteratingThis 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!
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.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.
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.
// 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
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++){
I'm not totally sure I'm following correctly, but I think that the issues are: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.
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
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
Ok, so as long as the left side is true, it will continue? Let me retry this.
The for-loop ends when the expression evaluates to false.What is the logical operator I need to use so that one or the other condition triggers it to stop?
EDIT: We haven't learned the break method in class yet so I don't think the professor wants us to use that.
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
}
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;
}
}
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 (!).
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.
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
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 .
while (!response) {
//led stuff
}
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?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?
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.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.
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 think what you're looking for is "continue"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?
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.This is an slightly older post but I'll answer it now anyhow.
......
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!");
}
}
}
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?
#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);
}
}
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.
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.
while (1) {
switch (led_display) {
// Add your cases here
}
wait(1);
}
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.
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);
}
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.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.
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.
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
}
(define temp (list ""))
(define makeBlankWord n
(if (= (length n) 1)
"_ "
(define blankWord (makeBlankWord (cdr (append temp (list "_ "))))))
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?Code:(define temp (list "")) (define makeBlankWord n (if (= (length n) 1) "_ " (define blankWord (makeBlankWord (cdr (append temp (list "_ "))))))
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?
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.
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.
Thanks for the advice, I'll grab that community edition and get started.
Udacity also has one taught by Google employees.Not sure how good it is but Coursera has an Android 101 course assuming no knowledge.
https://www.coursera.org/course/androidapps101
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(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
}
}