Welcome, Guest. Please login or register.

Author Topic: Programming question! :)  (Read 3330 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Fats

  • Hero Member
  • *****
  • Join Date: Mar 2002
  • Posts: 672
    • Show all replies
Re: Programming question! :)
« on: April 16, 2012, 07:17:40 PM »
Quote from: SamuraiCrow;688795
Code: [Select]

int test(num)
{
  if (num<4185)return 4;
  if (num<4507)return 3;
  if (num<4883)return 2;
  if (num<5327)return 1;
  return 0;
}



If you don't want to do it in a function you could use ? : operator like:

Code: [Select]

  rank =
    (num<4185) ? 4 :
    (num<4507) ? 3 :
    (num<4883) ? 2 :
    (num<5327) ? 1 :
    0;


greets,
Staf.
Trust me...                                              I know what I\'m doing
 

Offline Fats

  • Hero Member
  • *****
  • Join Date: Mar 2002
  • Posts: 672
    • Show all replies
Re: Programming question! :)
« Reply #1 on: April 17, 2012, 07:08:10 PM »
Quote from: bloodline;689088
Appologies! I only quickly looked over it :) If I had a larger array I would certainly investigate this method... I'm intrigued to see how a tiny microcontroller would cope with this kind of search!


OK, then you can go really funky. Using something like this:

Code: [Select]

struct lookup
{
   int num;
   unsigned char rank;
}

struct lookup vals[] =
{
    {4185, 4},
    {4507, 3},
    {4883, 2},
    {5327, 1},
    {MAX, 0}
}


If you make the array size a power of two you should be able to implement the binary search with bit manipulation using |= and <<. Or you can start somewhere in the middle of the array with an index that is power of two and see that you don't go over the highest index.

greets,
Staf.
Trust me...                                              I know what I\'m doing