Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert the following code from Rust to VB, ensuring the logic remains intact. | #![feature(box_syntax, box_patterns)]
use std::collections::VecDeque;
#[derive(Debug)]
struct TreeNode<T> {
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
enum TraversalMethod {
PreOrder,
InOrder,
PostOrder,
LevelOrder,
}
impl<T> TreeNode<T> {
pub fn new(arr: &[[i8; 3]]) -> TreeNode<i8> {
let l = match arr[0][1] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
let r = match arr[0][2] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
TreeNode {
value: arr[0][0],
left: l,
right: r,
}
}
pub fn traverse(&self, tr: &TraversalMethod) -> Vec<&TreeNode<T>> {
match tr {
&TraversalMethod::PreOrder => self.iterative_preorder(),
&TraversalMethod::InOrder => self.iterative_inorder(),
&TraversalMethod::PostOrder => self.iterative_postorder(),
&TraversalMethod::LevelOrder => self.iterative_levelorder(),
}
}
fn iterative_preorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
}
res
}
fn iterative_inorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
let mut p = self;
loop {
loop {
match p.right {
None => {}
Some(box ref n) => stack.push(n),
}
stack.push(p);
match p.left {
None => break,
Some(box ref n) => p = n,
}
}
p = stack.pop().unwrap();
while !stack.is_empty() && p.right.is_none() {
res.push(p);
p = stack.pop().unwrap();
}
res.push(p);
if stack.is_empty() {
break;
} else {
p = stack.pop().unwrap();
}
}
res
}
fn iterative_postorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
}
let rev_iter = res.iter().rev();
let mut rev: Vec<&TreeNode<T>> = Vec::new();
for elem in rev_iter {
rev.push(elem);
}
rev
}
fn iterative_levelorder(&self) -> Vec<&TreeNode<T>> {
let mut queue: VecDeque<&TreeNode<T>> = VecDeque::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
queue.push_back(self);
while !queue.is_empty() {
let node = queue.pop_front().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => queue.push_back(n),
}
match node.right {
None => {}
Some(box ref n) => queue.push_back(n),
}
}
res
}
}
fn main() {
let arr_tree = [[1, 2, 3],
[2, 4, 5],
[3, 6, -1],
[4, 7, -1],
[5, -1, -1],
[6, 8, 9],
[7, -1, -1],
[8, -1, -1],
[9, -1, -1]];
let root = TreeNode::<i8>::new(&arr_tree);
for method_label in [(TraversalMethod::PreOrder, "pre-order:"),
(TraversalMethod::InOrder, "in-order:"),
(TraversalMethod::PostOrder, "post-order:"),
(TraversalMethod::LevelOrder, "level-order:")]
.iter() {
print!("{}\t", method_label.1);
for n in root.traverse(&method_label.0) {
print!(" {}", n.value);
}
print!("\n");
}
}
| Public Value As Integer
Public LeftChild As TreeItem
Public RightChild As TreeItem
|
Keep all operations the same but rewrite the snippet in Python. | #![feature(box_syntax, box_patterns)]
use std::collections::VecDeque;
#[derive(Debug)]
struct TreeNode<T> {
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
enum TraversalMethod {
PreOrder,
InOrder,
PostOrder,
LevelOrder,
}
impl<T> TreeNode<T> {
pub fn new(arr: &[[i8; 3]]) -> TreeNode<i8> {
let l = match arr[0][1] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
let r = match arr[0][2] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
TreeNode {
value: arr[0][0],
left: l,
right: r,
}
}
pub fn traverse(&self, tr: &TraversalMethod) -> Vec<&TreeNode<T>> {
match tr {
&TraversalMethod::PreOrder => self.iterative_preorder(),
&TraversalMethod::InOrder => self.iterative_inorder(),
&TraversalMethod::PostOrder => self.iterative_postorder(),
&TraversalMethod::LevelOrder => self.iterative_levelorder(),
}
}
fn iterative_preorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
}
res
}
fn iterative_inorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
let mut p = self;
loop {
loop {
match p.right {
None => {}
Some(box ref n) => stack.push(n),
}
stack.push(p);
match p.left {
None => break,
Some(box ref n) => p = n,
}
}
p = stack.pop().unwrap();
while !stack.is_empty() && p.right.is_none() {
res.push(p);
p = stack.pop().unwrap();
}
res.push(p);
if stack.is_empty() {
break;
} else {
p = stack.pop().unwrap();
}
}
res
}
fn iterative_postorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
}
let rev_iter = res.iter().rev();
let mut rev: Vec<&TreeNode<T>> = Vec::new();
for elem in rev_iter {
rev.push(elem);
}
rev
}
fn iterative_levelorder(&self) -> Vec<&TreeNode<T>> {
let mut queue: VecDeque<&TreeNode<T>> = VecDeque::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
queue.push_back(self);
while !queue.is_empty() {
let node = queue.pop_front().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => queue.push_back(n),
}
match node.right {
None => {}
Some(box ref n) => queue.push_back(n),
}
}
res
}
}
fn main() {
let arr_tree = [[1, 2, 3],
[2, 4, 5],
[3, 6, -1],
[4, 7, -1],
[5, -1, -1],
[6, 8, 9],
[7, -1, -1],
[8, -1, -1],
[9, -1, -1]];
let root = TreeNode::<i8>::new(&arr_tree);
for method_label in [(TraversalMethod::PreOrder, "pre-order:"),
(TraversalMethod::InOrder, "in-order:"),
(TraversalMethod::PostOrder, "post-order:"),
(TraversalMethod::LevelOrder, "level-order:")]
.iter() {
print!("{}\t", method_label.1);
for n in root.traverse(&method_label.0) {
print!(" {}", n.value);
}
print!("\n");
}
}
| from collections import namedtuple
Node = namedtuple('Node', 'data, left, right')
tree = Node(1,
Node(2,
Node(4,
Node(7, None, None),
None),
Node(5, None, None)),
Node(3,
Node(6,
Node(8, None, None),
Node(9, None, None)),
None))
def printwithspace(i):
print(i, end=' ')
def dfs(order, node, visitor):
if node is not None:
for action in order:
if action == 'N':
visitor(node.data)
elif action == 'L':
dfs(order, node.left, visitor)
elif action == 'R':
dfs(order, node.right, visitor)
def preorder(node, visitor = printwithspace):
dfs('NLR', node, visitor)
def inorder(node, visitor = printwithspace):
dfs('LNR', node, visitor)
def postorder(node, visitor = printwithspace):
dfs('LRN', node, visitor)
def ls(node, more, visitor, order='TB'):
"Level-based Top-to-Bottom or Bottom-to-Top tree search"
if node:
if more is None:
more = []
more += [node.left, node.right]
for action in order:
if action == 'B' and more:
ls(more[0], more[1:], visitor, order)
elif action == 'T' and node:
visitor(node.data)
def levelorder(node, more=None, visitor = printwithspace):
ls(node, more, visitor, 'TB')
def reverse_preorder(node, visitor = printwithspace):
dfs('RLN', node, visitor)
def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'):
ls(node, more, visitor, 'BT')
if __name__ == '__main__':
w = 10
for traversal in [preorder, inorder, postorder, levelorder,
reverse_preorder, bottom_up_order]:
if traversal == reverse_preorder:
w = 20
print('\nThe generalisation of function dfs allows:')
if traversal == bottom_up_order:
print('The generalisation of function ls allows:')
print(f"{traversal.__name__:>{w}}:", end=' ')
traversal(tree)
print()
|
Rewrite this program in Rust while keeping its functionality equivalent to the C# version. | using System;
using System.Collections.Generic;
using System.Linq;
class Node
{
int Value;
Node Left;
Node Right;
Node(int value = default(int), Node left = default(Node), Node right = default(Node))
{
Value = value;
Left = left;
Right = right;
}
IEnumerable<int> Preorder()
{
yield return Value;
if (Left != null)
foreach (var value in Left.Preorder())
yield return value;
if (Right != null)
foreach (var value in Right.Preorder())
yield return value;
}
IEnumerable<int> Inorder()
{
if (Left != null)
foreach (var value in Left.Inorder())
yield return value;
yield return Value;
if (Right != null)
foreach (var value in Right.Inorder())
yield return value;
}
IEnumerable<int> Postorder()
{
if (Left != null)
foreach (var value in Left.Postorder())
yield return value;
if (Right != null)
foreach (var value in Right.Postorder())
yield return value;
yield return Value;
}
IEnumerable<int> LevelOrder()
{
var queue = new Queue<Node>();
queue.Enqueue(this);
while (queue.Any())
{
var node = queue.Dequeue();
yield return node.Value;
if (node.Left != null)
queue.Enqueue(node.Left);
if (node.Right != null)
queue.Enqueue(node.Right);
}
}
static void Main()
{
var tree = new Node(1, new Node(2, new Node(4, new Node(7)), new Node(5)), new Node(3, new Node(6, new Node(8), new Node(9))));
foreach (var traversal in new Func<IEnumerable<int>>[] { tree.Preorder, tree.Inorder, tree.Postorder, tree.LevelOrder })
Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal()));
}
}
| #![feature(box_syntax, box_patterns)]
use std::collections::VecDeque;
#[derive(Debug)]
struct TreeNode<T> {
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
enum TraversalMethod {
PreOrder,
InOrder,
PostOrder,
LevelOrder,
}
impl<T> TreeNode<T> {
pub fn new(arr: &[[i8; 3]]) -> TreeNode<i8> {
let l = match arr[0][1] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
let r = match arr[0][2] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
TreeNode {
value: arr[0][0],
left: l,
right: r,
}
}
pub fn traverse(&self, tr: &TraversalMethod) -> Vec<&TreeNode<T>> {
match tr {
&TraversalMethod::PreOrder => self.iterative_preorder(),
&TraversalMethod::InOrder => self.iterative_inorder(),
&TraversalMethod::PostOrder => self.iterative_postorder(),
&TraversalMethod::LevelOrder => self.iterative_levelorder(),
}
}
fn iterative_preorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
}
res
}
fn iterative_inorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
let mut p = self;
loop {
loop {
match p.right {
None => {}
Some(box ref n) => stack.push(n),
}
stack.push(p);
match p.left {
None => break,
Some(box ref n) => p = n,
}
}
p = stack.pop().unwrap();
while !stack.is_empty() && p.right.is_none() {
res.push(p);
p = stack.pop().unwrap();
}
res.push(p);
if stack.is_empty() {
break;
} else {
p = stack.pop().unwrap();
}
}
res
}
fn iterative_postorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
}
let rev_iter = res.iter().rev();
let mut rev: Vec<&TreeNode<T>> = Vec::new();
for elem in rev_iter {
rev.push(elem);
}
rev
}
fn iterative_levelorder(&self) -> Vec<&TreeNode<T>> {
let mut queue: VecDeque<&TreeNode<T>> = VecDeque::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
queue.push_back(self);
while !queue.is_empty() {
let node = queue.pop_front().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => queue.push_back(n),
}
match node.right {
None => {}
Some(box ref n) => queue.push_back(n),
}
}
res
}
}
fn main() {
let arr_tree = [[1, 2, 3],
[2, 4, 5],
[3, 6, -1],
[4, 7, -1],
[5, -1, -1],
[6, 8, 9],
[7, -1, -1],
[8, -1, -1],
[9, -1, -1]];
let root = TreeNode::<i8>::new(&arr_tree);
for method_label in [(TraversalMethod::PreOrder, "pre-order:"),
(TraversalMethod::InOrder, "in-order:"),
(TraversalMethod::PostOrder, "post-order:"),
(TraversalMethod::LevelOrder, "level-order:")]
.iter() {
print!("{}\t", method_label.1);
for n in root.traverse(&method_label.0) {
print!(" {}", n.value);
}
print!("\n");
}
}
|
Preserve the algorithm and functionality while converting the code from Ada to C#. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
procedure Pythagore_Set is
type Triangles is array (1 .. 3) of Positive;
package Triangle_Lists is new Ada.Containers.Doubly_Linked_Lists (
Triangles);
use Triangle_Lists;
function Find_List (Upper_Bound : Positive) return List is
L : List := Empty_List;
begin
for A in 1 .. Upper_Bound loop
for B in A + 1 .. Upper_Bound loop
for C in B + 1 .. Upper_Bound loop
if ((A * A + B * B) = C * C) then
Append (L, (A, B, C));
end if;
end loop;
end loop;
end loop;
return L;
end Find_List;
Triangle_List : List;
C : Cursor;
T : Triangles;
begin
Triangle_List := Find_List (Upper_Bound => 20);
C := First (Triangle_List);
while Has_Element (C) loop
T := Element (C);
Put
("(" &
Integer'Image (T (1)) &
Integer'Image (T (2)) &
Integer'Image (T (3)) &
") ");
Next (C);
end loop;
end Pythagore_Set;
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Translate the given Ada code snippet into C without altering its behavior. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
procedure Pythagore_Set is
type Triangles is array (1 .. 3) of Positive;
package Triangle_Lists is new Ada.Containers.Doubly_Linked_Lists (
Triangles);
use Triangle_Lists;
function Find_List (Upper_Bound : Positive) return List is
L : List := Empty_List;
begin
for A in 1 .. Upper_Bound loop
for B in A + 1 .. Upper_Bound loop
for C in B + 1 .. Upper_Bound loop
if ((A * A + B * B) = C * C) then
Append (L, (A, B, C));
end if;
end loop;
end loop;
end loop;
return L;
end Find_List;
Triangle_List : List;
C : Cursor;
T : Triangles;
begin
Triangle_List := Find_List (Upper_Bound => 20);
C := First (Triangle_List);
while Has_Element (C) loop
T := Element (C);
Put
("(" &
Integer'Image (T (1)) &
Integer'Image (T (2)) &
Integer'Image (T (3)) &
") ");
Next (C);
end loop;
end Pythagore_Set;
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Generate a C++ translation of this Ada snippet without changing its computational steps. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
procedure Pythagore_Set is
type Triangles is array (1 .. 3) of Positive;
package Triangle_Lists is new Ada.Containers.Doubly_Linked_Lists (
Triangles);
use Triangle_Lists;
function Find_List (Upper_Bound : Positive) return List is
L : List := Empty_List;
begin
for A in 1 .. Upper_Bound loop
for B in A + 1 .. Upper_Bound loop
for C in B + 1 .. Upper_Bound loop
if ((A * A + B * B) = C * C) then
Append (L, (A, B, C));
end if;
end loop;
end loop;
end loop;
return L;
end Find_List;
Triangle_List : List;
C : Cursor;
T : Triangles;
begin
Triangle_List := Find_List (Upper_Bound => 20);
C := First (Triangle_List);
while Has_Element (C) loop
T := Element (C);
Put
("(" &
Integer'Image (T (1)) &
Integer'Image (T (2)) &
Integer'Image (T (3)) &
") ");
Next (C);
end loop;
end Pythagore_Set;
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Ada version. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
procedure Pythagore_Set is
type Triangles is array (1 .. 3) of Positive;
package Triangle_Lists is new Ada.Containers.Doubly_Linked_Lists (
Triangles);
use Triangle_Lists;
function Find_List (Upper_Bound : Positive) return List is
L : List := Empty_List;
begin
for A in 1 .. Upper_Bound loop
for B in A + 1 .. Upper_Bound loop
for C in B + 1 .. Upper_Bound loop
if ((A * A + B * B) = C * C) then
Append (L, (A, B, C));
end if;
end loop;
end loop;
end loop;
return L;
end Find_List;
Triangle_List : List;
C : Cursor;
T : Triangles;
begin
Triangle_List := Find_List (Upper_Bound => 20);
C := First (Triangle_List);
while Has_Element (C) loop
T := Element (C);
Put
("(" &
Integer'Image (T (1)) &
Integer'Image (T (2)) &
Integer'Image (T (3)) &
") ");
Next (C);
end loop;
end Pythagore_Set;
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Change the following Ada code into Java without altering its purpose. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
procedure Pythagore_Set is
type Triangles is array (1 .. 3) of Positive;
package Triangle_Lists is new Ada.Containers.Doubly_Linked_Lists (
Triangles);
use Triangle_Lists;
function Find_List (Upper_Bound : Positive) return List is
L : List := Empty_List;
begin
for A in 1 .. Upper_Bound loop
for B in A + 1 .. Upper_Bound loop
for C in B + 1 .. Upper_Bound loop
if ((A * A + B * B) = C * C) then
Append (L, (A, B, C));
end if;
end loop;
end loop;
end loop;
return L;
end Find_List;
Triangle_List : List;
C : Cursor;
T : Triangles;
begin
Triangle_List := Find_List (Upper_Bound => 20);
C := First (Triangle_List);
while Has_Element (C) loop
T := Element (C);
Put
("(" &
Integer'Image (T (1)) &
Integer'Image (T (2)) &
Integer'Image (T (3)) &
") ");
Next (C);
end loop;
end Pythagore_Set;
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Generate an equivalent Python version of this Ada code. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
procedure Pythagore_Set is
type Triangles is array (1 .. 3) of Positive;
package Triangle_Lists is new Ada.Containers.Doubly_Linked_Lists (
Triangles);
use Triangle_Lists;
function Find_List (Upper_Bound : Positive) return List is
L : List := Empty_List;
begin
for A in 1 .. Upper_Bound loop
for B in A + 1 .. Upper_Bound loop
for C in B + 1 .. Upper_Bound loop
if ((A * A + B * B) = C * C) then
Append (L, (A, B, C));
end if;
end loop;
end loop;
end loop;
return L;
end Find_List;
Triangle_List : List;
C : Cursor;
T : Triangles;
begin
Triangle_List := Find_List (Upper_Bound => 20);
C := First (Triangle_List);
while Has_Element (C) loop
T := Element (C);
Put
("(" &
Integer'Image (T (1)) &
Integer'Image (T (2)) &
Integer'Image (T (3)) &
") ");
Next (C);
end loop;
end Pythagore_Set;
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Ensure the translated VB code behaves exactly like the original Ada snippet. | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
procedure Pythagore_Set is
type Triangles is array (1 .. 3) of Positive;
package Triangle_Lists is new Ada.Containers.Doubly_Linked_Lists (
Triangles);
use Triangle_Lists;
function Find_List (Upper_Bound : Positive) return List is
L : List := Empty_List;
begin
for A in 1 .. Upper_Bound loop
for B in A + 1 .. Upper_Bound loop
for C in B + 1 .. Upper_Bound loop
if ((A * A + B * B) = C * C) then
Append (L, (A, B, C));
end if;
end loop;
end loop;
end loop;
return L;
end Find_List;
Triangle_List : List;
C : Cursor;
T : Triangles;
begin
Triangle_List := Find_List (Upper_Bound => 20);
C := First (Triangle_List);
while Has_Element (C) loop
T := Element (C);
Put
("(" &
Integer'Image (T (1)) &
Integer'Image (T (2)) &
Integer'Image (T (3)) &
") ");
Next (C);
end loop;
end Pythagore_Set;
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Please provide an equivalent version of this Arturo code in C. | n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Please provide an equivalent version of this Arturo code in C#. | n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Keep all operations the same but rewrite the snippet in C++. | n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Port the following code from Arturo to Java with equivalent syntax and logic. | n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Ensure the translated Python code behaves exactly like the original Arturo snippet. | n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Port the following code from Arturo to VB with equivalent syntax and logic. | n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Translate the given Arturo code snippet into Go without altering its behavior. | n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Write the same code in C as shown below in AutoHotKey. | comprehend("show", range(1, 20), "triples")
return
comprehend(doToVariable, inSet, satisfying)
{
set := %satisfying%(inSet.begin, inSet.end)
index := 1
While % set[index, 1]
{
item := set[index, 1] . ", " . set[index, 2] . ", " . set[index, 3]
%doToVariable%(item)
index += 1
}
return
}
show(var)
{
msgbox % var
}
range(begin, end)
{
set := object()
set.begin := begin
set.end := end
return set
}
!r::reload
!q::exitapp
triples(begin, end)
{
set := object()
index := 1
range := end - begin
loop, % range
{
x := begin + A_Index
loop, % range
{
y := A_Index + x
if y > 20
break
loop, % range
{
z := A_Index + y
if z > 20
break
isTriple := ((x ** 2 + y ** 2) == z ** 2)
if isTriple
{
set[index, 1] := x
set[index, 2] := y
set[index, 3] := z
index += 1
}
}
}
}
return set
}
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Write the same algorithm in C# as shown in this AutoHotKey implementation. | comprehend("show", range(1, 20), "triples")
return
comprehend(doToVariable, inSet, satisfying)
{
set := %satisfying%(inSet.begin, inSet.end)
index := 1
While % set[index, 1]
{
item := set[index, 1] . ", " . set[index, 2] . ", " . set[index, 3]
%doToVariable%(item)
index += 1
}
return
}
show(var)
{
msgbox % var
}
range(begin, end)
{
set := object()
set.begin := begin
set.end := end
return set
}
!r::reload
!q::exitapp
triples(begin, end)
{
set := object()
index := 1
range := end - begin
loop, % range
{
x := begin + A_Index
loop, % range
{
y := A_Index + x
if y > 20
break
loop, % range
{
z := A_Index + y
if z > 20
break
isTriple := ((x ** 2 + y ** 2) == z ** 2)
if isTriple
{
set[index, 1] := x
set[index, 2] := y
set[index, 3] := z
index += 1
}
}
}
}
return set
}
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Write the same algorithm in C++ as shown in this AutoHotKey implementation. | comprehend("show", range(1, 20), "triples")
return
comprehend(doToVariable, inSet, satisfying)
{
set := %satisfying%(inSet.begin, inSet.end)
index := 1
While % set[index, 1]
{
item := set[index, 1] . ", " . set[index, 2] . ", " . set[index, 3]
%doToVariable%(item)
index += 1
}
return
}
show(var)
{
msgbox % var
}
range(begin, end)
{
set := object()
set.begin := begin
set.end := end
return set
}
!r::reload
!q::exitapp
triples(begin, end)
{
set := object()
index := 1
range := end - begin
loop, % range
{
x := begin + A_Index
loop, % range
{
y := A_Index + x
if y > 20
break
loop, % range
{
z := A_Index + y
if z > 20
break
isTriple := ((x ** 2 + y ** 2) == z ** 2)
if isTriple
{
set[index, 1] := x
set[index, 2] := y
set[index, 3] := z
index += 1
}
}
}
}
return set
}
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Transform the following AutoHotKey implementation into Java, maintaining the same output and logic. | comprehend("show", range(1, 20), "triples")
return
comprehend(doToVariable, inSet, satisfying)
{
set := %satisfying%(inSet.begin, inSet.end)
index := 1
While % set[index, 1]
{
item := set[index, 1] . ", " . set[index, 2] . ", " . set[index, 3]
%doToVariable%(item)
index += 1
}
return
}
show(var)
{
msgbox % var
}
range(begin, end)
{
set := object()
set.begin := begin
set.end := end
return set
}
!r::reload
!q::exitapp
triples(begin, end)
{
set := object()
index := 1
range := end - begin
loop, % range
{
x := begin + A_Index
loop, % range
{
y := A_Index + x
if y > 20
break
loop, % range
{
z := A_Index + y
if z > 20
break
isTriple := ((x ** 2 + y ** 2) == z ** 2)
if isTriple
{
set[index, 1] := x
set[index, 2] := y
set[index, 3] := z
index += 1
}
}
}
}
return set
}
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the AutoHotKey version. | comprehend("show", range(1, 20), "triples")
return
comprehend(doToVariable, inSet, satisfying)
{
set := %satisfying%(inSet.begin, inSet.end)
index := 1
While % set[index, 1]
{
item := set[index, 1] . ", " . set[index, 2] . ", " . set[index, 3]
%doToVariable%(item)
index += 1
}
return
}
show(var)
{
msgbox % var
}
range(begin, end)
{
set := object()
set.begin := begin
set.end := end
return set
}
!r::reload
!q::exitapp
triples(begin, end)
{
set := object()
index := 1
range := end - begin
loop, % range
{
x := begin + A_Index
loop, % range
{
y := A_Index + x
if y > 20
break
loop, % range
{
z := A_Index + y
if z > 20
break
isTriple := ((x ** 2 + y ** 2) == z ** 2)
if isTriple
{
set[index, 1] := x
set[index, 2] := y
set[index, 3] := z
index += 1
}
}
}
}
return set
}
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Write the same algorithm in VB as shown in this AutoHotKey implementation. | comprehend("show", range(1, 20), "triples")
return
comprehend(doToVariable, inSet, satisfying)
{
set := %satisfying%(inSet.begin, inSet.end)
index := 1
While % set[index, 1]
{
item := set[index, 1] . ", " . set[index, 2] . ", " . set[index, 3]
%doToVariable%(item)
index += 1
}
return
}
show(var)
{
msgbox % var
}
range(begin, end)
{
set := object()
set.begin := begin
set.end := end
return set
}
!r::reload
!q::exitapp
triples(begin, end)
{
set := object()
index := 1
range := end - begin
loop, % range
{
x := begin + A_Index
loop, % range
{
y := A_Index + x
if y > 20
break
loop, % range
{
z := A_Index + y
if z > 20
break
isTriple := ((x ** 2 + y ** 2) == z ** 2)
if isTriple
{
set[index, 1] := x
set[index, 2] := y
set[index, 3] := z
index += 1
}
}
}
}
return set
}
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Produce a language-to-language conversion: from AutoHotKey to Go, same semantics. | comprehend("show", range(1, 20), "triples")
return
comprehend(doToVariable, inSet, satisfying)
{
set := %satisfying%(inSet.begin, inSet.end)
index := 1
While % set[index, 1]
{
item := set[index, 1] . ", " . set[index, 2] . ", " . set[index, 3]
%doToVariable%(item)
index += 1
}
return
}
show(var)
{
msgbox % var
}
range(begin, end)
{
set := object()
set.begin := begin
set.end := end
return set
}
!r::reload
!q::exitapp
triples(begin, end)
{
set := object()
index := 1
range := end - begin
loop, % range
{
x := begin + A_Index
loop, % range
{
y := A_Index + x
if y > 20
break
loop, % range
{
z := A_Index + y
if z > 20
break
isTriple := ((x ** 2 + y ** 2) == z ** 2)
if isTriple
{
set[index, 1] := x
set[index, 2] := y
set[index, 3] := z
index += 1
}
}
}
}
return set
}
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Can you help me rewrite this code in C instead of Clojure, keeping it the same logically? | (defn triples [n]
(list-comp (, a b c) [a (range 1 (inc n))
b (range a (inc n))
c (range b (inc n))]
(= (pow c 2)
(+ (pow a 2)
(pow b 2)))))
(print (triples 15))
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Translate this program into C# but keep the logic exactly as in Clojure. | (defn triples [n]
(list-comp (, a b c) [a (range 1 (inc n))
b (range a (inc n))
c (range b (inc n))]
(= (pow c 2)
(+ (pow a 2)
(pow b 2)))))
(print (triples 15))
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Preserve the algorithm and functionality while converting the code from Clojure to C++. | (defn triples [n]
(list-comp (, a b c) [a (range 1 (inc n))
b (range a (inc n))
c (range b (inc n))]
(= (pow c 2)
(+ (pow a 2)
(pow b 2)))))
(print (triples 15))
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Transform the following Clojure implementation into Java, maintaining the same output and logic. | (defn triples [n]
(list-comp (, a b c) [a (range 1 (inc n))
b (range a (inc n))
c (range b (inc n))]
(= (pow c 2)
(+ (pow a 2)
(pow b 2)))))
(print (triples 15))
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Convert the following code from Clojure to Python, ensuring the logic remains intact. | (defn triples [n]
(list-comp (, a b c) [a (range 1 (inc n))
b (range a (inc n))
c (range b (inc n))]
(= (pow c 2)
(+ (pow a 2)
(pow b 2)))))
(print (triples 15))
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Please provide an equivalent version of this Clojure code in VB. | (defn triples [n]
(list-comp (, a b c) [a (range 1 (inc n))
b (range a (inc n))
c (range b (inc n))]
(= (pow c 2)
(+ (pow a 2)
(pow b 2)))))
(print (triples 15))
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Write the same code in Go as shown below in Clojure. | (defn triples [n]
(list-comp (, a b c) [a (range 1 (inc n))
b (range a (inc n))
c (range b (inc n))]
(= (pow c 2)
(+ (pow a 2)
(pow b 2)))))
(print (triples 15))
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Produce a functionally identical C code for the snippet given in Common_Lisp. | (defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z]))
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Produce a functionally identical C# code for the snippet given in Common_Lisp. | (defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z]))
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Common_Lisp code. | (defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z]))
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Common_Lisp to Java. | (defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z]))
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Generate a Python translation of this Common_Lisp snippet without changing its computational steps. | (defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z]))
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Maintain the same structure and functionality when rewriting this code in VB. | (defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z]))
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Generate a Go translation of this Common_Lisp snippet without changing its computational steps. | (defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z]))
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Rewrite the snippet below in C so it works the same as the original D code. | import std.stdio, std.meta, std.range;
TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP)
(lazy TA mapper,
ref TI1 iter1, TC1 items1,
ref TI2 iter2, lazy TC2 items2,
ref TI3 iter3, lazy TC3 items3,
lazy TP where) {
Appender!(TA[]) result;
auto iters = AliasSeq!(iter1, iter2, iter3);
foreach (el1; items1) {
iter1 = el1;
foreach (el2; items2) {
iter2 = el2;
foreach (el3; items3) {
iter3 = el3;
if (where())
result ~= mapper();
}
}
}
AliasSeq!(iter1, iter2, iter3) = iters;
return result.data;
}
void main() {
enum int n = 21;
int x, y, z;
auto r = select([x,y,z], x, iota(1,n+1), y, iota(x,n+1), z,
iota(y, n + 1), x*x + y*y == z*z);
writeln(r);
}
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Write the same algorithm in C# as shown in this D implementation. | import std.stdio, std.meta, std.range;
TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP)
(lazy TA mapper,
ref TI1 iter1, TC1 items1,
ref TI2 iter2, lazy TC2 items2,
ref TI3 iter3, lazy TC3 items3,
lazy TP where) {
Appender!(TA[]) result;
auto iters = AliasSeq!(iter1, iter2, iter3);
foreach (el1; items1) {
iter1 = el1;
foreach (el2; items2) {
iter2 = el2;
foreach (el3; items3) {
iter3 = el3;
if (where())
result ~= mapper();
}
}
}
AliasSeq!(iter1, iter2, iter3) = iters;
return result.data;
}
void main() {
enum int n = 21;
int x, y, z;
auto r = select([x,y,z], x, iota(1,n+1), y, iota(x,n+1), z,
iota(y, n + 1), x*x + y*y == z*z);
writeln(r);
}
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Produce a language-to-language conversion: from D to C++, same semantics. | import std.stdio, std.meta, std.range;
TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP)
(lazy TA mapper,
ref TI1 iter1, TC1 items1,
ref TI2 iter2, lazy TC2 items2,
ref TI3 iter3, lazy TC3 items3,
lazy TP where) {
Appender!(TA[]) result;
auto iters = AliasSeq!(iter1, iter2, iter3);
foreach (el1; items1) {
iter1 = el1;
foreach (el2; items2) {
iter2 = el2;
foreach (el3; items3) {
iter3 = el3;
if (where())
result ~= mapper();
}
}
}
AliasSeq!(iter1, iter2, iter3) = iters;
return result.data;
}
void main() {
enum int n = 21;
int x, y, z;
auto r = select([x,y,z], x, iota(1,n+1), y, iota(x,n+1), z,
iota(y, n + 1), x*x + y*y == z*z);
writeln(r);
}
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Port the provided D code into Java while preserving the original functionality. | import std.stdio, std.meta, std.range;
TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP)
(lazy TA mapper,
ref TI1 iter1, TC1 items1,
ref TI2 iter2, lazy TC2 items2,
ref TI3 iter3, lazy TC3 items3,
lazy TP where) {
Appender!(TA[]) result;
auto iters = AliasSeq!(iter1, iter2, iter3);
foreach (el1; items1) {
iter1 = el1;
foreach (el2; items2) {
iter2 = el2;
foreach (el3; items3) {
iter3 = el3;
if (where())
result ~= mapper();
}
}
}
AliasSeq!(iter1, iter2, iter3) = iters;
return result.data;
}
void main() {
enum int n = 21;
int x, y, z;
auto r = select([x,y,z], x, iota(1,n+1), y, iota(x,n+1), z,
iota(y, n + 1), x*x + y*y == z*z);
writeln(r);
}
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Port the following code from D to Python with equivalent syntax and logic. | import std.stdio, std.meta, std.range;
TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP)
(lazy TA mapper,
ref TI1 iter1, TC1 items1,
ref TI2 iter2, lazy TC2 items2,
ref TI3 iter3, lazy TC3 items3,
lazy TP where) {
Appender!(TA[]) result;
auto iters = AliasSeq!(iter1, iter2, iter3);
foreach (el1; items1) {
iter1 = el1;
foreach (el2; items2) {
iter2 = el2;
foreach (el3; items3) {
iter3 = el3;
if (where())
result ~= mapper();
}
}
}
AliasSeq!(iter1, iter2, iter3) = iters;
return result.data;
}
void main() {
enum int n = 21;
int x, y, z;
auto r = select([x,y,z], x, iota(1,n+1), y, iota(x,n+1), z,
iota(y, n + 1), x*x + y*y == z*z);
writeln(r);
}
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Convert the following code from D to VB, ensuring the logic remains intact. | import std.stdio, std.meta, std.range;
TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP)
(lazy TA mapper,
ref TI1 iter1, TC1 items1,
ref TI2 iter2, lazy TC2 items2,
ref TI3 iter3, lazy TC3 items3,
lazy TP where) {
Appender!(TA[]) result;
auto iters = AliasSeq!(iter1, iter2, iter3);
foreach (el1; items1) {
iter1 = el1;
foreach (el2; items2) {
iter2 = el2;
foreach (el3; items3) {
iter3 = el3;
if (where())
result ~= mapper();
}
}
}
AliasSeq!(iter1, iter2, iter3) = iters;
return result.data;
}
void main() {
enum int n = 21;
int x, y, z;
auto r = select([x,y,z], x, iota(1,n+1), y, iota(x,n+1), z,
iota(y, n + 1), x*x + y*y == z*z);
writeln(r);
}
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Write the same algorithm in Go as shown in this D implementation. | import std.stdio, std.meta, std.range;
TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP)
(lazy TA mapper,
ref TI1 iter1, TC1 items1,
ref TI2 iter2, lazy TC2 items2,
ref TI3 iter3, lazy TC3 items3,
lazy TP where) {
Appender!(TA[]) result;
auto iters = AliasSeq!(iter1, iter2, iter3);
foreach (el1; items1) {
iter1 = el1;
foreach (el2; items2) {
iter2 = el2;
foreach (el3; items3) {
iter3 = el3;
if (where())
result ~= mapper();
}
}
}
AliasSeq!(iter1, iter2, iter3) = iters;
return result.data;
}
void main() {
enum int n = 21;
int x, y, z;
auto r = select([x,y,z], x, iota(1,n+1), y, iota(x,n+1), z,
iota(y, n + 1), x*x + y*y == z*z);
writeln(r);
}
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Produce a functionally identical C code for the snippet given in Erlang. | pythag(N) ->
[ {A,B,C} || A <- lists:seq(1,N),
B <- lists:seq(A,N),
C <- lists:seq(B,N),
A+B+C =< N,
A*A+B*B == C*C ].
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Produce a functionally identical C# code for the snippet given in Erlang. | pythag(N) ->
[ {A,B,C} || A <- lists:seq(1,N),
B <- lists:seq(A,N),
C <- lists:seq(B,N),
A+B+C =< N,
A*A+B*B == C*C ].
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Generate a C++ translation of this Erlang snippet without changing its computational steps. | pythag(N) ->
[ {A,B,C} || A <- lists:seq(1,N),
B <- lists:seq(A,N),
C <- lists:seq(B,N),
A+B+C =< N,
A*A+B*B == C*C ].
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Erlang code. | pythag(N) ->
[ {A,B,C} || A <- lists:seq(1,N),
B <- lists:seq(A,N),
C <- lists:seq(B,N),
A+B+C =< N,
A*A+B*B == C*C ].
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Ensure the translated Python code behaves exactly like the original Erlang snippet. | pythag(N) ->
[ {A,B,C} || A <- lists:seq(1,N),
B <- lists:seq(A,N),
C <- lists:seq(B,N),
A+B+C =< N,
A*A+B*B == C*C ].
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Convert this Erlang block to VB, preserving its control flow and logic. | pythag(N) ->
[ {A,B,C} || A <- lists:seq(1,N),
B <- lists:seq(A,N),
C <- lists:seq(B,N),
A+B+C =< N,
A*A+B*B == C*C ].
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Maintain the same structure and functionality when rewriting this code in Go. | pythag(N) ->
[ {A,B,C} || A <- lists:seq(1,N),
B <- lists:seq(A,N),
C <- lists:seq(B,N),
A+B+C =< N,
A*A+B*B == C*C ].
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Change the following F# code into C without altering its purpose. | let pyth n = [ for a in [1..n] do
for b in [a..n] do
for c in [b..n] do
if (a*a+b*b = c*c) then yield (a,b,c)]
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Convert this F# snippet to C# and keep its semantics consistent. | let pyth n = [ for a in [1..n] do
for b in [a..n] do
for c in [b..n] do
if (a*a+b*b = c*c) then yield (a,b,c)]
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Preserve the algorithm and functionality while converting the code from F# to C++. | let pyth n = [ for a in [1..n] do
for b in [a..n] do
for c in [b..n] do
if (a*a+b*b = c*c) then yield (a,b,c)]
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Change the following F# code into Java without altering its purpose. | let pyth n = [ for a in [1..n] do
for b in [a..n] do
for c in [b..n] do
if (a*a+b*b = c*c) then yield (a,b,c)]
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Produce a language-to-language conversion: from F# to Python, same semantics. | let pyth n = [ for a in [1..n] do
for b in [a..n] do
for c in [b..n] do
if (a*a+b*b = c*c) then yield (a,b,c)]
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Translate this program into VB but keep the logic exactly as in F#. | let pyth n = [ for a in [1..n] do
for b in [a..n] do
for c in [b..n] do
if (a*a+b*b = c*c) then yield (a,b,c)]
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Rewrite this program in Go while keeping its functionality equivalent to the F# version. | let pyth n = [ for a in [1..n] do
for b in [a..n] do
for c in [b..n] do
if (a*a+b*b = c*c) then yield (a,b,c)]
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Convert this Factor snippet to C and keep its semantics consistent. | USING: backtrack kernel locals math math.ranges ;
:: pythagorean-triples ( n -- seq )
[
n [1,b] amb-lazy :> a
a n [a,b] amb-lazy :> b
b n [a,b] amb-lazy :> c
a a * b b * + c c * = must-be-true { a b c }
] bag-of ;
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Translate this program into C# but keep the logic exactly as in Factor. | USING: backtrack kernel locals math math.ranges ;
:: pythagorean-triples ( n -- seq )
[
n [1,b] amb-lazy :> a
a n [a,b] amb-lazy :> b
b n [a,b] amb-lazy :> c
a a * b b * + c c * = must-be-true { a b c }
] bag-of ;
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Write the same algorithm in C++ as shown in this Factor implementation. | USING: backtrack kernel locals math math.ranges ;
:: pythagorean-triples ( n -- seq )
[
n [1,b] amb-lazy :> a
a n [a,b] amb-lazy :> b
b n [a,b] amb-lazy :> c
a a * b b * + c c * = must-be-true { a b c }
] bag-of ;
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Write the same algorithm in Java as shown in this Factor implementation. | USING: backtrack kernel locals math math.ranges ;
:: pythagorean-triples ( n -- seq )
[
n [1,b] amb-lazy :> a
a n [a,b] amb-lazy :> b
b n [a,b] amb-lazy :> c
a a * b b * + c c * = must-be-true { a b c }
] bag-of ;
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Write the same code in Python as shown below in Factor. | USING: backtrack kernel locals math math.ranges ;
:: pythagorean-triples ( n -- seq )
[
n [1,b] amb-lazy :> a
a n [a,b] amb-lazy :> b
b n [a,b] amb-lazy :> c
a a * b b * + c c * = must-be-true { a b c }
] bag-of ;
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Rewrite this program in VB while keeping its functionality equivalent to the Factor version. | USING: backtrack kernel locals math math.ranges ;
:: pythagorean-triples ( n -- seq )
[
n [1,b] amb-lazy :> a
a n [a,b] amb-lazy :> b
b n [a,b] amb-lazy :> c
a a * b b * + c c * = must-be-true { a b c }
] bag-of ;
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in Go. | USING: backtrack kernel locals math math.ranges ;
:: pythagorean-triples ( n -- seq )
[
n [1,b] amb-lazy :> a
a n [a,b] amb-lazy :> b
b n [a,b] amb-lazy :> c
a a * b b * + c c * = must-be-true { a b c }
] bag-of ;
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Convert this Fortran snippet to C# and keep its semantics consistent. |
program list_comprehension
integer, parameter :: n = 20
integer, parameter :: m = n*(n+1)/2
integer :: i, j
complex, dimension(m) :: a
real, dimension(m) :: b
logical, dimension(m) :: c
integer, dimension(3, m) :: d
a = [ ( ( cmplx(i,j), i=j,n), j=1,n) ]
b = abs(a)
c = (b .eq. int(b)) .and. (b .le. n)
i = sum(merge(1,0,c))
d(2,:i) = int(real(pack(a, c)))
d(1,:i) = int(imag(pack(a, c)))
d(3,:i) = int(pack(b,c))
print '(3i4)',d(:,:i)
end program list_comprehension
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Change the following Fortran code into C++ without altering its purpose. |
program list_comprehension
integer, parameter :: n = 20
integer, parameter :: m = n*(n+1)/2
integer :: i, j
complex, dimension(m) :: a
real, dimension(m) :: b
logical, dimension(m) :: c
integer, dimension(3, m) :: d
a = [ ( ( cmplx(i,j), i=j,n), j=1,n) ]
b = abs(a)
c = (b .eq. int(b)) .and. (b .le. n)
i = sum(merge(1,0,c))
d(2,:i) = int(real(pack(a, c)))
d(1,:i) = int(imag(pack(a, c)))
d(3,:i) = int(pack(b,c))
print '(3i4)',d(:,:i)
end program list_comprehension
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Change the following Fortran code into C without altering its purpose. |
program list_comprehension
integer, parameter :: n = 20
integer, parameter :: m = n*(n+1)/2
integer :: i, j
complex, dimension(m) :: a
real, dimension(m) :: b
logical, dimension(m) :: c
integer, dimension(3, m) :: d
a = [ ( ( cmplx(i,j), i=j,n), j=1,n) ]
b = abs(a)
c = (b .eq. int(b)) .and. (b .le. n)
i = sum(merge(1,0,c))
d(2,:i) = int(real(pack(a, c)))
d(1,:i) = int(imag(pack(a, c)))
d(3,:i) = int(pack(b,c))
print '(3i4)',d(:,:i)
end program list_comprehension
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Convert this Fortran snippet to Java and keep its semantics consistent. |
program list_comprehension
integer, parameter :: n = 20
integer, parameter :: m = n*(n+1)/2
integer :: i, j
complex, dimension(m) :: a
real, dimension(m) :: b
logical, dimension(m) :: c
integer, dimension(3, m) :: d
a = [ ( ( cmplx(i,j), i=j,n), j=1,n) ]
b = abs(a)
c = (b .eq. int(b)) .and. (b .le. n)
i = sum(merge(1,0,c))
d(2,:i) = int(real(pack(a, c)))
d(1,:i) = int(imag(pack(a, c)))
d(3,:i) = int(pack(b,c))
print '(3i4)',d(:,:i)
end program list_comprehension
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Generate an equivalent Python version of this Fortran code. |
program list_comprehension
integer, parameter :: n = 20
integer, parameter :: m = n*(n+1)/2
integer :: i, j
complex, dimension(m) :: a
real, dimension(m) :: b
logical, dimension(m) :: c
integer, dimension(3, m) :: d
a = [ ( ( cmplx(i,j), i=j,n), j=1,n) ]
b = abs(a)
c = (b .eq. int(b)) .and. (b .le. n)
i = sum(merge(1,0,c))
d(2,:i) = int(real(pack(a, c)))
d(1,:i) = int(imag(pack(a, c)))
d(3,:i) = int(pack(b,c))
print '(3i4)',d(:,:i)
end program list_comprehension
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Change the programming language of this snippet from Fortran to VB without modifying what it does. |
program list_comprehension
integer, parameter :: n = 20
integer, parameter :: m = n*(n+1)/2
integer :: i, j
complex, dimension(m) :: a
real, dimension(m) :: b
logical, dimension(m) :: c
integer, dimension(3, m) :: d
a = [ ( ( cmplx(i,j), i=j,n), j=1,n) ]
b = abs(a)
c = (b .eq. int(b)) .and. (b .le. n)
i = sum(merge(1,0,c))
d(2,:i) = int(real(pack(a, c)))
d(1,:i) = int(imag(pack(a, c)))
d(3,:i) = int(pack(b,c))
print '(3i4)',d(:,:i)
end program list_comprehension
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Write the same algorithm in C as shown in this Haskell implementation. | pyth :: Int -> [(Int, Int, Int)]
pyth n =
[ (x, y, z)
| x <- [1 .. n]
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Write the same code in C# as shown below in Haskell. | pyth :: Int -> [(Int, Int, Int)]
pyth n =
[ (x, y, z)
| x <- [1 .. n]
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Translate this program into C++ but keep the logic exactly as in Haskell. | pyth :: Int -> [(Int, Int, Int)]
pyth n =
[ (x, y, z)
| x <- [1 .. n]
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Can you help me rewrite this code in Java instead of Haskell, keeping it the same logically? | pyth :: Int -> [(Int, Int, Int)]
pyth n =
[ (x, y, z)
| x <- [1 .. n]
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Produce a functionally identical Python code for the snippet given in Haskell. | pyth :: Int -> [(Int, Int, Int)]
pyth n =
[ (x, y, z)
| x <- [1 .. n]
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Convert this Haskell block to VB, preserving its control flow and logic. | pyth :: Int -> [(Int, Int, Int)]
pyth n =
[ (x, y, z)
| x <- [1 .. n]
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Can you help me rewrite this code in Go instead of Haskell, keeping it the same logically? | pyth :: Int -> [(Int, Int, Int)]
pyth n =
[ (x, y, z)
| x <- [1 .. n]
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Port the following code from J to C with equivalent syntax and logic. | require'stats'
buildSet=:conjunction def '(#~ v) u y'
triples=: 1 + 3&comb
isPyth=: 2&{"1 = 1&{"1 +&.:*: 0&{"1
pythTr=: triples buildSet isPyth
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Translate this program into C# but keep the logic exactly as in J. | require'stats'
buildSet=:conjunction def '(#~ v) u y'
triples=: 1 + 3&comb
isPyth=: 2&{"1 = 1&{"1 +&.:*: 0&{"1
pythTr=: triples buildSet isPyth
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Write the same code in C++ as shown below in J. | require'stats'
buildSet=:conjunction def '(#~ v) u y'
triples=: 1 + 3&comb
isPyth=: 2&{"1 = 1&{"1 +&.:*: 0&{"1
pythTr=: triples buildSet isPyth
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Change the programming language of this snippet from J to Java without modifying what it does. | require'stats'
buildSet=:conjunction def '(#~ v) u y'
triples=: 1 + 3&comb
isPyth=: 2&{"1 = 1&{"1 +&.:*: 0&{"1
pythTr=: triples buildSet isPyth
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | require'stats'
buildSet=:conjunction def '(#~ v) u y'
triples=: 1 + 3&comb
isPyth=: 2&{"1 = 1&{"1 +&.:*: 0&{"1
pythTr=: triples buildSet isPyth
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Can you help me rewrite this code in VB instead of J, keeping it the same logically? | require'stats'
buildSet=:conjunction def '(#~ v) u y'
triples=: 1 + 3&comb
isPyth=: 2&{"1 = 1&{"1 +&.:*: 0&{"1
pythTr=: triples buildSet isPyth
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Write a version of this J function in Go with identical behavior. | require'stats'
buildSet=:conjunction def '(#~ v) u y'
triples=: 1 + 3&comb
isPyth=: 2&{"1 = 1&{"1 +&.:*: 0&{"1
pythTr=: triples buildSet isPyth
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Produce a functionally identical C code for the snippet given in Julia. | julia> n = 20
20
julia> [(x, y, z) for x = 1:n for y = x:n for z = y:n if x^2 + y^2 == z^2]
6-element Array{Tuple{Int64,Int64,Int64},1}:
(3,4,5)
(5,12,13)
(6,8,10)
(8,15,17)
(9,12,15)
(12,16,20)
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Produce a language-to-language conversion: from Julia to C#, same semantics. | julia> n = 20
20
julia> [(x, y, z) for x = 1:n for y = x:n for z = y:n if x^2 + y^2 == z^2]
6-element Array{Tuple{Int64,Int64,Int64},1}:
(3,4,5)
(5,12,13)
(6,8,10)
(8,15,17)
(9,12,15)
(12,16,20)
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Convert this Julia block to C++, preserving its control flow and logic. | julia> n = 20
20
julia> [(x, y, z) for x = 1:n for y = x:n for z = y:n if x^2 + y^2 == z^2]
6-element Array{Tuple{Int64,Int64,Int64},1}:
(3,4,5)
(5,12,13)
(6,8,10)
(8,15,17)
(9,12,15)
(12,16,20)
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Can you help me rewrite this code in Java instead of Julia, keeping it the same logically? | julia> n = 20
20
julia> [(x, y, z) for x = 1:n for y = x:n for z = y:n if x^2 + y^2 == z^2]
6-element Array{Tuple{Int64,Int64,Int64},1}:
(3,4,5)
(5,12,13)
(6,8,10)
(8,15,17)
(9,12,15)
(12,16,20)
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Translate the given Julia code snippet into Python without altering its behavior. | julia> n = 20
20
julia> [(x, y, z) for x = 1:n for y = x:n for z = y:n if x^2 + y^2 == z^2]
6-element Array{Tuple{Int64,Int64,Int64},1}:
(3,4,5)
(5,12,13)
(6,8,10)
(8,15,17)
(9,12,15)
(12,16,20)
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Rewrite this program in VB while keeping its functionality equivalent to the Julia version. | julia> n = 20
20
julia> [(x, y, z) for x = 1:n for y = x:n for z = y:n if x^2 + y^2 == z^2]
6-element Array{Tuple{Int64,Int64,Int64},1}:
(3,4,5)
(5,12,13)
(6,8,10)
(8,15,17)
(9,12,15)
(12,16,20)
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Transform the following Julia implementation into Go, maintaining the same output and logic. | julia> n = 20
20
julia> [(x, y, z) for x = 1:n for y = x:n for z = y:n if x^2 + y^2 == z^2]
6-element Array{Tuple{Int64,Int64,Int64},1}:
(3,4,5)
(5,12,13)
(6,8,10)
(8,15,17)
(9,12,15)
(12,16,20)
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Preserve the algorithm and functionality while converting the code from Lua to C. | LC={}
LC.__index = LC
function LC:new(o)
o = o or {}
setmetatable(o, self)
return o
end
function LC:add_iter(func)
local prev_iter = self.iter
self.iter = coroutine.wrap(
(prev_iter == nil) and (function() func{} end)
or (function() for arg in prev_iter do func(arg) end end))
return self
end
function maybe_call(maybe_func, arg)
if type(maybe_func) == "function" then return maybe_func(arg) end
return maybe_func
end
function LC:range(key, first, last)
return self:add_iter(function(arg)
for value=maybe_call(first, arg), maybe_call(last, arg) do
arg[key] = value
coroutine.yield(arg)
end
end)
end
function LC:where(pred)
return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end)
end
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Translate this program into C# but keep the logic exactly as in Lua. | LC={}
LC.__index = LC
function LC:new(o)
o = o or {}
setmetatable(o, self)
return o
end
function LC:add_iter(func)
local prev_iter = self.iter
self.iter = coroutine.wrap(
(prev_iter == nil) and (function() func{} end)
or (function() for arg in prev_iter do func(arg) end end))
return self
end
function maybe_call(maybe_func, arg)
if type(maybe_func) == "function" then return maybe_func(arg) end
return maybe_func
end
function LC:range(key, first, last)
return self:add_iter(function(arg)
for value=maybe_call(first, arg), maybe_call(last, arg) do
arg[key] = value
coroutine.yield(arg)
end
end)
end
function LC:where(pred)
return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end)
end
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Can you help me rewrite this code in C++ instead of Lua, keeping it the same logically? | LC={}
LC.__index = LC
function LC:new(o)
o = o or {}
setmetatable(o, self)
return o
end
function LC:add_iter(func)
local prev_iter = self.iter
self.iter = coroutine.wrap(
(prev_iter == nil) and (function() func{} end)
or (function() for arg in prev_iter do func(arg) end end))
return self
end
function maybe_call(maybe_func, arg)
if type(maybe_func) == "function" then return maybe_func(arg) end
return maybe_func
end
function LC:range(key, first, last)
return self:add_iter(function(arg)
for value=maybe_call(first, arg), maybe_call(last, arg) do
arg[key] = value
coroutine.yield(arg)
end
end)
end
function LC:where(pred)
return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end)
end
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | LC={}
LC.__index = LC
function LC:new(o)
o = o or {}
setmetatable(o, self)
return o
end
function LC:add_iter(func)
local prev_iter = self.iter
self.iter = coroutine.wrap(
(prev_iter == nil) and (function() func{} end)
or (function() for arg in prev_iter do func(arg) end end))
return self
end
function maybe_call(maybe_func, arg)
if type(maybe_func) == "function" then return maybe_func(arg) end
return maybe_func
end
function LC:range(key, first, last)
return self:add_iter(function(arg)
for value=maybe_call(first, arg), maybe_call(last, arg) do
arg[key] = value
coroutine.yield(arg)
end
end)
end
function LC:where(pred)
return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end)
end
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Produce a language-to-language conversion: from Lua to Python, same semantics. | LC={}
LC.__index = LC
function LC:new(o)
o = o or {}
setmetatable(o, self)
return o
end
function LC:add_iter(func)
local prev_iter = self.iter
self.iter = coroutine.wrap(
(prev_iter == nil) and (function() func{} end)
or (function() for arg in prev_iter do func(arg) end end))
return self
end
function maybe_call(maybe_func, arg)
if type(maybe_func) == "function" then return maybe_func(arg) end
return maybe_func
end
function LC:range(key, first, last)
return self:add_iter(function(arg)
for value=maybe_call(first, arg), maybe_call(last, arg) do
arg[key] = value
coroutine.yield(arg)
end
end)
end
function LC:where(pred)
return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end)
end
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Rewrite the snippet below in VB so it works the same as the original Lua code. | LC={}
LC.__index = LC
function LC:new(o)
o = o or {}
setmetatable(o, self)
return o
end
function LC:add_iter(func)
local prev_iter = self.iter
self.iter = coroutine.wrap(
(prev_iter == nil) and (function() func{} end)
or (function() for arg in prev_iter do func(arg) end end))
return self
end
function maybe_call(maybe_func, arg)
if type(maybe_func) == "function" then return maybe_func(arg) end
return maybe_func
end
function LC:range(key, first, last)
return self:add_iter(function(arg)
for value=maybe_call(first, arg), maybe_call(last, arg) do
arg[key] = value
coroutine.yield(arg)
end
end)
end
function LC:where(pred)
return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end)
end
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Convert this Lua snippet to Go and keep its semantics consistent. | LC={}
LC.__index = LC
function LC:new(o)
o = o or {}
setmetatable(o, self)
return o
end
function LC:add_iter(func)
local prev_iter = self.iter
self.iter = coroutine.wrap(
(prev_iter == nil) and (function() func{} end)
or (function() for arg in prev_iter do func(arg) end end))
return self
end
function maybe_call(maybe_func, arg)
if type(maybe_func) == "function" then return maybe_func(arg) end
return maybe_func
end
function LC:range(key, first, last)
return self:add_iter(function(arg)
for value=maybe_call(first, arg), maybe_call(last, arg) do
arg[key] = value
coroutine.yield(arg)
end
end)
end
function LC:where(pred)
return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end)
end
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.