Download code

Jump to: navigation, search

Back to Subarray_with_Sum_Divisible_by_Length_of_Array_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

SubarraySumDivisible.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Subarray_with_Sum_Divisible_by_Length_of_Array_(Java)?oldid=12497
14 */
15 
16 import java.util.Arrays;
17 public class SubarraySumDivisible
18 {
19     public static void computeSubarray(int[] a) {
20         int[] b = new int[a.length + 1];
21 	b[0] = 0;
22 	for (int i = 0; i < a.length; i++)
23 	    b[i+1] = (b[i] + a[i]) % a.length;
24         int[] c = new int[a.length];
25 	Arrays.fill(c, -1);
26 	for (int i = 0; i < b.length; i++) {
27 	    int pos = b[i];
28 	    if (c[pos] < 0)
29 	        c[pos] = i;
30 	    else {
31 	        int begin = c[pos], end = i;
32 		int sum = 0;
33 		for (int j = begin; j < end; j++)
34 		    sum += a[j];
35 		    
36 		System.out.println("found solution: subarray from index " + begin + " (inclusive) to " + end + " (exclusive)");
37 		System.out.println("has sum = " + sum + ", which is divisible by length of array " + a.length);
38 
39 		return;
40 	    }
41 	}
42 	// you are not supposed to get here
43 	System.err.println("You broke math.");
44 	System.exit(1);
45     }
46 
47 
48     public static void main(String[] args) {
49         // TODO: parse this from the user or generate randomly
50         int[] a = {63, 92, 51, 92, 39, 15, 43, 89, 36, 69, 40, 16, 23, 2, 29, 91, 57, 43, 55, 22};
51         computeSubarray(a);
52     }
53 }


hijacker
hijacker
hijacker
hijacker