【问题标题】:Adding everything but the nth element to another arraylist将除第 n 个元素之外的所有内容添加到另一个数组列表
【发布时间】:2015-02-11 01:02:27
【问题描述】:

对于我的项目,我们必须使用 Java 来处理某些 LISP 措辞。给了其中一项任务:

'((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);

【问题讨论】:

  • 也许可以和你的增量器一起玩,一次跳两个,因为 (num-char) 是一个 2 组。您还必须将模数加倍以进行补偿。
  • 我的问题是每个字母都有一个数字。因此,如果第 n 个元素是 2,我的意思是我必须忽略 2 个索引。如果第 n 个元素是 3,我将不得不忽略 3 个索引。我试图找出正确的逻辑,但我遇到了麻烦@AlexPopov

标签: java arraylist lisp logic


【解决方案1】:

这个问题的一个解决方案(虽然不是直接在你的解决方案中解决你的问题)是使用正则表达式模式,因为这些模式非常适合这种事情,特别是如果这段代码不需要适应不同的输入字符串.我发现如果这样的事情是可能的,它比尝试直接操作字符串更容易,尽管这些模式(和一般的正则表达式)很慢。

// 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)

【讨论】:

  • 你有一个算法,因为我还不知道/不能使用高级编码,但我可以将它翻译成更基本的 java
  • 在这个练习中你需要使用列表吗?我有一些建议,但这取决于您是否需要使用列表。
猜你喜欢
  • 2018-07-11
  • 1970-01-01
  • 2017-07-24
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多