user3671032
user3671032

Reputation: 211

Need help generating a unique request code for alarm

My app structure is like, there are 1000 masjids/mosques and each masjid has been given a unique id like 1,2,3,4 ..... 1000 . Now each mosque has seven alarms associated with it , I wish to generate a unique request code number for each alarm so that they don't overlap each other,

Following is the code:

//note integer NamazType has range 0 to 5
       public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
        {
                return (MasjidID *(10)) + (namazType);
        }

Will this code work?

Upvotes: 2

Views: 1235

Answers (4)

Waqar Ahmed
Waqar Ahmed

Reputation: 5068

you can simply concatenate masjidID and namaztype( or specifically namaz ID). This will always return unique.

    public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
    {
            return Integer.ParseInt(String.valueOf(MasjidID)+""+NamazType)
    }

Upvotes: 2

ngrashia
ngrashia

Reputation: 9904

If MasjidID and NamazType are unique, then

Integer.parseInt( MasjidID + "" + NamazType  ); 

would be enough to do the trick!

Example:

Masjid ID = 96, Namaz type = 1, Unique no = 961
MasjidId  = 960, Namaz type = 1, Unique no = 9601
MasjidID  = 999, Namaz type = 6, Unique no = 9996

I don't find any way in which it would get repeated. However, it is very similar to

(MasjidID * 10) + NamazType

Irrespective of MasjidID and NamazType, if a random number needs to be generated, this can be used.

public class NoRepeatRandom {

  private int[] number = null;
  private int N = -1;
  private int size = 0;
  public NoRepeatRandom(int minVal, int maxVal)
  {
    N = (maxVal - minVal) + 1;
    number = new int[N];
    int n = minVal;
    for(int i = 0; i < N; i++)
      number[i] = n++;
    size = N;
  }

  public void Reset() { size = N; }

   // Returns -1 if none left
  public int GetRandom()
  {
    if(size <= 0) return -1;
    int index = (int) (size * Math.random()); 
  int randNum = number[index];

    // Swap current value with current last, so we don't actually
    // have to remove anything, and our list still contains everything
    // if we want to reset
    number[index] = number[size-1];
    number[--size] = randNum;

    return randNum;
  }
}

Upvotes: -1

Mehul Joisar
Mehul Joisar

Reputation: 15358

It will work for sure.

public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
    {
            return (MasjidID*(10)) + (NamazType );
    }

Output:

Have a look at this

Upvotes: 0

Pratik Butani
Pratik Butani

Reputation: 62429

Use Random class:

Try out like this:

//note integer NamazType has range 0 to 5
public int generateRequestCodeForAlarm(int MasjidID, int NamazType)
{
    return (MasjidID * (Math.abs(new Random().nextInt()))) + (namazType);
}

Upvotes: 0

Related Questions