首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将所选元素移位一位并返回其更新的索引

将所选元素移位一位并返回其更新的索引
EN

Stack Overflow用户
提问于 2018-06-09 20:31:07
回答 2查看 126关注 0票数 2

背景:

我最近对我的一个旧项目进行了反编译,我丢失了它的源代码,并且正在重构我几年前写的所有这些糟糕的代码。

我有一个由UI显示的项目列表,这些项目可以上下移动,并且允许多选。我有一个int[] moveUp(int[] selectedIndices)方法,它更新模型并返回列表中移位元素的新索引(这样我就可以在模型更改后更新UI )。

selectedIndices来自JList#getSelectedIndices,它保证排序后的顺序不会重复。

旧解决方案:

代码语言:javascript
复制
public int[] moveUp(int[] selectedIndices) {
    Action[] array = concatenate(new Action[]{null}, actions.toArray(new Action[0]));
    for (int i = 0; i < selectedIndices.length; i++) {
        swap(array, selectedIndices[i] + 1, selectedIndices[i]);
        selectedIndices[i] -= 1;
    }
    actions = new ArrayList<>(this.actions.size());
    for (Action action : array) {
        if (action != null) {
            actions.add(action);
        }
    }
    return selectedIndices;
}

问题:

如果我的操作[a, b, c, d]selectedIndices[0, 1, 3],尽管结果将是正确的([a, b, d, c]),但返回的新索引是[-1, 0, 2],而它们应该是[0, 1, 2]

新解决方案:

代码语言:javascript
复制
public int[] moveUp(int[] selectedIndices) {
    List<Action> selectedActions = stream(selectedIndices).mapToObj(actions::get).collect(toList());

    actions.add(0, null);
    for (int selectedIndex : selectedIndices) {
        swap(actions, selectedIndex + 1, selectedIndex);
    }
    actions.remove(null);

    return selectedActions.stream().mapToInt(actions::indexOf).toArray();
}

问题:

它既不干净,也不高效。

问题:

如何以一种干净高效的方式实现它?

MCVE和测试:

代码语言:javascript
复制
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.shazam</groupId>
        <artifactId>shazamcrest</artifactId>
        <version>0.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

/////////////////////////////////////////////////////////////////////////

public interface Action {

}

/////////////////////////////////////////////////////////////////////////

import java.util.ArrayList;
import java.util.List;

import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;

public class Actions {

    private List<Action> actions = new ArrayList<>();

    public void add(Action action) {
        this.actions.add(action);
    }

    public int[] moveUp(int[] selectedIndices) {
        List<Action> selectedActions = stream(selectedIndices).mapToObj(actions::get).collect(toList());

        actions.add(0, null);
        for (int selectedIndex : selectedIndices) {
            swap(actions, selectedIndex + 1, selectedIndex);
        }
        actions.remove(null);

        return selectedActions.stream().mapToInt(actions::indexOf).toArray();
    }

    private static <T> void swap(List<T> list, int index, int index2) {
        T t = list.get(index);
        list.set(index, list.get(index2));
        list.set(index2, t);
    }

}

/////////////////////////////////////////////////////////////////////////

public class FakeAction implements Action {

    @SuppressWarnings("FieldCanBeLocal") // used by shazamcrest
    private final String name;

    private FakeAction(String name) {
        this.name = name;
    }

    static Actions actionsWithElements(int... elementsNames) {
        Actions actions = new Actions();
        for (int elementName : elementsNames) {
            actions.add(new FakeAction(String.valueOf(elementName)));
        }
        return actions;
    }

    static int[] indices(int... indices) {
        return indices;
    }

}

/////////////////////////////////////////////////////////////////////////

import org.junit.Test;

import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static FakeAction.actionsWithElements;
import static FakeAction.indices;

public class ActionsMoveUpTest {

    @Test
    public void movesUpSingleAction() {
        Actions actions = actionsWithElements(0, 1, 2, 3);

        actions.moveUp(indices(2));

        assertThat(actions, sameBeanAs(actionsWithElements(0, 2, 1, 3)));
    }

    @Test
    public void movesUpMultipleActions() {
        Actions actions = actionsWithElements(0, 1, 2, 3);

        actions.moveUp(indices(1, 3));

        assertThat(actions, sameBeanAs(actionsWithElements(1, 0, 3, 2)));
    }

