Banker's algorithm: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
m (syntax highlighting fixup automation)
Line 42: Line 42:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V resources = Int(input(‘Cantidad de recursos: ’))
<syntaxhighlight lang=11l>V resources = Int(input(‘Cantidad de recursos: ’))
V processes = Int(input(‘Cantidad de procesos: ’))
V processes = Int(input(‘Cantidad de procesos: ’))
V max_resources = input(‘Recursos máximos: ’).split_py().map(i -> Int(i))
V max_resources = input(‘Recursos máximos: ’).split_py().map(i -> Int(i))
Line 84: Line 84:
L.break
L.break


print("El proceso está en un estado seguro.\nRecursos disponibles: #.\n".format(available))</lang>
print("El proceso está en un estado seguro.\nRecursos disponibles: #.\n".format(available))</syntaxhighlight>


{{out}}
{{out}}
Line 122: Line 122:


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.
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.
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include <stdbool.h>
#include <stdbool.h>


Line 234: Line 234:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out|Input and Output}}
{{out|Input and Output}}
<pre>Enter the number of resources: 4
<pre>Enter the number of resources: 4
Line 287: Line 287:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang freebasic>
<syntaxhighlight lang=freebasic>
Dim As Integer i, j, r, p
Dim As Integer i, j, r, p
Input "Ingrese la cantidad de recursos: ", r
Input "Ingrese la cantidad de recursos: ", r
Line 379: Line 379:
Loop
Loop
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 420: Line 420:


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.
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.
<lang go>package bank
<syntaxhighlight lang=go>package bank


import (
import (
Line 581: Line 581:
perm[h] = perm[m]
perm[h] = perm[m]
}
}
}</lang>
}</syntaxhighlight>
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 609: Line 609:
fmt.Println("\nP3 request:")
fmt.Println("\nP3 request:")
fmt.Println(b.Request("P3", bank.RMap{"A": 1, "B": 2, "C": 1}))
fmt.Println(b.Request("P3", bank.RMap{"A": 1, "B": 2, "C": 1}))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 631: Line 631:
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.
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.


<lang j>bankrun=:1 :0
<syntaxhighlight lang=j>bankrun=:1 :0
'MAX ALLOC TOTAL'=. y
'MAX ALLOC TOTAL'=. y
todo=.(#ALLOC)#1
todo=.(#ALLOC)#1
Line 659: Line 659:
end.
end.
echo 'DONE'
echo 'DONE'
)</lang>
)</syntaxhighlight>


Definitions for task example:
Definitions for task example:


<lang j>max=: 3 3 2 2,1 2 3 4,:1 3 5 0
<syntaxhighlight 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
alloc=: 1 2 2 1,1 0 3 3,:1 2 1 0
total=:6 5 7 6
total=:6 5 7 6
Line 670: Line 670:
NB. left arg: newly available resources, right: previously available
NB. left arg: newly available resources, right: previously available
NB. result: resources freed
NB. result: resources freed
run=: +</lang>
run=: +</syntaxhighlight>


Example run:
Example run:


<lang J> run bankrun max;alloc;total
<syntaxhighlight lang=J> run bankrun max;alloc;total
currently available: 3 1 1 2
currently available: 3 1 1 2
running process 0, allocating 2 1 0 1
running process 0, allocating 2 1 0 1
Line 684: Line 684:
running process 2, allocating 0 1 4 0
running process 2, allocating 0 1 4 0
process 2 freeing 1 3 5 0
process 2 freeing 1 3 5 0
DONE</lang>
DONE</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang julia>function queryprompt(query, typ)
<syntaxhighlight lang=julia>function queryprompt(query, typ)
print(query, ": ")
print(query, ": ")
entry = uppercase(strip(readline(stdin)))
entry = uppercase(strip(readline(stdin)))
Line 753: Line 753:


testbankers()
testbankers()
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
Enter the number of resources: 4
Enter the number of resources: 4
Line 820: Line 820:
{{trans|C}}
{{trans|C}}
For simplicity, input checking is ignored:
For simplicity, input checking is ignored:
<lang scala>// version 1.1.4-3
<syntaxhighlight lang=scala>// version 1.1.4-3


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 888: Line 888:
println("\nAvailable Vector: ${avl.joinToString(" ")}")
println("\nAvailable Vector: ${avl.joinToString(" ")}")
}
}
}</lang>
}</syntaxhighlight>


Sample input/output:
Sample input/output:
Line 943: Line 943:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module BankerAlgo {
Module BankerAlgo {
Form 80, 44
Form 80, 44
Line 1,112: Line 1,112:
End Sub
End Sub
}
}
BankerAlgo</lang>
BankerAlgo</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang Nim>import sequtils, strformat, strutils, sugar
<syntaxhighlight lang=Nim>import sequtils, strformat, strutils, sugar


stdout.write "Enter the number of resources: "
stdout.write "Enter the number of resources: "
Line 1,173: Line 1,173:


