Banker's algorithm: Difference between revisions

m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
 
(6 intermediate revisions by 4 users not shown)
Line 41:
=={{header|11l}}==
{{trans|Python}}
{{todo|Python|Translate all Spanish texts to English}}
 
<langsyntaxhighlight lang="11l">V resources = Int(input(‘Cantidad de recursos: ’))
V processes = Int(input(‘Cantidad de procesos: ’))
V max_resources = input(‘Recursos máximos: ’).split_py().map(i -> Int(i))
Line 84 ⟶ 85:
L.break
 
print("El proceso está en un estado seguro.\nRecursos disponibles: #.\n".format(available))</langsyntaxhighlight>
 
{{out}}
Line 122 ⟶ 123:
 
There are two <code>main()</code> functions to choose from (look for <code>#define BIG_EXAMPLE</code>), one is for task example, the other is a much heavier duty test case.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdbool.h>
 
Line 234 ⟶ 235:
 
return 0;
}</langsyntaxhighlight>
{{out|Input and Output}}
<pre>Enter the number of resources: 4
Line 287 ⟶ 288:
=={{header|FreeBASIC}}==
{{trans|Kotlin}}
{{todo|Python|Translate all Spanish texts to English}}
<lang freebasic>
<syntaxhighlight lang="freebasic">
Dim As Integer i, j, r, p
Input "Ingrese la cantidad de recursos: ", r
Line 379 ⟶ 381:
Loop
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 420 ⟶ 422:
 
This solution is more inspired by EWD-623 than WP. EWD-623, while it talks of finding a permutation of processes, notes that the "ordering effort" can be stopped as soon as the process requesting resources happens to be found satisfiable. The solution here attempts to make this finding as soon as possible by moving the process to the front of a list of unsatisfied processes. Also since the solved permutation of satisfied processes has no use, it is not kept which simplifies the algorithm a bit.
<langsyntaxhighlight lang="go">package bank
 
