欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二维坐标,x从小到大排列,y从大到小排列

程序员文章站 2024-02-20 19:19:04
...

目前能想到的最完美的方案,还没得到扩展,仅仅可用于二维数组

重点思路:将xy捆绑到一块排序,因为y是倒叙需要计算下对应正序时的值,也就是拿y组最大值减去当前值,得到x升序y升序组合数组xy,需要考虑到y组位数问题

import java.util.Arrays;


public class Test {
	public static void main(String[] args) {
		Test test = new Test();
		int[][] param = new int[][] { { 3, 20 }, { 1, 9 }, { 5, 8 }, { 2, 1 }, { 3, 6 }, { 2, 1 } };
		int[][] result = test.sortArrayTwoDimension(param);
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i][0] + "  " + result[i][1]);
		}
	}


	public int[][] sortArrayTwoDimension(int[][] param) {
		int[] x = new int[param.length];
		int[] y = new int[param.length];
		for (int i = 0; i < param.length; i++) {
			int[] temp = param[i];
			x[i] = temp[0];
			y[i] = temp[1];
		}
		
		int maxy = 0;
		for (int i = 0; i < y.length; i++) {
			if (y[i] > maxy) {
				maxy = y[i];
			}
		}
		// 将y数组用最大值-原有值获取倒叙值数组
		int[] sortp = new int[param.length];
		for (int i = 0; i < y.length; i++) {
			sortp[i] = maxy - y[i];
		}
		
		// y数组最大长度
		int ylmax = String.valueOf(maxy).length();
		long[] xy = new long[param.length];
		for (int i = 0;i<x.length;i++) {
			xy[i] = Long.valueOf(String.valueOf(x[i]) + Test.addZeroForNum(String.valueOf(sortp[i]), ylmax));
		}
		
		Arrays.sort(xy);


		int index = 0;
		int[][] result = new int[x.length][2];
		for (int j = 0; j < xy.length; j++) {
			for (int i = 0; i < x.length; i++) {
				if (xy[j] == Long.valueOf(String.valueOf(x[i]) + Test.addZeroForNum(String.valueOf(sortp[i]), ylmax))) {
					result[index] = new int[]{x[i],y[i]};
					index++;
					break;
				}
			}
		}
		return result;
	}
	
	public static String addZeroForNum(String str, int strLength) {
		int strLen = str.length();
		if (strLen < strLength) {
			while (strLen < strLength) {
				StringBuffer sb = new StringBuffer();
				sb.append("0").append(str);
				str = sb.toString();
				strLen = str.length();
			}
		}
		return str;
	}
}