Find middle point segment from given segment lengths | Function that returns the segment for the middle point ; the middle point ; stores the segment index ; increment sum by length of the segment ; if the middle is in between two segments ; if sum is greater than middle point ; Driver code
< ? php function findSegment ( $ n , $ m , $ segment_length ) { $ meet_point = ( 1.0 * $ n ) / 2.0 ; $ sum = 0 ; $ segment_number = 0 ; for ( $ i = 0 ; $ i < $ m ; $ i ++ ) { $ sum += $ segment_length [ $ i ] ; if ( ( double ) $ sum == $ meet_point ) { $ segment_number = -1 ; break ; } if ( $ sum > $ meet_point ) { $ segment_number = $ i + 1 ; break ; } } return $ segment_number ; } $ n = 13 ; $ m = 3 ; $ segment_length = array ( 3 , 2 , 8 ) ; $ ans = findSegment ( $ n , $ m , $ segment_length ) ; echo ( $ ans ) ; ? >