Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in C while keeping its functionality equivalent to the Perl version. | 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;
}
|
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);
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Generate a C# translation of this Perl snippet without changing its computational steps. | 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);
| 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 Perl code snippet into C++ without altering its behavior. | 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 <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 Perl snippet to C++ and keep its semantics consistent. | 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 <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Produce a functionally identical Java code for the snippet given in Perl. | 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);
| 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 Perl to Java, ensuring the logic remains intact. | 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);
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Perl version. | 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);
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Maintain the same structure and functionality when rewriting this code in Python. | 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);
| >>> 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 an equivalent VB version of this Perl code. | 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);
| 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 Perl version. | 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);
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Rewrite this program in Go while keeping its functionality equivalent to the Perl version. | 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);
| 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 Perl snippet to Go and keep its semantics consistent. | 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);
| 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 R to C with equivalent syntax and logic. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| #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 R version. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| #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 R to C#. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Convert the following code from R to C#, ensuring the logic remains intact. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| 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 R code snippet into C++ without altering its behavior. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the R version. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| #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 R code into Java without altering its purpose. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| 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 R implementation. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Translate the given R code snippet into Python without altering its behavior. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Can you help me rewrite this code in Python instead of R, keeping it the same logically? | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Convert the following code from R to VB, ensuring the logic remains intact. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| 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 R to VB, ensuring the logic remains intact. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| 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 the snippet below in Go so it works the same as the original R code. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| 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 R code into Go without altering its purpose. | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}
| 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 Racket implementation into C, maintaining the same output and logic. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| #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 language-to-language conversion: from Racket to C, same semantics. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| #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 provided Racket code into C# while preserving the original functionality. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| 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}");
}
}
}
}
|
Please provide an equivalent version of this Racket code in C#. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Can you help me rewrite this code in C++ instead of Racket, keeping it the same logically? | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| #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++. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Write the same algorithm in Java as shown in this Racket implementation. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| 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 Racket implementation. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| 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 Racket snippet to Python and keep its semantics consistent. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Convert the following code from Racket to Python, ensuring the logic remains intact. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| >>> 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 Racket code into VB without altering its purpose. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| 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 Racket block to VB, preserving its control flow and logic. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| 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 Racket to Go, ensuring the logic remains intact. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| 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 Racket block to Go, preserving its control flow and logic. | #lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
| 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 provided REXX code into C while preserving the original functionality. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Can you help me rewrite this code in C instead of REXX, keeping it the same logically? |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| #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 REXX code. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| 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 REXX to C# with equivalent syntax and logic. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| 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 REXX version. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| #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 REXX to C++, same semantics. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| #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 REXX to Java, same semantics. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Translate this program into Java but keep the logic exactly as in REXX. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| 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 REXX snippet to Python and keep its semantics consistent. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| >>> 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 REXX code into Python while preserving the original functionality. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| >>> 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 REXX function in VB with identical behavior. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| 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 provided REXX code into VB while preserving the original functionality. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Please provide an equivalent version of this REXX code in Go. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| 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))
}
}
|
Preserve the algorithm and functionality while converting the code from REXX to Go. |
#=0; @.=
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del()
exit
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return #
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end
return top#
| 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 functionally identical C code for the snippet given in Ruby. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| #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 Ruby. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Translate this program into C# but keep the logic exactly as in Ruby. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Convert the following code from Ruby to C#, ensuring the logic remains intact. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| 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 Ruby to C++, same semantics. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Ruby. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| #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 Ruby code snippet into Java without altering its behavior. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Keep all operations the same but rewrite the snippet in Java. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| 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 Python as shown below in Ruby. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| >>> 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 Ruby code into Python while preserving the original functionality. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| >>> 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 algorithm in VB as shown in this Ruby implementation. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| 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 Ruby to VB with equivalent syntax and logic. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| 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
|
Write the same algorithm in Go as shown in this Ruby implementation. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| 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 functionally identical Go code for the snippet given in Ruby. | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek :
until pq3.empty?
puts pq3.pop
end
puts "peek :
| 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 Scala snippet to C and keep its semantics consistent. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Change the following Scala code into C without altering its purpose. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Can you help me rewrite this code in C# instead of Scala, keeping it the same logically? | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Ensure the translated C# code behaves exactly like the original Scala snippet. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| using System;
using System.Collections.Generic;
namespace PriorityQueueExample
{
class Program
{
static void Main(string[] args)
{
var p = new PriorityQueue<string, int>();
p.Enqueue("Clear drains", 3);
p.Enqueue("Feed cat", 4);
p.Enqueue("Make tea", 5);
p.Enqueue("Solve RC tasks", 1);
p.Enqueue("Tax return", 2);
while (p.TryDequeue(out string task, out int priority))
{
Console.WriteLine($"{priority}\t{task}");
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Scala to C++. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Scala to C++. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| #include <iostream>
#include <string>
#include <queue>
#include <utility>
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Clear drains"));
pq.push(std::make_pair(4, "Feed cat"));
pq.push(std::make_pair(5, "Make tea"));
pq.push(std::make_pair(1, "Solve RC tasks"));
pq.push(std::make_pair(2, "Tax return"));
while (!pq.empty()) {
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
pq.pop();
}
return 0;
}
|
Transform the following Scala implementation into Java, maintaining the same output and logic. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Keep all operations the same but rewrite the snippet in Java. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| import java.util.PriorityQueue;
class Task implements Comparable<Task> {
final int priority;
final String name;
public Task(int p, String n) {
priority = p;
name = n;
}
public String toString() {
return priority + ", " + name;
}
public int compareTo(Task other) {
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
}
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<Task>();
pq.add(new Task(3, "Clear drains"));
pq.add(new Task(4, "Feed cat"));
pq.add(new Task(5, "Make tea"));
pq.add(new Task(1, "Solve RC tasks"));
pq.add(new Task(2, "Tax return"));
while (!pq.isEmpty())
System.out.println(pq.remove());
}
}
|
Convert this Scala block to Python, preserving its control flow and logic. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Rewrite the snippet below in Python so it works the same as the original Scala code. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>>
|
Transform the following Scala implementation into VB, maintaining the same output and logic. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Produce a language-to-language conversion: from Scala to VB, same semantics. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
Preserve the algorithm and functionality while converting the code from Scala to Go. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Translate the given Scala code snippet into Go without altering its behavior. | import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
| package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
func (self *TaskPQ) Pop() (popped interface{}) {
popped = (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return
}
func main() {
pq := &TaskPQ{{3, "Clear drains"},
{4, "Feed cat"},
{5, "Make tea"},
{1, "Solve RC tasks"}}
heap.Init(pq)
heap.Push(pq, Task{2, "Tax return"})
for pq.Len() != 0 {
fmt.Println(heap.Pop(pq))
}
}
|
Change the programming language of this snippet from Swift to C without modifying what it does. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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;
}
|
Produce a language-to-language conversion: from Swift to C, same semantics. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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;
}
|
Transform the following Swift implementation into C#, maintaining the same output and logic. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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}");
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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}");
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Swift to C++. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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;
}
|
Please provide an equivalent version of this Swift code in C++. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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;
}
|
Translate this program into Java but keep the logic exactly as in Swift. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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());
}
}
|
Rewrite the snippet below in Java so it works the same as the original Swift code. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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());
}
}
|
Change the following Swift code into Python without altering its purpose. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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')
>>>
|
Convert this Swift block to Python, preserving its control flow and logic. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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')
>>>
|
Write the same algorithm in VB as shown in this Swift implementation. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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
|
Port the following code from Swift to VB with equivalent syntax and logic. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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
|
Produce a language-to-language conversion: from Swift to Go, same semantics. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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))
}
}
|
Generate an equivalent Go version of this Swift code. | class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
init(priority: Int, name: String) {
self.priority = priority
self.name = name
}
var description: String {
return "\(priority), \(name)"
}
}
func ==(t1: Task, t2: Task) -> Bool {
return t1.priority == t2.priority
}
func <(t1: Task, t2: Task) -> Bool {
return t1.priority < t2.priority
}
struct TaskPriorityQueue {
let heap : CFBinaryHeapRef = {
var callBacks = CFBinaryHeapCallBacks(version: 0, retain: {
UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque())
}, release: {
Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release()
}, copyDescription: nil, compare: { (ptr1, ptr2, _) in
let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue()
let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue()
return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan
})
return CFBinaryHeapCreate(nil, 0, &callBacks, nil)
}()
var count : Int { return CFBinaryHeapGetCount(heap) }
mutating func push(t: Task) {
CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque()))
}
func peek() -> Task {
return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
}
mutating func pop() -> Task {
let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue()
CFBinaryHeapRemoveMinimumValue(heap)
return result
}
}
var pq = TaskPriorityQueue()
pq.push(Task(priority: 3, name: "Clear drains"))
pq.push(Task(priority: 4, name: "Feed cat"))
pq.push(Task(priority: 5, name: "Make tea"))
pq.push(Task(priority: 1, name: "Solve RC tasks"))
pq.push(Task(priority: 2, name: "Tax return"))
while pq.count != 0 {
print(pq.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))
}
}
|
Write the same algorithm in C as shown in this Tcl implementation. | package require struct::prioqueue
set pq [struct::prioqueue]
foreach {priority task} {
3 "Clear drains"
4 "Feed cat"
5 "Make tea"
1 "Solve RC tasks"
2 "Tax return"
} {
$pq put $task $priority
}
while {[$pq size]} {
puts [$pq get]
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Translate the given Tcl code snippet into C without altering its behavior. | package require struct::prioqueue
set pq [struct::prioqueue]
foreach {priority task} {
3 "Clear drains"
4 "Feed cat"
5 "Make tea"
1 "Solve RC tasks"
2 "Tax return"
} {
$pq put $task $priority
}
while {[$pq size]} {
puts [$pq get]
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
char *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, char *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
char *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
char *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (i!=h->len+1) {
k = h->len+1;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
h->nodes[i] = h->nodes[k];
i = k;
}
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, "Clear drains");
push(h, 4, "Feed cat");
push(h, 5, "Make tea");
push(h, 1, "Solve RC tasks");
push(h, 2, "Tax return");
int i;
for (i = 0; i < 5; i++) {
printf("%s\n", pop(h));
}
return 0;
}
|
Rewrite the snippet below in C# so it works the same as the original Tcl code. | package require struct::prioqueue
set pq [struct::prioqueue]
foreach {priority task} {
3 "Clear drains"
4 "Feed cat"
5 "Make tea"
1 "Solve RC tasks"
2 "Tax return"
} {
$pq put $task $priority
}
while {[$pq size]} {
puts [$pq get]
}
| 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}");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.