算法一直是自己的弱项 通过算法来学习语言吧
Java版:
/**
* 算法练习 1
* Created by Exile on 2017/5/25.
* 1 N(N为偶数)个数字,把数字平分 N/2 组,使得每组的数字和相等。
*/
public class ArithmeticTest1 {
// 题目1偶数个数组
public static void main(String[] args) {
int[] evenNumberArry = new int[]{1, 7, 2, 7, 6, 5, 2, 8, 3, 4};
int arryNum = evenNumberArry.length / 2;
// 1 计算sum;
int sum = 0;
for (int i : evenNumberArry) {
sum = sum + i;
}
// 2 计算出每组的和是多少
int arryMax = sum / arryNum;
for (int i = 0; i < evenNumberArry.length; i++) {
int value = arryMax - evenNumberArry[i];
int temp;
// 假定一定会有一个与之组成一组
for (int j = i + 1; j < evenNumberArry.length; j++) {
if (evenNumberArry[j] == value) {
temp = evenNumberArry[i + 1];
evenNumberArry[i + 1] = value;
evenNumberArry[j] = temp;
}
}
}
for (int i : evenNumberArry) {
System.out.println(i);
}
}
}
import java.util.ArrayList;
import java.util.Random;
/**
* 算法练习 2
* Created by Exile on 2017/5/25.
* NxN的棋盘,每个格子可以放一个车,有M个车,问:每个车放完后,棋盘还剩多少格子是所有车攻击范围外?
* 车可以重叠
*/
public class ArithmeticTest2 {
public static void main(String[] args) {
// n和m
int m = 3;
int n = 3;
ArrayList<Model> modelList = createModelList(m, n);
ArrayList<Model> manList = new ArrayList<>();
for (Model model : modelList) {
System.out.println("当前model:" + model.toString());
}
// 方法1:从头到尾撸一遍
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
manList.add(new Model(i, j));
}
}
System.out.println("筛选前:" + manList.size());
// 速度太快的话会出问题
for (int i = 0; i < modelList.size(); i++) {
for (int j = 0; j < manList.size(); j++) {
if (!modelList.get(i).getAttackOutCall(manList.get(j))) {
manList.remove(j);
}
}
}
// }
System.out.println("筛选后:" + manList.size());
for (Model model : manList) {
System.out.println(model.toString());
}
}
/**
* 根据输入的mn生成对应个数的m对象
*
* @param m
* @param n
* @return
*/
private static ArrayList<Model> createModelList(int m, int n) {
ArrayList<Model> models = new ArrayList<>();
for (int i = 0; i < m; i++) {
models.add(new Model(n));
}
return models;
}
public static class Model {
private int x;
private int y;
public Model(int n) {
Random random = new Random();
this.x = random.nextInt(n);
this.y = random.nextInt(n);
}
public Model(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public String toString() {
return "Model{" +
"x=" + x +
", y=" + y +
'}';
}
public boolean getAttackOutCall(Model mainModel) {
if (this.getX() == mainModel.getX() || this.getY() == mainModel.getY()) {
return false;
}
return true;
}
}
}
golang版:
有疑问加站长微信联系(非本文作者)