echo "\nThe process is in a safe state."
echo "\nThe process is in a safe state."
echo &"Available Vector: {avl.join(\" \")}"</lang>
echo &"Available Vector: {avl.join(\" \")}"</syntaxhighlight>


{{out}}
{{out}}
Line 1,222: Line 1,222:
=={{header|Perl}}==
=={{header|Perl}}==
{{trans|Raku}}
{{trans|Raku}}
<lang perl>use strict;
<syntaxhighlight lang=perl>use strict;
use warnings;
use warnings;
use feature 'say';
use feature 'say';
Line 1,277: Line 1,277:
my($safe_state,$status_message) = isSafe(\@avail, \@maxm, \@allot);
my($safe_state,$status_message) = isSafe(\@avail, \@maxm, \@allot);
say "Safe state? " . ($safe_state ? 'True' : 'False');
say "Safe state? " . ($safe_state ? 'True' : 'False');
say "Message: $status_message";</lang>
say "Message: $status_message";</syntaxhighlight>
{{out}}
{{out}}
<pre>available resources: 4 3 3 3
<pre>available resources: 4 3 3 3
Line 1,286: Line 1,286:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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: Line 1,341:
<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: #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>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,364: Line 1,364:


=={{header|Python}}==
=={{header|Python}}==
<lang python>
<syntaxhighlight lang=python>
def main():
def main():
resources = int(input("Cantidad de recursos: "))
resources = int(input("Cantidad de recursos: "))
Line 1,413: Line 1,413:
if __name__ == '__main__':
if __name__ == '__main__':
main()
main()
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,448: Line 1,448:
=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>#lang racket/base
<syntaxhighlight lang=racket>#lang racket/base
(require racket/block racket/pretty racket/port racket/vector)
(require racket/block racket/pretty racket/port racket/vector)


Line 1,532: Line 1,532:


EOS
EOS
(λ () (call-with-values bankers-input bankers-algorithm))))</lang>
(λ () (call-with-values bankers-input bankers-algorithm))))</syntaxhighlight>


{{out}}
{{out}}
Line 1,583: Line 1,583:
Based on the Python3 solution by Shubham Singh found
Based on the Python3 solution by Shubham Singh found
[https://www.geeksforgeeks.org/program-bankers-algorithm-set-1-safety-algorithm/ here]
[https://www.geeksforgeeks.org/program-bankers-algorithm-set-1-safety-algorithm/ here]
<lang perl6>my @avail = <3 1 1 2>; # Available instances of resource
<syntaxhighlight lang=raku lines>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 @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
my @allot = <1 2 2 1>, <1 0 3 3>, <1 2 1 0>; # Resources allocated to processes
Line 1,619: Line 1,619:
my ($safe-state,$status-message) = isSafe @avail, @maxm, @allot;
my ($safe-state,$status-message) = isSafe @avail, @maxm, @allot;
say "Safe state? $safe-state";
say "Safe state? $safe-state";
say "Message: $status-message";</lang>
say "Message: $status-message";</syntaxhighlight>
{{out}}
{{out}}
<pre>available resources: 4 3 3 3
<pre>available resources: 4 3 3 3
Line 1,631: Line 1,631:
Adapted from the C language version. It crashes for invalid input.
Adapted from the C language version. It crashes for invalid input.


<lang rust>
<syntaxhighlight lang=rust>
fn read_numbers<T>() -> Vec<T>
fn read_numbers<T>() -> Vec<T>
where T: std::str::FromStr {
where T: std::str::FromStr {
Line 1,750: Line 1,750:
println!();
println!();
}
}
}</lang>
}</syntaxhighlight>


{{out|Input and Output}}
{{out|Input and Output}}
Line 1,803: Line 1,803:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>import Foundation
<syntaxhighlight lang=swift>import Foundation


print("Enter the number of resources: ", terminator: "")
print("Enter the number of resources: ", terminator: "")
Line 1,906: Line 1,906:


print("The available vector is: \(available)")
print("The available vector is: \(available)")
}</lang>
}</syntaxhighlight>


{{out|Input and Output}}
{{out|Input and Output}}
Line 1,948: Line 1,948:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>import "io" for Stdin, Stdout
<syntaxhighlight lang=ecmascript>import "io" for Stdin, Stdout


System.write("Enter the number of resources: ")
System.write("Enter the number of resources: ")
Line 2,020: Line 2,020:
System.write("\nThe process is in a safe state.")
System.write("\nThe process is in a safe state.")
System.print("\nAvailable Vector: %(avl.join(" "))")
System.print("\nAvailable Vector: %(avl.join(" "))")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,078: Line 2,078:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang yabasic>
<syntaxhighlight lang=yabasic>
clear screen
clear screen
input "Ingrese la cantidad de recursos: " r
input "Ingrese la cantidad de recursos: " r
Line 2,171: Line 2,171:
print
print
end
end
</syntaxhighlight>
</lang>