Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the programming language of this snippet from Elixir to VB without modifying what it does. | defmodule Priority do
def create, do: :gb_trees.empty
def insert( element, priority, queue ), do: :gb_trees.enter( priority, element, queue )
def peek( queue ) do
{_priority, element, _new_queue} = :gb_trees.take_smallest( queue )
element
end
def task do
items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}]
queue = Enum.reduce(items, create, fn({priority, element}, acc) -> insert( element, priority, acc ) end)
IO.puts "peek priority:
Enum.reduce(1..length(items), queue, fn(_n, q) -> write_top( q ) end)
end
def top( queue ) do
{_priority, element, new_queue} = :gb_trees.take_smallest( queue )
{element, new_queue}
end
defp write_top( q ) do
{element, new_queue} = top( q )
IO.puts "top priority:
new_queue
end
end
Priority.task
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Change the programming language of this snippet from Elixir to VB without modifying what it does. | defmodule Priority do
def create, do: :gb_trees.empty
def insert( element, priority, queue ), do: :gb_trees.enter( priority, element, queue )
def peek( queue ) do
{_priority, element, _new_queue} = :gb_trees.take_smallest( queue )
element
end
def task do
items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}]
queue = Enum.reduce(items, create, fn({priority, element}, acc) -> insert( element, priority, acc ) end)
IO.puts "peek priority:
Enum.reduce(1..length(items), queue, fn(_n, q) -> write_top( q ) end)
end
def top( queue ) do
{_priority, element, new_queue} = :gb_trees.take_smallest( queue )
{element, new_queue}
end
defp write_top( q ) do
{element, new_queue} = top( q )
IO.puts "top priority:
new_queue
end
end
Priority.task
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Change the programming language of this snippet from Elixir to Go without modifying what it does. | defmodule Priority do
def create, do: :gb_trees.empty
def insert( element, priority, queue ), do: :gb_trees.enter( priority, element, queue )
def peek( queue ) do
{_priority, element, _new_queue} = :gb_trees.take_smallest( queue )
element
end
def task do
items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}]
queue = Enum.reduce(items, create, fn({priority, element}, acc) -> insert( element, priority, acc ) end)
IO.puts "peek priority:
Enum.reduce(1..length(items), queue, fn(_n, q) -> write_top( q ) end)
end
def top( queue ) do
{_priority, element, new_queue} = :gb_trees.take_smallest( queue )
{element, new_queue}
end
defp write_top( q ) do
{element, new_queue} = top( q )
IO.puts "top priority:
new_queue
end
end
Priority.task
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Generate a Go translation of this Elixir snippet without changing its computational steps. | defmodule Priority do
def create, do: :gb_trees.empty
def insert( element, priority, queue ), do: :gb_trees.enter( priority, element, queue )
def peek( queue ) do
{_priority, element, _new_queue} = :gb_trees.take_smallest( queue )
element
end
def task do
items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}]
queue = Enum.reduce(items, create, fn({priority, element}, acc) -> insert( element, priority, acc ) end)
IO.puts "peek priority:
Enum.reduce(1..length(items), queue, fn(_n, q) -> write_top( q ) end)
end
def top( queue ) do
{_priority, element, new_queue} = :gb_trees.take_smallest( queue )
{element, new_queue}
end
defp write_top( q ) do
{element, new_queue} = top( q )
IO.puts "top priority:
new_queue
end
end
Priority.task
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Generate a C translation of this Erlang snippet without changing its computational steps. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Erlang code. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Port the following code from Erlang to C# with equivalent syntax and logic. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Generate an equivalent C# version of this Erlang code. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Port the following code from Erlang to C++ with equivalent syntax and logic. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Change the programming language of this snippet from Erlang to C++ without modifying what it does. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Produce a language-to-language conversion: from Erlang to Java, same semantics. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Port the provided Erlang code into Java while preserving the original functionality. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Keep all operations the same but rewrite the snippet in Python. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Produce a language-to-language conversion: from Erlang to Python, same semantics. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Convert this Erlang block to VB, preserving its control flow and logic. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Maintain the same structure and functionality when rewriting this code in VB. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Convert this Erlang snippet to Go and keep its semantics consistent. | -module( priority_queue ).
-export( [create/0, insert/3, peek/1, task/0, top/1] ).
create() -> gb_trees:empty().
insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ).
peek( Queue ) ->
{_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ),
Element.
task() ->
Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}],
Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ),
io:fwrite( "peek priority: ~p~n", [peek( Queue )] ),
lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ).
top( Queue ) ->
{_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ),
{Element, New_queue}.
write_top( Q ) ->
{Element, New_queue} = top( Q ),
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Write the same algorithm in C as shown in this F# implementation. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Convert this F# snippet to C and keep its semantics consistent. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Port the following code from F# to C# with equivalent syntax and logic. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Convert this F# snippet to C# and keep its semantics consistent. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Write a version of this F# function in C++ with identical behavior. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Port the provided F# code into C++ while preserving the original functionality. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Translate this program into Java but keep the logic exactly as in F#. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Produce a language-to-language conversion: from F# to Java, same semantics. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Transform the following F# implementation into Python, maintaining the same output and logic. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Translate the given F# code snippet into Python without altering its behavior. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Transform the following F# implementation into VB, maintaining the same output and logic. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Please provide an equivalent version of this F# code in VB. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Convert this F# snippet to Go and keep its semantics consistent. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Write a version of this F# function in Go with identical behavior. | [<RequireQualifiedAccess>]
module PriorityQ =
type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end
type 'a tree = Node of uint32 * 'a treeElement * 'a tree list
type 'a heap = 'a tree list
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
[<NoEquality; NoComparison>]
type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap
let empty = HeapEmpty
let isEmpty = function | HeapEmpty -> true | _ -> false
let inline private rank (Node(r,_,_)) = r
let inline private root (Node(_,x,_)) = x
exception Empty_Heap
let peekMin = function | HeapEmpty -> None
| HeapNotEmpty(min, _) -> Some (min.k, min.v)
let rec private findMin heap =
match heap with | [] -> raise Empty_Heap
| [node] -> root node,[]
| topnode::heap' ->
let min,subheap = findMin heap' in let rtn = root topnode
match subheap with
| [] -> if rtn.k > min.k then min,[] else rtn,[]
| minnode::heap'' ->
let rmn = root minnode
if rtn.k <= rmn.k then rtn,heap
else rmn,minnode::topnode::heap''
let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) =
if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2)
else Node(r+1u,kv1,tree2::ts1)
let rec private insTree (newnode: 'a tree) heap =
match heap with
| [] -> [newnode]
| topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap
else insTree (mergeTree newnode topnode) heap'
let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[])
function | HeapEmpty -> HeapNotEmpty(kv,[nn])
| HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv
HeapNotEmpty(nmin,insTree nn heap)
let rec private merge' heap1 heap2 =
match heap1,heap2 with
| _,[] -> heap1
| [],_ -> heap2
| topheap1::heap1',topheap2::heap2' ->
match compare (rank topheap1) (rank topheap2) with
| -1 -> topheap1::merge' heap1' heap2
| 1 -> topheap2::merge' heap1 heap2'
| _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2')
let merge oheap1 oheap2 = match oheap1,oheap2 with
| _,HeapEmpty -> oheap1
| HeapEmpty,_ -> oheap2
| HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) ->
let min = if min1.k > min2.k then min2 else min1
HeapNotEmpty(min,merge' heap1 heap2)
let rec private removeMinTree = function
| [] -> raise Empty_Heap
| [node] -> node,[]
| t::ts -> let t',ts' = removeMinTree ts
if (root t).k <= (root t').k then t,ts else t',t::ts'
let deleteMin =
function | HeapEmpty -> HeapEmpty
| HeapNotEmpty(_,heap) ->
match heap with
| [] -> HeapEmpty
| [Node(_,_,heap')] -> match heap' with
| [] -> HeapEmpty
| _ -> let min,_ = findMin heap'
HeapNotEmpty(min,heap')
| _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap
let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap
HeapNotEmpty(min,nheap)
let replaceMin k v pq = push k v (deleteMin pq)
let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq
let popMin pq = match peekMin pq with
| None -> None
| Some(kv) -> Some(kv, deleteMin pq)
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Generate an equivalent C version of this Factor code. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Translate the given Factor code snippet into C without altering its behavior. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Generate an equivalent C# version of this Factor code. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Change the following Factor code into C# without altering its purpose. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Factor. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Transform the following Factor implementation into Java, maintaining the same output and logic. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Generate an equivalent Python version of this Factor code. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Convert the following code from Factor to Python, ensuring the logic remains intact. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Produce a functionally identical VB code for the snippet given in Factor. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Maintain the same structure and functionality when rewriting this code in VB. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Generate an equivalent Go version of this Factor code. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Change the following Factor code into Go without altering its purpose. | <min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Produce a language-to-language conversion: from Forth to C, same semantics. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Forth to C. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Convert this Forth snippet to C# and keep its semantics consistent. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Can you help me rewrite this code in C# instead of Forth, keeping it the same logically? | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Translate this program into C++ but keep the logic exactly as in Forth. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Please provide an equivalent version of this Forth code in C++. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Rewrite the snippet below in Java so it works the same as the original Forth code. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Transform the following Forth implementation into Python, maintaining the same output and logic. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Preserve the algorithm and functionality while converting the code from Forth to Python. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Preserve the algorithm and functionality while converting the code from Forth to VB. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Transform the following Forth implementation into VB, maintaining the same output and logic. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Convert the following code from Forth to Go, ensuring the logic remains intact. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Translate this program into Go but keep the logic exactly as in Forth. | #! /usr/bin/gforth
10 CONSTANT INITIAL-CAPACITY
: new-queue
2 INITIAL-CAPACITY 3 * + cells allocate throw
INITIAL-CAPACITY over !
0 over cell + !
;
: delete-queue
free throw
;
: queue-capacity
@
;
: queue-size
cell + @
;
: resize-queue
dup queue-capacity 2 * dup >r 3 * 2 + cells resize throw
r> over !
;
: ix->addr
3 * 2 + cells +
;
: ix!
ix->addr
tuck 2 cells + !
tuck cell + !
!
;
: ix@
ix->addr
dup @ swap
cell + dup @ swap
cell + @
;
: ix->priority
ix->addr @
;
: ix<->ix
-rot over swap
2over swap 2>r
2dup ix@ 2>r >r
2>r
swap ix@
2r> ix!
r> 2r> 2r> ix!
;
: ix-parent
dup 0> IF
1- 2/
THEN
;
: ix-left-son
2* 1+
;
: ix-right-son
2* 2 +
;
: swap?
rot >r
2dup
r> tuck swap
ix->priority >r
tuck swap
ix->priority r>
> IF
-rot ix<->ix
true
ELSE
2drop drop
false
THEN
;
: ix?
swap queue-size <
;
: bubble-up
2dup dup ix-parent swap
swap? IF
ix-parent recurse
ELSE
2drop
THEN
;
: bubble-down
2dup ix-right-son ix? IF
2dup ix-left-son ix->priority >r
2dup ix-right-son ix->priority r> < IF
2dup dup ix-right-son swap? IF
ix-right-son recurse
ELSE
2drop
THEN
ELSE
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
THEN
ELSE
2dup ix-left-son ix? IF
2dup dup ix-left-son swap? IF
ix-left-son recurse
ELSE
2drop
THEN
ELSE
2drop
THEN
THEN
;
: >queue
dup queue-capacity over queue-size =
IF
resize-queue
THEN
dup >r
dup queue-size
ix!
r>
1 over cell + +!
dup dup queue-size 1- bubble-up
;
: queue>
dup queue-size 0= IF
1 throw
THEN
dup 0 ix@ 2>r >r dup >r
dup dup queue-size 1- ix@ r> 0 ix!
dup cell + -1 swap +!
0 bubble-down
r> 2r>
;
: drain-queue
dup queue-size 0> IF
dup queue>
rot
. ." - " type cr
recurse
ELSE
drop
THEN
;
new-queue
>r 3 s" Clear drains" r> >queue
>r 4 s" Feed cat" r> >queue
>r 5 s" Make tea" r> >queue
>r 1 s" Solve RC tasks" r> >queue
>r 2 s" Tax return" r> >queue
drain-queue
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Produce a language-to-language conversion: from Fortran to C#, same semantics. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Convert the following code from Fortran to C#, ensuring the logic remains intact. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Generate an equivalent C++ version of this Fortran code. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Fortran code. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Convert the following code from Fortran to C, ensuring the logic remains intact. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Fortran version. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Fortran version. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Change the following Fortran code into Java without altering its purpose. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Produce a functionally identical Python code for the snippet given in Fortran. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Change the programming language of this snippet from Fortran to Python without modifying what it does. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Translate this program into VB but keep the logic exactly as in Fortran. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Convert the following code from Fortran to VB, ensuring the logic remains intact. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Preserve the algorithm and functionality while converting the code from Fortran to PHP. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| <?php
$pq = new SplPriorityQueue;
$pq->insert('Clear drains', 3);
$pq->insert('Feed cat', 4);
$pq->insert('Make tea', 5);
$pq->insert('Solve RC tasks', 1);
$pq->insert('Tax return', 2);
$pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
while (!$pq->isEmpty()) {
print_r($pq->extract());
}
?>
|
Transform the following Fortran implementation into PHP, maintaining the same output and logic. | module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
| <?php
$pq = new SplPriorityQueue;
$pq->insert('Clear drains', 3);
$pq->insert('Feed cat', 4);
$pq->insert('Make tea', 5);
$pq->insert('Solve RC tasks', 1);
$pq->insert('Tax return', 2);
$pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
while (!$pq->isEmpty()) {
print_r($pq->extract());
}
?>
|
Write a version of this Groovy function in C with identical behavior. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Can you help me rewrite this code in C instead of Groovy, keeping it the same logically? | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Generate an equivalent C# version of this Groovy code. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Ensure the translated C# code behaves exactly like the original Groovy snippet. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Generate a C++ translation of this Groovy snippet without changing its computational steps. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Translate the given Groovy code snippet into C++ without altering its behavior. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Write the same code in Java as shown below in Groovy. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Preserve the algorithm and functionality while converting the code from Groovy to Java. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Generate a Python translation of this Groovy snippet without changing its computational steps. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Can you help me rewrite this code in Python instead of Groovy, keeping it the same logically? | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Produce a language-to-language conversion: from Groovy to VB, same semantics. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Convert the following code from Groovy to VB, ensuring the logic remains intact. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Transform the following Groovy implementation into Go, maintaining the same output and logic. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Transform the following Groovy implementation into Go, maintaining the same output and logic. | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add new Task(priority: 5, name: 'Make tea')
add new Task(priority: 1, name: 'Solve RC tasks')
add new Task(priority: 2, name: 'Tax return')
while (!empty) { println remove() }
}
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Write the same code in C as shown below in Haskell. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Translate the given Haskell code snippet into C without altering its behavior. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Generate a C# translation of this Haskell snippet without changing its computational steps. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Port the provided Haskell code into C# while preserving the original functionality. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Haskell code. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Transform the following Haskell implementation into C++, maintaining the same output and logic. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Convert the following code from Haskell to Java, ensuring the logic remains intact. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Haskell version. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Translate the given Haskell code snippet into Python without altering its behavior. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Maintain the same structure and functionality when rewriting this code in Python. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Convert this Haskell snippet to VB and keep its semantics consistent. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Generate an equivalent VB version of this Haskell code. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Rewrite this program in Go while keeping its functionality equivalent to the Haskell version. | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.