How to write a recursive function that works it's way through every element in an array?

Hello, so I have this array: Now I have to work my way through this array, by increments of 1

I have no clue how to do this, I've tried various solutions and they all failed. I did successfully try using on that checks to see if the track in front is a -1 or 1 but that wouldn't work because the player is supposed to be blindfolded, can anyone give me any suggestions on how I can solve this/write this program? thank you.
Last edited on
How do simulate every possible score outcome and determine the best score possible using recursion? [...snip...] but that wouldn't work because the player is supposed to be blindfolded, can anyone give me any suggestions on how I can solve this/write this program?


The player being blindfolded is a red herring. Remove that particular fact from your mind. It is irrelevant after you've decided to simulate every possible game to determine the best score possible.

I'd like to make one modification to your function prototype. It isn't necessary for the function to take a parameter bestScore, so I'm removing it for the purposes of the following pseudo-code.

1
2
3
4
5
6
7
8
9
10
11
 // given your function prototype:
int maximumScore(int track[], int size, int loc) {

    if loc is greater than or equal to size      // I trust you can figure out why greater is needed
        return 0

    let score1 be the value returned by calling maximumScore(track,size, loc+1)
    let score2 be the value returned by calling maximumScore(track,size, loc+2)

    return the max of score1 and score2 added to track[loc]
}



Thank you for the reply @cire, I'm not sure I really understand what you mean entirely. Do you mean something like this? (see code) Should I return the max of score1 and score 2 based on which is larger? Thank you for the help, it is appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

int maximumScore(int track[], int size, int loc) {
int score1 = 0, score2 = 0;

if (loc >= size) {
	
	return 0;
	
} else {

score1 = maximumScore(track, size, loc+1);
score2 = maximumScore(track, size, loc+2); //edited

}

// return?


}
Last edited on
Do you mean something like this?

Something like that, but more like what I wrote. For your code, score1 and score2 will always be the same value.
@cire ,

oh okay, sorry I didn't realize I hadn't changed the second one. How does score1/score 2 increase by calling it?

Sorry for all these questions, I'm quite new to programming.
Last edited on
oh okay, sorry I didn't realize I hadn't changed the second one. How does score1/score 2 increase by calling it?


For each invocation of maximumScore where loc is less than size, you should return the value of the current location (track[loc]) + the higher of score1/score2). The "increase" comes from that addition.
oh...okay! I see! I got it working, thank you!
Last edited on
Topic archived. No new replies allowed.