Equal Stacks

Sort by

recency

|

95 Discussions

|

  • + 0 comments

    JavaScript Soution:

    function equalStacks(h1, h2, h3) {
      let h1Total = h1.reduce((a, c) => a + c);
      let h2Total = h2.reduce((a, c) => a + c);
      let h3Total = h3.reduce((a, c) => a + c);
    
      function checkEquality(one, two, three) {
        if (one === two && two === three) {
          return true;
        }
        return false;
      }
    
      while (!checkEquality(h1Total, h2Total, h3Total)) {
        let numberToSubtract = 0;
        if (h1Total >= h2Total && h1Total >= h3Total) {
          numberToSubtract = h1.shift();
          h1Total -= numberToSubtract;
        } else if (h2Total >= h1Total && h2Total >= h3Total) {
          numberToSubtract = h2.shift();
          h2Total -= numberToSubtract;
        } else if (h3Total >= h1Total && h3Total >= h1Total) {
          numberToSubtract = h3.shift();
          h3Total -= numberToSubtract;
        }
      }
    
      return h1Total;
    }
    
  • + 0 comments

    It's readable

    def equalStacks(h1, h2, h3): h1.reverse() h2.reverse() h3.reverse()

    stacks = [h1, h2, h3]
    
    heights = [sum(stack) for stack in stacks]
    while True:
        if len(set(heights)) == 1:
            return heights[0]
        else:
            idx = heights.index(max(heights))
            heights[idx] -= stacks[idx].pop()   
    
  • + 0 comments

    def equalStacks(h1, h2, h3):

    sums = [sum(h1), sum(h2), sum(h3)]
    stacks = [h1, h2, h3]
    
    t = min(sums)
    
    while sums[0] != sums[1] or sums[1] != sums[2] or sums[0] != sums[2]: 
    
        for i in range(len(sums)):
            while sums[i] > t:
                sums[i] -= stacks[i].pop(0)   
    
        t = min(sums)
    
    return t
    
  • + 0 comments
    from itertools import accumulate as a
    
    def equalStacks(h1, h2, h3):
        return max(set(a(h1[::-1])) & set(a(h2[::-1])) & set(a(h3[::-1])) | {0})
    
  • + 0 comments

    Java 8 - Based on all way subtracting a cylinder from the highest stack. This naturally protects from indexing exceptions and negative values since 0,0,0 is always true.

        public static int equalStacks(List<Integer> h1, List<Integer> h2, List<Integer> h3) {
            int s1h = h1.stream().collect(Collectors.summingInt(Integer::intValue));
            int s2h = h2.stream().collect(Collectors.summingInt(Integer::intValue));
            int s3h = h3.stream().collect(Collectors.summingInt(Integer::intValue));
            
            int s1i=0,s2i=0,s3i=0;
            
            while(s1h != s2h || s1h != s3h) {
                if (s1h>=s2h && s1h>=s3h )
                    s1h -= h1.get(s1i++);
                else if (s2h>=s1h && s2h>=s3h )
                    s2h -= h2.get(s2i++);
                else if (s3h>=s1h && s3h>=s2h )
                    s3h -= h3.get(s3i++);
            }
            return s1h;
        }