找出多组分辨率中最接近目标值的一组

java 复制代码
package com.test;

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

public class Test {
	
	public static void main(String[] args) {
		
		// 目标分辨率
		int targetWidth = 640;
		int targetHeight = 480;
		
		//String str = "3264x2448,3264x1836,2560x1920,3264x1472,3200x1440,2304x1728,2560x1440,1920x1920,2048x1536,2304x1296,1920x1440,2400x1080,1920x1080";
		String str = "2560x1920,3264x1472,3200x1440,2304x1728,2560x1440,1920x1920,2048x1536,2304x1296,1920x1440,2400x1080,2304x1040,1920x1080,1632x1224,1600x1200,1440x1080,1280x960,1088x1088,1600x720,1280x720,960x540,800x600,800x480,720x480,352x288,320x240,176x144";
		
		String[] ary1 = str.split(",");
		List<String> list = new ArrayList<String>();
		
		for (int i = 0; i < ary1.length; i++) {
			String sss = ary1[i];
			list.add(sss);
		}
		
		//获取和目标值最接近的一组分辨率
		String s = getBestResolution(list,targetWidth,targetHeight);
		
		// 输出最接近目标分辨率的数据
		System.out.println("最接近目标分辨率的数据为:"+s);
		
	}

	/**
	 * 	获取和目标值最接近的一组分辨率
	 * @param list 分辨率集合,例如:[960x540,800x600,800x480,720x480,352x288,320x240,176x144]
	 * @param targetWidth 目标分辨率宽,例如:640
	 * @param targetHeight 目标分辨率高,例如:480
	 * @return 和目标值最接近的一组分辨率,例如:720x480
	 */
	public static String getBestResolution(List<String>list,int targetWidth,int targetHeight) {
		// 数据集合
		List<Resolution> resolutions = new ArrayList<Resolution>();
		
		for (int i = 0; i < list.size(); i++) {
			String sss = list.get(i);
			String[] ary2 = sss.split("x");
			Resolution resolution = new Resolution(Integer.parseInt(ary2[0]), Integer.parseInt(ary2[1]));
			resolutions.add(resolution);
		}
		
		// 初始化最小差距为最大值
		int minDifference = Integer.MAX_VALUE;
		Resolution closestResolution = null;

		// 遍历数据集合,找到最接近目标分辨率的数据
		for (Resolution resolution : resolutions) {
			int difference = Math.abs(resolution.width - targetWidth) + Math.abs(resolution.height - targetHeight);
			if (difference < minDifference) {
				minDifference = difference;
				closestResolution = resolution;
			}
		}
		String res = String.format("%dx%d",closestResolution.width,closestResolution.height);
		return res;
	}

	// 分辨率类
	static class Resolution {
		int width;
		int height;

		public Resolution(int width, int height) {
			this.width = width;
			this.height = height;
		}
	}
}

输出结果

java 复制代码
最接近目标分辨率的数据为:720x480
相关推荐
Theodore_10223 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
冰帝海岸4 小时前
01-spring security认证笔记
java·笔记·spring
世间万物皆对象4 小时前
Spring Boot核心概念:日志管理
java·spring boot·单元测试
没书读了5 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
小二·5 小时前
java基础面试题笔记(基础篇)
java·笔记·python
开心工作室_kaic5 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
懒洋洋大魔王5 小时前
RocketMQ的使⽤
java·rocketmq·java-rocketmq
武子康5 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
转世成为计算机大神6 小时前
易考八股文之Java中的设计模式?
java·开发语言·设计模式
qq_327342736 小时前
Java实现离线身份证号码OCR识别
java·开发语言