Posted By

smundall on 02/07/16


Tagged


Versions (?)

Array Split


 / Published in: Java
 

Simple java function for splitting arrays. We find variables matching X starting from 0. Then, we find 'odd' matches (variables not equal to X) . Next we make sure that the number of evens and odds can be made equal and return the size.

  1. //split array function . test 2
  2. public static int splitArray(int X, int[] A){
  3.  
  4. //declare our integers.
  5. int even = 0, odd = 0, i = 0;
  6.  
  7. //two while loops.
  8. while(i < A.length && A[i] == X) {
  9. ++even;
  10. ++i;
  11. }
  12. while(i < A.length && A[i] != X) {
  13. ++odd;
  14. ++i;
  15. }
  16.  
  17. if(odd >= even)
  18. return even * 2;
  19. else
  20. return 0;
  21.  
  22.  
  23. }

Report this snippet  

You need to login to post a comment.