Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in Go as shown below in Lua.
List.iterateForward = function(self) local function iter(self, node) if node then return node.next else return self.head end end return iter, self, nil end List.iterateReverse = function(self) local function iter(self, node) if node then return node.prev else return self.tail end end return iter, self, nil end local list = List() for i = 1, 5 do list:insertTail(i) end io.write("Forward: ") for node in list:iterateForward() do io.write(node.data..",") end print() io.write("Reverse: ") for node in list:iterateReverse() do io.write(node.data..",") end print()
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) fmt.Print("From tail:") for p := dll.tail; p != nil; p = p.prev { fmt.Print(" ", p.string) } fmt.Println("") }
Ensure the translated C code behaves exactly like the original Nim snippet.
type List[T] = object head, tail: Node[T] Node[T] = ref TNode[T] TNode[T] = object next, prev: Node[T] data: T proc initList[T](): List[T] = discard proc newNode[T](data: T): Node[T] = new(result) result.data = data proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.head != nil: l.head.prev = n l.head = n if l.tail == nil: l.tail = n proc append[T](l: var List[T], n: Node[T]) = n.next = nil n.prev = l.tail if l.tail != nil: l.tail.next = n l.tail = n if l.head == nil: l.head = n proc insertAfter[T](l: var List[T], r, n: Node[T]) = n.prev = r n.next = r.next n.next.prev = n r.next = n if r == l.tail: l.tail = n proc remove[T](l: var List[T], n: Node[T]) = if n == l.tail: l.tail = n.prev if n == l.head: l.head = n.next if n.next != nil: n.next.prev = n.prev if n.prev != nil: n.prev.next = n.next proc `$`[T](l: var List[T]): string = result = "" var n = l.head while n != nil: if result.len > 0: result.add(" -> ") result.add($n.data) n = n.next iterator traverseForward[T](l: List[T]): T = var n = l.head while n != nil: yield n.data n = n.next iterator traverseBackward[T](l: List[T]): T = var n = l.tail while n != nil: yield n.data n = n.prev var l = initList[int]() var n = newNode(12) var m = newNode(13) var i = newNode(14) var j = newNode(15) l.append(n) l.prepend(m) l.insertAfter(m, i) l.prepend(j) l.remove(m) for i in l.traverseForward(): echo "> ", i for i in l.traverseBackward(): echo "< ", i
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct sListEntry { const char *value; struct sListEntry *next; struct sListEntry *prev; } *ListEntry, *LinkedList; typedef struct sListIterator{ ListEntry link; LinkedList head; } *LIterator; LinkedList NewList() { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = NULL; le->next = le->prev = NULL; } return le; } int LL_Append(LinkedList ll, const char *newVal) { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); le->prev = ll->prev; le->next = NULL; if (le->prev) le->prev->next = le; else ll->next = le; ll->prev = le; } return (le!= NULL); } int LI_Insert(LIterator iter, const char *newVal) { ListEntry crnt = iter->link; ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); if ( crnt == iter->head) { le->prev = NULL; le->next = crnt->next; crnt->next = le; if (le->next) le->next->prev = le; else crnt->prev = le; } else { le->prev = ( crnt == NULL)? iter->head->prev : crnt->prev; le->next = crnt; if (le->prev) le->prev->next = le; else iter->head->next = le; if (crnt) crnt->prev = le; else iter->head->prev = le; } } return (le!= NULL); } LIterator LL_GetIterator(LinkedList ll ) { LIterator liter = malloc(sizeof(struct sListIterator)); liter->head = ll; liter->link = ll; return liter; } #define LLI_Delete( iter ) \ {free(iter); \ iter = NULL;} int LLI_AtEnd(LIterator iter) { return iter->link == NULL; } const char *LLI_Value(LIterator iter) { return (iter->link)? iter->link->value: NULL; } int LLI_Next(LIterator iter) { if (iter->link) iter->link = iter->link->next; return(iter->link != NULL); } int LLI_Prev(LIterator iter) { if (iter->link) iter->link = iter->link->prev; return(iter->link != NULL); } int main() { static const char *contents[] = {"Read", "Orage", "Yeller", "Glean", "Blew", "Burple"}; int ix; LinkedList ll = NewList(); LIterator iter; for (ix=0; ix<6; ix++) LL_Append(ll, contents[ix]); iter = LL_GetIterator(ll); printf("forward\n"); while(LLI_Next(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); printf("\nreverse\n"); iter = LL_GetIterator(ll); while(LLI_Prev(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); return 0; }
Generate a C# translation of this Nim snippet without changing its computational steps.
type List[T] = object head, tail: Node[T] Node[T] = ref TNode[T] TNode[T] = object next, prev: Node[T] data: T proc initList[T](): List[T] = discard proc newNode[T](data: T): Node[T] = new(result) result.data = data proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.head != nil: l.head.prev = n l.head = n if l.tail == nil: l.tail = n proc append[T](l: var List[T], n: Node[T]) = n.next = nil n.prev = l.tail if l.tail != nil: l.tail.next = n l.tail = n if l.head == nil: l.head = n proc insertAfter[T](l: var List[T], r, n: Node[T]) = n.prev = r n.next = r.next n.next.prev = n r.next = n if r == l.tail: l.tail = n proc remove[T](l: var List[T], n: Node[T]) = if n == l.tail: l.tail = n.prev if n == l.head: l.head = n.next if n.next != nil: n.next.prev = n.prev if n.prev != nil: n.prev.next = n.next proc `$`[T](l: var List[T]): string = result = "" var n = l.head while n != nil: if result.len > 0: result.add(" -> ") result.add($n.data) n = n.next iterator traverseForward[T](l: List[T]): T = var n = l.head while n != nil: yield n.data n = n.next iterator traverseBackward[T](l: List[T]): T = var n = l.tail while n != nil: yield n.data n = n.prev var l = initList[int]() var n = newNode(12) var m = newNode(13) var i = newNode(14) var j = newNode(15) l.append(n) l.prepend(m) l.insertAfter(m, i) l.prepend(j) l.remove(m) for i in l.traverseForward(): echo "> ", i for i in l.traverseBackward(): echo "< ", i
using System; using System.Collections.Generic; namespace RosettaCode.DoublyLinkedList { internal static class Program { private static void Main() { var list = new LinkedList<char>("hello"); var current = list.First; do { Console.WriteLine(current.Value); } while ((current = current.Next) != null); Console.WriteLine(); current = list.Last; do { Console.WriteLine(current.Value); } while ((current = current.Previous) != null); } } }
Can you help me rewrite this code in C++ instead of Nim, keeping it the same logically?
type List[T] = object head, tail: Node[T] Node[T] = ref TNode[T] TNode[T] = object next, prev: Node[T] data: T proc initList[T](): List[T] = discard proc newNode[T](data: T): Node[T] = new(result) result.data = data proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.head != nil: l.head.prev = n l.head = n if l.tail == nil: l.tail = n proc append[T](l: var List[T], n: Node[T]) = n.next = nil n.prev = l.tail if l.tail != nil: l.tail.next = n l.tail = n if l.head == nil: l.head = n proc insertAfter[T](l: var List[T], r, n: Node[T]) = n.prev = r n.next = r.next n.next.prev = n r.next = n if r == l.tail: l.tail = n proc remove[T](l: var List[T], n: Node[T]) = if n == l.tail: l.tail = n.prev if n == l.head: l.head = n.next if n.next != nil: n.next.prev = n.prev if n.prev != nil: n.prev.next = n.next proc `$`[T](l: var List[T]): string = result = "" var n = l.head while n != nil: if result.len > 0: result.add(" -> ") result.add($n.data) n = n.next iterator traverseForward[T](l: List[T]): T = var n = l.head while n != nil: yield n.data n = n.next iterator traverseBackward[T](l: List[T]): T = var n = l.tail while n != nil: yield n.data n = n.prev var l = initList[int]() var n = newNode(12) var m = newNode(13) var i = newNode(14) var j = newNode(15) l.append(n) l.prepend(m) l.insertAfter(m, i) l.prepend(j) l.remove(m) for i in l.traverseForward(): echo "> ", i for i in l.traverseBackward(): echo "< ", i
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
Rewrite this program in Java while keeping its functionality equivalent to the Nim version.
type List[T] = object head, tail: Node[T] Node[T] = ref TNode[T] TNode[T] = object next, prev: Node[T] data: T proc initList[T](): List[T] = discard proc newNode[T](data: T): Node[T] = new(result) result.data = data proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.head != nil: l.head.prev = n l.head = n if l.tail == nil: l.tail = n proc append[T](l: var List[T], n: Node[T]) = n.next = nil n.prev = l.tail if l.tail != nil: l.tail.next = n l.tail = n if l.head == nil: l.head = n proc insertAfter[T](l: var List[T], r, n: Node[T]) = n.prev = r n.next = r.next n.next.prev = n r.next = n if r == l.tail: l.tail = n proc remove[T](l: var List[T], n: Node[T]) = if n == l.tail: l.tail = n.prev if n == l.head: l.head = n.next if n.next != nil: n.next.prev = n.prev if n.prev != nil: n.prev.next = n.next proc `$`[T](l: var List[T]): string = result = "" var n = l.head while n != nil: if result.len > 0: result.add(" -> ") result.add($n.data) n = n.next iterator traverseForward[T](l: List[T]): T = var n = l.head while n != nil: yield n.data n = n.next iterator traverseBackward[T](l: List[T]): T = var n = l.tail while n != nil: yield n.data n = n.prev var l = initList[int]() var n = newNode(12) var m = newNode(13) var i = newNode(14) var j = newNode(15) l.append(n) l.prepend(m) l.insertAfter(m, i) l.prepend(j) l.remove(m) for i in l.traverseForward(): echo "> ", i for i in l.traverseBackward(): echo "< ", i
package com.rosettacode; import java.util.LinkedList; import java.util.stream.Collectors; import java.util.stream.IntStream; public class DoubleLinkedListTraversing { public static void main(String[] args) { final LinkedList<String> doubleLinkedList = IntStream.range(1, 10) .mapToObj(String::valueOf) .collect(Collectors.toCollection(LinkedList::new)); doubleLinkedList.iterator().forEachRemaining(System.out::print); System.out.println(); doubleLinkedList.descendingIterator().forEachRemaining(System.out::print); } }
Produce a language-to-language conversion: from Nim to Python, same semantics.
type List[T] = object head, tail: Node[T] Node[T] = ref TNode[T] TNode[T] = object next, prev: Node[T] data: T proc initList[T](): List[T] = discard proc newNode[T](data: T): Node[T] = new(result) result.data = data proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.head != nil: l.head.prev = n l.head = n if l.tail == nil: l.tail = n proc append[T](l: var List[T], n: Node[T]) = n.next = nil n.prev = l.tail if l.tail != nil: l.tail.next = n l.tail = n if l.head == nil: l.head = n proc insertAfter[T](l: var List[T], r, n: Node[T]) = n.prev = r n.next = r.next n.next.prev = n r.next = n if r == l.tail: l.tail = n proc remove[T](l: var List[T], n: Node[T]) = if n == l.tail: l.tail = n.prev if n == l.head: l.head = n.next if n.next != nil: n.next.prev = n.prev if n.prev != nil: n.prev.next = n.next proc `$`[T](l: var List[T]): string = result = "" var n = l.head while n != nil: if result.len > 0: result.add(" -> ") result.add($n.data) n = n.next iterator traverseForward[T](l: List[T]): T = var n = l.head while n != nil: yield n.data n = n.next iterator traverseBackward[T](l: List[T]): T = var n = l.tail while n != nil: yield n.data n = n.prev var l = initList[int]() var n = newNode(12) var m = newNode(13) var i = newNode(14) var j = newNode(15) l.append(n) l.prepend(m) l.insertAfter(m, i) l.prepend(j) l.remove(m) for i in l.traverseForward(): echo "> ", i for i in l.traverseBackward(): echo "< ", i
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.append(data) tail = head = List(10) for i in [ 20, 30, 40 ]: tail = tail.append(i) node = head while node != None: print(node.data) node = node.next node = tail while node != None: print(node.data) node = node.prev
Write a version of this Nim function in Go with identical behavior.
type List[T] = object head, tail: Node[T] Node[T] = ref TNode[T] TNode[T] = object next, prev: Node[T] data: T proc initList[T](): List[T] = discard proc newNode[T](data: T): Node[T] = new(result) result.data = data proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.head != nil: l.head.prev = n l.head = n if l.tail == nil: l.tail = n proc append[T](l: var List[T], n: Node[T]) = n.next = nil n.prev = l.tail if l.tail != nil: l.tail.next = n l.tail = n if l.head == nil: l.head = n proc insertAfter[T](l: var List[T], r, n: Node[T]) = n.prev = r n.next = r.next n.next.prev = n r.next = n if r == l.tail: l.tail = n proc remove[T](l: var List[T], n: Node[T]) = if n == l.tail: l.tail = n.prev if n == l.head: l.head = n.next if n.next != nil: n.next.prev = n.prev if n.prev != nil: n.prev.next = n.next proc `$`[T](l: var List[T]): string = result = "" var n = l.head while n != nil: if result.len > 0: result.add(" -> ") result.add($n.data) n = n.next iterator traverseForward[T](l: List[T]): T = var n = l.head while n != nil: yield n.data n = n.next iterator traverseBackward[T](l: List[T]): T = var n = l.tail while n != nil: yield n.data n = n.prev var l = initList[int]() var n = newNode(12) var m = newNode(13) var i = newNode(14) var j = newNode(15) l.append(n) l.prepend(m) l.insertAfter(m, i) l.prepend(j) l.remove(m) for i in l.traverseForward(): echo "> ", i for i in l.traverseBackward(): echo "< ", i
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) fmt.Print("From tail:") for p := dll.tail; p != nil; p = p.prev { fmt.Print(" ", p.string) } fmt.Println("") }
Generate a C translation of this Racket snippet without changing its computational steps.
(define (dlist-elements dlist) (let loop ([elements '()] [dlink (dlist-tail dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-prev dlink)) elements))) (define (dlist-elements/reverse dlist) (let loop ([elements '()] [dlink (dlist-head dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-next dlink)) elements)))
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct sListEntry { const char *value; struct sListEntry *next; struct sListEntry *prev; } *ListEntry, *LinkedList; typedef struct sListIterator{ ListEntry link; LinkedList head; } *LIterator; LinkedList NewList() { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = NULL; le->next = le->prev = NULL; } return le; } int LL_Append(LinkedList ll, const char *newVal) { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); le->prev = ll->prev; le->next = NULL; if (le->prev) le->prev->next = le; else ll->next = le; ll->prev = le; } return (le!= NULL); } int LI_Insert(LIterator iter, const char *newVal) { ListEntry crnt = iter->link; ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); if ( crnt == iter->head) { le->prev = NULL; le->next = crnt->next; crnt->next = le; if (le->next) le->next->prev = le; else crnt->prev = le; } else { le->prev = ( crnt == NULL)? iter->head->prev : crnt->prev; le->next = crnt; if (le->prev) le->prev->next = le; else iter->head->next = le; if (crnt) crnt->prev = le; else iter->head->prev = le; } } return (le!= NULL); } LIterator LL_GetIterator(LinkedList ll ) { LIterator liter = malloc(sizeof(struct sListIterator)); liter->head = ll; liter->link = ll; return liter; } #define LLI_Delete( iter ) \ {free(iter); \ iter = NULL;} int LLI_AtEnd(LIterator iter) { return iter->link == NULL; } const char *LLI_Value(LIterator iter) { return (iter->link)? iter->link->value: NULL; } int LLI_Next(LIterator iter) { if (iter->link) iter->link = iter->link->next; return(iter->link != NULL); } int LLI_Prev(LIterator iter) { if (iter->link) iter->link = iter->link->prev; return(iter->link != NULL); } int main() { static const char *contents[] = {"Read", "Orage", "Yeller", "Glean", "Blew", "Burple"}; int ix; LinkedList ll = NewList(); LIterator iter; for (ix=0; ix<6; ix++) LL_Append(ll, contents[ix]); iter = LL_GetIterator(ll); printf("forward\n"); while(LLI_Next(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); printf("\nreverse\n"); iter = LL_GetIterator(ll); while(LLI_Prev(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); return 0; }
Translate this program into C# but keep the logic exactly as in Racket.
(define (dlist-elements dlist) (let loop ([elements '()] [dlink (dlist-tail dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-prev dlink)) elements))) (define (dlist-elements/reverse dlist) (let loop ([elements '()] [dlink (dlist-head dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-next dlink)) elements)))
using System; using System.Collections.Generic; namespace RosettaCode.DoublyLinkedList { internal static class Program { private static void Main() { var list = new LinkedList<char>("hello"); var current = list.First; do { Console.WriteLine(current.Value); } while ((current = current.Next) != null); Console.WriteLine(); current = list.Last; do { Console.WriteLine(current.Value); } while ((current = current.Previous) != null); } } }
Write the same code in C++ as shown below in Racket.
(define (dlist-elements dlist) (let loop ([elements '()] [dlink (dlist-tail dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-prev dlink)) elements))) (define (dlist-elements/reverse dlist) (let loop ([elements '()] [dlink (dlist-head dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-next dlink)) elements)))
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
Rewrite this program in Java while keeping its functionality equivalent to the Racket version.
(define (dlist-elements dlist) (let loop ([elements '()] [dlink (dlist-tail dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-prev dlink)) elements))) (define (dlist-elements/reverse dlist) (let loop ([elements '()] [dlink (dlist-head dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-next dlink)) elements)))
package com.rosettacode; import java.util.LinkedList; import java.util.stream.Collectors; import java.util.stream.IntStream; public class DoubleLinkedListTraversing { public static void main(String[] args) { final LinkedList<String> doubleLinkedList = IntStream.range(1, 10) .mapToObj(String::valueOf) .collect(Collectors.toCollection(LinkedList::new)); doubleLinkedList.iterator().forEachRemaining(System.out::print); System.out.println(); doubleLinkedList.descendingIterator().forEachRemaining(System.out::print); } }
Port the provided Racket code into Python while preserving the original functionality.
(define (dlist-elements dlist) (let loop ([elements '()] [dlink (dlist-tail dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-prev dlink)) elements))) (define (dlist-elements/reverse dlist) (let loop ([elements '()] [dlink (dlist-head dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-next dlink)) elements)))
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.append(data) tail = head = List(10) for i in [ 20, 30, 40 ]: tail = tail.append(i) node = head while node != None: print(node.data) node = node.next node = tail while node != None: print(node.data) node = node.prev
Convert the following code from Racket to Go, ensuring the logic remains intact.
(define (dlist-elements dlist) (let loop ([elements '()] [dlink (dlist-tail dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-prev dlink)) elements))) (define (dlist-elements/reverse dlist) (let loop ([elements '()] [dlink (dlist-head dlist)]) (if dlink (loop (cons (dlink-content dlink) elements) (dlink-next dlink)) elements)))
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) fmt.Print("From tail:") for p := dll.tail; p != nil; p = p.prev { fmt.Print(" ", p.string) } fmt.Println("") }
Port the provided REXX code into C while preserving the original functionality.
β”Œβ”€β”˜ Functions of the List Manager └─┐ β”‚ β”‚ β”‚ @init ─── initializes the List. β”‚ β”‚ β”‚ β”‚ @size ─── returns the size of the List [could be 0 (zero)]. β”‚ β”‚ β”‚ β”‚ @show ─── shows (displays) the complete List. β”‚ β”‚ @show k,1 ─── shows (displays) the Kth item. β”‚ β”‚ @show k,m ─── shows (displays) M items, starting with Kth item. β”‚ β”‚ @show ,,─1 ─── shows (displays) the complete List backwards. β”‚ β”‚ β”‚ β”‚ @get k ─── returns the Kth item. β”‚ β”‚ @get k,m ─── returns the M items starting with the Kth item. β”‚ β”‚ β”‚ β”‚ @put x ─── adds the X items to the end (tail) of the List. β”‚ β”‚ @put x,0 ─── adds the X items to the start (head) of the List. β”‚ β”‚ @put x,k ─── adds the X items to before of the Kth item. β”‚ β”‚ β”‚ β”‚ @del k ─── deletes the item K. β”‚ β”‚ @del k,m ─── deletes the M items starting with item K. β”‚ └─┐ β”Œβ”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜*/ call sy 'initializing the list.' ; call @init call sy 'building list: Was it a cat I saw'; call @put 'Was it a cat I saw' call sy 'displaying list size.' ; say 'list size='@size() call sy 'forward list' ; call @show call sy 'backward list' ; call @show ,,-1 call sy 'showing 4th item' ; call @show 4,1 call sy 'showing 6th & 6th items' ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list' ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' call sy 'showing list' ; call @show call sy 'adding to head: Oy!' ; call @put 'Oy!',0 call sy 'showing list' ; call @show exit p: return word(arg(1),1) sy: say; say left('',30) "───" arg(1) '───'; return @hasopt: arg o; return pos(o,opt)\==0 @size: return $.# @init: $.@=''; $.#=0; return 0 @adjust: $.@=space($.@); $.#=words($.@); return 0 @parms: arg opt if @hasopt('k') then k=min($.#+1,max(1,p(k 1))) if @hasopt('m') then m=p(m 1) if @hasopt('d') then dir=p(dir 1) return @show: procedure expose $.; parse arg k,m,dir if dir==-1 & k=='' then k=$.# m=p(m $.#); call @parms 'kmd' say @get(k,m,dir); return 0 @get: procedure expose $.; arg k,m,dir,_ call @parms 'kmd' do j=k for m by dir while j>0 & j<=$.# _=_ subword($.@,j,1) end return strip(_) @put: procedure expose $.; parse arg x,k k=p(k $.#+1) call @parms 'k' $.@=subword($.@,1,max(0,k-1)) x subword($.@,k) call @adjust return 0 @del: procedure expose $.; arg k,m call @parms 'km' _=subword($.@,k,k-1) subword($.@,k+m) $.@=_ call @adjust return
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct sListEntry { const char *value; struct sListEntry *next; struct sListEntry *prev; } *ListEntry, *LinkedList; typedef struct sListIterator{ ListEntry link; LinkedList head; } *LIterator; LinkedList NewList() { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = NULL; le->next = le->prev = NULL; } return le; } int LL_Append(LinkedList ll, const char *newVal) { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); le->prev = ll->prev; le->next = NULL; if (le->prev) le->prev->next = le; else ll->next = le; ll->prev = le; } return (le!= NULL); } int LI_Insert(LIterator iter, const char *newVal) { ListEntry crnt = iter->link; ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); if ( crnt == iter->head) { le->prev = NULL; le->next = crnt->next; crnt->next = le; if (le->next) le->next->prev = le; else crnt->prev = le; } else { le->prev = ( crnt == NULL)? iter->head->prev : crnt->prev; le->next = crnt; if (le->prev) le->prev->next = le; else iter->head->next = le; if (crnt) crnt->prev = le; else iter->head->prev = le; } } return (le!= NULL); } LIterator LL_GetIterator(LinkedList ll ) { LIterator liter = malloc(sizeof(struct sListIterator)); liter->head = ll; liter->link = ll; return liter; } #define LLI_Delete( iter ) \ {free(iter); \ iter = NULL;} int LLI_AtEnd(LIterator iter) { return iter->link == NULL; } const char *LLI_Value(LIterator iter) { return (iter->link)? iter->link->value: NULL; } int LLI_Next(LIterator iter) { if (iter->link) iter->link = iter->link->next; return(iter->link != NULL); } int LLI_Prev(LIterator iter) { if (iter->link) iter->link = iter->link->prev; return(iter->link != NULL); } int main() { static const char *contents[] = {"Read", "Orage", "Yeller", "Glean", "Blew", "Burple"}; int ix; LinkedList ll = NewList(); LIterator iter; for (ix=0; ix<6; ix++) LL_Append(ll, contents[ix]); iter = LL_GetIterator(ll); printf("forward\n"); while(LLI_Next(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); printf("\nreverse\n"); iter = LL_GetIterator(ll); while(LLI_Prev(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); return 0; }
Preserve the algorithm and functionality while converting the code from REXX to C#.
β”Œβ”€β”˜ Functions of the List Manager └─┐ β”‚ β”‚ β”‚ @init ─── initializes the List. β”‚ β”‚ β”‚ β”‚ @size ─── returns the size of the List [could be 0 (zero)]. β”‚ β”‚ β”‚ β”‚ @show ─── shows (displays) the complete List. β”‚ β”‚ @show k,1 ─── shows (displays) the Kth item. β”‚ β”‚ @show k,m ─── shows (displays) M items, starting with Kth item. β”‚ β”‚ @show ,,─1 ─── shows (displays) the complete List backwards. β”‚ β”‚ β”‚ β”‚ @get k ─── returns the Kth item. β”‚ β”‚ @get k,m ─── returns the M items starting with the Kth item. β”‚ β”‚ β”‚ β”‚ @put x ─── adds the X items to the end (tail) of the List. β”‚ β”‚ @put x,0 ─── adds the X items to the start (head) of the List. β”‚ β”‚ @put x,k ─── adds the X items to before of the Kth item. β”‚ β”‚ β”‚ β”‚ @del k ─── deletes the item K. β”‚ β”‚ @del k,m ─── deletes the M items starting with item K. β”‚ └─┐ β”Œβ”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜*/ call sy 'initializing the list.' ; call @init call sy 'building list: Was it a cat I saw'; call @put 'Was it a cat I saw' call sy 'displaying list size.' ; say 'list size='@size() call sy 'forward list' ; call @show call sy 'backward list' ; call @show ,,-1 call sy 'showing 4th item' ; call @show 4,1 call sy 'showing 6th & 6th items' ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list' ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' call sy 'showing list' ; call @show call sy 'adding to head: Oy!' ; call @put 'Oy!',0 call sy 'showing list' ; call @show exit p: return word(arg(1),1) sy: say; say left('',30) "───" arg(1) '───'; return @hasopt: arg o; return pos(o,opt)\==0 @size: return $.# @init: $.@=''; $.#=0; return 0 @adjust: $.@=space($.@); $.#=words($.@); return 0 @parms: arg opt if @hasopt('k') then k=min($.#+1,max(1,p(k 1))) if @hasopt('m') then m=p(m 1) if @hasopt('d') then dir=p(dir 1) return @show: procedure expose $.; parse arg k,m,dir if dir==-1 & k=='' then k=$.# m=p(m $.#); call @parms 'kmd' say @get(k,m,dir); return 0 @get: procedure expose $.; arg k,m,dir,_ call @parms 'kmd' do j=k for m by dir while j>0 & j<=$.# _=_ subword($.@,j,1) end return strip(_) @put: procedure expose $.; parse arg x,k k=p(k $.#+1) call @parms 'k' $.@=subword($.@,1,max(0,k-1)) x subword($.@,k) call @adjust return 0 @del: procedure expose $.; arg k,m call @parms 'km' _=subword($.@,k,k-1) subword($.@,k+m) $.@=_ call @adjust return
using System; using System.Collections.Generic; namespace RosettaCode.DoublyLinkedList { internal static class Program { private static void Main() { var list = new LinkedList<char>("hello"); var current = list.First; do { Console.WriteLine(current.Value); } while ((current = current.Next) != null); Console.WriteLine(); current = list.Last; do { Console.WriteLine(current.Value); } while ((current = current.Previous) != null); } } }
Please provide an equivalent version of this REXX code in C++.
β”Œβ”€β”˜ Functions of the List Manager └─┐ β”‚ β”‚ β”‚ @init ─── initializes the List. β”‚ β”‚ β”‚ β”‚ @size ─── returns the size of the List [could be 0 (zero)]. β”‚ β”‚ β”‚ β”‚ @show ─── shows (displays) the complete List. β”‚ β”‚ @show k,1 ─── shows (displays) the Kth item. β”‚ β”‚ @show k,m ─── shows (displays) M items, starting with Kth item. β”‚ β”‚ @show ,,─1 ─── shows (displays) the complete List backwards. β”‚ β”‚ β”‚ β”‚ @get k ─── returns the Kth item. β”‚ β”‚ @get k,m ─── returns the M items starting with the Kth item. β”‚ β”‚ β”‚ β”‚ @put x ─── adds the X items to the end (tail) of the List. β”‚ β”‚ @put x,0 ─── adds the X items to the start (head) of the List. β”‚ β”‚ @put x,k ─── adds the X items to before of the Kth item. β”‚ β”‚ β”‚ β”‚ @del k ─── deletes the item K. β”‚ β”‚ @del k,m ─── deletes the M items starting with item K. β”‚ └─┐ β”Œβ”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜*/ call sy 'initializing the list.' ; call @init call sy 'building list: Was it a cat I saw'; call @put 'Was it a cat I saw' call sy 'displaying list size.' ; say 'list size='@size() call sy 'forward list' ; call @show call sy 'backward list' ; call @show ,,-1 call sy 'showing 4th item' ; call @show 4,1 call sy 'showing 6th & 6th items' ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list' ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' call sy 'showing list' ; call @show call sy 'adding to head: Oy!' ; call @put 'Oy!',0 call sy 'showing list' ; call @show exit p: return word(arg(1),1) sy: say; say left('',30) "───" arg(1) '───'; return @hasopt: arg o; return pos(o,opt)\==0 @size: return $.# @init: $.@=''; $.#=0; return 0 @adjust: $.@=space($.@); $.#=words($.@); return 0 @parms: arg opt if @hasopt('k') then k=min($.#+1,max(1,p(k 1))) if @hasopt('m') then m=p(m 1) if @hasopt('d') then dir=p(dir 1) return @show: procedure expose $.; parse arg k,m,dir if dir==-1 & k=='' then k=$.# m=p(m $.#); call @parms 'kmd' say @get(k,m,dir); return 0 @get: procedure expose $.; arg k,m,dir,_ call @parms 'kmd' do j=k for m by dir while j>0 & j<=$.# _=_ subword($.@,j,1) end return strip(_) @put: procedure expose $.; parse arg x,k k=p(k $.#+1) call @parms 'k' $.@=subword($.@,1,max(0,k-1)) x subword($.@,k) call @adjust return 0 @del: procedure expose $.; arg k,m call @parms 'km' _=subword($.@,k,k-1) subword($.@,k+m) $.@=_ call @adjust return
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
Maintain the same structure and functionality when rewriting this code in Java.
β”Œβ”€β”˜ Functions of the List Manager └─┐ β”‚ β”‚ β”‚ @init ─── initializes the List. β”‚ β”‚ β”‚ β”‚ @size ─── returns the size of the List [could be 0 (zero)]. β”‚ β”‚ β”‚ β”‚ @show ─── shows (displays) the complete List. β”‚ β”‚ @show k,1 ─── shows (displays) the Kth item. β”‚ β”‚ @show k,m ─── shows (displays) M items, starting with Kth item. β”‚ β”‚ @show ,,─1 ─── shows (displays) the complete List backwards. β”‚ β”‚ β”‚ β”‚ @get k ─── returns the Kth item. β”‚ β”‚ @get k,m ─── returns the M items starting with the Kth item. β”‚ β”‚ β”‚ β”‚ @put x ─── adds the X items to the end (tail) of the List. β”‚ β”‚ @put x,0 ─── adds the X items to the start (head) of the List. β”‚ β”‚ @put x,k ─── adds the X items to before of the Kth item. β”‚ β”‚ β”‚ β”‚ @del k ─── deletes the item K. β”‚ β”‚ @del k,m ─── deletes the M items starting with item K. β”‚ └─┐ β”Œβ”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜*/ call sy 'initializing the list.' ; call @init call sy 'building list: Was it a cat I saw'; call @put 'Was it a cat I saw' call sy 'displaying list size.' ; say 'list size='@size() call sy 'forward list' ; call @show call sy 'backward list' ; call @show ,,-1 call sy 'showing 4th item' ; call @show 4,1 call sy 'showing 6th & 6th items' ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list' ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' call sy 'showing list' ; call @show call sy 'adding to head: Oy!' ; call @put 'Oy!',0 call sy 'showing list' ; call @show exit p: return word(arg(1),1) sy: say; say left('',30) "───" arg(1) '───'; return @hasopt: arg o; return pos(o,opt)\==0 @size: return $.# @init: $.@=''; $.#=0; return 0 @adjust: $.@=space($.@); $.#=words($.@); return 0 @parms: arg opt if @hasopt('k') then k=min($.#+1,max(1,p(k 1))) if @hasopt('m') then m=p(m 1) if @hasopt('d') then dir=p(dir 1) return @show: procedure expose $.; parse arg k,m,dir if dir==-1 & k=='' then k=$.# m=p(m $.#); call @parms 'kmd' say @get(k,m,dir); return 0 @get: procedure expose $.; arg k,m,dir,_ call @parms 'kmd' do j=k for m by dir while j>0 & j<=$.# _=_ subword($.@,j,1) end return strip(_) @put: procedure expose $.; parse arg x,k k=p(k $.#+1) call @parms 'k' $.@=subword($.@,1,max(0,k-1)) x subword($.@,k) call @adjust return 0 @del: procedure expose $.; arg k,m call @parms 'km' _=subword($.@,k,k-1) subword($.@,k+m) $.@=_ call @adjust return
package com.rosettacode; import java.util.LinkedList; import java.util.stream.Collectors; import java.util.stream.IntStream; public class DoubleLinkedListTraversing { public static void main(String[] args) { final LinkedList<String> doubleLinkedList = IntStream.range(1, 10) .mapToObj(String::valueOf) .collect(Collectors.toCollection(LinkedList::new)); doubleLinkedList.iterator().forEachRemaining(System.out::print); System.out.println(); doubleLinkedList.descendingIterator().forEachRemaining(System.out::print); } }
Produce a language-to-language conversion: from REXX to Python, same semantics.
β”Œβ”€β”˜ Functions of the List Manager └─┐ β”‚ β”‚ β”‚ @init ─── initializes the List. β”‚ β”‚ β”‚ β”‚ @size ─── returns the size of the List [could be 0 (zero)]. β”‚ β”‚ β”‚ β”‚ @show ─── shows (displays) the complete List. β”‚ β”‚ @show k,1 ─── shows (displays) the Kth item. β”‚ β”‚ @show k,m ─── shows (displays) M items, starting with Kth item. β”‚ β”‚ @show ,,─1 ─── shows (displays) the complete List backwards. β”‚ β”‚ β”‚ β”‚ @get k ─── returns the Kth item. β”‚ β”‚ @get k,m ─── returns the M items starting with the Kth item. β”‚ β”‚ β”‚ β”‚ @put x ─── adds the X items to the end (tail) of the List. β”‚ β”‚ @put x,0 ─── adds the X items to the start (head) of the List. β”‚ β”‚ @put x,k ─── adds the X items to before of the Kth item. β”‚ β”‚ β”‚ β”‚ @del k ─── deletes the item K. β”‚ β”‚ @del k,m ─── deletes the M items starting with item K. β”‚ └─┐ β”Œβ”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜*/ call sy 'initializing the list.' ; call @init call sy 'building list: Was it a cat I saw'; call @put 'Was it a cat I saw' call sy 'displaying list size.' ; say 'list size='@size() call sy 'forward list' ; call @show call sy 'backward list' ; call @show ,,-1 call sy 'showing 4th item' ; call @show 4,1 call sy 'showing 6th & 6th items' ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list' ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' call sy 'showing list' ; call @show call sy 'adding to head: Oy!' ; call @put 'Oy!',0 call sy 'showing list' ; call @show exit p: return word(arg(1),1) sy: say; say left('',30) "───" arg(1) '───'; return @hasopt: arg o; return pos(o,opt)\==0 @size: return $.# @init: $.@=''; $.#=0; return 0 @adjust: $.@=space($.@); $.#=words($.@); return 0 @parms: arg opt if @hasopt('k') then k=min($.#+1,max(1,p(k 1))) if @hasopt('m') then m=p(m 1) if @hasopt('d') then dir=p(dir 1) return @show: procedure expose $.; parse arg k,m,dir if dir==-1 & k=='' then k=$.# m=p(m $.#); call @parms 'kmd' say @get(k,m,dir); return 0 @get: procedure expose $.; arg k,m,dir,_ call @parms 'kmd' do j=k for m by dir while j>0 & j<=$.# _=_ subword($.@,j,1) end return strip(_) @put: procedure expose $.; parse arg x,k k=p(k $.#+1) call @parms 'k' $.@=subword($.@,1,max(0,k-1)) x subword($.@,k) call @adjust return 0 @del: procedure expose $.; arg k,m call @parms 'km' _=subword($.@,k,k-1) subword($.@,k+m) $.@=_ call @adjust return
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.append(data) tail = head = List(10) for i in [ 20, 30, 40 ]: tail = tail.append(i) node = head while node != None: print(node.data) node = node.next node = tail while node != None: print(node.data) node = node.prev
Maintain the same structure and functionality when rewriting this code in Go.
β”Œβ”€β”˜ Functions of the List Manager └─┐ β”‚ β”‚ β”‚ @init ─── initializes the List. β”‚ β”‚ β”‚ β”‚ @size ─── returns the size of the List [could be 0 (zero)]. β”‚ β”‚ β”‚ β”‚ @show ─── shows (displays) the complete List. β”‚ β”‚ @show k,1 ─── shows (displays) the Kth item. β”‚ β”‚ @show k,m ─── shows (displays) M items, starting with Kth item. β”‚ β”‚ @show ,,─1 ─── shows (displays) the complete List backwards. β”‚ β”‚ β”‚ β”‚ @get k ─── returns the Kth item. β”‚ β”‚ @get k,m ─── returns the M items starting with the Kth item. β”‚ β”‚ β”‚ β”‚ @put x ─── adds the X items to the end (tail) of the List. β”‚ β”‚ @put x,0 ─── adds the X items to the start (head) of the List. β”‚ β”‚ @put x,k ─── adds the X items to before of the Kth item. β”‚ β”‚ β”‚ β”‚ @del k ─── deletes the item K. β”‚ β”‚ @del k,m ─── deletes the M items starting with item K. β”‚ └─┐ β”Œβ”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜*/ call sy 'initializing the list.' ; call @init call sy 'building list: Was it a cat I saw'; call @put 'Was it a cat I saw' call sy 'displaying list size.' ; say 'list size='@size() call sy 'forward list' ; call @show call sy 'backward list' ; call @show ,,-1 call sy 'showing 4th item' ; call @show 4,1 call sy 'showing 6th & 6th items' ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list' ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' call sy 'showing list' ; call @show call sy 'adding to head: Oy!' ; call @put 'Oy!',0 call sy 'showing list' ; call @show exit p: return word(arg(1),1) sy: say; say left('',30) "───" arg(1) '───'; return @hasopt: arg o; return pos(o,opt)\==0 @size: return $.# @init: $.@=''; $.#=0; return 0 @adjust: $.@=space($.@); $.#=words($.@); return 0 @parms: arg opt if @hasopt('k') then k=min($.#+1,max(1,p(k 1))) if @hasopt('m') then m=p(m 1) if @hasopt('d') then dir=p(dir 1) return @show: procedure expose $.; parse arg k,m,dir if dir==-1 & k=='' then k=$.# m=p(m $.#); call @parms 'kmd' say @get(k,m,dir); return 0 @get: procedure expose $.; arg k,m,dir,_ call @parms 'kmd' do j=k for m by dir while j>0 & j<=$.# _=_ subword($.@,j,1) end return strip(_) @put: procedure expose $.; parse arg x,k k=p(k $.#+1) call @parms 'k' $.@=subword($.@,1,max(0,k-1)) x subword($.@,k) call @adjust return 0 @del: procedure expose $.; arg k,m call @parms 'km' _=subword($.@,k,k-1) subword($.@,k+m) $.@=_ call @adjust return
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) fmt.Print("From tail:") for p := dll.tail; p != nil; p = p.prev { fmt.Print(" ", p.string) } fmt.Println("") }
Rewrite this program in C while keeping its functionality equivalent to the Ruby version.
class DListNode def get_tail self.find {|node| node.succ.nil?} end def each_previous(&b) yield self self.prev.each_previous(&b) if self.prev end end head = DListNode.from_array([:a, :b, :c]) head.each {|node| p node.value} head.get_tail.each_previous {|node| p node.value}
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct sListEntry { const char *value; struct sListEntry *next; struct sListEntry *prev; } *ListEntry, *LinkedList; typedef struct sListIterator{ ListEntry link; LinkedList head; } *LIterator; LinkedList NewList() { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = NULL; le->next = le->prev = NULL; } return le; } int LL_Append(LinkedList ll, const char *newVal) { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); le->prev = ll->prev; le->next = NULL; if (le->prev) le->prev->next = le; else ll->next = le; ll->prev = le; } return (le!= NULL); } int LI_Insert(LIterator iter, const char *newVal) { ListEntry crnt = iter->link; ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); if ( crnt == iter->head) { le->prev = NULL; le->next = crnt->next; crnt->next = le; if (le->next) le->next->prev = le; else crnt->prev = le; } else { le->prev = ( crnt == NULL)? iter->head->prev : crnt->prev; le->next = crnt; if (le->prev) le->prev->next = le; else iter->head->next = le; if (crnt) crnt->prev = le; else iter->head->prev = le; } } return (le!= NULL); } LIterator LL_GetIterator(LinkedList ll ) { LIterator liter = malloc(sizeof(struct sListIterator)); liter->head = ll; liter->link = ll; return liter; } #define LLI_Delete( iter ) \ {free(iter); \ iter = NULL;} int LLI_AtEnd(LIterator iter) { return iter->link == NULL; } const char *LLI_Value(LIterator iter) { return (iter->link)? iter->link->value: NULL; } int LLI_Next(LIterator iter) { if (iter->link) iter->link = iter->link->next; return(iter->link != NULL); } int LLI_Prev(LIterator iter) { if (iter->link) iter->link = iter->link->prev; return(iter->link != NULL); } int main() { static const char *contents[] = {"Read", "Orage", "Yeller", "Glean", "Blew", "Burple"}; int ix; LinkedList ll = NewList(); LIterator iter; for (ix=0; ix<6; ix++) LL_Append(ll, contents[ix]); iter = LL_GetIterator(ll); printf("forward\n"); while(LLI_Next(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); printf("\nreverse\n"); iter = LL_GetIterator(ll); while(LLI_Prev(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); return 0; }
Write the same algorithm in C# as shown in this Ruby implementation.
class DListNode def get_tail self.find {|node| node.succ.nil?} end def each_previous(&b) yield self self.prev.each_previous(&b) if self.prev end end head = DListNode.from_array([:a, :b, :c]) head.each {|node| p node.value} head.get_tail.each_previous {|node| p node.value}
using System; using System.Collections.Generic; namespace RosettaCode.DoublyLinkedList { internal static class Program { private static void Main() { var list = new LinkedList<char>("hello"); var current = list.First; do { Console.WriteLine(current.Value); } while ((current = current.Next) != null); Console.WriteLine(); current = list.Last; do { Console.WriteLine(current.Value); } while ((current = current.Previous) != null); } } }
Produce a functionally identical C++ code for the snippet given in Ruby.
class DListNode def get_tail self.find {|node| node.succ.nil?} end def each_previous(&b) yield self self.prev.each_previous(&b) if self.prev end end head = DListNode.from_array([:a, :b, :c]) head.each {|node| p node.value} head.get_tail.each_previous {|node| p node.value}
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
Preserve the algorithm and functionality while converting the code from Ruby to Java.
class DListNode def get_tail self.find {|node| node.succ.nil?} end def each_previous(&b) yield self self.prev.each_previous(&b) if self.prev end end head = DListNode.from_array([:a, :b, :c]) head.each {|node| p node.value} head.get_tail.each_previous {|node| p node.value}
package com.rosettacode; import java.util.LinkedList; import java.util.stream.Collectors; import java.util.stream.IntStream; public class DoubleLinkedListTraversing { public static void main(String[] args) { final LinkedList<String> doubleLinkedList = IntStream.range(1, 10) .mapToObj(String::valueOf) .collect(Collectors.toCollection(LinkedList::new)); doubleLinkedList.iterator().forEachRemaining(System.out::print); System.out.println(); doubleLinkedList.descendingIterator().forEachRemaining(System.out::print); } }
Generate a Python translation of this Ruby snippet without changing its computational steps.
class DListNode def get_tail self.find {|node| node.succ.nil?} end def each_previous(&b) yield self self.prev.each_previous(&b) if self.prev end end head = DListNode.from_array([:a, :b, :c]) head.each {|node| p node.value} head.get_tail.each_previous {|node| p node.value}
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.append(data) tail = head = List(10) for i in [ 20, 30, 40 ]: tail = tail.append(i) node = head while node != None: print(node.data) node = node.next node = tail while node != None: print(node.data) node = node.prev
Keep all operations the same but rewrite the snippet in Go.
class DListNode def get_tail self.find {|node| node.succ.nil?} end def each_previous(&b) yield self self.prev.each_previous(&b) if self.prev end end head = DListNode.from_array([:a, :b, :c]) head.each {|node| p node.value} head.get_tail.each_previous {|node| p node.value}
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) fmt.Print("From tail:") for p := dll.tail; p != nil; p = p.prev { fmt.Print(" ", p.string) } fmt.Println("") }
Rewrite the snippet below in C so it works the same as the original Scala code.
class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) node = node.next } return sb.toString() } } var first: Node<E>? = null var last: Node<E>? = null fun addFirst(value: E) { if (first == null) { first = Node(value) last = first } else { val node = first!! first = Node(value, null, node) node.prev = first } } fun addLast(value: E) { if (last == null) { last = Node(value) first = last } else { val node = last!! last = Node(value, node, null) node.next = last } } fun insert(after: Node<E>?, value: E) { if (after == null) addFirst(value) else if (after == last) addLast(value) else { val next = after.next val new = Node(value, after, next) after.next = new if (next != null) next.prev = new } } override fun toString() = first.toString() fun firstToLast() = first?.toString() ?: "" fun lastToFirst(): String { if (last == null) return "" val sb = StringBuilder(last.toString()) var node = last!!.prev while (node != null) { sb.append(" -> ", node.data.toString()) node = node.prev } return sb.toString() } } fun main(args: Array<String>) { val ll = LinkedList<Int>() ll.addFirst(1) ll.addLast(4) ll.insert(ll.first, 2) ll.insert(ll.last!!.prev, 3) println("First to lastΒ : ${ll.firstToLast()}") println("Last to firstΒ : ${ll.lastToFirst()}") }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct sListEntry { const char *value; struct sListEntry *next; struct sListEntry *prev; } *ListEntry, *LinkedList; typedef struct sListIterator{ ListEntry link; LinkedList head; } *LIterator; LinkedList NewList() { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = NULL; le->next = le->prev = NULL; } return le; } int LL_Append(LinkedList ll, const char *newVal) { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); le->prev = ll->prev; le->next = NULL; if (le->prev) le->prev->next = le; else ll->next = le; ll->prev = le; } return (le!= NULL); } int LI_Insert(LIterator iter, const char *newVal) { ListEntry crnt = iter->link; ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); if ( crnt == iter->head) { le->prev = NULL; le->next = crnt->next; crnt->next = le; if (le->next) le->next->prev = le; else crnt->prev = le; } else { le->prev = ( crnt == NULL)? iter->head->prev : crnt->prev; le->next = crnt; if (le->prev) le->prev->next = le; else iter->head->next = le; if (crnt) crnt->prev = le; else iter->head->prev = le; } } return (le!= NULL); } LIterator LL_GetIterator(LinkedList ll ) { LIterator liter = malloc(sizeof(struct sListIterator)); liter->head = ll; liter->link = ll; return liter; } #define LLI_Delete( iter ) \ {free(iter); \ iter = NULL;} int LLI_AtEnd(LIterator iter) { return iter->link == NULL; } const char *LLI_Value(LIterator iter) { return (iter->link)? iter->link->value: NULL; } int LLI_Next(LIterator iter) { if (iter->link) iter->link = iter->link->next; return(iter->link != NULL); } int LLI_Prev(LIterator iter) { if (iter->link) iter->link = iter->link->prev; return(iter->link != NULL); } int main() { static const char *contents[] = {"Read", "Orage", "Yeller", "Glean", "Blew", "Burple"}; int ix; LinkedList ll = NewList(); LIterator iter; for (ix=0; ix<6; ix++) LL_Append(ll, contents[ix]); iter = LL_GetIterator(ll); printf("forward\n"); while(LLI_Next(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); printf("\nreverse\n"); iter = LL_GetIterator(ll); while(LLI_Prev(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); return 0; }
Rewrite the snippet below in C# so it works the same as the original Scala code.
class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) node = node.next } return sb.toString() } } var first: Node<E>? = null var last: Node<E>? = null fun addFirst(value: E) { if (first == null) { first = Node(value) last = first } else { val node = first!! first = Node(value, null, node) node.prev = first } } fun addLast(value: E) { if (last == null) { last = Node(value) first = last } else { val node = last!! last = Node(value, node, null) node.next = last } } fun insert(after: Node<E>?, value: E) { if (after == null) addFirst(value) else if (after == last) addLast(value) else { val next = after.next val new = Node(value, after, next) after.next = new if (next != null) next.prev = new } } override fun toString() = first.toString() fun firstToLast() = first?.toString() ?: "" fun lastToFirst(): String { if (last == null) return "" val sb = StringBuilder(last.toString()) var node = last!!.prev while (node != null) { sb.append(" -> ", node.data.toString()) node = node.prev } return sb.toString() } } fun main(args: Array<String>) { val ll = LinkedList<Int>() ll.addFirst(1) ll.addLast(4) ll.insert(ll.first, 2) ll.insert(ll.last!!.prev, 3) println("First to lastΒ : ${ll.firstToLast()}") println("Last to firstΒ : ${ll.lastToFirst()}") }
using System; using System.Collections.Generic; namespace RosettaCode.DoublyLinkedList { internal static class Program { private static void Main() { var list = new LinkedList<char>("hello"); var current = list.First; do { Console.WriteLine(current.Value); } while ((current = current.Next) != null); Console.WriteLine(); current = list.Last; do { Console.WriteLine(current.Value); } while ((current = current.Previous) != null); } } }
Please provide an equivalent version of this Scala code in C++.
class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) node = node.next } return sb.toString() } } var first: Node<E>? = null var last: Node<E>? = null fun addFirst(value: E) { if (first == null) { first = Node(value) last = first } else { val node = first!! first = Node(value, null, node) node.prev = first } } fun addLast(value: E) { if (last == null) { last = Node(value) first = last } else { val node = last!! last = Node(value, node, null) node.next = last } } fun insert(after: Node<E>?, value: E) { if (after == null) addFirst(value) else if (after == last) addLast(value) else { val next = after.next val new = Node(value, after, next) after.next = new if (next != null) next.prev = new } } override fun toString() = first.toString() fun firstToLast() = first?.toString() ?: "" fun lastToFirst(): String { if (last == null) return "" val sb = StringBuilder(last.toString()) var node = last!!.prev while (node != null) { sb.append(" -> ", node.data.toString()) node = node.prev } return sb.toString() } } fun main(args: Array<String>) { val ll = LinkedList<Int>() ll.addFirst(1) ll.addLast(4) ll.insert(ll.first, 2) ll.insert(ll.last!!.prev, 3) println("First to lastΒ : ${ll.firstToLast()}") println("Last to firstΒ : ${ll.lastToFirst()}") }
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
Convert this Scala block to Java, preserving its control flow and logic.
class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) node = node.next } return sb.toString() } } var first: Node<E>? = null var last: Node<E>? = null fun addFirst(value: E) { if (first == null) { first = Node(value) last = first } else { val node = first!! first = Node(value, null, node) node.prev = first } } fun addLast(value: E) { if (last == null) { last = Node(value) first = last } else { val node = last!! last = Node(value, node, null) node.next = last } } fun insert(after: Node<E>?, value: E) { if (after == null) addFirst(value) else if (after == last) addLast(value) else { val next = after.next val new = Node(value, after, next) after.next = new if (next != null) next.prev = new } } override fun toString() = first.toString() fun firstToLast() = first?.toString() ?: "" fun lastToFirst(): String { if (last == null) return "" val sb = StringBuilder(last.toString()) var node = last!!.prev while (node != null) { sb.append(" -> ", node.data.toString()) node = node.prev } return sb.toString() } } fun main(args: Array<String>) { val ll = LinkedList<Int>() ll.addFirst(1) ll.addLast(4) ll.insert(ll.first, 2) ll.insert(ll.last!!.prev, 3) println("First to lastΒ : ${ll.firstToLast()}") println("Last to firstΒ : ${ll.lastToFirst()}") }
package com.rosettacode; import java.util.LinkedList; import java.util.stream.Collectors; import java.util.stream.IntStream; public class DoubleLinkedListTraversing { public static void main(String[] args) { final LinkedList<String> doubleLinkedList = IntStream.range(1, 10) .mapToObj(String::valueOf) .collect(Collectors.toCollection(LinkedList::new)); doubleLinkedList.iterator().forEachRemaining(System.out::print); System.out.println(); doubleLinkedList.descendingIterator().forEachRemaining(System.out::print); } }
Produce a functionally identical Python code for the snippet given in Scala.
class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) node = node.next } return sb.toString() } } var first: Node<E>? = null var last: Node<E>? = null fun addFirst(value: E) { if (first == null) { first = Node(value) last = first } else { val node = first!! first = Node(value, null, node) node.prev = first } } fun addLast(value: E) { if (last == null) { last = Node(value) first = last } else { val node = last!! last = Node(value, node, null) node.next = last } } fun insert(after: Node<E>?, value: E) { if (after == null) addFirst(value) else if (after == last) addLast(value) else { val next = after.next val new = Node(value, after, next) after.next = new if (next != null) next.prev = new } } override fun toString() = first.toString() fun firstToLast() = first?.toString() ?: "" fun lastToFirst(): String { if (last == null) return "" val sb = StringBuilder(last.toString()) var node = last!!.prev while (node != null) { sb.append(" -> ", node.data.toString()) node = node.prev } return sb.toString() } } fun main(args: Array<String>) { val ll = LinkedList<Int>() ll.addFirst(1) ll.addLast(4) ll.insert(ll.first, 2) ll.insert(ll.last!!.prev, 3) println("First to lastΒ : ${ll.firstToLast()}") println("Last to firstΒ : ${ll.lastToFirst()}") }
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.append(data) tail = head = List(10) for i in [ 20, 30, 40 ]: tail = tail.append(i) node = head while node != None: print(node.data) node = node.next node = tail while node != None: print(node.data) node = node.prev
Port the provided Scala code into Go while preserving the original functionality.
class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) node = node.next } return sb.toString() } } var first: Node<E>? = null var last: Node<E>? = null fun addFirst(value: E) { if (first == null) { first = Node(value) last = first } else { val node = first!! first = Node(value, null, node) node.prev = first } } fun addLast(value: E) { if (last == null) { last = Node(value) first = last } else { val node = last!! last = Node(value, node, null) node.next = last } } fun insert(after: Node<E>?, value: E) { if (after == null) addFirst(value) else if (after == last) addLast(value) else { val next = after.next val new = Node(value, after, next) after.next = new if (next != null) next.prev = new } } override fun toString() = first.toString() fun firstToLast() = first?.toString() ?: "" fun lastToFirst(): String { if (last == null) return "" val sb = StringBuilder(last.toString()) var node = last!!.prev while (node != null) { sb.append(" -> ", node.data.toString()) node = node.prev } return sb.toString() } } fun main(args: Array<String>) { val ll = LinkedList<Int>() ll.addFirst(1) ll.addLast(4) ll.insert(ll.first, 2) ll.insert(ll.last!!.prev, 3) println("First to lastΒ : ${ll.firstToLast()}") println("Last to firstΒ : ${ll.lastToFirst()}") }
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) fmt.Print("From tail:") for p := dll.tail; p != nil; p = p.prev { fmt.Print(" ", p.string) } fmt.Println("") }
Keep all operations the same but rewrite the snippet in C.
oo::define List { method foreach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node next]} { set v [$node value] uplevel 1 $script } } method revforeach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node previous]} { set v [$node value] uplevel 1 $script } } } set first [List new a [List new b [List new c [set last [List new d]]]]] puts "Forward..." $first foreach char { puts $char } puts "Backward..." $last revforeach char { puts $char }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct sListEntry { const char *value; struct sListEntry *next; struct sListEntry *prev; } *ListEntry, *LinkedList; typedef struct sListIterator{ ListEntry link; LinkedList head; } *LIterator; LinkedList NewList() { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = NULL; le->next = le->prev = NULL; } return le; } int LL_Append(LinkedList ll, const char *newVal) { ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); le->prev = ll->prev; le->next = NULL; if (le->prev) le->prev->next = le; else ll->next = le; ll->prev = le; } return (le!= NULL); } int LI_Insert(LIterator iter, const char *newVal) { ListEntry crnt = iter->link; ListEntry le = malloc(sizeof(struct sListEntry)); if (le) { le->value = strdup(newVal); if ( crnt == iter->head) { le->prev = NULL; le->next = crnt->next; crnt->next = le; if (le->next) le->next->prev = le; else crnt->prev = le; } else { le->prev = ( crnt == NULL)? iter->head->prev : crnt->prev; le->next = crnt; if (le->prev) le->prev->next = le; else iter->head->next = le; if (crnt) crnt->prev = le; else iter->head->prev = le; } } return (le!= NULL); } LIterator LL_GetIterator(LinkedList ll ) { LIterator liter = malloc(sizeof(struct sListIterator)); liter->head = ll; liter->link = ll; return liter; } #define LLI_Delete( iter ) \ {free(iter); \ iter = NULL;} int LLI_AtEnd(LIterator iter) { return iter->link == NULL; } const char *LLI_Value(LIterator iter) { return (iter->link)? iter->link->value: NULL; } int LLI_Next(LIterator iter) { if (iter->link) iter->link = iter->link->next; return(iter->link != NULL); } int LLI_Prev(LIterator iter) { if (iter->link) iter->link = iter->link->prev; return(iter->link != NULL); } int main() { static const char *contents[] = {"Read", "Orage", "Yeller", "Glean", "Blew", "Burple"}; int ix; LinkedList ll = NewList(); LIterator iter; for (ix=0; ix<6; ix++) LL_Append(ll, contents[ix]); iter = LL_GetIterator(ll); printf("forward\n"); while(LLI_Next(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); printf("\nreverse\n"); iter = LL_GetIterator(ll); while(LLI_Prev(iter)) printf("value=%s\n", LLI_Value(iter)); LLI_Delete(iter); return 0; }
Ensure the translated C# code behaves exactly like the original Tcl snippet.
oo::define List { method foreach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node next]} { set v [$node value] uplevel 1 $script } } method revforeach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node previous]} { set v [$node value] uplevel 1 $script } } } set first [List new a [List new b [List new c [set last [List new d]]]]] puts "Forward..." $first foreach char { puts $char } puts "Backward..." $last revforeach char { puts $char }
using System; using System.Collections.Generic; namespace RosettaCode.DoublyLinkedList { internal static class Program { private static void Main() { var list = new LinkedList<char>("hello"); var current = list.First; do { Console.WriteLine(current.Value); } while ((current = current.Next) != null); Console.WriteLine(); current = list.Last; do { Console.WriteLine(current.Value); } while ((current = current.Previous) != null); } } }
Change the following Tcl code into C++ without altering its purpose.
oo::define List { method foreach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node next]} { set v [$node value] uplevel 1 $script } } method revforeach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node previous]} { set v [$node value] uplevel 1 $script } } } set first [List new a [List new b [List new c [set last [List new d]]]]] puts "Forward..." $first foreach char { puts $char } puts "Backward..." $last revforeach char { puts $char }
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
Transform the following Tcl implementation into Java, maintaining the same output and logic.
oo::define List { method foreach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node next]} { set v [$node value] uplevel 1 $script } } method revforeach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node previous]} { set v [$node value] uplevel 1 $script } } } set first [List new a [List new b [List new c [set last [List new d]]]]] puts "Forward..." $first foreach char { puts $char } puts "Backward..." $last revforeach char { puts $char }
package com.rosettacode; import java.util.LinkedList; import java.util.stream.Collectors; import java.util.stream.IntStream; public class DoubleLinkedListTraversing { public static void main(String[] args) { final LinkedList<String> doubleLinkedList = IntStream.range(1, 10) .mapToObj(String::valueOf) .collect(Collectors.toCollection(LinkedList::new)); doubleLinkedList.iterator().forEachRemaining(System.out::print); System.out.println(); doubleLinkedList.descendingIterator().forEachRemaining(System.out::print); } }
Convert the following code from Tcl to Python, ensuring the logic remains intact.
oo::define List { method foreach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node next]} { set v [$node value] uplevel 1 $script } } method revforeach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node previous]} { set v [$node value] uplevel 1 $script } } } set first [List new a [List new b [List new c [set last [List new d]]]]] puts "Forward..." $first foreach char { puts $char } puts "Backward..." $last revforeach char { puts $char }
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.append(data) tail = head = List(10) for i in [ 20, 30, 40 ]: tail = tail.append(i) node = head while node != None: print(node.data) node = node.next node = tail while node != None: print(node.data) node = node.prev
Write the same algorithm in Go as shown in this Tcl implementation.
oo::define List { method foreach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node next]} { set v [$node value] uplevel 1 $script } } method revforeach {varName script} { upvar 1 $varName v for {set node [self]} {$node ne ""} {set node [$node previous]} { set v [$node value] uplevel 1 $script } } } set first [List new a [List new b [List new c [set last [List new d]]]]] puts "Forward..." $first foreach char { puts $char } puts "Backward..." $last revforeach char { puts $char }
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) fmt.Print("From tail:") for p := dll.tail; p != nil; p = p.prev { fmt.Print(" ", p.string) } fmt.Println("") }
Port the provided Ada code into C# while preserving the original functionality.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Produce a language-to-language conversion: from Ada to C#, same semantics.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Can you help me rewrite this code in C instead of Ada, keeping it the same logically?
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Preserve the algorithm and functionality while converting the code from Ada to C.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Write the same code in C++ as shown below in Ada.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Rewrite the snippet below in C++ so it works the same as the original Ada code.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Maintain the same structure and functionality when rewriting this code in Go.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Port the provided Ada code into Go while preserving the original functionality.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Port the provided Ada code into Java while preserving the original functionality.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Can you help me rewrite this code in Java instead of Ada, keeping it the same logically?
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Port the following code from Ada to Python with equivalent syntax and logic.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Ensure the translated Python code behaves exactly like the original Ada snippet.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Can you help me rewrite this code in VB instead of Ada, keeping it the same logically?
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Maintain the same structure and functionality when rewriting this code in VB.
with Ada.Text_IO; procedure Shoelace_Formula_For_Polygonal_Area is type Point is record x, y : Float; end record; type Polygon is array (Positive range <>) of Point; function Shoelace(input : in Polygon) return Float is sum_1 : Float := 0.0; sum_2 : Float := 0.0; tmp : constant Polygon := input & input(input'First); begin for I in tmp'First .. tmp'Last - 1 loop sum_1 := sum_1 + tmp(I).x * tmp(I+1).y; sum_2 := sum_2 + tmp(I+1).x * tmp(I).y; end loop; return abs(sum_1 - sum_2) / 2.0; end Shoelace; my_polygon : constant Polygon := ((3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)); begin Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img); end Shoelace_Formula_For_Polygonal_Area;
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Change the programming language of this snippet from AutoHotKey to C without modifying what it does.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Ensure the translated C code behaves exactly like the original AutoHotKey snippet.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Write the same code in C# as shown below in AutoHotKey.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Change the following AutoHotKey code into C# without altering its purpose.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Maintain the same structure and functionality when rewriting this code in C++.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Generate a C++ translation of this AutoHotKey snippet without changing its computational steps.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Write the same algorithm in Java as shown in this AutoHotKey implementation.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Generate an equivalent Java version of this AutoHotKey code.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Please provide an equivalent version of this AutoHotKey code in Python.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Produce a language-to-language conversion: from AutoHotKey to Python, same semantics.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Preserve the algorithm and functionality while converting the code from AutoHotKey to VB.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Keep all operations the same but rewrite the snippet in VB.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Port the following code from AutoHotKey to Go with equivalent syntax and logic.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Generate a Go translation of this AutoHotKey snippet without changing its computational steps.
V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]] n := V.Count() for i, O in V Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2] MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Generate a C translation of this D snippet without changing its computational steps.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Port the provided D code into C while preserving the original functionality.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Port the provided D code into C# while preserving the original functionality.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Generate an equivalent C# version of this D code.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Can you help me rewrite this code in C++ instead of D, keeping it the same logically?
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Produce a language-to-language conversion: from D to C++, same semantics.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Write the same code in Java as shown below in D.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Produce a functionally identical Java code for the snippet given in D.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Produce a functionally identical Python code for the snippet given in D.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Produce a functionally identical Python code for the snippet given in D.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Generate an equivalent VB version of this D code.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Preserve the algorithm and functionality while converting the code from D to VB.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Convert the following code from D to Go, ensuring the logic remains intact.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Keep all operations the same but rewrite the snippet in Go.
import std.stdio; Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}]; void main() { auto ans = shoelace(pnts); writeln(ans); } struct Point { real x, y; } real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0; for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length; leftSum += pnts[i].x * pnts[j].y; rightSum += pnts[j].x * pnts[i].y; } import std.math : abs; return 0.5 * abs(leftSum - rightSum); } unittest { auto ans = shoelace(pnts); assert(ans == 30); }
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Write a version of this F# function in C with identical behavior.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Change the following F# code into C# without altering its purpose.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Maintain the same structure and functionality when rewriting this code in C#.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Generate a C++ translation of this F# snippet without changing its computational steps.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Change the programming language of this snippet from F# to C++ without modifying what it does.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Convert this F# block to Java, preserving its control flow and logic.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Convert the following code from F# to Java, ensuring the logic remains intact.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Keep all operations the same but rewrite the snippet in Python.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Please provide an equivalent version of this F# code in Python.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Keep all operations the same but rewrite the snippet in VB.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Change the programming language of this snippet from F# to VB without modifying what it does.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Generate an equivalent Go version of this F# code.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Convert this F# block to Go, preserving its control flow and logic.
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nΞ±,gΞ±),(nΞ²,gΞ²))->n+(nΞ±*gΞ²)-(gΞ±*nΞ²)) 0.0)/2.0 printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.0)])
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Change the programming language of this snippet from Factor to C without modifying what it does.
USING: circular kernel math prettyprint sequences ; IN: rosetta-code.shoelace CONSTANT: input { { 3 4 } { 5 11 } { 12 8 } { 9 5 } { 5 6 } } : align-pairs ( pairs-seq -- seq1 seq2 ) <circular> dup clone [ 1 ] dip [ change-circular-start ] keep ; : shoelace-sum ( seq1 seq2 -- n ) [ [ first ] [ second ] bi* * ] 2map sum ; : shoelace-area ( pairs-seq -- area ) [ align-pairs ] [ align-pairs swap ] bi [ shoelace-sum ] 2bi@ - abs 2 / ; input shoelace-area .
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Ensure the translated C code behaves exactly like the original Factor snippet.
USING: circular kernel math prettyprint sequences ; IN: rosetta-code.shoelace CONSTANT: input { { 3 4 } { 5 11 } { 12 8 } { 9 5 } { 5 6 } } : align-pairs ( pairs-seq -- seq1 seq2 ) <circular> dup clone [ 1 ] dip [ change-circular-start ] keep ; : shoelace-sum ( seq1 seq2 -- n ) [ [ first ] [ second ] bi* * ] 2map sum ; : shoelace-area ( pairs-seq -- area ) [ align-pairs ] [ align-pairs swap ] bi [ shoelace-sum ] 2bi@ - abs 2 / ; input shoelace-area .
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsageΒ : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Change the programming language of this snippet from Factor to C# without modifying what it does.
USING: circular kernel math prettyprint sequences ; IN: rosetta-code.shoelace CONSTANT: input { { 3 4 } { 5 11 } { 12 8 } { 9 5 } { 5 6 } } : align-pairs ( pairs-seq -- seq1 seq2 ) <circular> dup clone [ 1 ] dip [ change-circular-start ] keep ; : shoelace-sum ( seq1 seq2 -- n ) [ [ first ] [ second ] bi* * ] 2map sum ; : shoelace-area ( pairs-seq -- area ) [ align-pairs ] [ align-pairs swap ] bi [ shoelace-sum ] 2bi@ - abs 2 / ; input shoelace-area .
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Transform the following Factor implementation into C#, maintaining the same output and logic.
USING: circular kernel math prettyprint sequences ; IN: rosetta-code.shoelace CONSTANT: input { { 3 4 } { 5 11 } { 12 8 } { 9 5 } { 5 6 } } : align-pairs ( pairs-seq -- seq1 seq2 ) <circular> dup clone [ 1 ] dip [ change-circular-start ] keep ; : shoelace-sum ( seq1 seq2 -- n ) [ [ first ] [ second ] bi* * ] 2map sum ; : shoelace-area ( pairs-seq -- area ) [ align-pairs ] [ align-pairs swap ] bi [ shoelace-sum ] 2bi@ - abs 2 / ; input shoelace-area .
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Preserve the algorithm and functionality while converting the code from Factor to C++.
USING: circular kernel math prettyprint sequences ; IN: rosetta-code.shoelace CONSTANT: input { { 3 4 } { 5 11 } { 12 8 } { 9 5 } { 5 6 } } : align-pairs ( pairs-seq -- seq1 seq2 ) <circular> dup clone [ 1 ] dip [ change-circular-start ] keep ; : shoelace-sum ( seq1 seq2 -- n ) [ [ first ] [ second ] bi* * ] 2map sum ; : shoelace-area ( pairs-seq -- area ) [ align-pairs ] [ align-pairs swap ] bi [ shoelace-sum ] 2bi@ - abs 2 / ; input shoelace-area .
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Rewrite this program in C++ while keeping its functionality equivalent to the Factor version.
USING: circular kernel math prettyprint sequences ; IN: rosetta-code.shoelace CONSTANT: input { { 3 4 } { 5 11 } { 12 8 } { 9 5 } { 5 6 } } : align-pairs ( pairs-seq -- seq1 seq2 ) <circular> dup clone [ 1 ] dip [ change-circular-start ] keep ; : shoelace-sum ( seq1 seq2 -- n ) [ [ first ] [ second ] bi* * ] 2map sum ; : shoelace-area ( pairs-seq -- area ) [ align-pairs ] [ align-pairs swap ] bi [ shoelace-sum ] 2bi@ - abs 2 / ; input shoelace-area .
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Convert the following code from Factor to Java, ensuring the logic remains intact.
USING: circular kernel math prettyprint sequences ; IN: rosetta-code.shoelace CONSTANT: input { { 3 4 } { 5 11 } { 12 8 } { 9 5 } { 5 6 } } : align-pairs ( pairs-seq -- seq1 seq2 ) <circular> dup clone [ 1 ] dip [ change-circular-start ] keep ; : shoelace-sum ( seq1 seq2 -- n ) [ [ first ] [ second ] bi* * ] 2map sum ; : shoelace-area ( pairs-seq -- area ) [ align-pairs ] [ align-pairs swap ] bi [ shoelace-sum ] 2bi@ - abs 2 / ; input shoelace-area .
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }