Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Please provide an equivalent version of this AWK code in Python.
BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() } function push(n) { q[length(q)+1] = n return n } function pop() { if (emptyP()) { print "Popping from empty queue." exit } r = q[length(q)] delete q[length(q)] return r } function emptyP() { return length(q) == 0 }
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 AWK code into VB without altering its purpose.
BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() } function push(n) { q[length(q)+1] = n return n } function pop() { if (emptyP()) { print "Popping from empty queue." exit } r = q[length(q)] delete q[length(q)] return r } function emptyP() { return length(q) == 0 }
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 AWK.
BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() } function push(n) { q[length(q)+1] = n return n } function pop() { if (emptyP()) { print "Popping from empty queue." exit } r = q[length(q)] delete q[length(q)] return r } function emptyP() { return length(q) == 0 }
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 BBC_Basic snippet to C and keep its semantics consistent.
FIFOSIZE = 1000 FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
#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; }
Port the following code from BBC_Basic to C# with equivalent syntax and logic.
FIFOSIZE = 1000 FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
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 BBC_Basic code into C++ without altering its purpose.
FIFOSIZE = 1000 FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
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; } }
Convert the following code from BBC_Basic to Java, ensuring the logic remains intact.
FIFOSIZE = 1000 FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
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 BBC_Basic to Python, ensuring the logic remains intact.
FIFOSIZE = 1000 FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
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 BBC_Basic snippet.
FIFOSIZE = 1000 FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
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 BBC_Basic.
FIFOSIZE = 1000 FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
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 }
Generate a C translation of this Clojure snippet without changing its computational steps.
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue user=> (empty? @aqueue) true user=> (swap! aqueue conj 1) user=> (swap! aqueue into [2 3 4]) user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (peek @aqueue) 1 user=> (pprint (pop @aqueue)) <-(2 3 4)-< user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (into [] @aqueue) [1 2 3 4] user=> (-> @aqueue rest (conj 5) pprint) (5 2 3 4) user=> (-> @aqueue pop (conj 5) pprint) <-(2 3 4 5)-<
#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 Clojure to C# without modifying what it does.
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue user=> (empty? @aqueue) true user=> (swap! aqueue conj 1) user=> (swap! aqueue into [2 3 4]) user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (peek @aqueue) 1 user=> (pprint (pop @aqueue)) <-(2 3 4)-< user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (into [] @aqueue) [1 2 3 4] user=> (-> @aqueue rest (conj 5) pprint) (5 2 3 4) user=> (-> @aqueue pop (conj 5) pprint) <-(2 3 4 5)-<
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 Clojure.
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue user=> (empty? @aqueue) true user=> (swap! aqueue conj 1) user=> (swap! aqueue into [2 3 4]) user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (peek @aqueue) 1 user=> (pprint (pop @aqueue)) <-(2 3 4)-< user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (into [] @aqueue) [1 2 3 4] user=> (-> @aqueue rest (conj 5) pprint) (5 2 3 4) user=> (-> @aqueue pop (conj 5) pprint) <-(2 3 4 5)-<
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; } }
Convert the following code from Clojure to Java, ensuring the logic remains intact.
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue user=> (empty? @aqueue) true user=> (swap! aqueue conj 1) user=> (swap! aqueue into [2 3 4]) user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (peek @aqueue) 1 user=> (pprint (pop @aqueue)) <-(2 3 4)-< user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (into [] @aqueue) [1 2 3 4] user=> (-> @aqueue rest (conj 5) pprint) (5 2 3 4) user=> (-> @aqueue pop (conj 5) pprint) <-(2 3 4 5)-<
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 Clojure to Python without modifying what it does.
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue user=> (empty? @aqueue) true user=> (swap! aqueue conj 1) user=> (swap! aqueue into [2 3 4]) user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (peek @aqueue) 1 user=> (pprint (pop @aqueue)) <-(2 3 4)-< user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (into [] @aqueue) [1 2 3 4] user=> (-> @aqueue rest (conj 5) pprint) (5 2 3 4) user=> (-> @aqueue pop (conj 5) pprint) <-(2 3 4 5)-<
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,
Convert the following code from Clojure to VB, ensuring the logic remains intact.
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue user=> (empty? @aqueue) true user=> (swap! aqueue conj 1) user=> (swap! aqueue into [2 3 4]) user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (peek @aqueue) 1 user=> (pprint (pop @aqueue)) <-(2 3 4)-< user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (into [] @aqueue) [1 2 3 4] user=> (-> @aqueue rest (conj 5) pprint) (5 2 3 4) user=> (-> @aqueue pop (conj 5) pprint) <-(2 3 4 5)-<
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.
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue user=> (empty? @aqueue) true user=> (swap! aqueue conj 1) user=> (swap! aqueue into [2 3 4]) user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (peek @aqueue) 1 user=> (pprint (pop @aqueue)) <-(2 3 4)-< user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (into [] @aqueue) [1 2 3 4] user=> (-> @aqueue rest (conj 5) pprint) (5 2 3 4) user=> (-> @aqueue pop (conj 5) pprint) <-(2 3 4 5)-<
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 provided Common_Lisp code into C while preserving the original functionality.
(defun enqueue (x xs) (cons x xs)) (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys))))) (defun empty (xs) (endp xs))
#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; }
Convert this Common_Lisp snippet to C# and keep its semantics consistent.
(defun enqueue (x xs) (cons x xs)) (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys))))) (defun empty (xs) (endp xs))
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 programming language of this snippet from Common_Lisp to C++ without modifying what it does.
(defun enqueue (x xs) (cons x xs)) (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys))))) (defun empty (xs) (endp xs))
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; } }
Convert the following code from Common_Lisp to Java, ensuring the logic remains intact.
(defun enqueue (x xs) (cons x xs)) (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys))))) (defun empty (xs) (endp xs))
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 Common_Lisp, keeping it the same logically?
(defun enqueue (x xs) (cons x xs)) (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys))))) (defun empty (xs) (endp xs))
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 a VB translation of this Common_Lisp snippet without changing its computational steps.
(defun enqueue (x xs) (cons x xs)) (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys))))) (defun empty (xs) (endp xs))
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 Common_Lisp implementation into Go, maintaining the same output and logic.
(defun enqueue (x xs) (cons x xs)) (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys))))) (defun empty (xs) (endp xs))
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 provided Delphi code into C while preserving the original functionality.
program QueueDefinition; uses System.Generics.Collections; type TQueue = System.Generics.Collections.TQueue<Integer>; TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end; function TQueueHelper.Empty: Boolean; begin Result := count = 0; end; function TQueueHelper.Pop: Integer; begin Result := Dequeue; end; procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end; var Queue: TQueue; i: Integer; begin Queue := TQueue.Create; for i := 1 to 1000 do Queue.push(i); while not Queue.Empty do Write(Queue.pop, ' '); Writeln; Queue.Free; Readln; 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 this program in C# while keeping its functionality equivalent to the Delphi version.
program QueueDefinition; uses System.Generics.Collections; type TQueue = System.Generics.Collections.TQueue<Integer>; TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end; function TQueueHelper.Empty: Boolean; begin Result := count = 0; end; function TQueueHelper.Pop: Integer; begin Result := Dequeue; end; procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end; var Queue: TQueue; i: Integer; begin Queue := TQueue.Create; for i := 1 to 1000 do Queue.push(i); while not Queue.Empty do Write(Queue.pop, ' '); Writeln; Queue.Free; Readln; 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; } }
Maintain the same structure and functionality when rewriting this code in C++.
program QueueDefinition; uses System.Generics.Collections; type TQueue = System.Generics.Collections.TQueue<Integer>; TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end; function TQueueHelper.Empty: Boolean; begin Result := count = 0; end; function TQueueHelper.Pop: Integer; begin Result := Dequeue; end; procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end; var Queue: TQueue; i: Integer; begin Queue := TQueue.Create; for i := 1 to 1000 do Queue.push(i); while not Queue.Empty do Write(Queue.pop, ' '); Writeln; Queue.Free; Readln; 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; } }
Write the same code in Java as shown below in Delphi.
program QueueDefinition; uses System.Generics.Collections; type TQueue = System.Generics.Collections.TQueue<Integer>; TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end; function TQueueHelper.Empty: Boolean; begin Result := count = 0; end; function TQueueHelper.Pop: Integer; begin Result := Dequeue; end; procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end; var Queue: TQueue; i: Integer; begin Queue := TQueue.Create; for i := 1 to 1000 do Queue.push(i); while not Queue.Empty do Write(Queue.pop, ' '); Writeln; Queue.Free; Readln; 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 the given Delphi code snippet into Python without altering its behavior.
program QueueDefinition; uses System.Generics.Collections; type TQueue = System.Generics.Collections.TQueue<Integer>; TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end; function TQueueHelper.Empty: Boolean; begin Result := count = 0; end; function TQueueHelper.Pop: Integer; begin Result := Dequeue; end; procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end; var Queue: TQueue; i: Integer; begin Queue := TQueue.Create; for i := 1 to 1000 do Queue.push(i); while not Queue.Empty do Write(Queue.pop, ' '); Writeln; Queue.Free; Readln; 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,
Write the same code in VB as shown below in Delphi.
program QueueDefinition; uses System.Generics.Collections; type TQueue = System.Generics.Collections.TQueue<Integer>; TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end; function TQueueHelper.Empty: Boolean; begin Result := count = 0; end; function TQueueHelper.Pop: Integer; begin Result := Dequeue; end; procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end; var Queue: TQueue; i: Integer; begin Queue := TQueue.Create; for i := 1 to 1000 do Queue.push(i); while not Queue.Empty do Write(Queue.pop, ' '); Writeln; Queue.Free; Readln; 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
Produce a language-to-language conversion: from Delphi to Go, same semantics.
program QueueDefinition; uses System.Generics.Collections; type TQueue = System.Generics.Collections.TQueue<Integer>; TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end; function TQueueHelper.Empty: Boolean; begin Result := count = 0; end; function TQueueHelper.Pop: Integer; begin Result := Dequeue; end; procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end; var Queue: TQueue; i: Integer; begin Queue := TQueue.Create; for i := 1 to 1000 do Queue.push(i); while not Queue.Empty do Write(Queue.pop, ' '); Writeln; Queue.Free; Readln; 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 }
Rewrite this program in C while keeping its functionality equivalent to the Elixir version.
defmodule Queue do def new, do: {Queue, [], []} def push({Queue, input, output}, x), do: {Queue, [x|input], output} def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false 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; }
Convert the following code from Elixir to C#, ensuring the logic remains intact.
defmodule Queue do def new, do: {Queue, [], []} def push({Queue, input, output}, x), do: {Queue, [x|input], output} def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false 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; } }
Generate an equivalent C++ version of this Elixir code.
defmodule Queue do def new, do: {Queue, [], []} def push({Queue, input, output}, x), do: {Queue, [x|input], output} def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false 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; } }
Convert the following code from Elixir to Java, ensuring the logic remains intact.
defmodule Queue do def new, do: {Queue, [], []} def push({Queue, input, output}, x), do: {Queue, [x|input], output} def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false 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; } }
Can you help me rewrite this code in Python instead of Elixir, keeping it the same logically?
defmodule Queue do def new, do: {Queue, [], []} def push({Queue, input, output}, x), do: {Queue, [x|input], output} def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false 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,
Change the programming language of this snippet from Elixir to VB without modifying what it does.
defmodule Queue do def new, do: {Queue, [], []} def push({Queue, input, output}, x), do: {Queue, [x|input], output} def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false 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
Generate a Go translation of this Elixir snippet without changing its computational steps.
defmodule Queue do def new, do: {Queue, [], []} def push({Queue, input, output}, x), do: {Queue, [x|input], output} def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false 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 }
Preserve the algorithm and functionality while converting the code from Erlang to C.
-module(fifo). -export([new/0, push/2, pop/1, empty/1]). new() -> {fifo, [], []}. push({fifo, In, Out}, X) -> {fifo, [X|In], Out}. pop({fifo, [], []}) -> erlang:error('empty fifo'); pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)}); pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}. empty({fifo, [], []}) -> true; empty({fifo, _, _}) -> false.
#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; }
Please provide an equivalent version of this Erlang code in C++.
-module(fifo). -export([new/0, push/2, pop/1, empty/1]). new() -> {fifo, [], []}. push({fifo, In, Out}, X) -> {fifo, [X|In], Out}. pop({fifo, [], []}) -> erlang:error('empty fifo'); pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)}); pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}. empty({fifo, [], []}) -> true; empty({fifo, _, _}) -> false.
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; } }
Port the following code from Erlang to Java with equivalent syntax and logic.
-module(fifo). -export([new/0, push/2, pop/1, empty/1]). new() -> {fifo, [], []}. push({fifo, In, Out}, X) -> {fifo, [X|In], Out}. pop({fifo, [], []}) -> erlang:error('empty fifo'); pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)}); pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}. empty({fifo, [], []}) -> true; empty({fifo, _, _}) -> false.
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 Erlang block to Python, preserving its control flow and logic.
-module(fifo). -export([new/0, push/2, pop/1, empty/1]). new() -> {fifo, [], []}. push({fifo, In, Out}, X) -> {fifo, [X|In], Out}. pop({fifo, [], []}) -> erlang:error('empty fifo'); pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)}); pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}. empty({fifo, [], []}) -> true; empty({fifo, _, _}) -> false.
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,
Port the provided Erlang code into VB while preserving the original functionality.
-module(fifo). -export([new/0, push/2, pop/1, empty/1]). new() -> {fifo, [], []}. push({fifo, In, Out}, X) -> {fifo, [X|In], Out}. pop({fifo, [], []}) -> erlang:error('empty fifo'); pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)}); pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}. empty({fifo, [], []}) -> true; empty({fifo, _, _}) -> false.
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 Erlang.
-module(fifo). -export([new/0, push/2, pop/1, empty/1]). new() -> {fifo, [], []}. push({fifo, In, Out}, X) -> {fifo, [X|In], Out}. pop({fifo, [], []}) -> erlang:error('empty fifo'); pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)}); pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}. empty({fifo, [], []}) -> true; empty({fifo, _, _}) -> false.
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 Factor to C without modifying what it does.
USING: accessors kernel ; IN: rosetta-code.queue-definition TUPLE: queue head tail ; TUPLE: node value next ; : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ; : empty? ( queue -- ? ) head>> >boolean not ; : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ; : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
#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 Factor code snippet into C# without altering its behavior.
USING: accessors kernel ; IN: rosetta-code.queue-definition TUPLE: queue head tail ; TUPLE: node value next ; : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ; : empty? ( queue -- ? ) head>> >boolean not ; : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ; : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
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 the snippet below in C++ so it works the same as the original Factor code.
USING: accessors kernel ; IN: rosetta-code.queue-definition TUPLE: queue head tail ; TUPLE: node value next ; : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ; : empty? ( queue -- ? ) head>> >boolean not ; : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ; : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
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; } }
Convert the following code from Factor to Java, ensuring the logic remains intact.
USING: accessors kernel ; IN: rosetta-code.queue-definition TUPLE: queue head tail ; TUPLE: node value next ; : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ; : empty? ( queue -- ? ) head>> >boolean not ; : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ; : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
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; } }
Produce a language-to-language conversion: from Factor to Python, same semantics.
USING: accessors kernel ; IN: rosetta-code.queue-definition TUPLE: queue head tail ; TUPLE: node value next ; : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ; : empty? ( queue -- ? ) head>> >boolean not ; : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ; : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
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,
Port the provided Factor code into VB while preserving the original functionality.
USING: accessors kernel ; IN: rosetta-code.queue-definition TUPLE: queue head tail ; TUPLE: node value next ; : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ; : empty? ( queue -- ? ) head>> >boolean not ; : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ; : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
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
Generate an equivalent Go version of this Factor code.
USING: accessors kernel ; IN: rosetta-code.queue-definition TUPLE: queue head tail ; TUPLE: node value next ; : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ; : empty? ( queue -- ? ) head>> >boolean not ; : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ; : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
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 provided Forth code into C while preserving the original functionality.
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used ! : empty? used @ 0= ; : full? used @ size = ; : next cell+ dup end = if drop buffer then ; : put full? abort" buffer full" tail @ ! tail @ next tail ! 1 used +! ; : get empty? abort" buffer empty" head @ @ head @ next head ! -1 used +! ;
#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 Forth.
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used ! : empty? used @ 0= ; : full? used @ size = ; : next cell+ dup end = if drop buffer then ; : put full? abort" buffer full" tail @ ! tail @ next tail ! 1 used +! ; : get empty? abort" buffer empty" head @ @ head @ next head ! -1 used +! ;
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; } }
Convert this Forth block to C++, preserving its control flow and logic.
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used ! : empty? used @ 0= ; : full? used @ size = ; : next cell+ dup end = if drop buffer then ; : put full? abort" buffer full" tail @ ! tail @ next tail ! 1 used +! ; : get empty? abort" buffer empty" head @ @ head @ next head ! -1 used +! ;
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 Forth code.
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used ! : empty? used @ 0= ; : full? used @ size = ; : next cell+ dup end = if drop buffer then ; : put full? abort" buffer full" tail @ ! tail @ next tail ! 1 used +! ; : get empty? abort" buffer empty" head @ @ head @ next head ! -1 used +! ;
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; } }
Keep all operations the same but rewrite the snippet in Python.
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used ! : empty? used @ 0= ; : full? used @ size = ; : next cell+ dup end = if drop buffer then ; : put full? abort" buffer full" tail @ ! tail @ next tail ! 1 used +! ; : get empty? abort" buffer empty" head @ @ head @ next head ! -1 used +! ;
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,
Port the following code from Forth to VB with equivalent syntax and logic.
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used ! : empty? used @ 0= ; : full? used @ size = ; : next cell+ dup end = if drop buffer then ; : put full? abort" buffer full" tail @ ! tail @ next tail ! 1 used +! ; : get empty? abort" buffer empty" head @ @ head @ next head ! -1 used +! ;
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
Generate an equivalent Go version of this Forth code.
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used ! : empty? used @ 0= ; : full? used @ size = ; : next cell+ dup end = if drop buffer then ; : put full? abort" buffer full" tail @ ! tail @ next tail ! 1 used +! ; : get empty? abort" buffer empty" head @ @ head @ next head ! -1 used +! ;
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 C# but keep the logic exactly as in Fortran.
module FIFO use fifo_nodes type fifo_head type(fifo_node), pointer :: head, tail end type fifo_head contains subroutine new_fifo(h) type(fifo_head), intent(out) :: h nullify(h%head) nullify(h%tail) end subroutine new_fifo subroutine fifo_enqueue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(inout), target :: n if ( associated(h%tail) ) then h%tail%next => n h%tail => n else h%tail => n h%head => n end if nullify(n%next) end subroutine fifo_enqueue subroutine fifo_dequeue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(out), target :: n if ( associated(h%head) ) then n = h%head if ( associated(n%next) ) then h%head => n%next else nullify(h%head) nullify(h%tail) end if n%valid = .true. else n%valid = .false. end if nullify(n%next) end subroutine fifo_dequeue function fifo_isempty(h) result(r) logical :: r type(fifo_head), intent(in) :: h if ( associated(h%head) ) then r = .false. else r = .true. end if end function fifo_isempty end module FIFO
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 Fortran implementation.
module FIFO use fifo_nodes type fifo_head type(fifo_node), pointer :: head, tail end type fifo_head contains subroutine new_fifo(h) type(fifo_head), intent(out) :: h nullify(h%head) nullify(h%tail) end subroutine new_fifo subroutine fifo_enqueue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(inout), target :: n if ( associated(h%tail) ) then h%tail%next => n h%tail => n else h%tail => n h%head => n end if nullify(n%next) end subroutine fifo_enqueue subroutine fifo_dequeue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(out), target :: n if ( associated(h%head) ) then n = h%head if ( associated(n%next) ) then h%head => n%next else nullify(h%head) nullify(h%tail) end if n%valid = .true. else n%valid = .false. end if nullify(n%next) end subroutine fifo_dequeue function fifo_isempty(h) result(r) logical :: r type(fifo_head), intent(in) :: h if ( associated(h%head) ) then r = .false. else r = .true. end if end function fifo_isempty end module FIFO
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; } }
Convert this Fortran block to C, preserving its control flow and logic.
module FIFO use fifo_nodes type fifo_head type(fifo_node), pointer :: head, tail end type fifo_head contains subroutine new_fifo(h) type(fifo_head), intent(out) :: h nullify(h%head) nullify(h%tail) end subroutine new_fifo subroutine fifo_enqueue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(inout), target :: n if ( associated(h%tail) ) then h%tail%next => n h%tail => n else h%tail => n h%head => n end if nullify(n%next) end subroutine fifo_enqueue subroutine fifo_dequeue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(out), target :: n if ( associated(h%head) ) then n = h%head if ( associated(n%next) ) then h%head => n%next else nullify(h%head) nullify(h%tail) end if n%valid = .true. else n%valid = .false. end if nullify(n%next) end subroutine fifo_dequeue function fifo_isempty(h) result(r) logical :: r type(fifo_head), intent(in) :: h if ( associated(h%head) ) then r = .false. else r = .true. end if end function fifo_isempty end module FIFO
#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 Fortran to Java without modifying what it does.
module FIFO use fifo_nodes type fifo_head type(fifo_node), pointer :: head, tail end type fifo_head contains subroutine new_fifo(h) type(fifo_head), intent(out) :: h nullify(h%head) nullify(h%tail) end subroutine new_fifo subroutine fifo_enqueue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(inout), target :: n if ( associated(h%tail) ) then h%tail%next => n h%tail => n else h%tail => n h%head => n end if nullify(n%next) end subroutine fifo_enqueue subroutine fifo_dequeue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(out), target :: n if ( associated(h%head) ) then n = h%head if ( associated(n%next) ) then h%head => n%next else nullify(h%head) nullify(h%tail) end if n%valid = .true. else n%valid = .false. end if nullify(n%next) end subroutine fifo_dequeue function fifo_isempty(h) result(r) logical :: r type(fifo_head), intent(in) :: h if ( associated(h%head) ) then r = .false. else r = .true. end if end function fifo_isempty end module FIFO
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 Fortran block to Python, preserving its control flow and logic.
module FIFO use fifo_nodes type fifo_head type(fifo_node), pointer :: head, tail end type fifo_head contains subroutine new_fifo(h) type(fifo_head), intent(out) :: h nullify(h%head) nullify(h%tail) end subroutine new_fifo subroutine fifo_enqueue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(inout), target :: n if ( associated(h%tail) ) then h%tail%next => n h%tail => n else h%tail => n h%head => n end if nullify(n%next) end subroutine fifo_enqueue subroutine fifo_dequeue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(out), target :: n if ( associated(h%head) ) then n = h%head if ( associated(n%next) ) then h%head => n%next else nullify(h%head) nullify(h%tail) end if n%valid = .true. else n%valid = .false. end if nullify(n%next) end subroutine fifo_dequeue function fifo_isempty(h) result(r) logical :: r type(fifo_head), intent(in) :: h if ( associated(h%head) ) then r = .false. else r = .true. end if end function fifo_isempty end module FIFO
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 Fortran.
module FIFO use fifo_nodes type fifo_head type(fifo_node), pointer :: head, tail end type fifo_head contains subroutine new_fifo(h) type(fifo_head), intent(out) :: h nullify(h%head) nullify(h%tail) end subroutine new_fifo subroutine fifo_enqueue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(inout), target :: n if ( associated(h%tail) ) then h%tail%next => n h%tail => n else h%tail => n h%head => n end if nullify(n%next) end subroutine fifo_enqueue subroutine fifo_dequeue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(out), target :: n if ( associated(h%head) ) then n = h%head if ( associated(n%next) ) then h%head => n%next else nullify(h%head) nullify(h%tail) end if n%valid = .true. else n%valid = .false. end if nullify(n%next) end subroutine fifo_dequeue function fifo_isempty(h) result(r) logical :: r type(fifo_head), intent(in) :: h if ( associated(h%head) ) then r = .false. else r = .true. end if end function fifo_isempty end module FIFO
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 this program into PHP but keep the logic exactly as in Fortran.
module FIFO use fifo_nodes type fifo_head type(fifo_node), pointer :: head, tail end type fifo_head contains subroutine new_fifo(h) type(fifo_head), intent(out) :: h nullify(h%head) nullify(h%tail) end subroutine new_fifo subroutine fifo_enqueue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(inout), target :: n if ( associated(h%tail) ) then h%tail%next => n h%tail => n else h%tail => n h%head => n end if nullify(n%next) end subroutine fifo_enqueue subroutine fifo_dequeue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(out), target :: n if ( associated(h%head) ) then n = h%head if ( associated(n%next) ) then h%head => n%next else nullify(h%head) nullify(h%tail) end if n%valid = .true. else n%valid = .false. end if nullify(n%next) end subroutine fifo_dequeue function fifo_isempty(h) result(r) logical :: r type(fifo_head), intent(in) :: h if ( associated(h%head) ) then r = .false. else r = .true. end if end function fifo_isempty end module 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); } }
Convert the following code from Groovy to C, ensuring the logic remains intact.
class Queue { private List buffer public Queue(List buffer = new LinkedList()) { assert buffer != null assert buffer.empty this.buffer = buffer } def push (def item) { buffer << item } final enqueue = this.&push def pop() { if (this.empty) throw new NoSuchElementException('Empty Queue') buffer.remove(0) } final dequeue = this.&pop def getEmpty() { buffer.empty } String toString() { "Queue:${buffer}" } }
#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 Groovy to C# without modifying what it does.
class Queue { private List buffer public Queue(List buffer = new LinkedList()) { assert buffer != null assert buffer.empty this.buffer = buffer } def push (def item) { buffer << item } final enqueue = this.&push def pop() { if (this.empty) throw new NoSuchElementException('Empty Queue') buffer.remove(0) } final dequeue = this.&pop def getEmpty() { buffer.empty } String toString() { "Queue:${buffer}" } }
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 Groovy, keeping it the same logically?
class Queue { private List buffer public Queue(List buffer = new LinkedList()) { assert buffer != null assert buffer.empty this.buffer = buffer } def push (def item) { buffer << item } final enqueue = this.&push def pop() { if (this.empty) throw new NoSuchElementException('Empty Queue') buffer.remove(0) } final dequeue = this.&pop def getEmpty() { buffer.empty } String toString() { "Queue:${buffer}" } }
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 an equivalent Java version of this Groovy code.
class Queue { private List buffer public Queue(List buffer = new LinkedList()) { assert buffer != null assert buffer.empty this.buffer = buffer } def push (def item) { buffer << item } final enqueue = this.&push def pop() { if (this.empty) throw new NoSuchElementException('Empty Queue') buffer.remove(0) } final dequeue = this.&pop def getEmpty() { buffer.empty } String toString() { "Queue:${buffer}" } }
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; } }
Write the same code in Python as shown below in Groovy.
class Queue { private List buffer public Queue(List buffer = new LinkedList()) { assert buffer != null assert buffer.empty this.buffer = buffer } def push (def item) { buffer << item } final enqueue = this.&push def pop() { if (this.empty) throw new NoSuchElementException('Empty Queue') buffer.remove(0) } final dequeue = this.&pop def getEmpty() { buffer.empty } String toString() { "Queue:${buffer}" } }
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 a VB translation of this Groovy snippet without changing its computational steps.
class Queue { private List buffer public Queue(List buffer = new LinkedList()) { assert buffer != null assert buffer.empty this.buffer = buffer } def push (def item) { buffer << item } final enqueue = this.&push def pop() { if (this.empty) throw new NoSuchElementException('Empty Queue') buffer.remove(0) } final dequeue = this.&pop def getEmpty() { buffer.empty } String toString() { "Queue:${buffer}" } }
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 Groovy block to Go, preserving its control flow and logic.
class Queue { private List buffer public Queue(List buffer = new LinkedList()) { assert buffer != null assert buffer.empty this.buffer = buffer } def push (def item) { buffer << item } final enqueue = this.&push def pop() { if (this.empty) throw new NoSuchElementException('Empty Queue') buffer.remove(0) } final dequeue = this.&pop def getEmpty() { buffer.empty } String toString() { "Queue:${buffer}" } }
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 }
Produce a language-to-language conversion: from Haskell to C, same semantics.
data Fifo a = F [a] [a] emptyFifo :: Fifo a emptyFifo = F [] [] push :: Fifo a -> a -> Fifo a push (F input output) item = F (item:input) output pop :: Fifo a -> (Maybe a, Fifo a) pop (F input (item:output)) = (Just item, F input output) pop (F [] [] ) = (Nothing, F [] []) pop (F input [] ) = pop (F [] (reverse input)) isEmpty :: Fifo a -> Bool isEmpty (F [] []) = True isEmpty _ = False
#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; }
Preserve the algorithm and functionality while converting the code from Haskell to C#.
data Fifo a = F [a] [a] emptyFifo :: Fifo a emptyFifo = F [] [] push :: Fifo a -> a -> Fifo a push (F input output) item = F (item:input) output pop :: Fifo a -> (Maybe a, Fifo a) pop (F input (item:output)) = (Just item, F input output) pop (F [] [] ) = (Nothing, F [] []) pop (F input [] ) = pop (F [] (reverse input)) isEmpty :: Fifo a -> Bool isEmpty (F [] []) = True isEmpty _ = False
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; } }
Convert this Haskell snippet to C++ and keep its semantics consistent.
data Fifo a = F [a] [a] emptyFifo :: Fifo a emptyFifo = F [] [] push :: Fifo a -> a -> Fifo a push (F input output) item = F (item:input) output pop :: Fifo a -> (Maybe a, Fifo a) pop (F input (item:output)) = (Just item, F input output) pop (F [] [] ) = (Nothing, F [] []) pop (F input [] ) = pop (F [] (reverse input)) isEmpty :: Fifo a -> Bool isEmpty (F [] []) = True isEmpty _ = False
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; } }
Change the following Haskell code into Java without altering its purpose.
data Fifo a = F [a] [a] emptyFifo :: Fifo a emptyFifo = F [] [] push :: Fifo a -> a -> Fifo a push (F input output) item = F (item:input) output pop :: Fifo a -> (Maybe a, Fifo a) pop (F input (item:output)) = (Just item, F input output) pop (F [] [] ) = (Nothing, F [] []) pop (F input [] ) = pop (F [] (reverse input)) isEmpty :: Fifo a -> Bool isEmpty (F [] []) = True isEmpty _ = False
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; } }
Write the same code in Python as shown below in Haskell.
data Fifo a = F [a] [a] emptyFifo :: Fifo a emptyFifo = F [] [] push :: Fifo a -> a -> Fifo a push (F input output) item = F (item:input) output pop :: Fifo a -> (Maybe a, Fifo a) pop (F input (item:output)) = (Just item, F input output) pop (F [] [] ) = (Nothing, F [] []) pop (F input [] ) = pop (F [] (reverse input)) isEmpty :: Fifo a -> Bool isEmpty (F [] []) = True isEmpty _ = False
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 Haskell.
data Fifo a = F [a] [a] emptyFifo :: Fifo a emptyFifo = F [] [] push :: Fifo a -> a -> Fifo a push (F input output) item = F (item:input) output pop :: Fifo a -> (Maybe a, Fifo a) pop (F input (item:output)) = (Just item, F input output) pop (F [] [] ) = (Nothing, F [] []) pop (F input [] ) = pop (F [] (reverse input)) isEmpty :: Fifo a -> Bool isEmpty (F [] []) = True isEmpty _ = False
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 Haskell code into Go while preserving the original functionality.
data Fifo a = F [a] [a] emptyFifo :: Fifo a emptyFifo = F [] [] push :: Fifo a -> a -> Fifo a push (F input output) item = F (item:input) output pop :: Fifo a -> (Maybe a, Fifo a) pop (F input (item:output)) = (Just item, F input output) pop (F [] [] ) = (Nothing, F [] []) pop (F input [] ) = pop (F [] (reverse input)) isEmpty :: Fifo a -> Bool isEmpty (F [] []) = True isEmpty _ = False
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 }
Transform the following Icon implementation into C, maintaining the same output and logic.
record Queue(items) procedure make_queue () return Queue ([]) end procedure queue_push (queue, item) put (queue.items, item) end procedure queue_pop (queue) return pop (queue.items) end procedure queue_empty (queue) return *queue.items = 0 end procedure main () queue := make_queue() every (item := 1 to 5) do queue_push (queue, item) every (1 to 6) do { write ("Popped value: " || queue_pop (queue)) if (queue_empty (queue)) then write ("empty queue") } 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; }
Can you help me rewrite this code in C# instead of Icon, keeping it the same logically?
record Queue(items) procedure make_queue () return Queue ([]) end procedure queue_push (queue, item) put (queue.items, item) end procedure queue_pop (queue) return pop (queue.items) end procedure queue_empty (queue) return *queue.items = 0 end procedure main () queue := make_queue() every (item := 1 to 5) do queue_push (queue, item) every (1 to 6) do { write ("Popped value: " || queue_pop (queue)) if (queue_empty (queue)) then write ("empty queue") } 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; } }
Port the provided Icon code into C++ while preserving the original functionality.
record Queue(items) procedure make_queue () return Queue ([]) end procedure queue_push (queue, item) put (queue.items, item) end procedure queue_pop (queue) return pop (queue.items) end procedure queue_empty (queue) return *queue.items = 0 end procedure main () queue := make_queue() every (item := 1 to 5) do queue_push (queue, item) every (1 to 6) do { write ("Popped value: " || queue_pop (queue)) if (queue_empty (queue)) then write ("empty queue") } 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; } }
Can you help me rewrite this code in Java instead of Icon, keeping it the same logically?
record Queue(items) procedure make_queue () return Queue ([]) end procedure queue_push (queue, item) put (queue.items, item) end procedure queue_pop (queue) return pop (queue.items) end procedure queue_empty (queue) return *queue.items = 0 end procedure main () queue := make_queue() every (item := 1 to 5) do queue_push (queue, item) every (1 to 6) do { write ("Popped value: " || queue_pop (queue)) if (queue_empty (queue)) then write ("empty queue") } 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 Icon to Python, ensuring the logic remains intact.
record Queue(items) procedure make_queue () return Queue ([]) end procedure queue_push (queue, item) put (queue.items, item) end procedure queue_pop (queue) return pop (queue.items) end procedure queue_empty (queue) return *queue.items = 0 end procedure main () queue := make_queue() every (item := 1 to 5) do queue_push (queue, item) every (1 to 6) do { write ("Popped value: " || queue_pop (queue)) if (queue_empty (queue)) then write ("empty queue") } 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 Icon code.
record Queue(items) procedure make_queue () return Queue ([]) end procedure queue_push (queue, item) put (queue.items, item) end procedure queue_pop (queue) return pop (queue.items) end procedure queue_empty (queue) return *queue.items = 0 end procedure main () queue := make_queue() every (item := 1 to 5) do queue_push (queue, item) every (1 to 6) do { write ("Popped value: " || queue_pop (queue)) if (queue_empty (queue)) then write ("empty queue") } 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
Write the same code in Go as shown below in Icon.
record Queue(items) procedure make_queue () return Queue ([]) end procedure queue_push (queue, item) put (queue.items, item) end procedure queue_pop (queue) return pop (queue.items) end procedure queue_empty (queue) return *queue.items = 0 end procedure main () queue := make_queue() every (item := 1 to 5) do queue_push (queue, item) every (1 to 6) do { write ("Popped value: " || queue_pop (queue)) if (queue_empty (queue)) then write ("empty queue") } 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 }
Write the same code in C as shown below in J.
queue_fifo_=: '' pop_fifo_=: verb define r=. {. ::] queue queue=: }.queue r ) push_fifo_=: verb define queue=: queue,y y ) isEmpty_fifo_=: verb define 0=#queue )
#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 J code snippet into C# without altering its behavior.
queue_fifo_=: '' pop_fifo_=: verb define r=. {. ::] queue queue=: }.queue r ) push_fifo_=: verb define queue=: queue,y y ) isEmpty_fifo_=: verb define 0=#queue )
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; } }
Convert this J block to C++, preserving its control flow and logic.
queue_fifo_=: '' pop_fifo_=: verb define r=. {. ::] queue queue=: }.queue r ) push_fifo_=: verb define queue=: queue,y y ) isEmpty_fifo_=: verb define 0=#queue )
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; } }
Change the programming language of this snippet from J to Java without modifying what it does.
queue_fifo_=: '' pop_fifo_=: verb define r=. {. ::] queue queue=: }.queue r ) push_fifo_=: verb define queue=: queue,y y ) isEmpty_fifo_=: verb define 0=#queue )
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 J block to VB, preserving its control flow and logic.
queue_fifo_=: '' pop_fifo_=: verb define r=. {. ::] queue queue=: }.queue r ) push_fifo_=: verb define queue=: queue,y y ) isEmpty_fifo_=: verb define 0=#queue )
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
Generate an equivalent Go version of this J code.
queue_fifo_=: '' pop_fifo_=: verb define r=. {. ::] queue queue=: }.queue r ) push_fifo_=: verb define queue=: queue,y y ) isEmpty_fifo_=: verb define 0=#queue )
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 }
Keep all operations the same but rewrite the snippet in C.
struct Queue{T} a::Array{T,1} end Queue() = Queue(Any[]) Queue(a::DataType) = Queue(a[]) Queue(a) = Queue(typeof(a)[]) Base.isempty(q::Queue) = isempty(q.a) function Base.pop!(q::Queue{T}) where {T} !isempty(q) || error("queue must be non-empty") pop!(q.a) end function Base.push!(q::Queue{T}, x::T) where {T} pushfirst!(q.a, x) return q end function Base.push!(q::Queue{Any}, x::T) where {T} pushfirst!(q.a, x) return q 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; }
Please provide an equivalent version of this Julia code in C#.
struct Queue{T} a::Array{T,1} end Queue() = Queue(Any[]) Queue(a::DataType) = Queue(a[]) Queue(a) = Queue(typeof(a)[]) Base.isempty(q::Queue) = isempty(q.a) function Base.pop!(q::Queue{T}) where {T} !isempty(q) || error("queue must be non-empty") pop!(q.a) end function Base.push!(q::Queue{T}, x::T) where {T} pushfirst!(q.a, x) return q end function Base.push!(q::Queue{Any}, x::T) where {T} pushfirst!(q.a, x) return q 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; } }
Generate an equivalent C++ version of this Julia code.
struct Queue{T} a::Array{T,1} end Queue() = Queue(Any[]) Queue(a::DataType) = Queue(a[]) Queue(a) = Queue(typeof(a)[]) Base.isempty(q::Queue) = isempty(q.a) function Base.pop!(q::Queue{T}) where {T} !isempty(q) || error("queue must be non-empty") pop!(q.a) end function Base.push!(q::Queue{T}, x::T) where {T} pushfirst!(q.a, x) return q end function Base.push!(q::Queue{Any}, x::T) where {T} pushfirst!(q.a, x) return q 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; } }
Translate this program into Java but keep the logic exactly as in Julia.
struct Queue{T} a::Array{T,1} end Queue() = Queue(Any[]) Queue(a::DataType) = Queue(a[]) Queue(a) = Queue(typeof(a)[]) Base.isempty(q::Queue) = isempty(q.a) function Base.pop!(q::Queue{T}) where {T} !isempty(q) || error("queue must be non-empty") pop!(q.a) end function Base.push!(q::Queue{T}, x::T) where {T} pushfirst!(q.a, x) return q end function Base.push!(q::Queue{Any}, x::T) where {T} pushfirst!(q.a, x) return q 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; } }
Please provide an equivalent version of this Julia code in Python.
struct Queue{T} a::Array{T,1} end Queue() = Queue(Any[]) Queue(a::DataType) = Queue(a[]) Queue(a) = Queue(typeof(a)[]) Base.isempty(q::Queue) = isempty(q.a) function Base.pop!(q::Queue{T}) where {T} !isempty(q) || error("queue must be non-empty") pop!(q.a) end function Base.push!(q::Queue{T}, x::T) where {T} pushfirst!(q.a, x) return q end function Base.push!(q::Queue{Any}, x::T) where {T} pushfirst!(q.a, x) return q 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,
Write a version of this Julia function in VB with identical behavior.
struct Queue{T} a::Array{T,1} end Queue() = Queue(Any[]) Queue(a::DataType) = Queue(a[]) Queue(a) = Queue(typeof(a)[]) Base.isempty(q::Queue) = isempty(q.a) function Base.pop!(q::Queue{T}) where {T} !isempty(q) || error("queue must be non-empty") pop!(q.a) end function Base.push!(q::Queue{T}, x::T) where {T} pushfirst!(q.a, x) return q end function Base.push!(q::Queue{Any}, x::T) where {T} pushfirst!(q.a, x) return q 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.
struct Queue{T} a::Array{T,1} end Queue() = Queue(Any[]) Queue(a::DataType) = Queue(a[]) Queue(a) = Queue(typeof(a)[]) Base.isempty(q::Queue) = isempty(q.a) function Base.pop!(q::Queue{T}) where {T} !isempty(q) || error("queue must be non-empty") pop!(q.a) end function Base.push!(q::Queue{T}, x::T) where {T} pushfirst!(q.a, x) return q end function Base.push!(q::Queue{Any}, x::T) where {T} pushfirst!(q.a, x) return q 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 }
Port the following code from Lua to C with equivalent syntax 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
#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; }