import (
Line 581 ⟶ 583:
perm[h] = perm[m]
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">package main
 
import (
Line 609 ⟶ 611:
fmt.Println("\nP3 request:")
fmt.Println(b.Request("P3", bank.RMap{"A": 1, "B": 2, "C": 1}))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 631 ⟶ 633:
The task description currently does not define the process being run. So we follow the example set by other implementations and have each process free all resources after successfully being run. Also, since this is a demo, we give a blow-by-blow description of what's happening as it runs.
 
<langsyntaxhighlight lang="j">bankrun=:1 :0
'MAX ALLOC TOTAL'=. y
todo=.(#ALLOC)#1
Line 659 ⟶ 661:
end.
echo 'DONE'
)</langsyntaxhighlight>
 
Definitions for task example:
 
<langsyntaxhighlight lang="j">max=: 3 3 2 2,1 2 3 4,:1 3 5 0
alloc=: 1 2 2 1,1 0 3 3,:1 2 1 0
total=:6 5 7 6
Line 670 ⟶ 672:
NB. left arg: newly available resources, right: previously available
NB. result: resources freed
run=: +</langsyntaxhighlight>
 
Example run:
 
<langsyntaxhighlight Jlang="j"> run bankrun max;alloc;total
currently available: 3 1 1 2
running process 0, allocating 2 1 0 1
Line 684 ⟶ 686:
running process 2, allocating 0 1 4 0
process 2 freeing 1 3 5 0
DONE</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="julia">function queryprompt(query, typ)
print(query, ": ")
entry = uppercase(strip(readline(stdin)))
Line 753 ⟶ 755:
 
testbankers()
</langsyntaxhighlight>{{out}}
<pre>
Enter the number of resources: 4
Line 820 ⟶ 822:
{{trans|C}}
For simplicity, input checking is ignored:
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
fun main(args: Array<String>) {
Line 888 ⟶ 890:
println("\nAvailable Vector: ${avl.joinToString(" ")}")
}
}</langsyntaxhighlight>
 
Sample input/output:
Line 943 ⟶ 945:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module BankerAlgo {
Form 80, 44
Line 1,112 ⟶ 1,114:
End Sub
}
BankerAlgo</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import sequtils, strformat, strutils, sugar
 
stdout.write "Enter the number of resources: "
Line 1,173 ⟶ 1,175:
 
echo "\nThe process is in a safe state."
echo &"Available Vector: {avl.join(\" \")}"</langsyntaxhighlight>
 
{{out}}
Line 1,222 ⟶ 1,224:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,277 ⟶ 1,279:
my($safe_state,$status_message) = isSafe(\@avail, \@maxm, \@allot);
say "Safe state? " . ($safe_state ? 'True' : 'False');
say "Message: $status_message";</langsyntaxhighlight>
{{out}}
<pre>available resources: 4 3 3 3
Line 1,286 ⟶ 1,288:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">max_res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
Line 1,341 ⟶ 1,343:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Safe state. Available resources: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">avl</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,364 ⟶ 1,366:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
def main():
resources = int(input("CantidadNumber deof recursosresources: "))
processes = int(input("CantidadNumber deof procesosprocesses: "))
max_resources = [int(i) for i in input("RecursosMaximum máximosresources: ").split()]
 
print("\n-- recursosresources asignadosallocated parafor cada procesoeach process --")
currently_allocated = [[int(i) for i in input(f"procesoprocess {j + 1}: ").split()] for j in range(processes)]
 
print("\n--- recursosmaximum máximosresources parafor cada procesoeach process ---")
max_need = [[int(i) for i in input(f"procesoprocess {j + 1}: ").split()] for j in range(processes)]
 
allocated = [0] * resources
Line 1,380 ⟶ 1,382:
for j in range(resources):
allocated[j] += currently_allocated[i][j]
print(f"\nRecursos totales asignadosnTotal resources allocated: {allocated}")
 
available = [max_resources[i] - allocated[i] for i in range(resources)]
print(f"RecursosTotal totalesresources disponiblesavailable: {available}\n")
 
running = [True] * processes
Line 1,397 ⟶ 1,399:
break
if executing:
print(f"procesoprocess {i + 1} ejecutándoserunning")
running[i] = False
count -= 1
Line 1,405 ⟶ 1,407:
break
if not safe:
print("ElThe procesoprocess estáis enin unan estadounsafe insegurostate.")
break
 
print(f"ElThe procesoprocess estáis enin una estadosafe segurostate.\nRecursosnAvailable disponiblesresources: {available}\n\n")
 
 
if __name__ == '__main__':
main()
</syntaxhighlight>
</lang>
{{out}}
<pre>
CantidadNumber deof recursosresources: 4
CantidadNumber deof procesosprocesses: 3
RecursosMaximum máximosresources: 6 5 7 6
 
-- recursosresources asignadosallocated parafor cadaeach procesoprocess --
procesoprocess 1: 1 2 2 1
procesoprocess 2: 1 0 3 3
procesoprocess 3: 1 2 1 0
 
--- recursosmaximum máximosresources parafor cada procesoeach process ---
procesoprocess 1: 3 3 2 2
procesoprocess 2: 1 2 3 4
procesoprocess 3: 1 3 5 0
 
Recursos totales asignadosTotal resources allocated: [3, 4, 6, 4]
RecursosTotal totalesresources disponiblesavailable: [3, 1, 1, 2]
 
process 1 running
proceso 1 ejecutándose
The process is in a safe state.
El proceso está en un estado seguro.
RecursosAvailable disponiblesresources: [4, 3, 3, 3]
 
process 2 running
proceso 2 ejecutándose
The process is in a safe state.
El proceso está en un estado seguro.
RecursosAvailable disponiblesresources: [5, 3, 6, 6]
 
process 3 running
proceso 3 ejecutándose
The process is in a safe state.
El proceso está en un estado seguro.
RecursosAvailable disponiblesresources: [6, 5, 7, 6]
</pre>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/block racket/pretty racket/port racket/vector)
 
Line 1,532 ⟶ 1,534:
 
EOS
(λ () (call-with-values bankers-input bankers-algorithm))))</langsyntaxhighlight>
 
{{out}}
Line 1,583 ⟶ 1,585:
Based on the Python3 solution by Shubham Singh found
[https://www.geeksforgeeks.org/program-bankers-algorithm-set-1-safety-algorithm/ here]
<syntaxhighlight lang="raku" perl6line>my @avail = <3 1 1 2>; # Available instances of resource
my @maxm = <3 3 2 2>, <1 2 3 4>, <1 3 5 0>; # Maximum resources that can be allocated to processes
my @allot = <1 2 2 1>, <1 0 3 3>, <1 2 1 0>; # Resources allocated to processes
Line 1,619 ⟶ 1,621:
my ($safe-state,$status-message) = isSafe @avail, @maxm, @allot;
say "Safe state? $safe-state";
say "Message: $status-message";</langsyntaxhighlight>
{{out}}
<pre>available resources: 4 3 3 3
Line 1,631 ⟶ 1,633:
Adapted from the C language version. It crashes for invalid input.
 
<langsyntaxhighlight lang="rust">
fn read_numbers<T>() -> Vec<T>
where T: std::str::FromStr {
Line 1,750 ⟶ 1,752:
println!();
}
}</langsyntaxhighlight>
 
