2015-02-11 70 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

相关问题