[SOLVED] Get Next and previous values from an array.

What could be included in further releases, or for the forum.
Locked
alexandros
Posts: 86
Joined: Mon Oct 02, 2017 6:51 pm

[SOLVED] Get Next and previous values from an array.

Post by alexandros » Fri Jan 11, 2019 8:48 pm

Hey there , my mind stuck and i need some help

i want to get from an array

Code: Select all

  static const char* listOne[]  =
	 {
	   "CAR",
	   "BIKE" ,
	   "BOAT",
	   "JET" ,
	   "PLANE",
	   "SPACESHIP"
	 };
say from listOne[2] wich is BOAT the previous two and previous 1 and also next 2 and next 1

so we have
menu_id_prev_prev = 0
menu_id_prev =1
menu_id_next =3
menu_id_next_next=4

its kinda mind blowing , if its in the end of the array listOne[5] the next 2 is "bike" and next 1 is "CAR"

is there any way without many if and elses , to get from a specific element directly the previous and next values ?

even if i have to reconstruct -sort the array its kinda complicated..

User avatar
Rick Kimball
Posts: 1400
Joined: Tue Apr 28, 2015 1:26 am
Location: Eastern NC, US
Contact:

Re: Get Next and previous values from an array.

Post by Rick Kimball » Fri Jan 11, 2019 9:03 pm

look into the modulo operator '%'
-rick

alexandros
Posts: 86
Joined: Mon Oct 02, 2017 6:51 pm

Re: Get Next and previous values from an array.

Post by alexandros » Fri Jan 11, 2019 9:55 pm

what about the negative indexes, modulo is getting sick with them

User avatar
Rick Kimball
Posts: 1400
Joined: Tue Apr 28, 2015 1:26 am
Location: Eastern NC, US
Contact:

Re: Get Next and previous values from an array.

Post by Rick Kimball » Fri Jan 11, 2019 10:03 pm

read up about unsigned math
-rick

alexandros
Posts: 86
Joined: Mon Oct 02, 2017 6:51 pm

Re: Get Next and previous values from an array.

Post by alexandros » Fri Jan 11, 2019 11:00 pm

thanks Rick

fredbox
Posts: 211
Joined: Tue Jul 07, 2015 4:44 pm

Re: Get Next and previous values from an array.

Post by fredbox » Sat Jan 12, 2019 3:32 am

As suggested, modulo arithmetic works (tested with gcc on Linux):

Code: Select all

uint8_t m;
uint8_t mod=6;
for (m=0; m<6; m++)
{
	printf("menu_prev_prev=%i menu_prev=%i menu=%i menu_next=%i menu_next_next=%i\n",
		(m+4)%mod, (m+5)%mod, (m+0)%mod, (m+1)%mod, (m+2)%mod);
}

Code: Select all

menu_prev_prev=4 menu_prev=5 menu=0 menu_next=1 menu_next_next=2
menu_prev_prev=5 menu_prev=0 menu=1 menu_next=2 menu_next_next=3
menu_prev_prev=0 menu_prev=1 menu=2 menu_next=3 menu_next_next=4
menu_prev_prev=1 menu_prev=2 menu=3 menu_next=4 menu_next_next=5
menu_prev_prev=2 menu_prev=3 menu=4 menu_next=5 menu_next_next=0
menu_prev_prev=3 menu_prev=4 menu=5 menu_next=0 menu_next_next=1

alexandros
Posts: 86
Joined: Mon Oct 02, 2017 6:51 pm

Re: Get Next and previous values from an array.

Post by alexandros » Sat Jan 12, 2019 8:23 am

Nice , Thank you guys , works perfectly

Locked