{{out|Input and Output}}
Line 1,799 ⟶ 1,801:
The process is in safe state.
The available vector is: 8 5 9 7
</pre>
 
=={{header|Scala}}==
{{trans|Python}}
<syntaxhighlight lang="Scala">
import scala.io.StdIn.readLine
 
object BankersAlgorithm {
def main(args: Array[String]): Unit = {
println("Number of resources: ")
val resources = readLine().toInt
 
println("Number of processes: ")
val processes = readLine().toInt
 
println("Maximum resources: ")
val maxResources = readLine().split(" ").map(_.toInt)
 
println("\n-- resources allocated for each process --")
val currentlyAllocated = Array.ofDim[Int](processes, resources)
for (i <- 0 until processes) {
println(s"process ${i + 1}: ")
currentlyAllocated(i) = readLine().split(" ").map(_.toInt)
}
 
println("\n--- maximum resources for each process ---")
val maxNeed = Array.ofDim[Int](processes, resources)
for (i <- 0 until processes) {
println(s"process ${i + 1}: ")
maxNeed(i) = readLine().split(" ").map(_.toInt)
}
 
val allocated = Array.fill(resources)(0)
for (i <- 0 until processes) {
for (j <- 0 until resources) {
allocated(j) += currentlyAllocated(i)(j)
}
}
println(s"\nTotal resources allocated: ${allocated.mkString(", ")}")
 
val available = maxResources.zip(allocated).map { case (max, alloc) => max - alloc }
println(s"Total resources available: ${available.mkString(", ")}\n")
 
var running = Array.fill(processes)(true)
var count = processes
 
while (count != 0) {
var safe = false
for (i <- 0 until processes if running(i)) {
var executing = true
for (j <- 0 until resources) {
if (maxNeed(i)(j) - currentlyAllocated(i)(j) > available(j)) {
executing = false
}
}
if (executing) {
println(s"process ${i + 1} is running")
running(i) = false
count -= 1
safe = true
for (j <- 0 until resources) {
available(j) += currentlyAllocated(i)(j)
}
}
}
 
if (!safe) {
println("The processes are in an unsafe state.")
return
}
 
println(s"The processes are in a safe state.\nAvailable resources: ${available.mkString(", ")}\n")
}
}
}
</syntaxhighlight>
 
'''input'''
 
<pre>
4
3
6 5 7 6
1 2 2 1
1 0 3 3
1 2 1 0
3 3 2 2
1 2 3 4
1 3 5 0
</pre>
{{out}}
<pre>
Number of resources: 4
Number of processes: 3
Maximum resources: 6 5 7 6
 
-- resources allocated for each process --
process 1: 1 2 2 1
process 2: 1 0 3 3
process 3: 1 2 1 0
 
--- maximum resources for each process ---
process 1: 3 3 2 2
process 2: 1 2 3 4
process 3: 1 3 5 0
 
Total resources allocated: 3, 4, 6, 4
Total resources available: 3, 1, 1, 2
 
process 1 is running
process 2 is running
process 3 is running
The processes are in a safe state.
Available resources: 6, 5, 7, 6
 
 
</pre>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
print("Enter the number of resources: ", terminator: "")
Line 1,906 ⟶ 2,024:
 
print("The available vector is: \(available)")
}</langsyntaxhighlight>
 
{{out|Input and Output}}
Line 1,948 ⟶ 2,066:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Stdin, Stdout
 
System.write("Enter the number of resources: ")
Line 2,020 ⟶ 2,138:
System.write("\nThe process is in a safe state.")
System.print("\nAvailable Vector: %(avl.join(" "))")
}</langsyntaxhighlight>
 
{{out}}
Line 2,074 ⟶ 2,192:
Available Vector: 8 5 9 7
</pre>
 
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
{{todo|Python|Translate all Spanish texts to English}}
<lang yabasic>
<syntaxhighlight lang="yabasic">
clear screen
input "Ingrese la cantidad de recursos: " r
Line 2,171 ⟶ 2,289:
print
end
</syntaxhighlight>
</lang>
 
 
338

edits