Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
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)) } }
Convert this J block to C, preserving its control flow and logic.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
#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; }
Produce a functionally identical C code for the snippet given in J.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
#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; }
Ensure the translated C# code behaves exactly like the original J snippet.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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 J code.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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 J code.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
#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 this J snippet to C++ and keep its semantics consistent.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
#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 J code in Java.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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()); } }
Convert this J snippet to Java and keep its semantics consistent.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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 J code into Python without altering its purpose.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
>>> 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') >>>
Generate a Python translation of this J snippet without changing its computational steps.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
>>> 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 J to VB without modifying what it does.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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
Port the following code from J to VB with equivalent syntax and logic.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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 J block to Go, preserving its control flow and logic.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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 J implementation into Go, maintaining the same output and logic.
coclass 'priorityQueue' PRI=: '' QUE=: '' insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 ) topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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 Julia implementation into C, maintaining the same output and logic.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
#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; }
Change the following Julia code into C without altering its purpose.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
#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 Julia to C#.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
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 Julia function in C# with identical behavior.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
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 Julia block to C++, preserving its control flow and logic.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
#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 C++.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
#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.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
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()); } }
Write the same code in Java as shown below in Julia.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
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 Julia code.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
>>> 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') >>>
Write the same code in Python as shown below in Julia.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
>>> 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') >>>
Rewrite this program in VB while keeping its functionality equivalent to the Julia version.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
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 Julia block to VB, preserving its control flow and logic.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
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 Go.
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
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)) } }
Can you help me rewrite this code in Go instead of Julia, keeping it the same logically?
using Base.Collections test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2] task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end println("Tasks, completed according to priority:") while !isempty(task) (t, p) = peek(task) dequeue!(task) println(" \"", t, "\" has priority ", p) end
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)) } }
Ensure the translated C code behaves exactly like the original Lua snippet.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
#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 Lua to C.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
#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; }
Write the same code in C# as shown below in Lua.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
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 Lua function in C# with identical behavior.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
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 programming language of this snippet from Lua to C++ without modifying what it does.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
#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 this Lua snippet to C++ and keep its semantics consistent.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
#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 Lua to Java, same semantics.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
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()); } }
Please provide an equivalent version of this Lua code in Java.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
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()); } }
Convert this Lua block to Python, preserving its control flow and logic.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
>>> 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') >>>
Ensure the translated Python code behaves exactly like the original Lua snippet.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
>>> 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') >>>
Rewrite the snippet below in VB so it works the same as the original Lua code.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
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
Ensure the translated VB code behaves exactly like the original Lua snippet.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
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 Lua to Go without modifying what it does.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
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 Lua to Go, same semantics.
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) for p, q in pairs(self) do if q.first <= q.last then local v = q[q.first] q[q.first] = nil q.first = q.first + 1 return p, v else self[p] = nil end end end }, __call = function(cls) return setmetatable({}, cls) end } setmetatable(PriorityQueue, PriorityQueue) pq = PriorityQueue() tasks = { {3, 'Clear drains'}, {4, 'Feed cat'}, {5, 'Make tea'}, {1, 'Solve RC tasks'}, {2, 'Tax return'} } for _, task in ipairs(tasks) do print(string.format("Putting: %d - %s", unpack(task))) pq:put(unpack(task)) end for prio, task in pq.pop, pq do print(string.format("Popped: %d - %s", prio, task)) end
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 Mathematica.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
#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 Mathematica to C with equivalent syntax and logic.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
#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 Mathematica code.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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 Mathematica to C# with equivalent syntax and logic.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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 this program in C++ while keeping its functionality equivalent to the Mathematica version.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
#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 following Mathematica code into C++ without altering its purpose.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
#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 a version of this Mathematica function in Java with identical behavior.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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()); } }
Write the same algorithm in Java as shown in this Mathematica implementation.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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 Mathematica.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
>>> 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') >>>
Write a version of this Mathematica function in Python with identical behavior.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
>>> 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 Mathematica.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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
Produce a functionally identical VB code for the snippet given in Mathematica.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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 Go.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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 Mathematica.
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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 Nim snippet without changing its computational steps.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
#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 Nim version.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
#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; }
Write the same algorithm in C# as shown in this Nim implementation.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
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}"); } } } }
Produce a language-to-language conversion: from Nim to C#, same semantics.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
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 the given Nim code snippet into C++ without altering its behavior.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
#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 Nim to C++, ensuring the logic remains intact.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
#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; }
Can you help me rewrite this code in Java instead of Nim, keeping it the same logically?
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
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 Nim to Java.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
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 Nim.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
>>> 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') >>>
Rewrite the snippet below in Python so it works the same as the original Nim code.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
>>> 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') >>>
Port the provided Nim code into VB while preserving the original functionality.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
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.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
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 Nim to Go.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
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)) } }
Rewrite this program in Go while keeping its functionality equivalent to the Nim version.
type PriElem[T] = tuple data: T pri: int PriQueue[T] = object buf: seq[PriElem[T]] count: int proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0 proc add[T](q: var PriQueue[T], data: T, pri: int) = var n = q.buf.len var m = n div 2 q.buf.setLen(n + 1) while m > 0 and pri < q.buf[m].pri: q.buf[n] = q.buf[m] n = m m = m div 2 q.buf[n] = (data, pri) q.count = q.buf.len - 1 proc pop[T](q: var PriQueue[T]): PriElem[T] = assert q.buf.len > 1 result = q.buf[1] var qn = q.buf.len - 1 var n = 1 var m = 2 while m < qn: if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri: inc m if q.buf[qn].pri <= q.buf[m].pri: break q.buf[n] = q.buf[m] n = m m = m * 2 q.buf[n] = q.buf[qn] q.buf.setLen(q.buf.len - 1) q.count = q.buf.len - 1 var p = initPriQueue[string]() p.add("Clear drains", 3) p.add("Feed cat", 4) p.add("Make tea", 5) p.add("Solve RC tasks", 1) p.add("Tax return", 2) while p.count > 0: echo p.pop()
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 OCaml code into C without altering its purpose.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
#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; }
Change the following OCaml code into C without altering its purpose.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
#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 OCaml version.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
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 OCaml function in C# with identical behavior.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
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}"); } } } }
Produce a functionally identical C++ code for the snippet given in OCaml.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
#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; }
Generate a C++ translation of this OCaml snippet without changing its computational steps.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
#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 OCaml code snippet into Java without altering its behavior.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
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()); } }
Write the same algorithm in Java as shown in this OCaml implementation.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
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 Python so it works the same as the original OCaml code.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
>>> 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 following OCaml code into Python without altering its purpose.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
>>> 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 OCaml to VB without modifying what it does.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
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 a VB translation of this OCaml snippet without changing its computational steps.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
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 OCaml to Go without modifying what it does.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
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)) } }
Port the following code from OCaml to Go with equivalent syntax and logic.
module PQ = Base.PriorityQueue let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = PQ.first pq in PQ.remove_first pq; print_endline task done
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 Pascal code into C without altering its purpose.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
#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; }
Produce a functionally identical C code for the snippet given in Pascal.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
#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; }
Write a version of this Pascal function in C# with identical behavior.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
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 Pascal to C# with equivalent syntax and logic.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
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 Pascal code.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
#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 C++.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
#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 Pascal implementation into Java, maintaining the same output and logic.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
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()); } }
Convert the following code from Pascal to Java, ensuring the logic remains intact.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
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 Pascal code into Python without altering its purpose.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
>>> 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 Pascal block to Python, preserving its control flow and logic.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
>>> 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 Pascal to VB.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
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 VB while keeping its functionality equivalent to the Pascal version.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
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 Pascal to Go, ensuring the logic remains intact.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
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)) } }
Port the following code from Pascal to Go with equivalent syntax and logic.
program PriorityQueueTest; uses Classes; Type TItem = record Priority:Integer; Value:string; end; PItem = ^TItem; TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end; procedure TPriorityQueue.Push(Priority:Integer;Value:string); var Item: PItem; begin new(Item); Item^.Priority := Priority; Item^.Value := Value; inherited Add(Item); SortPriority(); end; procedure TPriorityQueue.SortPriority(); var i,j:Integer; begin if(Count < 2) Then Exit(); for i:= 0 to Count-2 do for j:= i+1 to Count-1 do if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then Exchange(i,j); end; function TPriorityQueue.Pop():String; begin if count = 0 then Exit(''); result := PItem(First)^.value; Dispose(PItem(First)); Delete(0); end; function TPriorityQueue.Empty:Boolean; begin Result := Count = 0; end; var Queue : TPriorityQueue; begin Queue:= TPriorityQueue.Create(); Queue.Push(3,'Clear drains'); Queue.Push(4,'Feed cat'); Queue.Push(5,'Make tea'); Queue.Push(1,'Solve RC tasks'); Queue.Push(2,'Tax return'); while not Queue.Empty() do writeln(Queue.Pop()); Queue.free; end.
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 programming language of this snippet from Perl to C without modifying what it does.
use strict; use warnings; use feature 'say'; use Heap::Priority; my $h = Heap::Priority->new; $h->highest_first(); $h->add(@$_) for ["Clear drains", 3], ["Feed cat", 4], ["Make tea", 5], ["Solve RC tasks", 1], ["Tax return", 2]; say while ($_ = $h->pop);
#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; }