求:用JAVA语言编写的银行家算法的源代码

Python010

求:用JAVA语言编写的银行家算法的源代码,第1张

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 = 0i <typei++)

resource[i] = rand.nextInt(10) + 80

System.out.print("Resource:")

for(int i = 0i <typei++)

System.out.print(" " + resource[i])

System.out.println("")

for(int i = 0i <bank.lengthi++)

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 = 0i <typei++) {

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 = 0i <typei++) {

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 = 0i <typei++) {

resource[i] += allocation[i]

need[i] = allocation[i] = max[i] = 0

}

}

}

private void printer() {

//打印当前资源信息

System.out.print(getName() + " Max:")

for(int i = 0i <typei++)

System.out.print(" " + max[i])

System.out.print(" Allocation:")

for(int i = 0i <typei++)

System.out.print(" " + allocation[i])

System.out.print(" Need:")

for(int i = 0i <typei++)

System.out.print(" " + need[i])

System.out.print(" Available:")

for(int i = 0i <typei++)

System.out.print(" " + resource[i])

System.out.println("")

}

private boolean askFor() {

//随机产生申请资源量并检测是否超标

boolean canAsk = false

for(int i = 0i <typei++) {

request[i] = rand.nextInt(20)

//防止申请量超过所需量

if(request[i] >need[i])

request[i] = need[i]

}

for(int i = 0i <typei++) //防止随机申请资源全为0

if(request[i] >0)

canAsk = true

synchronized(resource) {

//锁住可供资源检查是否超标

for(int i = 0i <typei++) {

if(request[i] >resource[i])

//如果申请资源超过可供资源则等待一段时间后重新申请

return false

}

}

return canAsk

}

