Walther
Walther

Reputation:

How to create c# function to convert from groups of ranges of numbers to continues numbers

we have 6 groups of 253 machines each one ,
but each group are ranges from machine #2 to machine #254 ,
and continues IDs to represent each machine.

like in the following table:


Group Machine ID
0 2-254 1-253

1 2-254 254-506

2 2-254 507-759

3 2-254 760-1012

4 2-254 1013-1265

5 2-254 1266-1518


I am looking for a c# easy way to write a function to convert from an ID to a group-machine

example: ID 508 is the group #2 , machine #3
(machine 507 is the
first machine in group 2 and because it starts with 2 the second machin is machine#3)

and also the other way around
example: if I get the parameters:group #2 machine#5 ,
the function has to return the ID 510
How can I do this?
I came with a formula but it didn't work
any ideas?
thanks

Upvotes: 1

Views: 887

Answers (2)

Jamie
Jamie

Reputation: 6114

What about this?

function getid ( int g, int m ) {
    return g * (254 - 1 ) + m - 1; 
}

I think this is right? Simplified to:

function getid ( int g, int m ) {
    return g * 253 + m - 1; 
}

IE

2 * 253 + 3 = 508
2 * 253 + 5 = 510

Upvotes: 0

Guffa
Guffa

Reputation: 700242

First subtract one from the id to get it zero based, then you can divide it into group and machine, and adjust the machine number to the 2-254 range by adding two:

id--;
int group = id / 253;
int machine = (id % 253) + 2;

As two separate functions:

int GetGroup(int id) {
   return (id - 1) / 253;
}

int GetMachine(int id) {
   return ((id - 1) % 253) + 2;
}

To get the id from the group and machine you do the reverse; subtract two from the machine number to make it zero based, merge them, and add one:

int GetId(int group, int machine) {
   return group * 253 + (machine - 2) + 1;
}

Upvotes: 4

Related Questions