
正文
算法风格的java代码 java算法模型
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
JAVA 求助一段算法代码!求大神~~~~~
看完你的,自己写了一个。很简陋。你的改动比较大。一时半会改不了。
你的写好了。改动有点大。鼠标事件mousePressed()中实现移动。由于时间没做优化,主要处理方法是判断当前listenerPanel的上下左右是否存在上面是0的listenerPanel,存在则交换上面数字及背景颜色。自己可以优化下里面代码,
思路:
PuzzleTile jb = (PuzzleTile) e.getSource();
for(int i=0;ilistenerPanel.length;i++){
if(jb.equals(listenerPanel[i])){
//判断当前listenerPanel[i]上下左右是否存有listenerPanel的上面数字是0的,如果存在
则把当前的listenerPanel[i]的背景颜色及数字与上面是0 的交换。判断周围是否存在有点及是否交换有点复杂。
}
}
代码修改如下:少量注释
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.*;
public class PuzzleTile extends JPanel{
private String tileNumber;
public PuzzleTile(int number) {
super();
if (number == 0) {
this.setBackground(Color.white);
}
else {
this.setBackground(Color.darkGray);
}
this.tileNumber = "" + number;
}
public void setTitleNumber(int tileNumber){//设置上面的数字
this.tileNumber=tileNumber+"";
}
public int getTitleNumber(){//获得上面的数字
return Integer.parseInt(tileNumber);
}
public void paintComponent(Graphics graphics) {
Font a=new Font("Arial",Font.BOLD,30);
graphics.setFont(a);
graphics.setColor(Color.white);
super.paintComponent(graphics);
FontMetrics b=graphics.getFontMetrics(a);
int c=b.stringWidth(tileNumber);
int d=b.getAscent();
int e=getWidth()/2-c/2;
int f=getHeight()/2+d/2;
graphics.drawString(tileNumber,e,f);
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
public class SlidingPuzzle extends JFrame implements MouseListener
{
public static void main(String[] args){
SlidingPuzzle frame=new SlidingPuzzle();
frame.TestPanel();
frame.setTitle("Numeric Sliding Puzzle");
frame.setSize(400,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
PuzzleTile[] listenerPanel;
public void TestPanel(){
Container container=getContentPane();
container.setLayout(new GridLayout(3,3,5,5));
listenerPanel=new PuzzleTile[9];
ArrayListInteger myList=new ArrayListInteger();
int m;
for(int i=0;i9;i++){
m=new Random().nextInt(9);
if(!myList.contains(m))
myList.add(m);
else
i--;
}
for(int i=0;ilistenerPanel.length;i++){
listenerPanel[i]=new PuzzleTile(myList.get(i));
container.add(listenerPanel[i]);
listenerPanel[i].addMouseListener(this);
}
}
public void mousePressed(MouseEvent e){
PuzzleTile jb = (PuzzleTile) e.getSource();
int m=jb.getTitleNumber();
//依次判断每一个listenerPanel上下左右是否存在上面数字为0的listenerPanel
if(jb.equals(listenerPanel[0])){
if(listenerPanel[1].getTitleNumber()==0){
listenerPanel[0].setBackground(Color.white);
listenerPanel[0].setTitleNumber(0);
listenerPanel[1].setTitleNumber(m);
listenerPanel[1].setBackground(Color.darkGray);
}
if(listenerPanel[3].getTitleNumber()==0){
listenerPanel[0].setBackground(Color.white);
listenerPanel[0].setTitleNumber(0);
listenerPanel[3].setTitleNumber(m);
listenerPanel[3].setBackground(Color.darkGray);
}
}else if(jb.equals(listenerPanel[1])){
if(listenerPanel[0].getTitleNumber()==0){
listenerPanel[1].setBackground(Color.white);
listenerPanel[1].setTitleNumber(0);
listenerPanel[0].setTitleNumber(m);
listenerPanel[0].setBackground(Color.darkGray);
}
if(listenerPanel[2].getTitleNumber()==0){
listenerPanel[1].setBackground(Color.white);
listenerPanel[1].setTitleNumber(0);
listenerPanel[2].setTitleNumber(m);
listenerPanel[2].setBackground(Color.darkGray);
}
if(listenerPanel[4].getTitleNumber()==0){
listenerPanel[1].setBackground(Color.white);
listenerPanel[1].setTitleNumber(0);
listenerPanel[4].setTitleNumber(m);
listenerPanel[4].setBackground(Color.darkGray);
}
}else if(jb.equals(listenerPanel[2])){
if(listenerPanel[1].getTitleNumber()==0){
listenerPanel[2].setBackground(Color.white);
listenerPanel[2].setTitleNumber(0);
listenerPanel[1].setTitleNumber(m);
listenerPanel[1].setBackground(Color.darkGray);
}
if(listenerPanel[5].getTitleNumber()==0){
listenerPanel[2].setBackground(Color.white);
listenerPanel[2].setTitleNumber(0);
listenerPanel[5].setTitleNumber(m);
listenerPanel[5].setBackground(Color.darkGray);
}
}else if(jb.equals(listenerPanel[3])){
if(listenerPanel[0].getTitleNumber()==0){
listenerPanel[3].setBackground(Color.white);
listenerPanel[3].setTitleNumber(0);
listenerPanel[0].setTitleNumber(m);
listenerPanel[0].setBackground(Color.darkGray);
}
if(listenerPanel[4].getTitleNumber()==0){
listenerPanel[3].setBackground(Color.white);
listenerPanel[3].setTitleNumber(0);
listenerPanel[4].setTitleNumber(m);
listenerPanel[4].setBackground(Color.darkGray);
}
if(listenerPanel[6].getTitleNumber()==0){
listenerPanel[3].setBackground(Color.white);
listenerPanel[3].setTitleNumber(0);
listenerPanel[6].setTitleNumber(m);
listenerPanel[6].setBackground(Color.darkGray);
}
}else if(jb.equals(listenerPanel[4])){
if(listenerPanel[1].getTitleNumber()==0){
listenerPanel[4].setBackground(Color.white);
listenerPanel[4].setTitleNumber(0);
listenerPanel[1].setTitleNumber(m);
listenerPanel[1].setBackground(Color.darkGray);
}
if(listenerPanel[7].getTitleNumber()==0){
listenerPanel[4].setBackground(Color.white);
listenerPanel[4].setTitleNumber(0);
listenerPanel[7].setTitleNumber(m);
listenerPanel[7].setBackground(Color.darkGray);
}
if(listenerPanel[3].getTitleNumber()==0){
listenerPanel[4].setBackground(Color.white);
listenerPanel[4].setTitleNumber(0);
listenerPanel[3].setTitleNumber(m);
listenerPanel[3].setBackground(Color.darkGray);
}
if(listenerPanel[5].getTitleNumber()==0){
listenerPanel[4].setBackground(Color.white);
listenerPanel[4].setTitleNumber(0);
listenerPanel[5].setTitleNumber(m);
listenerPanel[5].setBackground(Color.darkGray);
}
}else if(jb.equals(listenerPanel[5])){
if(listenerPanel[4].getTitleNumber()==0){
listenerPanel[5].setBackground(Color.white);
listenerPanel[5].setTitleNumber(0);
listenerPanel[4].setTitleNumber(m);
listenerPanel[4].setBackground(Color.darkGray);
}
if(listenerPanel[2].getTitleNumber()==0){
listenerPanel[5].setBackground(Color.white);
listenerPanel[5].setTitleNumber(0);
listenerPanel[2].setTitleNumber(m);
listenerPanel[2].setBackground(Color.darkGray);
}
if(listenerPanel[8].getTitleNumber()==0){
listenerPanel[5].setBackground(Color.white);
listenerPanel[5].setTitleNumber(0);
listenerPanel[8].setTitleNumber(m);
listenerPanel[8].setBackground(Color.darkGray);
}
}else if(jb.equals(listenerPanel[6])){
if(listenerPanel[3].getTitleNumber()==0){
listenerPanel[6].setBackground(Color.white);
listenerPanel[6].setTitleNumber(0);
listenerPanel[3].setTitleNumber(m);
listenerPanel[3].setBackground(Color.darkGray);
}
if(listenerPanel[7].getTitleNumber()==0){
listenerPanel[6].setBackground(Color.white);
listenerPanel[6].setTitleNumber(0);
listenerPanel[7].setTitleNumber(m);
listenerPanel[7].setBackground(Color.darkGray);
}
}else if(jb.equals(listenerPanel[7])){
if(listenerPanel[6].getTitleNumber()==0){
listenerPanel[7].setBackground(Color.white);
listenerPanel[7].setTitleNumber(0);
listenerPanel[6].setTitleNumber(m);
listenerPanel[6].setBackground(Color.darkGray);
}
if(listenerPanel[8].getTitleNumber()==0){
listenerPanel[7].setBackground(Color.white);
listenerPanel[7].setTitleNumber(0);
listenerPanel[8].setTitleNumber(m);
listenerPanel[8].setBackground(Color.darkGray);
}
if(listenerPanel[4].getTitleNumber()==0){
listenerPanel[7].setBackground(Color.white);
listenerPanel[7].setTitleNumber(0);
listenerPanel[4].setTitleNumber(m);
listenerPanel[4].setBackground(Color.darkGray);
}
}else {
if(listenerPanel[5].getTitleNumber()==0){
listenerPanel[8].setBackground(Color.white);
listenerPanel[8].setTitleNumber(0);
listenerPanel[5].setTitleNumber(m);
listenerPanel[5].setBackground(Color.darkGray);
}
if(listenerPanel[7].getTitleNumber()==0){
listenerPanel[8].setBackground(Color.white);
listenerPanel[8].setTitleNumber(0);
listenerPanel[7].setTitleNumber(m);
listenerPanel[7].setBackground(Color.darkGray);
}
}
boolean b=true;//是否完成标记
for(int i=0;ilistenerPanel.length;i++){//判断listenerPanel[0]~listenerPanel[8]上的数字是从0~8.若是完成拼图
if(listenerPanel[i].getTitleNumber()!=i)
b=false;
}
if(b==true){
int i=JOptionPane.showConfirmDialog(null, "would you paly agin?");
if(i==0){
if(i==0){
Rectangle re=this.getBounds();
this.dispose();
SlidingPuzzle slidingPuzzle=new SlidingPuzzle();
slidingPuzzle.setBounds(re);
}
else if(i==1)
System.exit(0);
else ;
}
}
}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}
如果运行过程什么问题追问或者hi
相关问答
Q1: 求Pareto蚁群算法的源代码 Java的
说明:信息素权重,路径权重和信息素蒸发率对最后的结果影响很大,需要微调。
目前发现2 / 5 / 0.5 能达到稍微让人满意的效果。本程序离完美的ACO还差很远,仅供参考。
本蚁群算法为AS算法。
用法:
1.new一个对象
ACOforTSP tsp = new ACPforTSP(tsp数据文件名,迭代次数,蚂蚁数量,信息素权重,路径权重,信息素蒸发率);
2.用go()方法运行
tsp.go();
ACOforTSP.java
___________________________________________________________________
import java.io.File;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
import static java.lang.Math.random;
import java.util.HashMap;
import java.io.FileReader;
import java.io.BufferedReader;
/**
*
* @author dvdface
*/
public class ACOforTSP {
//城市的距离表
private double[][] distance;
//距离的倒数表
private double[][] heuristic;
//启发信息表
private double[][] pheromone;
//权重
private int alpha, beta;
//迭代的次数
private int iterationTimes;
//蚂蚁的数量
private int numbersOfAnt;
//蒸发率
private double rate;
ACOforTSP (String file, int iterationTimes, int numbersOfAnt, int alpha, int beta, double rate) {
//加载文件
this.initializeData(file);
//初始化参数
this.iterationTimes = iterationTimes;
//设置蚂蚁数量
this.numbersOfAnt = numbersOfAnt;
//设置权重
this.alpha = alpha;
this.beta = beta;
//设置蒸发率
this.rate = rate;
}
private void initializeData(String filename) {
//定义内部类
class City {
int no;
double x;
double y;
City(int no, double x, double y) {
this.no = no;
this.x = x;
this.y = y;
}
private double getDistance(City city) {
return sqrt(pow((x - city.x), 2) + pow((y - city.y), 2));
}
}
try {
//定义HashMap保存读取的坐标信息
HashMapInteger, City map = new HashMapInteger, City();
//读取文件
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
for (String str = reader.readLine(); str != null; str = reader.readLine()) {
//将读到的信息保存入HashMap
if (str.matches("([0-9]+)(\\s*)([0-9]+)(.?)([0-9]*)(\\s*)([0-9]+)(.?)([0-9]*)")) {
String[] data = str.split("(\\s+)");
City city = new City(Integer.parseInt(data[0]),
Double.parseDouble(data[1]),
Double.parseDouble(data[2]));
map.put(city.no, city);
}
}
//分配距离矩阵存储空间
distance = new double[map.size() + 1][map.size() + 1];
//分配距离倒数矩阵存储空间
heuristic = new double[map.size() + 1][map.size() + 1];
//分配信息素矩阵存储空间
pheromone = new double[map.size() + 1][map.size() + 1];
for (int i = 1; i map.size() + 1; i++) {
for (int j = 1; j map.size() + 1; j++) {
//计算城市间的距离,并存入距离矩阵
distance[i][j] = map.get(i).getDistance(map.get(j));
//计算距离倒数,并存入距离倒数矩阵
heuristic[i][j] = 1 / distance[i][j];
//初始化信息素矩阵
pheromone[i][j] = 1;
}
}
} catch (Exception exception) {
System.out.println("初始化数据失败!");
}
}
class Ant {
//已访问城市列表
private boolean[] visited;
//访问顺序表
private int[] tour;
//已访问城市的个数
private int n;
//总的距离
private double total;
Ant() {
//给访问顺序表分配空间
tour = new int[distance.length+1];
//已存入城市数量为n,刚开始为0
n = 0;
//将起始城市1,放入访问结点顺序表第一项
tour[++n] = 1;
//给已访问城市结点分配空间
visited = new boolean[distance.length];
//第一个城市为出发城市,设置为已访问
visited[tour[n]] = true;
}
private int chooseCity() {
//用来random的随机数
double m = 0;
//获得当前所在的城市号放入j,如果和j相邻的城市没有被访问,那么加入m
for (int i = 1, j = tour[n]; i pheromone.length; i++) {
if (!visited[i]) {
m += pow(pheromone[j][i], alpha) * pow(heuristic[j][i], beta);
}
}
//保存随机到的数
double p = m * random();
//寻找被随机到的城市
double k = 0;
//保存找到的城市
int q = 0;
for (int i = 1, j = tour[n]; k p; i++) {
if (!visited[i]) {
k += pow(pheromone[j][i], alpha) * pow(heuristic[j][i], beta);
q = i;
}
}
return q;
}
private void constructSolution () {
while (n != (distance.length-1) ) {
//选取下一个城市
int p = chooseCity();
//计算总的距离
total += distance[tour[n]][p];
//将选取到的城市放入已访问列表
tour[++n] = p;
//将选取到的城市标记为已访问
visited[p] = true;
}
//回到起点
total += distance[tour[1]][tour[n]];
//将起点加入访问顺序表的最后
tour[++n] = tour[1];
}
private void releasePheromone() {
//释放信息素的大小
double t = 1/total;
//释放信息素
for (int i=1;itour.length-1;i++) {
pheromone[tour[i]][tour[i+1]] += t;
pheromone[tour[i+1]][tour[i]] += t;
}
}
}
public void go() {
//保存最好的路径和路径长度
double bestTotal = Double.MAX_VALUE;
int[] bestTour = new int[distance.length+1];
//新建蚂蚁数组,用来引用所创建的蚂蚁
Ant[] ant = new Ant[numbersOfAnt];
//进行iterationTimes次迭代
while (iterationTimes != 0) {
//初始化新的一批蚂蚁(这里用构造新的蚂蚁代替重置蚂蚁状态)
for (int i=0; inumbersOfAnt; i++) {
ant[i] = new Ant();
}
//进行一次迭代(即让所有的蚂蚁构建一条路径)
for (int i=0; inumbersOfAnt; i++) {
ant[i].constructSolution();
//如果蚂蚁构建的路径长度比上次最好的还好,那么保存这个长度和它所走的路径
if (ant[i].totalbestTotal) {
bestTotal = ant[i].total;
System.arraycopy(ant[i].tour, 1, bestTour, 1, bestTour.length-1);
}
}
//蒸发信息素
evaporatePheromone();
//释放信息素
for (int i=0; inumbersOfAnt; i++) {
ant[i].releasePheromone();
}
//报告本次迭代的信息
System.out.format("本次为倒数第%d次迭代,当前最优路径长度为%10.2f\n",iterationTimes,bestTotal);
//迭代总数减去1,进行下次迭代
iterationTimes--;
}
//输出最好的路径长度
System.out.format("得到的最优的路径长度为:%10.2f\n",bestTotal);
//输出最好的路径
System.out.println("最优路径如下:");
for (int i=1; ibestTour.length; i++) {
System.out.print("→"+bestTour[i]);
}
}
private void evaporatePheromone() {
for (int i = 1; i pheromone.length; i++)
for (int j = 1; j pheromone.length; j++) {
pheromone[i][j] *= 1-rate;
}
}
}
Q2: 求此算法的Java代码
不给分就算了,这个题目也看不懂……如此下去直至黑板上 剩下一个数,在所有按这种操作方式最后得到的数中,最大的为max,最小的为min,什么意思?
Q3: java的md5的加密算法代码
import java.lang.reflect.*;
/*******************************************************************************
* keyBean 类实现了RSA Data Security, Inc.在提交给IETF 的RFC1321中的keyBean message-digest
* 算法。
******************************************************************************/
public class keyBean {
/*
* 下面这些S11-S44实际上是一个4*4的矩阵,在原始的C实现中是用#define 实现的, 这里把它们实现成为static
* final是表示了只读,切能在同一个进程空间内的多个 Instance间共享
*/
static final int S11 = 7;
static final int S12 = 12;
static final int S13 = 17;
static final int S14 = 22;
static final int S21 = 5;
static final int S22 = 9;
static final int S23 = 14;
static final int S24 = 20;
static final int S31 = 4;
static final int S32 = 11;
static final int S33 = 16;
static final int S34 = 23;
static final int S41 = 6;
static final int S42 = 10;
static final int S43 = 15;
static final int S44 = 21;
static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0 };
/*
* 下面的三个成员是keyBean计算过程中用到的3个核心数据,在原始的C实现中 被定义到keyBean_CTX结构中
*/
private long[] state = new long[4]; // state (ABCD)
private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb
// first)
private byte[] buffer = new byte[64]; // input buffer
/*
* digestHexStr是keyBean的唯一一个公共成员,是最新一次计算结果的 16进制ASCII表示.
*/
public String digestHexStr;
/*
* digest,是最新一次计算结果的2进制内部表示,表示128bit的keyBean值.
*/
private byte[] digest = new byte[16];
/*
* getkeyBeanofStr是类keyBean最主要的公共方法,入口参数是你想要进行keyBean变换的字符串
* 返回的是变换完的结果,这个结果是从公共成员digestHexStr取得的.
*/
public String getkeyBeanofStr(String inbuf) {
keyBeanInit();
keyBeanUpdate(inbuf.getBytes(), inbuf.length());
keyBeanFinal();
digestHexStr = "";
for (int i = 0; i 16; i++) {
digestHexStr += byteHEX(digest[i]);
}
return digestHexStr;
}
// 这是keyBean这个类的标准构造函数,JavaBean要求有一个public的并且没有参数的构造函数
public keyBean() {
keyBeanInit();
return;
}
/* keyBeanInit是一个初始化函数,初始化核心变量,装入标准的幻数 */
private void keyBeanInit() {
count[0] = 0L;
count[1] = 0L;
// /* Load magic initialization constants.
state[0] = 0x67452301L;
state[1] = 0xefcdab89L;
state[2] = 0x98badcfeL;
state[3] = 0x10325476L;
return;
}
/*
* F, G, H ,I 是4个基本的keyBean函数,在原始的keyBean的C实现中,由于它们是
* 简单的位运算,可能出于效率的考虑把它们实现成了宏,在java中,我们把它们 实现成了private方法,名字保持了原来C中的。
*/
private long F(long x, long y, long z) {
return (x y) | ((~x) z);
}
private long G(long x, long y, long z) {
return (x z) | (y (~z));
}
private long H(long x, long y, long z) {
return x ^ y ^ z;
}
private long I(long x, long y, long z) {
return y ^ (x | (~z));
}
/*
* FF,GG,HH和II将调用F,G,H,I进行近一步变换 FF, GG, HH, and II transformations for
* rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent
* recomputation.
*/
private long FF(long a, long b, long c, long d, long x, long s, long ac) {
a += F(b, c, d) + x + ac;
a = ((int) a s) | ((int) a (32 - s));
a += b;
return a;
}
private long GG(long a, long b, long c, long d, long x, long s, long ac) {
a += G(b, c, d) + x + ac;
a = ((int) a s) | ((int) a (32 - s));
a += b;
return a;
}
private long HH(long a, long b, long c, long d, long x, long s, long ac) {
a += H(b, c, d) + x + ac;
a = ((int) a s) | ((int) a (32 - s));
a += b;
return a;
}
private long II(long a, long b, long c, long d, long x, long s, long ac) {
a += I(b, c, d) + x + ac;
a = ((int) a s) | ((int) a (32 - s));
a += b;
return a;
}
/*
* keyBeanUpdate是keyBean的主计算过程,inbuf是要变换的字节串,inputlen是长度,这个
* 函数由getkeyBeanofStr调用,调用之前需要调用keyBeaninit,因此把它设计成private的
*/
private void keyBeanUpdate(byte[] inbuf, int inputLen) {
int i, index, partLen;
byte[] block = new byte[64];
index = (int) (count[0] 3) 0x3F;
// /* Update number of bits */
if ((count[0] += (inputLen 3)) (inputLen 3))
count[1]++;
count[1] += (inputLen 29);
partLen = 64 - index;
// Transform as many times as possible.
if (inputLen = partLen) {
keyBeanMemcpy(buffer, inbuf, index, 0, partLen);
keyBeanTransform(buffer);
for (i = partLen; i + 63 inputLen; i += 64) {
keyBeanMemcpy(block, inbuf, 0, i, 64);
keyBeanTransform(block);
}
index = 0;
} else
i = 0;
// /* Buffer remaining input */
keyBeanMemcpy(buffer, inbuf, index, i, inputLen - i);
}
/*
* keyBeanFinal整理和填写输出结果
*/
private void keyBeanFinal() {
byte[] bits = new byte[8];
int index, padLen;
// /* Save number of bits */
Encode(bits, count, 8);
// /* Pad out to 56 mod 64.
index = (int) (count[0] 3) 0x3f;
padLen = (index 56) ? (56 - index) : (120 - index);
keyBeanUpdate(PADDING, padLen);
// /* Append length (before padding) */
keyBeanUpdate(bits, 8);
// /* Store state in digest */
Encode(digest, state, 16);
}
/*
* keyBeanMemcpy是一个内部使用的byte数组的块拷贝函数,从input的inpos开始把len长度的
* 字节拷贝到output的outpos位置开始
*/
private void keyBeanMemcpy(byte[] output, byte[] input, int outpos,
int inpos, int len) {
int i;
for (i = 0; i len; i++)
output[outpos + i] = input[inpos + i];
}
/*
* keyBeanTransform是keyBean核心变换程序,有keyBeanUpdate调用,block是分块的原始字节
*/
private void keyBeanTransform(byte block[]) {
long a = state[0], b = state[1], c = state[2], d = state[3];
long[] x = new long[16];
Decode(x, block, 64);
/* Round 1 */
a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */
d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */
c = FF(c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */
b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */
a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */
d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */
c = FF(c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */
b = FF(b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */
a = FF(a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */
d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */
c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */
b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */
a = FF(a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */
d = FF(d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */
c = FF(c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */
b = FF(b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */
/* Round 2 */
a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */
d = GG(d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */
c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */
b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */
a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */
d = GG(d, a, b, c, x[10], S22, 0x2441453L); /* 22 */
c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */
b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */
a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */
d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */
c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */
b = GG(b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */
a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */
d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */
c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */
b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */
/* Round 3 */
a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */
d = HH(d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */
c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */
b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */
a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */
d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */
c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */
b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */
a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */
d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */
c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */
b = HH(b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */
a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */
d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */
c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */
b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */
/* Round 4 */
a = II(a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */
d = II(d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */
c = II(c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */
b = II(b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */
a = II(a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */
d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */
c = II(c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */
b = II(b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */
a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */
d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */
c = II(c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */
b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */
a = II(a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */
d = II(d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */
c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */
b = II(b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
/*
* Encode把long数组按顺序拆成byte数组,因为java的long类型是64bit的, 只拆低32bit,以适应原始C实现的用途
*/
private void Encode(byte[] output, long[] input, int len) {
int i, j;
for (i = 0, j = 0; j len; i++, j += 4) {
output[j] = (byte) (input[i] 0xffL);
output[j + 1] = (byte) ((input[i] 8) 0xffL);
output[j + 2] = (byte) ((input[i] 16) 0xffL);
output[j + 3] = (byte) ((input[i] 24) 0xffL);
}
}
/*
* Decode把byte数组按顺序合成成long数组,因为java的long类型是64bit的,
* 只合成低32bit,高32bit清零,以适应原始C实现的用途
*/
private void Decode(long[] output, byte[] input, int len) {
int i, j;
for (i = 0, j = 0; j len; i++, j += 4)
output[i] = b2iu(input[j]) | (b2iu(input[j + 1]) 8)
| (b2iu(input[j + 2]) 16) | (b2iu(input[j + 3]) 24);
return;
}
/*
* b2iu是我写的一个把byte按照不考虑正负号的原则的”升位”程序,因为java没有unsigned运算
*/
public static long b2iu(byte b) {
return b 0 ? b 0x7F + 128 : b;
}
/*
* byteHEX(),用来把一个byte类型的数转换成十六进制的ASCII表示,
* 因为java中的byte的toString无法实现这一点,我们又没有C语言中的 sprintf(outbuf,"%02X",ib)
*/
public static String byteHEX(byte ib) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
char[] ob = new char[2];
ob[0] = Digit[(ib 4) 0X0F];
ob[1] = Digit[ib 0X0F];
String s = new String(ob);
return s;
}
public static void main(String args[]) {
keyBean m = new keyBean();
if (Array.getLength(args) == 0) { // 如果没有参数,执行标准的Test Suite
System.out.println("keyBean Test suite:");
System.out.println("keyBean(\"):" + m.getkeyBeanofStr(""));
System.out.println("keyBean(\"a\"):" + m.getkeyBeanofStr("a"));
System.out.println("keyBean(\"abc\"):" + m.getkeyBeanofStr("abc"));
System.out.println("keyBean(\"message digest\"):"
+ m.getkeyBeanofStr("message digest"));
System.out.println("keyBean(\"abcdefghijklmnopqrstuvwxyz\"):"
+ m.getkeyBeanofStr("abcdefghijklmnopqrstuvwxyz"));
System.out
.println("keyBean(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"):"
+ m
.getkeyBeanofStr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"));
} else
System.out.println("keyBean(" + args[0] + ")="
+ m.getkeyBeanofStr(args[0]));
}
}
Q4: 求:用JAVA语言编写的银行家算法的源代码
import java.util.*;
class ThreadTest {
static int type = 4, num = 10; //定义资源数目和线程数目
static int[] resource = new int[type]; //系统资源总数
//static int[] copyResource = new int[type]; //副本
static Random rand = new Random();
static Bank[] bank = new Bank[num]; //线程组
Bank temp = new Bank();
public void init() {
//初始化组中每个线程,随机填充系统资源总数
for(int i = 0; i type; i++)
resource[i] = rand.nextInt(10) + 80;
System.out.print("Resource:");
for(int i = 0; i type; i++)
System.out.print(" " + resource[i]);
System.out.println("");
for(int i = 0; i bank.length; i++)
bank[i] = new Bank("#" + i);
}
public ThreadTest4() {
init();
}
class Bank extends Thread {
//银行家算法避免死锁
public int[]
max = new int[type], //总共需求量
need = new int[type], //尚需资源量
allocation = new int[type]; //已分配量
private int[]
request = new int[type], //申请资源量
copyResource = new int[type]; //资源副本
private boolean isFinish = false; //线程是否完成
int[][] table = new int[bank.length][type*4]; //二维资源分配表
private void init() {
// 随机填充总共、尚需、已分配量
synchronized(resource) {
for(int i = 0; i type; i++) {
max[i] = rand.nextInt(5) + 10;
need[i] = rand.nextInt(10);
allocation[i] = max[i] - need[i];
resource[i] -= allocation[i]; //从系统资源中减去已分配的
}
printer();
for(int i = 0; i type; i++) {
if(resource[i] 0) {
//若出现已分配量超出系统资源总数的错误则退出
System.out.println("The summation of Threads' allocations is out of range!");
System.exit(1);
}
}
}
}
public Bank(String s) {
setName(s);
init();
start();
}
public Bank() {
//none
}
public void run() {
try {
sleep(rand.nextInt(2000));
}
catch(InterruptedException e) {
throw new RuntimeException(e);
}
while(true) {
//程序没有完成时一直不断申请资源
if(askFor() == false) {
try {
sleep(1000);
}
catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
else
tryRequest();
if(noNeed() == true)
break;
}
//休眠一段时间模拟程序运行
try {
sleep(1000);
}
catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(getName() + " finish!");
synchronized(resource) {
//运行结束释放占有资源
for(int i = 0; i type; i++) {
resource[i] += allocation[i];
need[i] = allocation[i] = max[i] = 0;
}
}
}
private void printer() {
//打印当前资源信息
System.out.print(getName() + " Max:");
for(int i = 0; i type; i++)
System.out.print(" " + max[i]);
System.out.print(" Allocation:");
for(int i = 0; i type; i++)
System.out.print(" " + allocation[i]);
System.out.print(" Need:");
for(int i = 0; i type; i++)
System.out.print(" " + need[i]);
System.out.print(" Available:");
for(int i = 0; i type; i++)
System.out.print(" " + resource[i]);
System.out.println("");
}
private boolean askFor() {
//随机产生申请资源量并检测是否超标
boolean canAsk = false;
for(int i = 0; i type; i++) {
request[i] = rand.nextInt(20);
//防止申请量超过所需量
if(request[i] need[i])
request[i] = need[i];
}
for(int i = 0; i type; i++) //防止随机申请资源全为0
if(request[i] 0)
canAsk = true;
synchronized(resource) {
//锁住可供资源检查是否超标
for(int i = 0; i type; i++) {
if(request[i] resource[i])
//如果申请资源超过可供资源则等待一段时间后重新申请
return false;
}
}
return canAsk;
}
private void tryRequest() {
//创建副本尝试分配请求
synchronized(resource) {
for(int i = 0; i type; i++)
//依然要防止请求量超出范围
if(request[i] resource[i])
return;
for(int i = 0; i type; i++) {
//复制资源量并减去需求量到一个副本上
copyResource[i] = resource[i];
copyResource[i] -= request[i];
}
System.out.print(getName() + " ask for:");
for(int i = 0; i type; i++)
System.out.print(" " + request[i]);
System.out.println("");
if(checkSafe() == true) {
//如果检查安全则将副本值赋给资源量并修改占有量和需求量
for(int i = 0; i type; i++) {
resource[i] = copyResource[i];
allocation[i] += request[i];
need[i] -= request[i];
}
System.out.println(getName() + " request succeed!");
}
else
System.out.println(getName() + " request fail!");
}
}
private boolean checkSafe() {
//银行家算法检查安全性
synchronized(bank) {
//将线程资源信息放入二维资源分配表检查安全性,0~type可用资源/type~type*2所需资源/type*2~type*3占有资源/type*3~-1可用+占用资源
for(int i = 0; i bank.length; i++) {
for(int j = type; j type*2; j++) {
table[i][j] = bank[i].need[j%type];
}
for(int j = type*2; j type*3; j++) {
table[i][j] = bank[i].allocation[j%type];
}
}
//冒泡排序按需求资源从小到大排
for(int i = 0; i bank.length; i++) {
for(int j = i; j bank.length-1; j++) {
sort(j, 4);
}
}
//进行此时刻的安全性检查
for(int i = 0; i type; i++) {
table[0][i] = copyResource[i];
table[0][i+type*3] = table[0][i] + table[0][i+type*2];
if(table[0][i+type*3] table[1][i+type])
return false;
}
for(int j = 1; j bank.length-1; j++) {
for(int k = 0; k type; k++) {
table[j][k] = table[j-1][k+type*3];
table[j][k+type*3] = table[j][k] + table[j][k+type*2];
if(table[j][k+type*3] table[j+1][k+type])
return false;
}
}
}
return true;
}
private void sort(int j, int k) {
//递归冒泡排序
int tempNum;
if(table[j][k] table[j+1][k]) {
for(int i = type; i type*2; i++) {
tempNum = table[j][i];
table[j][i] = table[j+1][i];
table[j+1][i] = tempNum;
}
/*temp = bank[j];
bank[j] = bank[j+1];
bank[j+1] = temp;*/
}
else if(table[j][k] == table[j+1][k] k type*2) //此资源量相同时递归下一个资源量排序并且防止超出范围
sort(j, k+1);
}
private boolean noNeed() {
//是否还需要资源
boolean finish = true;
for(int i = 0; i type; i++) {
if(need[i] != 0) {
finish = false;
break;
}
}
return finish;
}
}
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
//后台线程,设定程序运行多长时间后自动结束
new Timeout(30000, "---Stop!!!---");
}
}
算法风格的java代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java算法模型、算法风格的java代码的信息别忘了在本站进行查找喔。






