2017-09-14 77 views
0

我有一個數組,這是我從網絡服務中獲得所以它總是不同的,但是看起來像這樣動態數組:的Groovy/Grails的 - 修改基於內容

def originalArray = [ 
     [startDate:7 October 2017, endDate:14 October 2017, type:A], 
     [startDate:7 October 2017, endDate:9 October 2017, type:A], 
     [startDate:9 October 2017, endDate:14 October 2017, type:A], 

     [startDate:7 October 2017, endDate:14 October 2017, type:B], 

     [startDate:7 October 2017, endDate:9 October 2017, type:C], 
     [startDate:9 October 2017, endDate:14 October 2017, type:C]] 

不介意約會「格式」使用,我寫這樣就簡化了這個問題。我想要做的是過濾類型類型,但也有發生的周全周,週中和週末都發生在同一周,並具有相同的類型它應該刪除週中和週末和給整週一個名爲的可拆分項設置爲true。所以,上面的例子最終會看起來像這樣:

def moddedArray = [ 
    [startDate:7 October 2017, endDate:14 October 2017, type:A, splittable:true], 

    [startDate:7 October 2017, endDate:14 October 2017, type:B, splittable:false], 

    [startDate:7 October 2017, endDate:9 October 2017, type:C, splittable:false], 
    [startDate:9 October 2017, endDate:14 October 2017, type:C, splittable:false]] 

這是我已經試過:

function startingFunction() { 
    def weeks = getWeeks() // gets the array 
    def fullWeeks = [] 
    weeks.each { 
     def days = it.endDate - it.startDate 
     if(days == 7) { 
      fullWeeks.add(it) 
     } 
    } 

    if(fullWeeks) { 
     return applySplittable(fullWeeks,weeks) 
    } else { 
     return weeks 
    } 
} 

function applySplittable(fullweeks,weeks) { 
    def prelimWeeks = [] 
    def weeksSinglesRemoved = [] 

    fullweeks.eachWithIndex { f, i -> 
     weeks.eachWithIndex { w, j -> 
      if(!(f.type == w.type && (f.startDate == w.startDate || f.endDate == w.endDate) && (!(f.startDate == w.startDate && f.endDate == w.endDate)))) { 
       prelimWeeks.add(w) 
      } 
     } 
    } 

    prelimWeeks.each { // when it gets here all the weeks will have been added as many times as there fullweeks, unless it's a midweek or weekend that have a fullweek 
     if(Collections.frequency(prelimWeeks,it) >= fullweeks.size()) { 
      weeksSinglesRemoved.add(it) 
     } 
    } 

    return weeksSinglesRemoved.unique() 
} 

因此,大家可以看到,我已經試過是一個爛攤子,可能是不即使這樣很有效,但如果有一整週的時間,它可以消除中周和週末,但它不適用可拆分屬性。如果任何人都可以爲我提供一種儘可能簡單地完成這項工作的方法。讓我知道是否需要提供更多信息。

回答

0

我更新了applySplittable功能,現在看起來是這樣的:

def applySplittable(fullweeks, weeks) { 
    def weeksSplit = [] 
    weeks.eachWithIndex { w, i -> 
     def days = w.endDate - w.startDate 
     if(days != 7) { 
      def hasFull = fullweeks.findAll { w.type == it.type && (w.startDate == it.startDate || w.endDate == it.endDate) } 
      if(!hasFull) { 
       w.splittable = false 
       weeksSplit.add(w) 
      } 
     } else { 
      def hasSplit = weeks.findAll { w.type == it.type && (w.startDate == it.startDate || w.endDate == it.endDate) && !(w.startDate == it.startDate && w.endDate == it.endDate) } 
      if(hasSplit) { 
       w.splittable = true 
      } else { 
       w.splittable = false 
      } 
      weeksSplit.add(w) 
     } 
    } 
    return weeksSplit 
} 

它仍然是一個爛攤子,它可能仍然是相當低效的,但它似乎是工作。