Search code examples
algorithmmathautoit

how to divide an interval into equal parts


Hi how to divide an interval into equal parts example :

[1-100] divide by 5 part -->

1- [1-20]
2- [21-40]
3- [41-60]
4- [61-80]
5- [81-100]

or

[1-102] divide by 5 part -->

1- [1-20]
2- [21-40]
3- [41-60]
4- [61-80]
5- [81-100]
6- [100-102]*

i try a code but sometimes work and in other nums not work as it must this is what i make (i know i am week in math :P , i code it 2 week ago and now i have no idea how i make it :D )


Func vall($a , $b)
    Local $inval = ''
    $all  = $a
    $c    = $b ; - 1

    $evv  = Int($all/$c)
    $rrt  = Int($all/$evv)

    $trtr = $evv
    $ee   = 1
    $fg   = 0

    If Mod($a,$evv) == 0 Then
        For $ll = 1 To $rrt ; $all
            If $ll = $rrt Then
                $inval = $inval & $ee & ':-:' & $trtr
            Else
                $inval = $inval & $ee & ':-:' & $trtr &','
            EndIf

            $ee   = $ee   + $evv
            $trtr = $trtr + $evv
        Next
    Else
        For $ll = 1 To $rrt ; $all
            $inval = $inval & $ee & ':-:' & $trtr &','
            $ee    = $ee   + $evv
            $trtr  = $trtr + $evv
        Next
        $uu    = $trtr - $evv + 1
        $inval = $inval & $uu & ':-:' & $all
    EndIf

    Return $inval
EndFunc

i use autoit , but i need the algorithm to use it in any lang .

thank you .


Solution

  • Here is a python implementation which is quite easy to understand.

    def divide(number, parts):
        '''number is the last number of the range and parts is no. of intervals you
            want to make'''
        chunksize = number//parts             # size of each interval
        chunkstart = 1                        # start of interval
        chunkend = chunkstart + chunksize -1  # end of that interval
        while chunkstart < number:            # don't go beyond the range
            if chunkend > number:             # interval end is beyond the range
                print chunkstart, number
                break                         # we are beyond the range now
            print chunkstart, chunkend
            chunkstart += chunksize           # take me to beginning of next interval
            chunkend += chunksize             # also tell me where to end that
    
    Sample Input and Ouputs
    
    divide(100, 5)
    1 20
    21 40
    41 60
    61 80
    81 100
    
    divide(102, 5)
    1 20
    21 40
    41 60
    61 80
    81 100
    101 102