Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate the given Lua code snippet into C# without altering its behavior. | Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[queue.first] = nil
queue.first = queue.first + 1
return val
end
function Queue.empty( queue )
return queue.first > queue.last
end
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Change the following Lua code into C++ without altering its purpose. | Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[queue.first] = nil
queue.first = queue.first + 1
return val
end
function Queue.empty( queue )
return queue.first > queue.last
end
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Produce a functionally identical Java code for the snippet given in Lua. | Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[queue.first] = nil
queue.first = queue.first + 1
return val
end
function Queue.empty( queue )
return queue.first > queue.last
end
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Translate this program into Python but keep the logic exactly as in Lua. | Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[queue.first] = nil
queue.first = queue.first + 1
return val
end
function Queue.empty( queue )
return queue.first > queue.last
end
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Ensure the translated VB code behaves exactly like the original Lua snippet. | Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[queue.first] = nil
queue.first = queue.first + 1
return val
end
function Queue.empty( queue )
return queue.first > queue.last
end
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Transform the following Lua implementation into Go, maintaining the same output and logic. | Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[queue.first] = nil
queue.first = queue.first + 1
return val
end
function Queue.empty( queue )
return queue.first > queue.last
end
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Change the programming language of this snippet from Mathematica to C without modifying what it does. | EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Translate the given Mathematica code snippet into C# without altering its behavior. | EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Ensure the translated C++ code behaves exactly like the original Mathematica snippet. | EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Mathematica code. | EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Generate a Python translation of this Mathematica snippet without changing its computational steps. | EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Write the same code in VB as shown below in Mathematica. | EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Rewrite this program in Go while keeping its functionality equivalent to the Mathematica version. | EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Write the same code in C as shown below in MATLAB. | myfifo = {};
myfifo{end+1} = x;
x = myfifo{1}; myfifo{1} = [];
isempty(myfifo)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | myfifo = {};
myfifo{end+1} = x;
x = myfifo{1}; myfifo{1} = [];
isempty(myfifo)
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Produce a functionally identical C++ code for the snippet given in MATLAB. | myfifo = {};
myfifo{end+1} = x;
x = myfifo{1}; myfifo{1} = [];
isempty(myfifo)
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | myfifo = {};
myfifo{end+1} = x;
x = myfifo{1}; myfifo{1} = [];
isempty(myfifo)
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Convert this MATLAB block to Python, preserving its control flow and logic. | myfifo = {};
myfifo{end+1} = x;
x = myfifo{1}; myfifo{1} = [];
isempty(myfifo)
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Write the same code in VB as shown below in MATLAB. | myfifo = {};
myfifo{end+1} = x;
x = myfifo{1}; myfifo{1} = [];
isempty(myfifo)
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Write the same code in Go as shown below in MATLAB. | myfifo = {};
myfifo{end+1} = x;
x = myfifo{1}; myfifo{1} = [];
isempty(myfifo)
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Convert this Nim snippet to C and keep its semantics consistent. | type
Node[T] = ref object
value: T
next: Node[T]
Queue*[T] = object
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
func push*[T](queue: var Queue[T]; value: T) =
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
func pop*[T](queue: var Queue[T]): T =
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
when isMainModule:
var fifo = initQueue[int]()
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo "Fifo size: ", fifo.len()
try:
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Generate an equivalent C# version of this Nim code. | type
Node[T] = ref object
value: T
next: Node[T]
Queue*[T] = object
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
func push*[T](queue: var Queue[T]; value: T) =
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
func pop*[T](queue: var Queue[T]): T =
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
when isMainModule:
var fifo = initQueue[int]()
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo "Fifo size: ", fifo.len()
try:
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Produce a language-to-language conversion: from Nim to C++, same semantics. | type
Node[T] = ref object
value: T
next: Node[T]
Queue*[T] = object
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
func push*[T](queue: var Queue[T]; value: T) =
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
func pop*[T](queue: var Queue[T]): T =
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
when isMainModule:
var fifo = initQueue[int]()
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo "Fifo size: ", fifo.len()
try:
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Generate a Java translation of this Nim snippet without changing its computational steps. | type
Node[T] = ref object
value: T
next: Node[T]
Queue*[T] = object
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
func push*[T](queue: var Queue[T]; value: T) =
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
func pop*[T](queue: var Queue[T]): T =
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
when isMainModule:
var fifo = initQueue[int]()
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo "Fifo size: ", fifo.len()
try:
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Convert this Nim snippet to Python and keep its semantics consistent. | type
Node[T] = ref object
value: T
next: Node[T]
Queue*[T] = object
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
func push*[T](queue: var Queue[T]; value: T) =
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
func pop*[T](queue: var Queue[T]): T =
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
when isMainModule:
var fifo = initQueue[int]()
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo "Fifo size: ", fifo.len()
try:
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Keep all operations the same but rewrite the snippet in VB. | type
Node[T] = ref object
value: T
next: Node[T]
Queue*[T] = object
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
func push*[T](queue: var Queue[T]; value: T) =
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
func pop*[T](queue: var Queue[T]): T =
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
when isMainModule:
var fifo = initQueue[int]()
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo "Fifo size: ", fifo.len()
try:
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Write a version of this Nim function in Go with identical behavior. | type
Node[T] = ref object
value: T
next: Node[T]
Queue*[T] = object
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
func push*[T](queue: var Queue[T]; value: T) =
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
func pop*[T](queue: var Queue[T]): T =
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
when isMainModule:
var fifo = initQueue[int]()
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo "Fifo size: ", fifo.len()
try:
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Port the following code from OCaml to C with equivalent syntax and logic. | module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_empty ~fifo =
match fifo with
| [], [] -> true
| _ -> false
let rec pop ~fifo =
match fifo with
| input, item :: output -> item, (input,output)
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Generate a C# translation of this OCaml snippet without changing its computational steps. | module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_empty ~fifo =
match fifo with
| [], [] -> true
| _ -> false
let rec pop ~fifo =
match fifo with
| input, item :: output -> item, (input,output)
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Write the same algorithm in C++ as shown in this OCaml implementation. | module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_empty ~fifo =
match fifo with
| [], [] -> true
| _ -> false
let rec pop ~fifo =
match fifo with
| input, item :: output -> item, (input,output)
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Produce a language-to-language conversion: from OCaml to Java, same semantics. | module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_empty ~fifo =
match fifo with
| [], [] -> true
| _ -> false
let rec pop ~fifo =
match fifo with
| input, item :: output -> item, (input,output)
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Convert the following code from OCaml to Python, ensuring the logic remains intact. | module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_empty ~fifo =
match fifo with
| [], [] -> true
| _ -> false
let rec pop ~fifo =
match fifo with
| input, item :: output -> item, (input,output)
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Maintain the same structure and functionality when rewriting this code in VB. | module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_empty ~fifo =
match fifo with
| [], [] -> true
| _ -> false
let rec pop ~fifo =
match fifo with
| input, item :: output -> item, (input,output)
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Keep all operations the same but rewrite the snippet in Go. | module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_empty ~fifo =
match fifo with
| [], [] -> true
| _ -> false
let rec pop ~fifo =
match fifo with
| input, item :: output -> item, (input,output)
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Translate the given Pascal code snippet into C without altering its behavior. | program queue;
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2);
Write(lQueue.DeQueue:2);
Writeln(lQueue.DeQueue:2);
Assert(lQueue.Count = 0, 'Queue is not empty');
finally
lQueue.Free;
end;
end.
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Rewrite the snippet below in C# so it works the same as the original Pascal code. | program queue;
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2);
Write(lQueue.DeQueue:2);
Writeln(lQueue.DeQueue:2);
Assert(lQueue.Count = 0, 'Queue is not empty');
finally
lQueue.Free;
end;
end.
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Can you help me rewrite this code in C++ instead of Pascal, keeping it the same logically? | program queue;
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2);
Write(lQueue.DeQueue:2);
Writeln(lQueue.DeQueue:2);
Assert(lQueue.Count = 0, 'Queue is not empty');
finally
lQueue.Free;
end;
end.
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Preserve the algorithm and functionality while converting the code from Pascal to Java. | program queue;
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2);
Write(lQueue.DeQueue:2);
Writeln(lQueue.DeQueue:2);
Assert(lQueue.Count = 0, 'Queue is not empty');
finally
lQueue.Free;
end;
end.
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Preserve the algorithm and functionality while converting the code from Pascal to Python. | program queue;
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2);
Write(lQueue.DeQueue:2);
Writeln(lQueue.DeQueue:2);
Assert(lQueue.Count = 0, 'Queue is not empty');
finally
lQueue.Free;
end;
end.
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Generate an equivalent VB version of this Pascal code. | program queue;
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2);
Write(lQueue.DeQueue:2);
Writeln(lQueue.DeQueue:2);
Assert(lQueue.Count = 0, 'Queue is not empty');
finally
lQueue.Free;
end;
end.
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Ensure the translated Go code behaves exactly like the original Pascal snippet. | program queue;
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2);
Write(lQueue.DeQueue:2);
Writeln(lQueue.DeQueue:2);
Assert(lQueue.Count = 0, 'Queue is not empty');
finally
lQueue.Free;
end;
end.
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Ensure the translated C code behaves exactly like the original Perl snippet. | use Carp;
sub my push :prototype(\@@) {my($list,@things)=@_; push @$list, @things}
sub maypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty :prototype(@) {not @_}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Perl version. | use Carp;
sub my push :prototype(\@@) {my($list,@things)=@_; push @$list, @things}
sub maypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty :prototype(@) {not @_}
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Perl version. | use Carp;
sub my push :prototype(\@@) {my($list,@things)=@_; push @$list, @things}
sub maypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty :prototype(@) {not @_}
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Transform the following Perl implementation into Java, maintaining the same output and logic. | use Carp;
sub my push :prototype(\@@) {my($list,@things)=@_; push @$list, @things}
sub maypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty :prototype(@) {not @_}
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Translate the given Perl code snippet into Python without altering its behavior. | use Carp;
sub my push :prototype(\@@) {my($list,@things)=@_; push @$list, @things}
sub maypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty :prototype(@) {not @_}
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Generate an equivalent VB version of this Perl code. | use Carp;
sub my push :prototype(\@@) {my($list,@things)=@_; push @$list, @things}
sub maypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty :prototype(@) {not @_}
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Preserve the algorithm and functionality while converting the code from Perl to Go. | use Carp;
sub my push :prototype(\@@) {my($list,@things)=@_; push @$list, @things}
sub maypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty :prototype(@) {not @_}
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Rewrite the snippet below in C so it works the same as the original PowerShell code. |
$Q = New-Object System.Collections.Queue
$Q.Enqueue( 1 )
$Q.Enqueue( 2 )
$Q.Enqueue( 3 )
$Q.Dequeue()
$Q.Dequeue()
$Q.Count -eq 0
$Q.Dequeue()
$Q.Count -eq 0
try
{ $Q.Dequeue() }
catch [System.InvalidOperationException]
{ If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Generate a C# translation of this PowerShell snippet without changing its computational steps. |
$Q = New-Object System.Collections.Queue
$Q.Enqueue( 1 )
$Q.Enqueue( 2 )
$Q.Enqueue( 3 )
$Q.Dequeue()
$Q.Dequeue()
$Q.Count -eq 0
$Q.Dequeue()
$Q.Count -eq 0
try
{ $Q.Dequeue() }
catch [System.InvalidOperationException]
{ If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Translate this program into C++ but keep the logic exactly as in PowerShell. |
$Q = New-Object System.Collections.Queue
$Q.Enqueue( 1 )
$Q.Enqueue( 2 )
$Q.Enqueue( 3 )
$Q.Dequeue()
$Q.Dequeue()
$Q.Count -eq 0
$Q.Dequeue()
$Q.Count -eq 0
try
{ $Q.Dequeue() }
catch [System.InvalidOperationException]
{ If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Preserve the algorithm and functionality while converting the code from PowerShell to Java. |
$Q = New-Object System.Collections.Queue
$Q.Enqueue( 1 )
$Q.Enqueue( 2 )
$Q.Enqueue( 3 )
$Q.Dequeue()
$Q.Dequeue()
$Q.Count -eq 0
$Q.Dequeue()
$Q.Count -eq 0
try
{ $Q.Dequeue() }
catch [System.InvalidOperationException]
{ If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Ensure the translated Python code behaves exactly like the original PowerShell snippet. |
$Q = New-Object System.Collections.Queue
$Q.Enqueue( 1 )
$Q.Enqueue( 2 )
$Q.Enqueue( 3 )
$Q.Dequeue()
$Q.Dequeue()
$Q.Count -eq 0
$Q.Dequeue()
$Q.Count -eq 0
try
{ $Q.Dequeue() }
catch [System.InvalidOperationException]
{ If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Write the same algorithm in VB as shown in this PowerShell implementation. |
$Q = New-Object System.Collections.Queue
$Q.Enqueue( 1 )
$Q.Enqueue( 2 )
$Q.Enqueue( 3 )
$Q.Dequeue()
$Q.Dequeue()
$Q.Count -eq 0
$Q.Dequeue()
$Q.Count -eq 0
try
{ $Q.Dequeue() }
catch [System.InvalidOperationException]
{ If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Produce a functionally identical Go code for the snippet given in PowerShell. |
$Q = New-Object System.Collections.Queue
$Q.Enqueue( 1 )
$Q.Enqueue( 2 )
$Q.Enqueue( 3 )
$Q.Dequeue()
$Q.Dequeue()
$Q.Count -eq 0
$Q.Dequeue()
$Q.Count -eq 0
try
{ $Q.Dequeue() }
catch [System.InvalidOperationException]
{ If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Please provide an equivalent version of this R code in C. | empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
push(3)
push("abc")
push(matrix(1:6, nrow=2))
empty()
pop()
pop()
pop()
pop()
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Write the same code in C# as shown below in R. | empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
push(3)
push("abc")
push(matrix(1:6, nrow=2))
empty()
pop()
pop()
pop()
pop()
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Produce a language-to-language conversion: from R to C++, same semantics. | empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
push(3)
push("abc")
push(matrix(1:6, nrow=2))
empty()
pop()
pop()
pop()
pop()
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the R version. | empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
push(3)
push("abc")
push(matrix(1:6, nrow=2))
empty()
pop()
pop()
pop()
pop()
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Please provide an equivalent version of this R code in Python. | empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
push(3)
push("abc")
push(matrix(1:6, nrow=2))
empty()
pop()
pop()
pop()
pop()
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Change the following R code into VB without altering its purpose. | empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
push(3)
push("abc")
push(matrix(1:6, nrow=2))
empty()
pop()
pop()
pop()
pop()
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Convert this R snippet to Go and keep its semantics consistent. | empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
push(3)
push("abc")
push(matrix(1:6, nrow=2))
empty()
pop()
pop()
pop()
pop()
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Translate the given Racket code snippet into C without altering its behavior. | #lang racket
(define (make-queue) (mcons #f #f))
(define (push! q x)
(define new (mcons x #f))
(if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new))
(set-mcdr! q new))
(define (pop! q)
(define old (mcar q))
(cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)]
[else (set-mcar! q (mcdr old))])
(mcar old))
(define (empty? q)
(not (mcar q)))
(define Q (make-queue))
(empty? Q)
(push! Q 'x)
(empty? Q)
(for ([x 3]) (push! Q x))
(pop! Q)
(list (pop! Q) (pop! Q) (pop! Q))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Change the programming language of this snippet from Racket to C# without modifying what it does. | #lang racket
(define (make-queue) (mcons #f #f))
(define (push! q x)
(define new (mcons x #f))
(if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new))
(set-mcdr! q new))
(define (pop! q)
(define old (mcar q))
(cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)]
[else (set-mcar! q (mcdr old))])
(mcar old))
(define (empty? q)
(not (mcar q)))
(define Q (make-queue))
(empty? Q)
(push! Q 'x)
(empty? Q)
(for ([x 3]) (push! Q x))
(pop! Q)
(list (pop! Q) (pop! Q) (pop! Q))
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Generate a C++ translation of this Racket snippet without changing its computational steps. | #lang racket
(define (make-queue) (mcons #f #f))
(define (push! q x)
(define new (mcons x #f))
(if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new))
(set-mcdr! q new))
(define (pop! q)
(define old (mcar q))
(cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)]
[else (set-mcar! q (mcdr old))])
(mcar old))
(define (empty? q)
(not (mcar q)))
(define Q (make-queue))
(empty? Q)
(push! Q 'x)
(empty? Q)
(for ([x 3]) (push! Q x))
(pop! Q)
(list (pop! Q) (pop! Q) (pop! Q))
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Transform the following Racket implementation into Java, maintaining the same output and logic. | #lang racket
(define (make-queue) (mcons #f #f))
(define (push! q x)
(define new (mcons x #f))
(if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new))
(set-mcdr! q new))
(define (pop! q)
(define old (mcar q))
(cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)]
[else (set-mcar! q (mcdr old))])
(mcar old))
(define (empty? q)
(not (mcar q)))
(define Q (make-queue))
(empty? Q)
(push! Q 'x)
(empty? Q)
(for ([x 3]) (push! Q x))
(pop! Q)
(list (pop! Q) (pop! Q) (pop! Q))
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Can you help me rewrite this code in Python instead of Racket, keeping it the same logically? | #lang racket
(define (make-queue) (mcons #f #f))
(define (push! q x)
(define new (mcons x #f))
(if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new))
(set-mcdr! q new))
(define (pop! q)
(define old (mcar q))
(cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)]
[else (set-mcar! q (mcdr old))])
(mcar old))
(define (empty? q)
(not (mcar q)))
(define Q (make-queue))
(empty? Q)
(push! Q 'x)
(empty? Q)
(for ([x 3]) (push! Q x))
(pop! Q)
(list (pop! Q) (pop! Q) (pop! Q))
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Rewrite this program in VB while keeping its functionality equivalent to the Racket version. | #lang racket
(define (make-queue) (mcons #f #f))
(define (push! q x)
(define new (mcons x #f))
(if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new))
(set-mcdr! q new))
(define (pop! q)
(define old (mcar q))
(cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)]
[else (set-mcar! q (mcdr old))])
(mcar old))
(define (empty? q)
(not (mcar q)))
(define Q (make-queue))
(empty? Q)
(push! Q 'x)
(empty? Q)
(for ([x 3]) (push! Q x))
(pop! Q)
(list (pop! Q) (pop! Q) (pop! Q))
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Ensure the translated Go code behaves exactly like the original Racket snippet. | #lang racket
(define (make-queue) (mcons #f #f))
(define (push! q x)
(define new (mcons x #f))
(if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new))
(set-mcdr! q new))
(define (pop! q)
(define old (mcar q))
(cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)]
[else (set-mcar! q (mcdr old))])
(mcar old))
(define (empty? q)
(not (mcar q)))
(define Q (make-queue))
(empty? Q)
(push! Q 'x)
(empty? Q)
(for ([x 3]) (push! Q x))
(pop! Q)
(list (pop! Q) (pop! Q) (pop! Q))
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Please provide an equivalent version of this REXX code in C. |
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('')
mqueue.push(a 2)
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2)
mqueue.add('')
viewQueue(mqueue)
loop q_ = 1 while mqueue.size > 0
parse mqueue.pop.toString line
say q_.right(3)':' line
end q_
viewQueue(mqueue)
return
method viewQueue(mqueue = Deque) private static
If mqueue.size = 0 then do
Say 'Queue is empty'
end
else do
Say 'There are' mqueue.size 'elements in the queue'
end
return
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Ensure the translated C# code behaves exactly like the original REXX snippet. |
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('')
mqueue.push(a 2)
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2)
mqueue.add('')
viewQueue(mqueue)
loop q_ = 1 while mqueue.size > 0
parse mqueue.pop.toString line
say q_.right(3)':' line
end q_
viewQueue(mqueue)
return
method viewQueue(mqueue = Deque) private static
If mqueue.size = 0 then do
Say 'Queue is empty'
end
else do
Say 'There are' mqueue.size 'elements in the queue'
end
return
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Produce a functionally identical C++ code for the snippet given in REXX. |
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('')
mqueue.push(a 2)
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2)
mqueue.add('')
viewQueue(mqueue)
loop q_ = 1 while mqueue.size > 0
parse mqueue.pop.toString line
say q_.right(3)':' line
end q_
viewQueue(mqueue)
return
method viewQueue(mqueue = Deque) private static
If mqueue.size = 0 then do
Say 'Queue is empty'
end
else do
Say 'There are' mqueue.size 'elements in the queue'
end
return
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Write a version of this REXX function in Java with identical behavior. |
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('')
mqueue.push(a 2)
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2)
mqueue.add('')
viewQueue(mqueue)
loop q_ = 1 while mqueue.size > 0
parse mqueue.pop.toString line
say q_.right(3)':' line
end q_
viewQueue(mqueue)
return
method viewQueue(mqueue = Deque) private static
If mqueue.size = 0 then do
Say 'Queue is empty'
end
else do
Say 'There are' mqueue.size 'elements in the queue'
end
return
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the REXX version. |
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('')
mqueue.push(a 2)
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2)
mqueue.add('')
viewQueue(mqueue)
loop q_ = 1 while mqueue.size > 0
parse mqueue.pop.toString line
say q_.right(3)':' line
end q_
viewQueue(mqueue)
return
method viewQueue(mqueue = Deque) private static
If mqueue.size = 0 then do
Say 'Queue is empty'
end
else do
Say 'There are' mqueue.size 'elements in the queue'
end
return
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Rewrite this program in VB while keeping its functionality equivalent to the REXX version. |
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('')
mqueue.push(a 2)
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2)
mqueue.add('')
viewQueue(mqueue)
loop q_ = 1 while mqueue.size > 0
parse mqueue.pop.toString line
say q_.right(3)':' line
end q_
viewQueue(mqueue)
return
method viewQueue(mqueue = Deque) private static
If mqueue.size = 0 then do
Say 'Queue is empty'
end
else do
Say 'There are' mqueue.size 'elements in the queue'
end
return
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Translate the given REXX code snippet into Go without altering its behavior. |
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('')
mqueue.push(a 2)
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2)
mqueue.add('')
viewQueue(mqueue)
loop q_ = 1 while mqueue.size > 0
parse mqueue.pop.toString line
say q_.right(3)':' line
end q_
viewQueue(mqueue)
return
method viewQueue(mqueue = Deque) private static
If mqueue.size = 0 then do
Say 'Queue is empty'
end
else do
Say 'There are' mqueue.size 'elements in the queue'
end
return
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Maintain the same structure and functionality when rewriting this code in C. | require 'forwardable'
class FIFO
extend Forwardable
def self.[](*objects)
new.push(*objects)
end
def initialize; @ary = []; end
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
def_delegator :@ary, :shift, :pop
alias shift pop
alias dequeue shift
def_delegator :@ary, :empty?
def_delegator :@ary, :size
alias length size
def to_s
"FIFO
end
alias inspect to_s
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Translate this program into C# but keep the logic exactly as in Ruby. | require 'forwardable'
class FIFO
extend Forwardable
def self.[](*objects)
new.push(*objects)
end
def initialize; @ary = []; end
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
def_delegator :@ary, :shift, :pop
alias shift pop
alias dequeue shift
def_delegator :@ary, :empty?
def_delegator :@ary, :size
alias length size
def to_s
"FIFO
end
alias inspect to_s
end
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Write the same algorithm in C++ as shown in this Ruby implementation. | require 'forwardable'
class FIFO
extend Forwardable
def self.[](*objects)
new.push(*objects)
end
def initialize; @ary = []; end
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
def_delegator :@ary, :shift, :pop
alias shift pop
alias dequeue shift
def_delegator :@ary, :empty?
def_delegator :@ary, :size
alias length size
def to_s
"FIFO
end
alias inspect to_s
end
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Ensure the translated Java code behaves exactly like the original Ruby snippet. | require 'forwardable'
class FIFO
extend Forwardable
def self.[](*objects)
new.push(*objects)
end
def initialize; @ary = []; end
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
def_delegator :@ary, :shift, :pop
alias shift pop
alias dequeue shift
def_delegator :@ary, :empty?
def_delegator :@ary, :size
alias length size
def to_s
"FIFO
end
alias inspect to_s
end
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Rewrite the snippet below in Python so it works the same as the original Ruby code. | require 'forwardable'
class FIFO
extend Forwardable
def self.[](*objects)
new.push(*objects)
end
def initialize; @ary = []; end
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
def_delegator :@ary, :shift, :pop
alias shift pop
alias dequeue shift
def_delegator :@ary, :empty?
def_delegator :@ary, :size
alias length size
def to_s
"FIFO
end
alias inspect to_s
end
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Generate an equivalent VB version of this Ruby code. | require 'forwardable'
class FIFO
extend Forwardable
def self.[](*objects)
new.push(*objects)
end
def initialize; @ary = []; end
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
def_delegator :@ary, :shift, :pop
alias shift pop
alias dequeue shift
def_delegator :@ary, :empty?
def_delegator :@ary, :size
alias length size
def to_s
"FIFO
end
alias inspect to_s
end
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Port the provided Scala code into C while preserving the original functionality. |
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queue")
return data.removeFirst()
}
val top: E
get() {
if (empty) throw RuntimeException("Empty queue can't have a top element")
return data.first()
}
fun clear() = data.clear()
override fun toString() = data.toString()
}
fun main(args: Array<String>) {
val q = Queue<Int>()
(1..5).forEach { q.push(it) }
println(q)
println("Size of queue = ${q.size}")
print("Popping: ")
(1..3).forEach { print("${q.pop()} ") }
println("\nRemaining in queue: $q")
println("Top element is now ${q.top}")
q.clear()
println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
try {
q.pop()
}
catch (e: Exception) {
println(e.message)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Generate an equivalent C# version of this Scala code. |
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queue")
return data.removeFirst()
}
val top: E
get() {
if (empty) throw RuntimeException("Empty queue can't have a top element")
return data.first()
}
fun clear() = data.clear()
override fun toString() = data.toString()
}
fun main(args: Array<String>) {
val q = Queue<Int>()
(1..5).forEach { q.push(it) }
println(q)
println("Size of queue = ${q.size}")
print("Popping: ")
(1..3).forEach { print("${q.pop()} ") }
println("\nRemaining in queue: $q")
println("Top element is now ${q.top}")
q.clear()
println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
try {
q.pop()
}
catch (e: Exception) {
println(e.message)
}
}
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Keep all operations the same but rewrite the snippet in C++. |
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queue")
return data.removeFirst()
}
val top: E
get() {
if (empty) throw RuntimeException("Empty queue can't have a top element")
return data.first()
}
fun clear() = data.clear()
override fun toString() = data.toString()
}
fun main(args: Array<String>) {
val q = Queue<Int>()
(1..5).forEach { q.push(it) }
println(q)
println("Size of queue = ${q.size}")
print("Popping: ")
(1..3).forEach { print("${q.pop()} ") }
println("\nRemaining in queue: $q")
println("Top element is now ${q.top}")
q.clear()
println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
try {
q.pop()
}
catch (e: Exception) {
println(e.message)
}
}
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Preserve the algorithm and functionality while converting the code from Scala to Java. |
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queue")
return data.removeFirst()
}
val top: E
get() {
if (empty) throw RuntimeException("Empty queue can't have a top element")
return data.first()
}
fun clear() = data.clear()
override fun toString() = data.toString()
}
fun main(args: Array<String>) {
val q = Queue<Int>()
(1..5).forEach { q.push(it) }
println(q)
println("Size of queue = ${q.size}")
print("Popping: ")
(1..3).forEach { print("${q.pop()} ") }
println("\nRemaining in queue: $q")
println("Top element is now ${q.top}")
q.clear()
println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
try {
q.pop()
}
catch (e: Exception) {
println(e.message)
}
}
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Change the programming language of this snippet from Scala to Python without modifying what it does. |
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queue")
return data.removeFirst()
}
val top: E
get() {
if (empty) throw RuntimeException("Empty queue can't have a top element")
return data.first()
}
fun clear() = data.clear()
override fun toString() = data.toString()
}
fun main(args: Array<String>) {
val q = Queue<Int>()
(1..5).forEach { q.push(it) }
println(q)
println("Size of queue = ${q.size}")
print("Popping: ")
(1..3).forEach { print("${q.pop()} ") }
println("\nRemaining in queue: $q")
println("Top element is now ${q.top}")
q.clear()
println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
try {
q.pop()
}
catch (e: Exception) {
println(e.message)
}
}
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Produce a language-to-language conversion: from Scala to VB, same semantics. |
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queue")
return data.removeFirst()
}
val top: E
get() {
if (empty) throw RuntimeException("Empty queue can't have a top element")
return data.first()
}
fun clear() = data.clear()
override fun toString() = data.toString()
}
fun main(args: Array<String>) {
val q = Queue<Int>()
(1..5).forEach { q.push(it) }
println(q)
println("Size of queue = ${q.size}")
print("Popping: ")
(1..3).forEach { print("${q.pop()} ") }
println("\nRemaining in queue: $q")
println("Top element is now ${q.top}")
q.clear()
println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
try {
q.pop()
}
catch (e: Exception) {
println(e.message)
}
}
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Translate the given Scala code snippet into Go without altering its behavior. |
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queue")
return data.removeFirst()
}
val top: E
get() {
if (empty) throw RuntimeException("Empty queue can't have a top element")
return data.first()
}
fun clear() = data.clear()
override fun toString() = data.toString()
}
fun main(args: Array<String>) {
val q = Queue<Int>()
(1..5).forEach { q.push(it) }
println(q)
println("Size of queue = ${q.size}")
print("Popping: ")
(1..3).forEach { print("${q.pop()} ") }
println("\nRemaining in queue: $q")
println("Top element is now ${q.top}")
q.clear()
println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
try {
q.pop()
}
catch (e: Exception) {
println(e.message)
}
}
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Preserve the algorithm and functionality while converting the code from Tcl to C. | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;
push Q foo
empty Q ;
push Q bar
peek Q ;
pop Q ;
peek Q ;
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
Write the same code in C# as shown below in Tcl. | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;
push Q foo
empty Q ;
push Q bar
peek Q ;
pop Q ;
peek Q ;
| public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}
|
Change the following Tcl code into C++ without altering its purpose. | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;
push Q foo
empty Q ;
push Q bar
peek Q ;
pop Q ;
peek Q ;
| namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}
|
Translate this program into Java but keep the logic exactly as in Tcl. | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;
push Q foo
empty Q ;
push Q bar
peek Q ;
pop Q ;
peek Q ;
| public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
Preserve the algorithm and functionality while converting the code from Tcl to Python. | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;
push Q foo
empty Q ;
push Q bar
peek Q ;
pop Q ;
peek Q ;
| class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i,
|
Please provide an equivalent version of this Tcl code in VB. | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;
push Q foo
empty Q ;
push Q bar
peek Q ;
pop Q ;
peek Q ;
| Public queue As New Collection
Private Sub push(what As Variant)
queue.Add what
End Sub
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
Private Function empty_()
empty_ = queue.Count = 0
End Function
|
Port the provided Tcl code into Go while preserving the original functionality. | proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;
push Q foo
empty Q ;
push Q bar
peek Q ;
pop Q ;
peek Q ;
| package queue
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}
|
Translate this program into PHP but keep the logic exactly as in Rust. | use std::collections::VecDeque;
fn main() {
let mut stack = VecDeque::new();
stack.push_back("Element1");
stack.push_back("Element2");
stack.push_back("Element3");
assert_eq!(Some(&"Element1"), stack.front());
assert_eq!(Some("Element1"), stack.pop_front());
assert_eq!(Some("Element2"), stack.pop_front());
assert_eq!(Some("Element3"), stack.pop_front());
assert_eq!(None, stack.pop_front());
}
| class Fifo {
private $data = array();
public function push($element){
array_push($this->data, $element);
}
public function pop(){
if ($this->isEmpty()){
throw new Exception('Attempt to pop from an empty queue');
}
return array_shift($this->data);
}
public function enqueue($element) { $this->push($element); }
public function dequeue() { return $this->pop(); }
public function isEmpty(){
return empty($this->data);
}
}
|
Write a version of this Ada function in PHP with identical behavior. | generic
type Element_Type is private;
package Fifo is
type Fifo_Type is private;
procedure Push(List : in out Fifo_Type; Item : in Element_Type);
procedure Pop(List : in out Fifo_Type; Item : out Element_Type);
function Is_Empty(List : Fifo_Type) return Boolean;
Empty_Error : exception;
private
type Fifo_Element;
type Fifo_Ptr is access Fifo_Element;
type Fifo_Type is record
Head : Fifo_Ptr := null;
Tail : Fifo_Ptr := null;
end record;
type Fifo_Element is record
Value : Element_Type;
Next : Fifo_Ptr := null;
end record;
end Fifo;
| class Fifo {
private $data = array();
public function push($element){
array_push($this->data, $element);
}
public function pop(){
if ($this->isEmpty()){
throw new Exception('Attempt to pop from an empty queue');
}
return array_shift($this->data);
}
public function enqueue($element) { $this->push($element); }
public function dequeue() { return $this->pop(); }
public function isEmpty(){
return empty($this->data);
}
}
|
Transform the following Arturo implementation into PHP, maintaining the same output and logic. | rebol [
Title: "FIFO"
URL: http://rosettacode.org/wiki/FIFO
]
fifo: make object! [
queue: copy []
push: func [x][append queue x]
pop: func [/local x][
if empty [return none]
x: first queue remove queue x]
empty: does [empty? queue]
]
q: make fifo []
q/push 'a
q/push 2
q/push USD$12.34
q/push [Athos Porthos Aramis]
q/push [[Huey Dewey Lewey]]
print rejoin ["Queue is " either q/empty [""]["not "] "empty."]
while [not q/empty][print [" " q/pop]]
print rejoin ["Queue is " either q/empty [""]["not "] "empty."]
print ["Trying to pop an empty queue yields:" q/pop]
| class Fifo {
private $data = array();
public function push($element){
array_push($this->data, $element);
}
public function pop(){
if ($this->isEmpty()){
throw new Exception('Attempt to pop from an empty queue');
}
return array_shift($this->data);
}
public function enqueue($element) { $this->push($element); }
public function dequeue() { return $this->pop(); }
public function isEmpty(){
return empty($this->data);
}
}
|
Rewrite this program in PHP while keeping its functionality equivalent to the AutoHotKey version. | push("qu", 2), push("qu", 44), push("qu", "xyz")
MsgBox % "Len = " len("qu")
While !empty("qu")
MsgBox % pop("qu")
MsgBox Error = %ErrorLevel%
MsgBox % pop("qu")
MsgBox Error = %ErrorLevel%
MsgBox % "Len = " len("qu")
push(queue,_) {
Global
%queue% .= %queue% = "" ? _ : "|" _
}
pop(queue) {
Global
RegExMatch(%queue%, "([^\|]*)\|?(.*)", _)
Return _1, ErrorLevel := -(%queue%=""), %queue% := _2
}
empty(queue) {
Global
Return %queue% = ""
}
len(queue) {
Global
StringReplace %queue%, %queue%, |, |, UseErrorLevel
Return %queue% = "" ? 0 : ErrorLevel+1
}
| class Fifo {
private $data = array();
public function push($element){
array_push($this->data, $element);
}
public function pop(){
if ($this->isEmpty()){
throw new Exception('Attempt to pop from an empty queue');
}
return array_shift($this->data);
}
public function enqueue($element) { $this->push($element); }
public function dequeue() { return $this->pop(); }
public function isEmpty(){
return empty($this->data);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.