How to find which range is in

I have folders named like this:

"1-500" "501-1000" "1001-1500" "1501-2000" "2501-3000" etc.... 

Given an identifier like 1777 , how can I find the name of the folder in which it belongs?

I use Java, but your answer may be pseudo code.

Thanks!

+4
source share
9 answers

Here's how:

 // Folder 0: 1-500 // Folder 1: 501-1000 // Folder 2: 1001-1500 // ... int n = 1777; int folder = (n-1) / 500; System.out.printf("%d belongs to folder %d - %d", n, folder * 500 + 1, (folder+1) * 500); 

Output:

 1777 belongs to folder 1501 - 2000 

Integer division takes care of the "gender" required to get the correct folder index. Be careful by turning on - 1 . Otherwise, n = 500 will be in group 1 (instead of 0).

+6
source
  int n = 1777; int temp = ((n / 500) * 500) + 1 ; if(temp > n && n !=0){ temp-=500; } String result = "" + temp + " - "+ (temp + 499); System.out.println(result); 
+3
source

If you need a more general method, here it goes (based on the solution https://stackoverflow.com/users/276052/aioobe ):

 public static void main(String[] args) { for (int i = 1; i <= 3000; i++) { System.out.println(i + "\t" + getRange(i, 1000)); } } private static String getRange(int id, int step) { int x = ((id - 1) / step); return (x * step + 1) + "-" + ((x + 1) * step); } 
+2
source
 foreach ( folder in folders ) [from, to] = split( folder.name, "-" ) if ( id < from || id > to ) continue // found the right folder. 
+1
source

"1-500" → folder 0
"501-1000" → folder 1
"1001-1500" → folder 2
...

Take (1777 - 1) / 500 using integer division to get the folder number.

+1
source

Just iterate over your folders, divide the name into "-", analyze the two numbers and check if your number is in the range :)

0
source

You could just use a few cases where you would check to see if there are between the specified values, for example: 10 < x && x < 20

0
source

If it will always be five hundred, you can do this:

 for(int i = 0; i < Integer.MAX_VALUE; i++){ if(i*500+1 >= x && (i+1)*500 < x){ System.out.println("X is between " + (i*500 + 1) + " and " + ((i+1) * 500)); } } 

If the variable 'x' is an identifier.

If you need to use folder names, you will need to read the folder names, divide by "-", and then try to parse them into integers and use them instead of the for loop.

0
source

Here is your function:

  public String folderName(int num) { StringBuilder sb = new StringBuilder(); sb.append(1+(num-1)/500).append('-').append((1+((num-1)/500))*500); return sb.toString(); } 
0
source

Source: https://habr.com/ru/post/1332915/


All Articles