2015-02-11 40 views
0

對於我的項目,我們必須使用Java來操縱某些LISP語句。其中一項任務是:將除第n個元素之外的所有元素添加到另一個ArrayList中

'((4A)(1B)(2C)(2A)(1D)(4E)2) 

最後的數字是「n」。任務是從表達式中刪除每個第n個元素。例如,上面的表達式將計算爲:

′((4A)(2C)(1D)2) 

我現在的做法是將不在第n個索引處的所有元素添加到另一個數組。我的錯誤是它將每個元素添加到新陣列中,使兩個元素相同。

我的代碼:

String input4=inData.nextLine(); 
    length=input4.length(); 
    String nString=input4.substring(length-2,length-1); 
    int n = Integer.parseInt(nString); 
    count=n; 
    String delete1=input4.replace("'(",""); 
    String delete2=delete1.replace("(",""); 
    final1=delete2.replace(")",""); 
    length=final1.length(); 


    for (int i=1;i<length;i++) 
    { 
     part=final1.substring(i-1,i); 
     list.add(part); 

    }  

    for(int i=0;i<=list.size();i++) 
    { 

     if(!(i%n==0)) 
     { 
      delete.add(list.get(i-1)); 
      delete.add(list.get(i)); 

     } 
     else 
     { 

     } 

    } 
    System.out.print("\n"+list); 
+0

也許玩弄你的incrementors自(NUM字元)在一次跳躍前進二是2組。你也必須加倍你的模數來補償。 – 2015-02-11 01:38:28

+0

我的問題是每個字母都帶有一個數字。所以如果第n個元素是2,那麼我意味着我必須忽略2個索引。如果第n個元素是3,我不得不忽略3個索引。我試圖找出正確的邏輯,但我有麻煩@AlexPopov – OoOoOoOoOoO 2015-02-11 02:08:30

回答

0

一個解決這個問題(雖然不能直接解決您的解決方案您的問題)是特別是如果這一點,使用正則表達式,因爲這些工作很好地爲這樣的事情代碼不需要適應不同的輸入字符串。我發現如果這樣的事情是可能的,它比試圖直接操縱字符串更容易,儘管這些模式(和一般的正則表達式)很慢。

// Same as you had before 
String input4="'((4A)(1B)(2C)(2A)(1D)(4E)2)"; 
int length=input4.length(); 
String nString=input4.substring(length-2,length-1); 
int n = Integer.parseInt(nString); 
int count=n; 

// Match (..) 
// This could be adapted to catch () with anything in it other than another 
// set of parentheses. 
Matcher m = Pattern.compile("\\(.{2}\\)").matcher(input4); 

// Initialize with the start of the resulting string. 
StringBuilder sb = new StringBuilder("'("); 
int i = 0; 
while (m.find()) 
{ 
    // If we are not at an index to skip, then append this group 
    if (++i % count != 0) 
    { 
    sb.append(m.group()); 
    } 
} 

// Add the end, which is the count and the ending parentheses. 
sb.append(count).append(")"); 

System.out.println(sb.toString()); 

一些示例輸入/輸出:

'((4A)(1B)(2C)(2A)(1D)(4E)2) 
'((4A)(2C)(1D)2) 

'((4A)(1B)(2C)(2A)(1D)(4E)3) 
'((4A)(1B)(2A)(1D)3) 
+0

你有一個算法,因爲我不知道/不能使用高級編碼,但我也許可以將它翻譯成更基本的java的東西 – OoOoOoOoOoO 2015-02-11 02:29:53

+0

您在此練習中是否需要使用列表?我有一些建議,但這取決於您是否需要使用列表。 – Dish 2015-02-11 15:41:04

相關問題