    @Test
    public void doesNothingWhenArrayOfIndicesToMoveUpIsEmpty() {
        Actions actions = actionsWithElements(0, 1, 2, 3);

        actions.moveUp(indices());

        assertThat(actions, sameBeanAs(actionsWithElements(0, 1, 2, 3)));
    }

    @Test
    public void doesNotLoseSelectionWhenMovingUpTheTopAction() {
        Actions actions = actionsWithElements(0, 1, 2, 3);

        int[] newIndices = actions.moveUp(indices(0));

        assertThat(newIndices, sameBeanAs(indices(0)));
    }

    @Test
    public void movesUpOnlyThoseActionsWhichAreNotOnTheTopAlready() {
        Actions actions = actionsWithElements(0, 1, 2, 3, 4, 5, 6);

        actions.moveUp(indices(0, 1, 4, 6));

        assertThat(actions, sameBeanAs(actionsWithElements(0, 1, 2, 4, 3, 6, 5)));
    }

    @Test
    public void doesNotLoseSelectionOfTheTopActionsWhenMovingMultipleActions() {
        Actions actions = actionsWithElements(0, 1, 2, 3, 4, 5, 6);

        int[] newIndices = actions.moveUp(indices(0, 1, 4, 6));

        assertThat(newIndices, sameBeanAs(indices(0, 1, 3, 5)));
    }

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-12 19:34:41

多亏了Misha的观察,我带来了更简单的东西。

关键是,如果为selectedIndices[i] == i,则元素不会移动:

代码语言:javascript
复制
actions:               [a, b, c, d, e, f, g, h, i]
index:                  0  1  2  3  4  5  6  7  8
selectedIndices:       [0, 1, 2,       5, 6,    8]
elements to move left:                 f  g     i
output:                [a, b, c, d, f, g, e, i, h]

在这里,可以很容易地使用O(m)时间复杂度(其中m = selectedIndices.length)来实现它,如下所示:

代码语言:javascript
复制
public int[] moveUp(int[] selectedIndices) {
    int[] newIndices = Arrays.copyOf(selectedIndices, selectedIndices.length);

    for (int i = 0; i < selectedIndices.length; i++) {
        if (selectedIndices[i] != i) {
            swap(actions, selectedIndices[i], selectedIndices[i] - 1);
            newIndices[i]--;
        }
    }

    return newIndices;
}

或者使用一些Java streams:

代码语言:javascript
复制
public int[] moveUp(int[] selectedIndices) {
    int[] newIndices = Arrays.copyOf(selectedIndices, selectedIndices.length);

    IntStream.range(0, selectedIndices.length)
            .filter(i -> selectedIndices[i] != i)
            .forEach(i -> {
                swap(actions, selectedIndices[i], selectedIndices[i] - 1);
                newIndices[i]--;
            });

    return newIndices;
}
票数 0
EN

Stack Overflow用户

发布于 2018-06-10 03:21:25

由于假设对selectedIndices进行了排序,因此可以通过将索引与其在selectedIndices中的位置进行比较,轻松地确定要向上移动哪些元素。如果索引高于其位置,则移动相关联的元素。

代码语言:javascript
复制
public int[] moveUp(int[] selecteIndices) {
    // this assumes that selectedIndices is sorted
    int[] newSelection = IntStream.range(0, selectedIndices.length)
        .map(x -> selectedIndices[x] > x ? selectedIndices[x] - 1 : selectedIndices[x])
        .toArray();

    IntStream.range(0, selectedIndices.length)
        .filter(x -> selectedIndices[x] > x)
        .map(x -> selectedIndices[x])
        .forEachOrdered(i -> swap(actions, i - 1, i));

    return newSelection;
}

为了最大限度地减少思考"index of index“所耗费的精力,您可以单独计算要移动的第一个元素。对我来说,这是比较清楚的,但这是主观的:

代码语言:javascript
复制
public int[] moveUp(int[] selecteIndices) {
    // this assumes that selecteIndices are sorted

    // index of the first element to move up or actions.size() if nothing needs to move
    int firstToMove = IntStream.range(0, selectedIndices.length)
        .filter(x -> selectedIndices[x] > x)
        .map(x -> selectedIndices[x])
        .findFirst()
        .orElse(actions.size());  

    int[] newSelection = Arrays.stream(selectedIndices)
        .map(i -> i >= firstToMove ? i - 1 : i)
        .toArray();

    Arrays.stream(selectedIndices)
        .filter(i -> i >= firstToMove)
        .forEachOrdered(i -> swap(actions, i - 1, i));

    return newSelection;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50774335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档