private void tryRequest() {

//创建副本尝试分配请求

synchronized(resource) {

for(int i = 0i <typei++)

//依然要防止请求量超出范围

if(request[i] >resource[i])

return

for(int i = 0i <typei++) {

//复制资源量并减去需求量到一个副本上

copyResource[i] = resource[i]

copyResource[i] -= request[i]

}

System.out.print(getName() + " ask for:")

for(int i = 0i <typei++)

System.out.print(" " + request[i])

System.out.println("")

if(checkSafe() == true) {

//如果检查安全则将副本值赋给资源量并修改占有量和需求量

for(int i = 0i <typei++) {

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 = 0i <bank.lengthi++) {

for(int j = typej <type*2j++) {

table[i][j] = bank[i].need[j%type]

}

for(int j = type*2j <type*3j++) {

table[i][j] = bank[i].allocation[j%type]

}

}

//冒泡排序按需求资源从小到大排

for(int i = 0i <bank.lengthi++) {

for(int j = ij <bank.length-1j++) {

sort(j, 4)

}

}

//进行此时刻的安全性检查

for(int i = 0i <typei++) {

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 = 1j <bank.length-1j++) {

for(int k = 0k <typek++) {

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 = typei <type*2i++) {

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 = 0i <typei++) {

if(need[i] != 0) {

finish = false

break

}

}

return finish

}

}

public static void main(String[] args) {

ThreadTest t = new ThreadTest()

//后台线程,设定程序运行多长时间后自动结束

new Timeout(30000, "---Stop!!!---")

}

}

package tv.bilibili

import java.util.Scanner

import java.util.regex.MatchResult

public class test3 {

public static void main(String[] args) {

double price, money

Scanner input = new Scanner(System.in)

System.out.println("请输入物品价格:")

price = input.nextDouble()// 接受输入数字

System.out.println("请输入支付金额:")

money = input.nextDouble()// 接受输入数字

if (price <= money) {

money = money - price

int bai, wushi, ershi, shi, wu, yi, wujiao, yijiao

bai = (int) (money / 100)

money = money - bai * 100

wushi = (int) (money / 50)

money = money - wushi * 50

ershi = (int) (money / 20)

money = money - ershi * 20

shi = (int) (money / 10)

money = money - shi * 10

wu = (int) (money / 5)

money = money - wu * 5

yi = (int) (money / 1)

money = money - yi * 1

wujiao = (int) (money / 0.5)

money = money - wujiao * 0.5

yijiao = (int) (money / 0.1)

money = money - yijiao * 0.1

System.out.println("主要支付给顾客100元:" + bai + "张" + "50元:" + wushi

+ "张" + "20元:" + ershi + "张" + "10元:" + shi + "张"

+ "5元:" + wu + "张" + "1元:" + yi + "张" + "5角:"

+ wujiao + "张" + "1角:" + yijiao + "张")

} else {

System.out.println("您所支付的金额不足!")

}

}

}

算是写完了,其实很简单自己不动手只会害了自己,既然选择这个,以后问问题不要直接求代码,而是求方法,不然你永远从事不了这一行

/*

*This program is free softwareyou can redistribute it and/or modify

*it under the terms of the GNU General Public License as published by

*the Free Software Foundationeither version 2 of the License, or

*(at your option) any later version.

*

*This program is distributed in the hope that it will be useful,

*but WITHOUT ANY WARRANTYwithout even the implied warranty of

*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

*GNU General Public License for more details.

*

*You should have received a copy of the GNU General Public License

*along with this programif not, write to the Free Software

*Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

/*

*Id3.java

*Copyright (C) 1999 University of Waikato, Hamilton, New Zealand

*

*/

package weka.classifiers.trees

import weka.classifiers.Classifier

import weka.classifiers.Sourcable

import weka.core.Attribute

import weka.core.Capabilities

import weka.core.Instance

import weka.core.Instances

import weka.core.NoSupportForMissingValuesException

import weka.core.RevisionUtils

import weka.core.TechnicalInformation

import weka.core.TechnicalInformationHandler

import weka.core.Utils

import weka.core.Capabilities.Capability

import weka.core.TechnicalInformation.Field

import weka.core.TechnicalInformation.Type

import java.util.Enumeration

/**

<!-- globalinfo-start -->

* Class for constructing an unpruned decision tree based on the ID3 algorithm. Can only deal with nominal attributes. No missing values allowed. Empty leaves may result in unclassified instances. For more information see: <br/>

* <br/>

* R. Quinlan (1986). Induction of decision trees. Machine Learning. 1(1):81-106.

* <p/>

<!-- globalinfo-end -->

*

<!-- technical-bibtex-start -->

* BibTeX:

* <pre>

* &#64article{Quinlan1986,

*author = {R. Quinlan},

*journal = {Machine Learning},

*number = {1},

*pages = {81-106},

*title = {Induction of decision trees},

*volume = {1},

*year = {1986}

* }

* </pre>

* <p/>

<!-- technical-bibtex-end -->

*

<!-- options-start -->

* Valid options are: <p/>

*

* <pre>-D

* If set, classifier is run in debug mode and

* may output additional info to the console</pre>

*

<!-- options-end -->

*

* @author Eibe Frank ([email protected])

* @version $Revision: 6404 $

*/

public class Id3

extends Classifier

implements TechnicalInformationHandler, Sourcable {

/** for serialization */

static final long serialVersionUID = -2693678647096322561L

/** The node's successors. */

private Id3[] m_Successors

/** Attribute used for splitting. */

private Attribute m_Attribute

/** Class value if node is leaf. */

private double m_ClassValue

/** Class distribution if node is leaf. */

private double[] m_Distribution

/** Class attribute of dataset. */

private Attribute m_ClassAttribute

/**

* Returns a string describing the classifier.

* @return a description suitable for the GUI.

*/

public String globalInfo() {

return "Class for constructing an unpruned decision tree based on the ID3 "

+ "algorithm. Can only deal with nominal attributes. No missing values "

+ "allowed. Empty leaves may result in unclassified instances. For more "

+ "information see: \n\n"

+ getTechnicalInformation().toString()

}

/**

* Returns an instance of a TechnicalInformation object, containing

* detailed information about the technical background of this class,

* e.g., paper reference or book this class is based on.

*

* @return the technical information about this class

*/

public TechnicalInformation getTechnicalInformation() {

TechnicalInformationresult

result = new TechnicalInformation(Type.ARTICLE)

result.setValue(Field.AUTHOR, "R. Quinlan")

result.setValue(Field.YEAR, "1986")

result.setValue(Field.TITLE, "Induction of decision trees")

result.setValue(Field.JOURNAL, "Machine Learning")

result.setValue(Field.VOLUME, "1")

result.setValue(Field.NUMBER, "1")

result.setValue(Field.PAGES, "81-106")

return result

}

/**

* Returns default capabilities of the classifier.

*

* @return the capabilities of this classifier

*/

public Capabilities getCapabilities() {

Capabilities result = super.getCapabilities()

result.disableAll()

// attributes

result.enable(Capability.NOMINAL_ATTRIBUTES)

// class

result.enable(Capability.NOMINAL_CLASS)

result.enable(Capability.MISSING_CLASS_VALUES)

// instances

result.setMinimumNumberInstances(0)

return result

}

/**

* Builds Id3 decision tree classifier.

*

* @param data the training data

* @exception Exception if classifier can't be built successfully

*/

public void buildClassifier(Instances data) throws Exception {

// can classifier handle the data?

getCapabilities().testWithFail(data)

// remove instances with missing class

data = new Instances(data)

data.deleteWithMissingClass()

makeTree(data)

}

/**

* Method for building an Id3 tree.

*

* @param data the training data

* @exception Exception if decision tree can't be built successfully

*/

private void makeTree(Instances data) throws Exception {

// Check if no instances have reached this node.

if (data.numInstances() == 0) {

m_Attribute = null

m_ClassValue = Instance.missingValue()

m_Distribution = new double[data.numClasses()]

return

}

// Compute attribute with maximum information gain.

double[] infoGains = new double[data.numAttributes()]

Enumeration attEnum = data.enumerateAttributes()

while (attEnum.hasMoreElements()) {

Attribute att = (Attribute) attEnum.nextElement()

infoGains[att.index()] = computeInfoGain(data, att)

}

m_Attribute = data.attribute(Utils.maxIndex(infoGains))

// Make leaf if information gain is zero.

// Otherwise create successors.

if (Utils.eq(infoGains[m_Attribute.index()], 0)) {

m_Attribute = null

m_Distribution = new double[data.numClasses()]

Enumeration instEnum = data.enumerateInstances()

while (instEnum.hasMoreElements()) {

Instance inst = (Instance) instEnum.nextElement()

m_Distribution[(int) inst.classValue()]++

}

Utils.normalize(m_Distribution)

m_ClassValue = Utils.maxIndex(m_Distribution)

m_ClassAttribute = data.classAttribute()

} else {

Instances[] splitData = splitData(data, m_Attribute)

m_Successors = new Id3[m_Attribute.numValues()]

for (int j = 0j <m_Attribute.numValues()j++) {

m_Successors[j] = new Id3()

m_Successors[j].makeTree(splitData[j])

}

}

}

/**

* Classifies a given test instance using the decision tree.

*

* @param instance the instance to be classified

* @return the classification

* @throws NoSupportForMissingValuesException if instance has missing values

*/

public double classifyInstance(Instance instance)

throws NoSupportForMissingValuesException {

if (instance.hasMissingValue()) {

throw new NoSupportForMissingValuesException("Id3: no missing values, "

+ "please.")

}

if (m_Attribute == null) {

return m_ClassValue

} else {

return m_Successors[(int) instance.value(m_Attribute)].

classifyInstance(instance)

}

}

/**

* Computes class distribution for instance using decision tree.

*

* @param instance the instance for which distribution is to be computed

* @return the class distribution for the given instance

* @throws NoSupportForMissingValuesException if instance has missing values

*/

public double[] distributionForInstance(Instance instance)

throws NoSupportForMissingValuesException {

if (instance.hasMissingValue()) {

throw new NoSupportForMissingValuesException("Id3: no missing values, "

+ "please.")

}

if (m_Attribute == null) {

return m_Distribution

} else {

return m_Successors[(int) instance.value(m_Attribute)].

distributionForInstance(instance)

}

}

/**

* Prints the decision tree using the private toString method from below.

*

* @return a textual description of the classifier

*/

public String toString() {

if ((m_Distribution == null) &&(m_Successors == null)) {

return "Id3: No model built yet."

}

return "Id3\n\n" + toString(0)

}

/**

* Computes information gain for an attribute.

*

* @param data the data for which info gain is to be computed

* @param att the attribute

* @return the information gain for the given attribute and data

* @throws Exception if computation fails

*/

private double computeInfoGain(Instances data, Attribute att)

throws Exception {

double infoGain = computeEntropy(data)

Instances[] splitData = splitData(data, att)

for (int j = 0j <att.numValues()j++) {

if (splitData[j].numInstances() >0) {

infoGain -= ((double) splitData[j].numInstances() /

(double) data.numInstances()) *

computeEntropy(splitData[j])

}

}

return infoGain

}

/**

* Computes the entropy of a dataset.

*

* @param data the data for which entropy is to be computed

* @return the entropy of the data's class distribution

* @throws Exception if computation fails

*/

private double computeEntropy(Instances data) throws Exception {

double [] classCounts = new double[data.numClasses()]

Enumeration instEnum = data.enumerateInstances()

while (instEnum.hasMoreElements()) {

Instance inst = (Instance) instEnum.nextElement()

classCounts[(int) inst.classValue()]++

}

double entropy = 0

for (int j = 0j <data.numClasses()j++) {

if (classCounts[j] >0) {

entropy -= classCounts[j] * Utils.log2(classCounts[j])

}

}

entropy /= (double) data.numInstances()

return entropy + Utils.log2(data.numInstances())

}

/**

* Splits a dataset according to the values of a nominal attribute.

*

* @param data the data which is to be split

* @param att the attribute to be used for splitting

* @return the sets of instances produced by the split

*/

private Instances[] splitData(Instances data, Attribute att) {

Instances[] splitData = new Instances[att.numValues()]

for (int j = 0j <att.numValues()j++) {

splitData[j] = new Instances(data, data.numInstances())

}

Enumeration instEnum = data.enumerateInstances()

while (instEnum.hasMoreElements()) {

Instance inst = (Instance) instEnum.nextElement()

splitData[(int) inst.value(att)].add(inst)

}

for (int i = 0i <splitData.lengthi++) {

splitData[i].compactify()

}

return splitData

}

/**

* Outputs a tree at a certain level.

*

* @param level the level at which the tree is to be printed

* @return the tree as string at the given level

*/

private String toString(int level) {

StringBuffer text = new StringBuffer()

if (m_Attribute == null) {

if (Instance.isMissingValue(m_ClassValue)) {

text.append(": null")

} else {

text.append(": " + m_ClassAttribute.value((int) m_ClassValue))

}

} else {

for (int j = 0j <m_Attribute.numValues()j++) {

text.append("\n")

for (int i = 0i <leveli++) {

text.append("| ")

}

text.append(m_Attribute.name() + " = " + m_Attribute.value(j))

text.append(m_Successors[j].toString(level + 1))

}

}

return text.toString()

}

/**

* Adds this tree recursively to the buffer.

*

* @param id the unqiue id for the method

* @param buffer the buffer to add the source code to

* @returnthe last ID being used

* @throws Exception if something goes wrong

*/

protected int toSource(int id, StringBuffer buffer) throws Exception {

int result

int i

int newID

StringBuffer[] subBuffers

buffer.append("\n")

buffer.append(" protected static double node" + id + "(Object[] i) {\n")

// leaf?

if (m_Attribute == null) {

result = id

if (Double.isNaN(m_ClassValue)) {

buffer.append("return Double.NaN")

} else {

buffer.append("return " + m_ClassValue + "")

}

if (m_ClassAttribute != null) {

buffer.append(" // " + m_ClassAttribute.value((int) m_ClassValue))

}

buffer.append("\n")

buffer.append(" }\n")

} else {

buffer.append("checkMissing(i, " + m_Attribute.index() + ")\n\n")

buffer.append("// " + m_Attribute.name() + "\n")

// subtree calls

subBuffers = new StringBuffer[m_Attribute.numValues()]

newID = id

for (i = 0i <m_Attribute.numValues()i++) {

newID++

buffer.append("")

if (i >0) {

buffer.append("else ")

}

buffer.append("if (((String) i[" + m_Attribute.index()

+ "]).equals(\"" + m_Attribute.value(i) + "\"))\n")

buffer.append(" return node" + newID + "(i)\n")

subBuffers[i] = new StringBuffer()

newID = m_Successors[i].toSource(newID, subBuffers[i])

}

buffer.append("else\n")

buffer.append(" throw new IllegalArgumentException(\"Value '\" + i["

+ m_Attribute.index() + "] + \"' is not allowed!\")\n")

buffer.append(" }\n")

// output subtree code

for (i = 0i <m_Attribute.numValues()i++) {

buffer.append(subBuffers[i].toString())

}

subBuffers = null

result = newID

}

return result

}

/**

* Returns a string that describes the classifier as source. The

* classifier will be contained in a class with the given name (there may

* be auxiliary classes),

* and will contain a method with the signature:

* <pre><code>

* public static double classify(Object[] i)

* </code></pre>

* where the array <code>i</code>contains elements that are either

* Double, String, with missing values represented as null. The generated

* code is public domain and comes with no warranty. <br/>

* Note: works only if class attribute is the last attribute in the dataset.

*

* @param className the name that should be given to the source class.

* @return the object source described by a string

* @throws Exception if the source can't be computed

*/

public String toSource(String className) throws Exception {

StringBufferresult

int id

result = new StringBuffer()

result.append("class " + className + " {\n")

result.append(" private static void checkMissing(Object[] i, int index) {\n")

result.append("if (i[index] == null)\n")

result.append(" throw new IllegalArgumentException(\"Null values "

+ "are not allowed!\")\n")

result.append(" }\n\n")

result.append(" public static double classify(Object[] i) {\n")

id = 0

result.append("return node" + id + "(i)\n")

result.append(" }\n")

toSource(id, result)

result.append("}\n")

return result.toString()

}

/**

* Returns the revision string.

*

* @returnthe revision

*/

public String getRevision() {

return RevisionUtils.extract("$Revision: 6404 $")

}

/**

* Main method.

*

* @param args the options for the classifier

*/

public static void main(String[] args) {

runClassifier(new Id3(), args)

}

}