简体   繁体   English

根据基于两个数组的值对数组进行排序

[英]Sorting an array by its values based on two arrays

I currently have 2 arrays, power and energy:我目前有 2 个阵列,功率和能量:

int[] power = [20, 10, 50, 10, 30, 5];
powerIndex     0   1   2   3   4   5
int[] energy = [20, 5, 15, 3, 10, 30];
energyIndex    0   1   2   3   4   5

I would like get an array with the indices of the power array sorted (lowest to highest), and in case the power number is the same, the power that uses less energy should get the first spot.我想得到一个排序的功率数组索引的数组(从最低到最高),如果功率数相同,则使用较少能量的功率应该获得第一名。 So basically my desired output would be:所以基本上我想要的输出是:

int[] result = [5, 3, 1, 0, 4, 2]

This is my code so far:到目前为止,这是我的代码:

        int[] result = new int[power.length];
        int answerIndex = 0;
        int tempSmallest = Integer.MAX_VALUE;
        int lastNumberSaved = 0;
        int posWithSmallerPower = 0;


        while (answerIndex < power.length) {

            for (int i = 0; i < power.length; i++) {
                int current = power[i];
                if (tempSmallest > current && current > lastNumberSaved) {
                    tempSmallest = current;
                    posWithSmallerPower = i;
                }

                if (tempSmallest >= current && current > lastNumberSaved) {
                    if (current != lastNumberSaved && energy[posWithSmallerPower] > energy[i]) {
                        tempSmallest = current;
                        posWithSmallerPower = i;
                    }
                }
            }
            answer[answerIndex] = posWithSmallerPower;
            answerIndex++;
            lastNumberSaved = tempSmallest;
            tempSmallest = Integer.MAX_VALUE;
        }

        return answer;

What i'm getting: [5, 3, 0, 4, 2, 2].我得到了什么:[5, 3, 0, 4, 2, 2]。 And again, what I'm supposed to get: [5, 3, 1, 0, 4, 2]再一次,我应该得到什么:[5, 3, 1, 0, 4, 2]

I'm having trouble dealing with the powers that have the same number.我在处理具有相同数字的权力时遇到了麻烦。 I do compare them in the second array by their energy and I actually get the power in the index 3 first, but then the code completely forgots about the second power that also had the same number (10).我确实通过它们的能量在第二个数组中比较了它们,实际上我首先获得了索引 3 中的幂,但随后代码完全忘记了同样具有相同数字 (10) 的第二次幂。

How do I achieve this?我如何实现这一目标? Thank you!谢谢!

This seems like a good use case for a temporary data structure that implements the Comparable interface.对于实现Comparable接口的临时数据结构来说,这似乎是一个很好的用例。 The javadoc for Comparable explains how this works pretty well but this is an example: Comparablejavadoc解释了它是如何工作得很好,但这是一个例子:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public final class Main {

    private static class Entry implements Comparable<Entry> {
        private final int power;
        private final int energy;
        private final int index;

        public Entry(int power, int energy, int index) {
            this.power = power;
            this.energy = energy;
            this.index = index;
        }

        @Override
        public int compareTo(Entry o) {
            if (this.power != o.power) {
                return this.power - o.power;
            }
            return this.energy - o.energy;
        }
    }

    public static void main(String[] args) {
        int[] power = {20, 10, 50, 10, 30, 5};
        int[] energy = {20, 5, 15, 3, 10, 30};

        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < power.length; i++) {
            entries.add(new Entry(power[i], energy[i], i));
        }

        Collections.sort(entries);
        List<Integer> result = entries.stream()
                .map(entry -> entry.index)
                .collect(Collectors.toList());
        System.out.println(result);
    }
}

Which outputs:哪些输出:

[5, 3, 1, 0, 4, 2]

Used an inline Comparator<T> in list.sort() to compare the two powerEnergyIndex.list.sort()使用内联Comparator<T>来比较两个 powerEnergyIndex。

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

public class MainApplication {
    public static void main(String[] args) {
        int[] power = {20, 10, 50, 10, 30, 5};

        int[] energy = {20, 5, 15, 3, 10, 30};

        List<PowerEnergyIndex> powerEnergyIndices = new ArrayList<>();

        for(int i=0;i<power.length;i++) {
            powerEnergyIndices.add(new PowerEnergyIndex(power[i],energy[i],i));
        }

        powerEnergyIndices.sort((p1, p2)-> {
            if(p1.power!=p2.power) {
                return p1.power-p2.power;
            }
            return p1.energy-p2.energy;
        });

        int[] result = powerEnergyIndices.stream()
                                            .map(powerEnergyIndex -> powerEnergyIndex.index)
                                            .mapToInt(x->x)
                                            .toArray();

        for(int i:result) {
            System.out.print(i + " ");
        }



    }

    static class PowerEnergyIndex {
        private int power;
        private int energy;
        private int index;

        public PowerEnergyIndex(final int power, final int energy, final int index) {
            this.power = power;
            this.energy = energy;
            this.index = index;
        }
    }
}

which outputs 5 3 1 0 4 2输出5 3 1 0 4 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM