Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 删除arraylist中的每三个元素_Java_Arrays_Arraylist - Fatal编程技术网

Java 删除arraylist中的每三个元素

Java 删除arraylist中的每三个元素,java,arrays,arraylist,Java,Arrays,Arraylist,我试图循环遍历一个arraylist,并每隔3个索引逐渐删除一个元素。一旦它到达arraylist的末尾,我想将索引重置回开头,然后再次循环遍历arraylist,再次每隔3个索引移除一个元素,直到arraylist中只剩下一个元素 ListoWords是一个长度为3的数组,之前已填充该数组 int listIndex = 0; do { // just to display contents of arraylist System.out.pri

我试图循环遍历一个arraylist,并每隔3个索引逐渐删除一个元素。一旦它到达arraylist的末尾,我想将索引重置回开头,然后再次循环遍历arraylist,再次每隔3个索引移除一个元素,直到arraylist中只剩下一个元素

ListoWords是一个长度为3的数组,之前已填充该数组

int listIndex = 0;

do
{           
    // just to display contents of arraylist    
    System.out.println(listOfPlayers);

    for(int wordIndex = 0; wordIndex < listOfWords.length; wordIndex++
    {
        System.out.print("Player");
        System.out.print(listOfPlayers.get(wordIndex));
        System.out.println("");
        listIndex = wordIndex;                                  
    }           

    listOfPlayers.remove(listOfPlayers.get(listIndex)); 
}
while(listOfPlayers.size() > 1);

然后在检查第三个元素(不再存在)时抛出“索引越界错误”异常。一旦它到达最后一个元素,我希望它环绕到第一个元素并继续通过数组。我还希望它从它停止的地方开始,而不是在它从arraylist中删除一个元素后从开始

您可以使用一个计数器
intk
,它将不断递增3,比如
k+=3
。但是,在使用该计数器作为索引踢出任何数组元素之前,请检查是否已经超出了范围,如果超出了范围,请从计数器
k
中减去该数组的长度。还要确保,一旦发现数组只剩下一个元素,就将
从循环中断开

int k = -1;
int sz = list.length;
while (sz > 1)
{
    k += 3;
    if (k >= sz)
    {
        k -= sz;
    }
    list.remove(k);
    sz --;
}
这个例子表明,您已经知道要逐出一个元素的频率,即
sz-1


顺便说一下,
sz%3
只有三个可能的结果,0、1、2。只需一张纸和一杯咖啡,你就可以发现幸存的元素将依赖于它,而无需运行任何循环

您可以将每三个元素移动到一个临时列表中,然后在完成每个循环时使用删除项目…直到主列表为空…

让我们回顾一下,并从算法上查看问题

  • 从第一项开始,开始计数
  • 转到下一项并增加您的计数。如果没有下一项,请转到开头
  • 如果计数为“3”,则删除该项目并重置计数。(或模。)
  • 如果列表中还有一项,请停止
让我们编写伪代码:

function (takes a list)
  remember what index in that list we're at
  remember whether this is the item we want to delete.

  loop until the list is size 1
    increment the item we're looking at.
    increment the delete count we're on

    should we delete?
      if so, delete!
      reset delete count

    are we at the end of the list?
      if so, reset our index
从这个角度来看,很容易立即将其转换为代码:

public void doIt(List<String> arrayList) {
  int index = 0;
  int count = 0;

  while(arrayList.size() != 1) {
    index = index + 1;
    count = count + 1; //increment count

    String word = arrayList.get(index);//get next item, and do stuff with it

    if (count == 3) {
      //note that the [Java API][1] allows you to remove by index
      arrayList.remove(index - 1);//otherwise you'll get an off-by-one error
      count = 0; //reset count
    }

    if (index = arrayList.size()) {
      index = 0; //reset index
    }
  } 
}
public void doIt(列表arrayList){
int指数=0;
整数计数=0;
while(arrayList.size()!=1){
指数=指数+1;
count=count+1;//递增计数
String word=arrayList.get(index);//获取下一项,并处理它
如果(计数=3){
//请注意,[JavaAPI][1]允许您按索引删除
remove(索引-1);//否则您将得到一个错误
计数=0;//重置计数
}
if(index=arrayList.size()){
index=0;//重置索引
}
} 
}

所以,你可以看到诀窍是一步一步地思考你在做什么,然后慢慢地将其转化为代码。我认为您可能已经在修复最初的尝试:永远不要害怕抛出代码。

您可以尝试使用迭代器。时间不早了,所以不要期望太多

public removeThirdIndex( listOfWords ) {
    Iterator iterator = listOfWords.iterator
    while( iterator.hasNext() ){
        iterator.next();
        iterator.next();
        iterator.next();
        iterator.remove();
    }
}


@Test
public void tester(){
    // JUnit test > main
    List listOfWords = ... // Add a collection data structure with "words"

    while( listOfWords.size() < 3 ) {
        removeThirdIndex( listOfWords ); // collections are mutable ;(
    }

    assertTrue( listOfWords.size() < 3 );
}
public removeThirdIndex(listOfWords){
迭代器迭代器=ListofWord.Iterator
while(iterator.hasNext()){
iterator.next();
iterator.next();
iterator.next();
iterator.remove();
}
}
@试验
公共空间测试器(){
//JUnit测试>主
List listOfWords=…//添加带有“words”的集合数据结构
while(listOfWords.size()<3){
removeThirdIndex(listOfWords);//集合是可变的(
}
assertTrue(listOfWords.size()<3);
}

我只需将removed设置为null,然后跳过内部循环中的null

boolean continue;
do {
   continue = false;
   for( int i = 2; i < list.length; i += 3 ){
      while( list.item(i++) == null &&  i < list.length );
      Sout("Player " + list.item(--i) );
      continue = true;
   }
} while (continue);
boolean继续;
做{
continue=false;
对于(int i=2;i
我会选择这个而不是不合理的数组洗牌


(i++和--i可能看起来很难看,可能会被很好地重写。)

也许我刚刚错过了机会,但这就是你想要的吗

import java.util.ArrayList;
import java.util.Random;

public class Test {

    public static void main(String[] args) {

        ArrayList<Integer> numbers = new ArrayList<Integer>();
        Random r = new Random();

        //Populate array with ten random elements
        for(int i = 0 ; i < 4; i++){
            numbers.add(r.nextInt());
        }

        while(numbers.size() > 1){
            for(int i = 0; i < numbers.size();i++){
                if(i%3 == 0){//Every 3rd element should be true
                    numbers.remove(i);
                }
            }
        }
    }
}
import java.util.ArrayList;
导入java.util.Random;
公开课考试{
公共静态void main(字符串[]args){
ArrayList编号=新的ArrayList();
随机r=新随机();
//用十个随机元素填充数组
对于(int i=0;i<4;i++){
add(r.nextInt());
}
while(numbers.size()>1){
对于(int i=0;i
尝试以下代码。它会不断删除
列表中的每个
n
元素,直到只剩下一个元素

    List<Integer> array = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    int nth = 3;
    int step = nth - 1;
    int benchmark = 0;

    while (array.size() > 1) {
        benchmark += step;
        benchmark = benchmark > array.size() - 1 ? benchmark % array.size() : benchmark;
        System.out.println(benchmark);
        array.remove(array.get(benchmark));
        System.out.println(array);
    }
List array=newarraylist(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
int n=3;
int阶跃=n次-1;
int基准=0;
while(array.size()>1){
基准+=步进;
benchmark=benchmark>array.size()-1?基准%array.size():基准;
System.out.println(基准);
array.remove(array.get(benchmark));
System.out.println(数组);
}

您是只需要最后一个元素,还是还需要所有中间步骤和删除的元素?我只希望循环后剩下一个元素。我想展示删除播放器的中间步骤。可能是关于被回音的播放器的排列?我真的想确定阵列中的最后一个元素然后在数组列表的开始处,一旦它到达最后一个元素,就从数组列表的开始处开始。你能澄清一下吗?(对不起,咖啡因今天不管用:P)感谢所有的建议。通过阅读您的一些评论,我找到了一个解决方案。我是java API新手,所以我不知道您可以使用的一些类和方法。再次感谢大家!
    List<Integer> array = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    int nth = 3;
    int step = nth - 1;
    int benchmark = 0;

    while (array.size() > 1) {
        benchmark += step;
        benchmark = benchmark > array.size() - 1 ? benchmark % array.size() : benchmark;
        System.out.println(benchmark);
        array.remove(array.get(benchmark));
        System.out.println(array);
    }