Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the following REXX code into Python without altering its purpose. |
parse arg target stopAt chunkette .
if target=='' | target=="," then target= 0
if stopAt=='' | stopAt=="," then stopAt= 1
y= 0
zz= 'archbishop -915 covariate 590 mycenae 183 brute 870 balm 397 fiat 170' ,
'smokescreen 423 eradicate 376 efferent 54 bonnet 452 vein 813 ' ,
'diophantine 645 departure 952 lindholm 999 moresby 756 isis -982 ' ,
'mincemeat -880 alliance -624 flatworm 503 elysee -326 cobol 362 ' ,
'centipede -658 exorcism -983 gestapo 915 filmy -874 deploy 44 ' ,
'speakeasy -745 plugging -266 markham 475 infra -847 escritoire 856 '
@.= 0
do N=1 until zz=''
parse var zz @.N #.N zz
end
call eSort N
call tellZ 'sorted'
chunkStart= 1
chunkEnd = N
if chunkette\=='' then do
chunkStart= chunkette
chunkEnd = chunkette
end
call time 'Reset'
??= 0
do chunk=chunkStart to chunkEnd
call tello center(' doing chunk:' chunk" ", 79, '─')
call combN N, chunk
_= ??
if _==0 then _= 'No'
call tello _ 'solution's(??) "found so far."
end
if ??==0 then ??= 'no'
call tello 'Found' ?? "subset"s(??) 'whose summed weight's(??) "=" target
exit
combN: procedure expose @. #. ?? stopAt target; parse arg x,y; !.= @.0
base= x + 1; bbase= base - y
do n=1 for y; !.n=n
end
ym= y - 1
do j=1; _= !.1; s= #._
if s>target then leave
do k=2 for ym; _= !.k; s= s + #._
if s>target then do; if .combUp(k-1) then return; iterate j; end
end
if s==target then call telly
!.y= !.y + 1; if !.y==base then if .combUp(ym) then leave
end
.combUp: procedure expose !. y bbase; parse arg d; if d==0 then return 1
p= !.d; do u=d to y; !.u= p + 1
if !.u >= bbase+u then return .combUp(u-1)
p= !.u
end
eSort: procedure expose #. @. $.; parse arg N,$; h= N
do while h>1; h= h % 2
do i=1 for N-h; j= i; k= h + i
if $==. then do while $.k<$.j; parse value $.j $.k with $.k $.j
if h>=j then leave; j= j - h; k= k - h
end
else do while #.k<#.j; parse value @.j @.k #.j #.k with @.k @.j #.k #.j
if h>=j then leave; j= j - h; k= k - h
end
end
end
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
tello: parse arg _,e; if e==. then say; say _; call lineout 'SUBSET.'y, _; return
telly: ??= ?? + 1; nameL=
do gi=1 for y; ggg= !.gi
$.gi= @.ggg
end
call eSort y, .
do gs=1 for y; nameL= nameL $.gs
end
call tello '['y" name"s(y)']' space(nameL)
if ??<stopAt | stopAt==0 then return
call tello 'Stopped after finding ' ?? " subset"s(??)'.', .
exit
tellz: do j=1 for N
call tello right('['j']', 30) right(@.j, 11) right(#.j, 5)
end
call tello
call tello 'There are ' N " entries in the (above)" arg(1) 'table.'
call tello; return
| words = {
"alliance": -624, "archbishop": -925, "balm": 397,
"bonnet": 452, "brute": 870, "centipede": -658,
"cobol": 362, "covariate": 590, "departure": 952,
"deploy": 44, "diophantine": 645, "efferent": 54,
"elysee": -326, "eradicate": 376, "escritoire": 856,
"exorcism": -983, "fiat": 170, "filmy": -874,
"flatworm": 503, "gestapo": 915, "infra": -847,
"isis": -982, "lindholm": 999, "markham": 475,
"mincemeat": -880, "moresby": 756, "mycenae": 183,
"plugging": -266, "smokescreen": 423, "speakeasy": -745,
"vein": 813
}
neg = 0
pos = 0
for (w,v) in words.iteritems():
if v > 0: pos += v
else: neg += v
sums = [0] * (pos - neg + 1)
for (w,v) in words.iteritems():
s = sums[:]
if not s[v - neg]: s[v - neg] = (w,)
for (i, w2) in enumerate(sums):
if w2 and not s[i + v]:
s[i + v] = w2 + (w,)
sums = s
if s[-neg]:
for x in s[-neg]:
print(x, words[x])
break
|
Write the same algorithm in Python as shown in this REXX implementation. |
parse arg target stopAt chunkette .
if target=='' | target=="," then target= 0
if stopAt=='' | stopAt=="," then stopAt= 1
y= 0
zz= 'archbishop -915 covariate 590 mycenae 183 brute 870 balm 397 fiat 170' ,
'smokescreen 423 eradicate 376 efferent 54 bonnet 452 vein 813 ' ,
'diophantine 645 departure 952 lindholm 999 moresby 756 isis -982 ' ,
'mincemeat -880 alliance -624 flatworm 503 elysee -326 cobol 362 ' ,
'centipede -658 exorcism -983 gestapo 915 filmy -874 deploy 44 ' ,
'speakeasy -745 plugging -266 markham 475 infra -847 escritoire 856 '
@.= 0
do N=1 until zz=''
parse var zz @.N #.N zz
end
call eSort N
call tellZ 'sorted'
chunkStart= 1
chunkEnd = N
if chunkette\=='' then do
chunkStart= chunkette
chunkEnd = chunkette
end
call time 'Reset'
??= 0
do chunk=chunkStart to chunkEnd
call tello center(' doing chunk:' chunk" ", 79, '─')
call combN N, chunk
_= ??
if _==0 then _= 'No'
call tello _ 'solution's(??) "found so far."
end
if ??==0 then ??= 'no'
call tello 'Found' ?? "subset"s(??) 'whose summed weight's(??) "=" target
exit
combN: procedure expose @. #. ?? stopAt target; parse arg x,y; !.= @.0
base= x + 1; bbase= base - y
do n=1 for y; !.n=n
end
ym= y - 1
do j=1; _= !.1; s= #._
if s>target then leave
do k=2 for ym; _= !.k; s= s + #._
if s>target then do; if .combUp(k-1) then return; iterate j; end
end
if s==target then call telly
!.y= !.y + 1; if !.y==base then if .combUp(ym) then leave
end
.combUp: procedure expose !. y bbase; parse arg d; if d==0 then return 1
p= !.d; do u=d to y; !.u= p + 1
if !.u >= bbase+u then return .combUp(u-1)
p= !.u
end
eSort: procedure expose #. @. $.; parse arg N,$; h= N
do while h>1; h= h % 2
do i=1 for N-h; j= i; k= h + i
if $==. then do while $.k<$.j; parse value $.j $.k with $.k $.j
if h>=j then leave; j= j - h; k= k - h
end
else do while #.k<#.j; parse value @.j @.k #.j #.k with @.k @.j #.k #.j
if h>=j then leave; j= j - h; k= k - h
end
end
end
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
tello: parse arg _,e; if e==. then say; say _; call lineout 'SUBSET.'y, _; return
telly: ??= ?? + 1; nameL=
do gi=1 for y; ggg= !.gi
$.gi= @.ggg
end
call eSort y, .
do gs=1 for y; nameL= nameL $.gs
end
call tello '['y" name"s(y)']' space(nameL)
if ??<stopAt | stopAt==0 then return
call tello 'Stopped after finding ' ?? " subset"s(??)'.', .
exit
tellz: do j=1 for N
call tello right('['j']', 30) right(@.j, 11) right(#.j, 5)
end
call tello
call tello 'There are ' N " entries in the (above)" arg(1) 'table.'
call tello; return
| words = {
"alliance": -624, "archbishop": -925, "balm": 397,
"bonnet": 452, "brute": 870, "centipede": -658,
"cobol": 362, "covariate": 590, "departure": 952,
"deploy": 44, "diophantine": 645, "efferent": 54,
"elysee": -326, "eradicate": 376, "escritoire": 856,
"exorcism": -983, "fiat": 170, "filmy": -874,
"flatworm": 503, "gestapo": 915, "infra": -847,
"isis": -982, "lindholm": 999, "markham": 475,
"mincemeat": -880, "moresby": 756, "mycenae": 183,
"plugging": -266, "smokescreen": 423, "speakeasy": -745,
"vein": 813
}
neg = 0
pos = 0
for (w,v) in words.iteritems():
if v > 0: pos += v
else: neg += v
sums = [0] * (pos - neg + 1)
for (w,v) in words.iteritems():
s = sums[:]
if not s[v - neg]: s[v - neg] = (w,)
for (i, w2) in enumerate(sums):
if w2 and not s[i + v]:
s[i + v] = w2 + (w,)
sums = s
if s[-neg]:
for x in s[-neg]:
print(x, words[x])
break
|
Transform the following REXX implementation into Go, maintaining the same output and logic. |
parse arg target stopAt chunkette .
if target=='' | target=="," then target= 0
if stopAt=='' | stopAt=="," then stopAt= 1
y= 0
zz= 'archbishop -915 covariate 590 mycenae 183 brute 870 balm 397 fiat 170' ,
'smokescreen 423 eradicate 376 efferent 54 bonnet 452 vein 813 ' ,
'diophantine 645 departure 952 lindholm 999 moresby 756 isis -982 ' ,
'mincemeat -880 alliance -624 flatworm 503 elysee -326 cobol 362 ' ,
'centipede -658 exorcism -983 gestapo 915 filmy -874 deploy 44 ' ,
'speakeasy -745 plugging -266 markham 475 infra -847 escritoire 856 '
@.= 0
do N=1 until zz=''
parse var zz @.N #.N zz
end
call eSort N
call tellZ 'sorted'
chunkStart= 1
chunkEnd = N
if chunkette\=='' then do
chunkStart= chunkette
chunkEnd = chunkette
end
call time 'Reset'
??= 0
do chunk=chunkStart to chunkEnd
call tello center(' doing chunk:' chunk" ", 79, '─')
call combN N, chunk
_= ??
if _==0 then _= 'No'
call tello _ 'solution's(??) "found so far."
end
if ??==0 then ??= 'no'
call tello 'Found' ?? "subset"s(??) 'whose summed weight's(??) "=" target
exit
combN: procedure expose @. #. ?? stopAt target; parse arg x,y; !.= @.0
base= x + 1; bbase= base - y
do n=1 for y; !.n=n
end
ym= y - 1
do j=1; _= !.1; s= #._
if s>target then leave
do k=2 for ym; _= !.k; s= s + #._
if s>target then do; if .combUp(k-1) then return; iterate j; end
end
if s==target then call telly
!.y= !.y + 1; if !.y==base then if .combUp(ym) then leave
end
.combUp: procedure expose !. y bbase; parse arg d; if d==0 then return 1
p= !.d; do u=d to y; !.u= p + 1
if !.u >= bbase+u then return .combUp(u-1)
p= !.u
end
eSort: procedure expose #. @. $.; parse arg N,$; h= N
do while h>1; h= h % 2
do i=1 for N-h; j= i; k= h + i
if $==. then do while $.k<$.j; parse value $.j $.k with $.k $.j
if h>=j then leave; j= j - h; k= k - h
end
else do while #.k<#.j; parse value @.j @.k #.j #.k with @.k @.j #.k #.j
if h>=j then leave; j= j - h; k= k - h
end
end
end
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
tello: parse arg _,e; if e==. then say; say _; call lineout 'SUBSET.'y, _; return
telly: ??= ?? + 1; nameL=
do gi=1 for y; ggg= !.gi
$.gi= @.ggg
end
call eSort y, .
do gs=1 for y; nameL= nameL $.gs
end
call tello '['y" name"s(y)']' space(nameL)
if ??<stopAt | stopAt==0 then return
call tello 'Stopped after finding ' ?? " subset"s(??)'.', .
exit
tellz: do j=1 for N
call tello right('['j']', 30) right(@.j, 11) right(#.j, 5)
end
call tello
call tello 'There are ' N " entries in the (above)" arg(1) 'table.'
call tello; return
| package main
import "fmt"
type ww struct {
word string
weight int
}
var input = []*ww{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
}
type sss struct {
subset []*ww
sum int
}
func main() {
ps := []sss{{nil, 0}}
for _, i := range input {
pl := len(ps)
for j := 0; j < pl; j++ {
subset := append([]*ww{i}, ps[j].subset...)
sum := i.weight + ps[j].sum
if sum == 0 {
fmt.Println("this subset sums to 0:")
for _, i := range subset {
fmt.Println(*i)
}
return
}
ps = append(ps, sss{subset, sum})
}
}
fmt.Println("no subset sums to 0")
}
|
Translate the given REXX code snippet into Go without altering its behavior. |
parse arg target stopAt chunkette .
if target=='' | target=="," then target= 0
if stopAt=='' | stopAt=="," then stopAt= 1
y= 0
zz= 'archbishop -915 covariate 590 mycenae 183 brute 870 balm 397 fiat 170' ,
'smokescreen 423 eradicate 376 efferent 54 bonnet 452 vein 813 ' ,
'diophantine 645 departure 952 lindholm 999 moresby 756 isis -982 ' ,
'mincemeat -880 alliance -624 flatworm 503 elysee -326 cobol 362 ' ,
'centipede -658 exorcism -983 gestapo 915 filmy -874 deploy 44 ' ,
'speakeasy -745 plugging -266 markham 475 infra -847 escritoire 856 '
@.= 0
do N=1 until zz=''
parse var zz @.N #.N zz
end
call eSort N
call tellZ 'sorted'
chunkStart= 1
chunkEnd = N
if chunkette\=='' then do
chunkStart= chunkette
chunkEnd = chunkette
end
call time 'Reset'
??= 0
do chunk=chunkStart to chunkEnd
call tello center(' doing chunk:' chunk" ", 79, '─')
call combN N, chunk
_= ??
if _==0 then _= 'No'
call tello _ 'solution's(??) "found so far."
end
if ??==0 then ??= 'no'
call tello 'Found' ?? "subset"s(??) 'whose summed weight's(??) "=" target
exit
combN: procedure expose @. #. ?? stopAt target; parse arg x,y; !.= @.0
base= x + 1; bbase= base - y
do n=1 for y; !.n=n
end
ym= y - 1
do j=1; _= !.1; s= #._
if s>target then leave
do k=2 for ym; _= !.k; s= s + #._
if s>target then do; if .combUp(k-1) then return; iterate j; end
end
if s==target then call telly
!.y= !.y + 1; if !.y==base then if .combUp(ym) then leave
end
.combUp: procedure expose !. y bbase; parse arg d; if d==0 then return 1
p= !.d; do u=d to y; !.u= p + 1
if !.u >= bbase+u then return .combUp(u-1)
p= !.u
end
eSort: procedure expose #. @. $.; parse arg N,$; h= N
do while h>1; h= h % 2
do i=1 for N-h; j= i; k= h + i
if $==. then do while $.k<$.j; parse value $.j $.k with $.k $.j
if h>=j then leave; j= j - h; k= k - h
end
else do while #.k<#.j; parse value @.j @.k #.j #.k with @.k @.j #.k #.j
if h>=j then leave; j= j - h; k= k - h
end
end
end
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
tello: parse arg _,e; if e==. then say; say _; call lineout 'SUBSET.'y, _; return
telly: ??= ?? + 1; nameL=
do gi=1 for y; ggg= !.gi
$.gi= @.ggg
end
call eSort y, .
do gs=1 for y; nameL= nameL $.gs
end
call tello '['y" name"s(y)']' space(nameL)
if ??<stopAt | stopAt==0 then return
call tello 'Stopped after finding ' ?? " subset"s(??)'.', .
exit
tellz: do j=1 for N
call tello right('['j']', 30) right(@.j, 11) right(#.j, 5)
end
call tello
call tello 'There are ' N " entries in the (above)" arg(1) 'table.'
call tello; return
| package main
import "fmt"
type ww struct {
word string
weight int
}
var input = []*ww{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
}
type sss struct {
subset []*ww
sum int
}
func main() {
ps := []sss{{nil, 0}}
for _, i := range input {
pl := len(ps)
for j := 0; j < pl; j++ {
subset := append([]*ww{i}, ps[j].subset...)
sum := i.weight + ps[j].sum
if sum == 0 {
fmt.Println("this subset sums to 0:")
for _, i := range subset {
fmt.Println(*i)
}
return
}
ps = append(ps, sss{subset, sum})
}
}
fmt.Println("no subset sums to 0")
}
|
Rewrite the snippet below in C so it works the same as the original Ruby code. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *word;
int weight;
} item_t;
item_t items[] = {
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
int n = sizeof (items) / sizeof (item_t);
int *set;
void subsum (int i, int weight) {
int j;
if (i && !weight) {
for (j = 0; j < i; j++) {
item_t item = items[set[j]];
printf("%s%s", j ? " " : "", items[set[j]].word);
}
printf("\n");
}
for (j = i ? set[i - 1] + 1: 0; j < n; j++) {
set[i] = j;
subsum(i + 1, weight + items[j].weight);
}
}
int main () {
set = malloc(n * sizeof (int));
subsum(0, 0);
return 0;
}
|
Change the programming language of this snippet from Ruby to C without modifying what it does. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *word;
int weight;
} item_t;
item_t items[] = {
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
int n = sizeof (items) / sizeof (item_t);
int *set;
void subsum (int i, int weight) {
int j;
if (i && !weight) {
for (j = 0; j < i; j++) {
item_t item = items[set[j]];
printf("%s%s", j ? " " : "", items[set[j]].word);
}
printf("\n");
}
for (j = i ? set[i - 1] + 1: 0; j < n; j++) {
set[i] = j;
subsum(i + 1, weight + items[j].weight);
}
}
int main () {
set = malloc(n * sizeof (int));
subsum(0, 0);
return 0;
}
|
Generate a C# translation of this Ruby snippet without changing its computational steps. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| using System;
using System.Collections.Generic;
namespace SubsetSum {
class Item {
public Item(string word, int weight) {
Word = word;
Weight = weight;
}
public string Word { get; set; }
public int Weight { get; set; }
public override string ToString() {
return string.Format("({0}, {1})", Word, Weight);
}
}
class Program {
private static readonly List<Item> items = new List<Item>() {
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static readonly int n = items.Count;
private static readonly int LIMIT = 5;
private static int[] indices = new int[n];
private static int count = 0;
private static void ZeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; j++) {
Console.Write("{0} ", items[indices[j]]);
}
Console.WriteLine("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; j++) {
indices[i] = j;
ZeroSum(i + 1, w + items[j].Weight);
if (count == LIMIT) return;
}
}
static void Main(string[] args) {
Console.WriteLine("The weights of the following {0} subsets add up to zero:\n", LIMIT);
ZeroSum(0, 0);
}
}
}
|
Translate this program into C# but keep the logic exactly as in Ruby. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| using System;
using System.Collections.Generic;
namespace SubsetSum {
class Item {
public Item(string word, int weight) {
Word = word;
Weight = weight;
}
public string Word { get; set; }
public int Weight { get; set; }
public override string ToString() {
return string.Format("({0}, {1})", Word, Weight);
}
}
class Program {
private static readonly List<Item> items = new List<Item>() {
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static readonly int n = items.Count;
private static readonly int LIMIT = 5;
private static int[] indices = new int[n];
private static int count = 0;
private static void ZeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; j++) {
Console.Write("{0} ", items[indices[j]]);
}
Console.WriteLine("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; j++) {
indices[i] = j;
ZeroSum(i + 1, w + items[j].Weight);
if (count == LIMIT) return;
}
}
static void Main(string[] args) {
Console.WriteLine("The weights of the following {0} subsets add up to zero:\n", LIMIT);
ZeroSum(0, 0);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| #include <iostream>
#include <vector>
std::ostream& operator<<(std::ostream& out, const std::string& str) {
return out << str.c_str();
}
std::vector<std::pair<std::string, int>> items{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
std::vector<int> indices;
int count = 0;
const int LIMIT = 5;
void subsum(int i, int weight) {
if (i != 0 && weight == 0) {
for (int j = 0; j < i; ++j) {
auto item = items[indices[j]];
std::cout << (j ? " " : "") << item.first;
}
std::cout << '\n';
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < items.size(); ++j) {
indices[i] = j;
subsum(i + 1, weight + items[j].second);
if (count == LIMIT) return;
}
}
int main() {
indices.resize(items.size());
subsum(0, 0);
return 0;
}
|
Port the provided Ruby code into C++ while preserving the original functionality. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| #include <iostream>
#include <vector>
std::ostream& operator<<(std::ostream& out, const std::string& str) {
return out << str.c_str();
}
std::vector<std::pair<std::string, int>> items{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
std::vector<int> indices;
int count = 0;
const int LIMIT = 5;
void subsum(int i, int weight) {
if (i != 0 && weight == 0) {
for (int j = 0; j < i; ++j) {
auto item = items[indices[j]];
std::cout << (j ? " " : "") << item.first;
}
std::cout << '\n';
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < items.size(); ++j) {
indices[i] = j;
subsum(i + 1, weight + items[j].second);
if (count == LIMIT) return;
}
}
int main() {
indices.resize(items.size());
subsum(0, 0);
return 0;
}
|
Translate this program into Java but keep the logic exactly as in Ruby. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| public class SubsetSum {
private static class Item {
private String word;
private int weight;
public Item(String word, int weight) {
this.word = word;
this.weight = weight;
}
@Override
public String toString() {
return String.format("(%s, %d)", word, weight);
}
}
private static Item[] items = new Item[]{
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static final int n = items.length;
private static final int[] indices = new int[n];
private static int count = 0;
private static final int LIMIT = 5;
private static void zeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; ++j) {
System.out.printf("%s ", items[indices[j]]);
}
System.out.println("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; ++j) {
indices[i] = j;
zeroSum(i + 1, w + items[j].weight);
if (count == LIMIT) return;
}
}
public static void main(String[] args) {
System.out.printf("The weights of the following %d subsets add up to zero:\n\n", LIMIT);
zeroSum(0, 0);
}
}
|
Generate an equivalent Java version of this Ruby code. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| public class SubsetSum {
private static class Item {
private String word;
private int weight;
public Item(String word, int weight) {
this.word = word;
this.weight = weight;
}
@Override
public String toString() {
return String.format("(%s, %d)", word, weight);
}
}
private static Item[] items = new Item[]{
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static final int n = items.length;
private static final int[] indices = new int[n];
private static int count = 0;
private static final int LIMIT = 5;
private static void zeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; ++j) {
System.out.printf("%s ", items[indices[j]]);
}
System.out.println("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; ++j) {
indices[i] = j;
zeroSum(i + 1, w + items[j].weight);
if (count == LIMIT) return;
}
}
public static void main(String[] args) {
System.out.printf("The weights of the following %d subsets add up to zero:\n\n", LIMIT);
zeroSum(0, 0);
}
}
|
Generate a Python translation of this Ruby snippet without changing its computational steps. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| words = {
"alliance": -624, "archbishop": -925, "balm": 397,
"bonnet": 452, "brute": 870, "centipede": -658,
"cobol": 362, "covariate": 590, "departure": 952,
"deploy": 44, "diophantine": 645, "efferent": 54,
"elysee": -326, "eradicate": 376, "escritoire": 856,
"exorcism": -983, "fiat": 170, "filmy": -874,
"flatworm": 503, "gestapo": 915, "infra": -847,
"isis": -982, "lindholm": 999, "markham": 475,
"mincemeat": -880, "moresby": 756, "mycenae": 183,
"plugging": -266, "smokescreen": 423, "speakeasy": -745,
"vein": 813
}
neg = 0
pos = 0
for (w,v) in words.iteritems():
if v > 0: pos += v
else: neg += v
sums = [0] * (pos - neg + 1)
for (w,v) in words.iteritems():
s = sums[:]
if not s[v - neg]: s[v - neg] = (w,)
for (i, w2) in enumerate(sums):
if w2 and not s[i + v]:
s[i + v] = w2 + (w,)
sums = s
if s[-neg]:
for x in s[-neg]:
print(x, words[x])
break
|
Preserve the algorithm and functionality while converting the code from Ruby to Python. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| words = {
"alliance": -624, "archbishop": -925, "balm": 397,
"bonnet": 452, "brute": 870, "centipede": -658,
"cobol": 362, "covariate": 590, "departure": 952,
"deploy": 44, "diophantine": 645, "efferent": 54,
"elysee": -326, "eradicate": 376, "escritoire": 856,
"exorcism": -983, "fiat": 170, "filmy": -874,
"flatworm": 503, "gestapo": 915, "infra": -847,
"isis": -982, "lindholm": 999, "markham": 475,
"mincemeat": -880, "moresby": 756, "mycenae": 183,
"plugging": -266, "smokescreen": 423, "speakeasy": -745,
"vein": 813
}
neg = 0
pos = 0
for (w,v) in words.iteritems():
if v > 0: pos += v
else: neg += v
sums = [0] * (pos - neg + 1)
for (w,v) in words.iteritems():
s = sums[:]
if not s[v - neg]: s[v - neg] = (w,)
for (i, w2) in enumerate(sums):
if w2 and not s[i + v]:
s[i + v] = w2 + (w,)
sums = s
if s[-neg]:
for x in s[-neg]:
print(x, words[x])
break
|
Please provide an equivalent version of this Ruby code in Go. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| package main
import "fmt"
type ww struct {
word string
weight int
}
var input = []*ww{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
}
type sss struct {
subset []*ww
sum int
}
func main() {
ps := []sss{{nil, 0}}
for _, i := range input {
pl := len(ps)
for j := 0; j < pl; j++ {
subset := append([]*ww{i}, ps[j].subset...)
sum := i.weight + ps[j].sum
if sum == 0 {
fmt.Println("this subset sums to 0:")
for _, i := range subset {
fmt.Println(*i)
}
return
}
ps = append(ps, sss{subset, sum})
}
}
fmt.Println("no subset sums to 0")
}
|
Change the programming language of this snippet from Ruby to Go without modifying what it does. | weights = {
'alliance' =>-624, 'archbishop'=>-915, 'balm' => 397, 'bonnet' => 452,
'brute' => 870, 'centipede' =>-658, 'cobol' => 362, 'covariate'=> 590,
'departure' => 952, 'deploy' => 44, 'diophantine'=> 645, 'efferent' => 54,
'elysee' =>-326, 'eradicate' => 376, 'escritoire' => 856, 'exorcism' =>-983,
'fiat' => 170, 'filmy' =>-874, 'flatworm' => 503, 'gestapo' => 915,
'infra' =>-847, 'isis' =>-982, 'lindholm' => 999, 'markham' => 475,
'mincemeat' =>-880, 'moresby' => 756, 'mycenae' => 183, 'plugging' =>-266,
'smokescreen'=> 423, 'speakeasy' =>-745, 'vein' => 813,
}
words = weights.keys
1.upto(words.length) do |n|
zerosum = words.combination(n).find do |subset|
subset.reduce(0) {|sum, word| sum + weights[word]} == 0
end
if zerosum
puts "a subset of length
else
puts "no subsets of length
end
end
| package main
import "fmt"
type ww struct {
word string
weight int
}
var input = []*ww{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
}
type sss struct {
subset []*ww
sum int
}
func main() {
ps := []sss{{nil, 0}}
for _, i := range input {
pl := len(ps)
for j := 0; j < pl; j++ {
subset := append([]*ww{i}, ps[j].subset...)
sum := i.weight + ps[j].sum
if sum == 0 {
fmt.Println("this subset sums to 0:")
for _, i := range subset {
fmt.Println(*i)
}
return
}
ps = append(ps, sss{subset, sum})
}
}
fmt.Println("no subset sums to 0")
}
|
Port the provided Scala code into C while preserving the original functionality. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *word;
int weight;
} item_t;
item_t items[] = {
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
int n = sizeof (items) / sizeof (item_t);
int *set;
void subsum (int i, int weight) {
int j;
if (i && !weight) {
for (j = 0; j < i; j++) {
item_t item = items[set[j]];
printf("%s%s", j ? " " : "", items[set[j]].word);
}
printf("\n");
}
for (j = i ? set[i - 1] + 1: 0; j < n; j++) {
set[i] = j;
subsum(i + 1, weight + items[j].weight);
}
}
int main () {
set = malloc(n * sizeof (int));
subsum(0, 0);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Scala. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *word;
int weight;
} item_t;
item_t items[] = {
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
int n = sizeof (items) / sizeof (item_t);
int *set;
void subsum (int i, int weight) {
int j;
if (i && !weight) {
for (j = 0; j < i; j++) {
item_t item = items[set[j]];
printf("%s%s", j ? " " : "", items[set[j]].word);
}
printf("\n");
}
for (j = i ? set[i - 1] + 1: 0; j < n; j++) {
set[i] = j;
subsum(i + 1, weight + items[j].weight);
}
}
int main () {
set = malloc(n * sizeof (int));
subsum(0, 0);
return 0;
}
|
Convert this Scala snippet to C# and keep its semantics consistent. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| using System;
using System.Collections.Generic;
namespace SubsetSum {
class Item {
public Item(string word, int weight) {
Word = word;
Weight = weight;
}
public string Word { get; set; }
public int Weight { get; set; }
public override string ToString() {
return string.Format("({0}, {1})", Word, Weight);
}
}
class Program {
private static readonly List<Item> items = new List<Item>() {
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static readonly int n = items.Count;
private static readonly int LIMIT = 5;
private static int[] indices = new int[n];
private static int count = 0;
private static void ZeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; j++) {
Console.Write("{0} ", items[indices[j]]);
}
Console.WriteLine("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; j++) {
indices[i] = j;
ZeroSum(i + 1, w + items[j].Weight);
if (count == LIMIT) return;
}
}
static void Main(string[] args) {
Console.WriteLine("The weights of the following {0} subsets add up to zero:\n", LIMIT);
ZeroSum(0, 0);
}
}
}
|
Generate an equivalent C# version of this Scala code. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| using System;
using System.Collections.Generic;
namespace SubsetSum {
class Item {
public Item(string word, int weight) {
Word = word;
Weight = weight;
}
public string Word { get; set; }
public int Weight { get; set; }
public override string ToString() {
return string.Format("({0}, {1})", Word, Weight);
}
}
class Program {
private static readonly List<Item> items = new List<Item>() {
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static readonly int n = items.Count;
private static readonly int LIMIT = 5;
private static int[] indices = new int[n];
private static int count = 0;
private static void ZeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; j++) {
Console.Write("{0} ", items[indices[j]]);
}
Console.WriteLine("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; j++) {
indices[i] = j;
ZeroSum(i + 1, w + items[j].Weight);
if (count == LIMIT) return;
}
}
static void Main(string[] args) {
Console.WriteLine("The weights of the following {0} subsets add up to zero:\n", LIMIT);
ZeroSum(0, 0);
}
}
}
|
Transform the following Scala implementation into C++, maintaining the same output and logic. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| #include <iostream>
#include <vector>
std::ostream& operator<<(std::ostream& out, const std::string& str) {
return out << str.c_str();
}
std::vector<std::pair<std::string, int>> items{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
std::vector<int> indices;
int count = 0;
const int LIMIT = 5;
void subsum(int i, int weight) {
if (i != 0 && weight == 0) {
for (int j = 0; j < i; ++j) {
auto item = items[indices[j]];
std::cout << (j ? " " : "") << item.first;
}
std::cout << '\n';
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < items.size(); ++j) {
indices[i] = j;
subsum(i + 1, weight + items[j].second);
if (count == LIMIT) return;
}
}
int main() {
indices.resize(items.size());
subsum(0, 0);
return 0;
}
|
Generate a C++ translation of this Scala snippet without changing its computational steps. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| #include <iostream>
#include <vector>
std::ostream& operator<<(std::ostream& out, const std::string& str) {
return out << str.c_str();
}
std::vector<std::pair<std::string, int>> items{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
std::vector<int> indices;
int count = 0;
const int LIMIT = 5;
void subsum(int i, int weight) {
if (i != 0 && weight == 0) {
for (int j = 0; j < i; ++j) {
auto item = items[indices[j]];
std::cout << (j ? " " : "") << item.first;
}
std::cout << '\n';
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < items.size(); ++j) {
indices[i] = j;
subsum(i + 1, weight + items[j].second);
if (count == LIMIT) return;
}
}
int main() {
indices.resize(items.size());
subsum(0, 0);
return 0;
}
|
Port the following code from Scala to Java with equivalent syntax and logic. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| public class SubsetSum {
private static class Item {
private String word;
private int weight;
public Item(String word, int weight) {
this.word = word;
this.weight = weight;
}
@Override
public String toString() {
return String.format("(%s, %d)", word, weight);
}
}
private static Item[] items = new Item[]{
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static final int n = items.length;
private static final int[] indices = new int[n];
private static int count = 0;
private static final int LIMIT = 5;
private static void zeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; ++j) {
System.out.printf("%s ", items[indices[j]]);
}
System.out.println("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; ++j) {
indices[i] = j;
zeroSum(i + 1, w + items[j].weight);
if (count == LIMIT) return;
}
}
public static void main(String[] args) {
System.out.printf("The weights of the following %d subsets add up to zero:\n\n", LIMIT);
zeroSum(0, 0);
}
}
|
Convert the following code from Scala to Java, ensuring the logic remains intact. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| public class SubsetSum {
private static class Item {
private String word;
private int weight;
public Item(String word, int weight) {
this.word = word;
this.weight = weight;
}
@Override
public String toString() {
return String.format("(%s, %d)", word, weight);
}
}
private static Item[] items = new Item[]{
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static final int n = items.length;
private static final int[] indices = new int[n];
private static int count = 0;
private static final int LIMIT = 5;
private static void zeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; ++j) {
System.out.printf("%s ", items[indices[j]]);
}
System.out.println("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; ++j) {
indices[i] = j;
zeroSum(i + 1, w + items[j].weight);
if (count == LIMIT) return;
}
}
public static void main(String[] args) {
System.out.printf("The weights of the following %d subsets add up to zero:\n\n", LIMIT);
zeroSum(0, 0);
}
}
|
Write the same algorithm in Python as shown in this Scala implementation. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| words = {
"alliance": -624, "archbishop": -925, "balm": 397,
"bonnet": 452, "brute": 870, "centipede": -658,
"cobol": 362, "covariate": 590, "departure": 952,
"deploy": 44, "diophantine": 645, "efferent": 54,
"elysee": -326, "eradicate": 376, "escritoire": 856,
"exorcism": -983, "fiat": 170, "filmy": -874,
"flatworm": 503, "gestapo": 915, "infra": -847,
"isis": -982, "lindholm": 999, "markham": 475,
"mincemeat": -880, "moresby": 756, "mycenae": 183,
"plugging": -266, "smokescreen": 423, "speakeasy": -745,
"vein": 813
}
neg = 0
pos = 0
for (w,v) in words.iteritems():
if v > 0: pos += v
else: neg += v
sums = [0] * (pos - neg + 1)
for (w,v) in words.iteritems():
s = sums[:]
if not s[v - neg]: s[v - neg] = (w,)
for (i, w2) in enumerate(sums):
if w2 and not s[i + v]:
s[i + v] = w2 + (w,)
sums = s
if s[-neg]:
for x in s[-neg]:
print(x, words[x])
break
|
Convert the following code from Scala to Python, ensuring the logic remains intact. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| words = {
"alliance": -624, "archbishop": -925, "balm": 397,
"bonnet": 452, "brute": 870, "centipede": -658,
"cobol": 362, "covariate": 590, "departure": 952,
"deploy": 44, "diophantine": 645, "efferent": 54,
"elysee": -326, "eradicate": 376, "escritoire": 856,
"exorcism": -983, "fiat": 170, "filmy": -874,
"flatworm": 503, "gestapo": 915, "infra": -847,
"isis": -982, "lindholm": 999, "markham": 475,
"mincemeat": -880, "moresby": 756, "mycenae": 183,
"plugging": -266, "smokescreen": 423, "speakeasy": -745,
"vein": 813
}
neg = 0
pos = 0
for (w,v) in words.iteritems():
if v > 0: pos += v
else: neg += v
sums = [0] * (pos - neg + 1)
for (w,v) in words.iteritems():
s = sums[:]
if not s[v - neg]: s[v - neg] = (w,)
for (i, w2) in enumerate(sums):
if w2 and not s[i + v]:
s[i + v] = w2 + (w,)
sums = s
if s[-neg]:
for x in s[-neg]:
print(x, words[x])
break
|
Port the provided Scala code into Go while preserving the original functionality. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| package main
import "fmt"
type ww struct {
word string
weight int
}
var input = []*ww{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
}
type sss struct {
subset []*ww
sum int
}
func main() {
ps := []sss{{nil, 0}}
for _, i := range input {
pl := len(ps)
for j := 0; j < pl; j++ {
subset := append([]*ww{i}, ps[j].subset...)
sum := i.weight + ps[j].sum
if sum == 0 {
fmt.Println("this subset sums to 0:")
for _, i := range subset {
fmt.Println(*i)
}
return
}
ps = append(ps, sss{subset, sum})
}
}
fmt.Println("no subset sums to 0")
}
|
Convert this Scala block to Go, preserving its control flow and logic. |
class Item(val word: String, val weight: Int) {
override fun toString() = "($word $weight)"
}
val items = arrayOf(
Item("alliance", -624),
Item("archbishop", -915),
Item("balm", 397),
Item("bonnet", 452),
Item("brute", 870),
Item("centipede", -658),
Item("cobol", 362),
Item("covariate", 590),
Item("departure", 952),
Item("deploy", 44),
Item("diophantine", 645),
Item("efferent", 54),
Item("elysee", -326),
Item("eradicate", 376),
Item("escritoire", 856),
Item("exorcism", -983),
Item("fiat", 170),
Item("filmy", -874),
Item("flatworm", 503),
Item("gestapo", 915),
Item("infra", -847),
Item("isis", -982),
Item("lindholm", 999),
Item("markham", 475),
Item("mincemeat", -880),
Item("moresby", 756),
Item("mycenae", 183),
Item("plugging", -266),
Item("smokescreen", 423),
Item("speakeasy", -745),
Item("vein", 813)
)
val n = items.size
val indices = IntArray(n)
var count = 0
const val LIMIT = 5
fun zeroSum(i: Int, w: Int) {
if (i != 0 && w == 0) {
for (j in 0 until i) print("${items[indices[j]]} ")
println("\n")
if (count < LIMIT) count++ else return
}
val k = if (i != 0) indices[i - 1] + 1 else 0
for (j in k until n) {
indices[i] = j
zeroSum(i + 1, w + items[j].weight)
if (count == LIMIT) return
}
}
fun main(args: Array<String>) {
println("The weights of the following $LIMIT subsets add up to zero:\n")
zeroSum(0, 0)
}
| package main
import "fmt"
type ww struct {
word string
weight int
}
var input = []*ww{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
}
type sss struct {
subset []*ww
sum int
}
func main() {
ps := []sss{{nil, 0}}
for _, i := range input {
pl := len(ps)
for j := 0; j < pl; j++ {
subset := append([]*ww{i}, ps[j].subset...)
sum := i.weight + ps[j].sum
if sum == 0 {
fmt.Println("this subset sums to 0:")
for _, i := range subset {
fmt.Println(*i)
}
return
}
ps = append(ps, sss{subset, sum})
}
}
fmt.Println("no subset sums to 0")
}
|
Preserve the algorithm and functionality while converting the code from Tcl to C. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *word;
int weight;
} item_t;
item_t items[] = {
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
int n = sizeof (items) / sizeof (item_t);
int *set;
void subsum (int i, int weight) {
int j;
if (i && !weight) {
for (j = 0; j < i; j++) {
item_t item = items[set[j]];
printf("%s%s", j ? " " : "", items[set[j]].word);
}
printf("\n");
}
for (j = i ? set[i - 1] + 1: 0; j < n; j++) {
set[i] = j;
subsum(i + 1, weight + items[j].weight);
}
}
int main () {
set = malloc(n * sizeof (int));
subsum(0, 0);
return 0;
}
|
Port the following code from Tcl to C with equivalent syntax and logic. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *word;
int weight;
} item_t;
item_t items[] = {
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
int n = sizeof (items) / sizeof (item_t);
int *set;
void subsum (int i, int weight) {
int j;
if (i && !weight) {
for (j = 0; j < i; j++) {
item_t item = items[set[j]];
printf("%s%s", j ? " " : "", items[set[j]].word);
}
printf("\n");
}
for (j = i ? set[i - 1] + 1: 0; j < n; j++) {
set[i] = j;
subsum(i + 1, weight + items[j].weight);
}
}
int main () {
set = malloc(n * sizeof (int));
subsum(0, 0);
return 0;
}
|
Can you help me rewrite this code in C# instead of Tcl, keeping it the same logically? | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| using System;
using System.Collections.Generic;
namespace SubsetSum {
class Item {
public Item(string word, int weight) {
Word = word;
Weight = weight;
}
public string Word { get; set; }
public int Weight { get; set; }
public override string ToString() {
return string.Format("({0}, {1})", Word, Weight);
}
}
class Program {
private static readonly List<Item> items = new List<Item>() {
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static readonly int n = items.Count;
private static readonly int LIMIT = 5;
private static int[] indices = new int[n];
private static int count = 0;
private static void ZeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; j++) {
Console.Write("{0} ", items[indices[j]]);
}
Console.WriteLine("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; j++) {
indices[i] = j;
ZeroSum(i + 1, w + items[j].Weight);
if (count == LIMIT) return;
}
}
static void Main(string[] args) {
Console.WriteLine("The weights of the following {0} subsets add up to zero:\n", LIMIT);
ZeroSum(0, 0);
}
}
}
|
Ensure the translated C# code behaves exactly like the original Tcl snippet. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| using System;
using System.Collections.Generic;
namespace SubsetSum {
class Item {
public Item(string word, int weight) {
Word = word;
Weight = weight;
}
public string Word { get; set; }
public int Weight { get; set; }
public override string ToString() {
return string.Format("({0}, {1})", Word, Weight);
}
}
class Program {
private static readonly List<Item> items = new List<Item>() {
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static readonly int n = items.Count;
private static readonly int LIMIT = 5;
private static int[] indices = new int[n];
private static int count = 0;
private static void ZeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; j++) {
Console.Write("{0} ", items[indices[j]]);
}
Console.WriteLine("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; j++) {
indices[i] = j;
ZeroSum(i + 1, w + items[j].Weight);
if (count == LIMIT) return;
}
}
static void Main(string[] args) {
Console.WriteLine("The weights of the following {0} subsets add up to zero:\n", LIMIT);
ZeroSum(0, 0);
}
}
}
|
Translate the given Tcl code snippet into C++ without altering its behavior. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| #include <iostream>
#include <vector>
std::ostream& operator<<(std::ostream& out, const std::string& str) {
return out << str.c_str();
}
std::vector<std::pair<std::string, int>> items{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
std::vector<int> indices;
int count = 0;
const int LIMIT = 5;
void subsum(int i, int weight) {
if (i != 0 && weight == 0) {
for (int j = 0; j < i; ++j) {
auto item = items[indices[j]];
std::cout << (j ? " " : "") << item.first;
}
std::cout << '\n';
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < items.size(); ++j) {
indices[i] = j;
subsum(i + 1, weight + items[j].second);
if (count == LIMIT) return;
}
}
int main() {
indices.resize(items.size());
subsum(0, 0);
return 0;
}
|
Convert the following code from Tcl to C++, ensuring the logic remains intact. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| #include <iostream>
#include <vector>
std::ostream& operator<<(std::ostream& out, const std::string& str) {
return out << str.c_str();
}
std::vector<std::pair<std::string, int>> items{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
};
std::vector<int> indices;
int count = 0;
const int LIMIT = 5;
void subsum(int i, int weight) {
if (i != 0 && weight == 0) {
for (int j = 0; j < i; ++j) {
auto item = items[indices[j]];
std::cout << (j ? " " : "") << item.first;
}
std::cout << '\n';
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < items.size(); ++j) {
indices[i] = j;
subsum(i + 1, weight + items[j].second);
if (count == LIMIT) return;
}
}
int main() {
indices.resize(items.size());
subsum(0, 0);
return 0;
}
|
Convert this Tcl block to Java, preserving its control flow and logic. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| public class SubsetSum {
private static class Item {
private String word;
private int weight;
public Item(String word, int weight) {
this.word = word;
this.weight = weight;
}
@Override
public String toString() {
return String.format("(%s, %d)", word, weight);
}
}
private static Item[] items = new Item[]{
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static final int n = items.length;
private static final int[] indices = new int[n];
private static int count = 0;
private static final int LIMIT = 5;
private static void zeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; ++j) {
System.out.printf("%s ", items[indices[j]]);
}
System.out.println("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; ++j) {
indices[i] = j;
zeroSum(i + 1, w + items[j].weight);
if (count == LIMIT) return;
}
}
public static void main(String[] args) {
System.out.printf("The weights of the following %d subsets add up to zero:\n\n", LIMIT);
zeroSum(0, 0);
}
}
|
Please provide an equivalent version of this Tcl code in Java. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| public class SubsetSum {
private static class Item {
private String word;
private int weight;
public Item(String word, int weight) {
this.word = word;
this.weight = weight;
}
@Override
public String toString() {
return String.format("(%s, %d)", word, weight);
}
}
private static Item[] items = new Item[]{
new Item("alliance", -624),
new Item("archbishop", -915),
new Item("balm", 397),
new Item("bonnet", 452),
new Item("brute", 870),
new Item("centipede", -658),
new Item("cobol", 362),
new Item("covariate", 590),
new Item("departure", 952),
new Item("deploy", 44),
new Item("diophantine", 645),
new Item("efferent", 54),
new Item("elysee", -326),
new Item("eradicate", 376),
new Item("escritoire", 856),
new Item("exorcism", -983),
new Item("fiat", 170),
new Item("filmy", -874),
new Item("flatworm", 503),
new Item("gestapo", 915),
new Item("infra", -847),
new Item("isis", -982),
new Item("lindholm", 999),
new Item("markham", 475),
new Item("mincemeat", -880),
new Item("moresby", 756),
new Item("mycenae", 183),
new Item("plugging", -266),
new Item("smokescreen", 423),
new Item("speakeasy", -745),
new Item("vein", 813),
};
private static final int n = items.length;
private static final int[] indices = new int[n];
private static int count = 0;
private static final int LIMIT = 5;
private static void zeroSum(int i, int w) {
if (i != 0 && w == 0) {
for (int j = 0; j < i; ++j) {
System.out.printf("%s ", items[indices[j]]);
}
System.out.println("\n");
if (count < LIMIT) count++;
else return;
}
int k = (i != 0) ? indices[i - 1] + 1 : 0;
for (int j = k; j < n; ++j) {
indices[i] = j;
zeroSum(i + 1, w + items[j].weight);
if (count == LIMIT) return;
}
}
public static void main(String[] args) {
System.out.printf("The weights of the following %d subsets add up to zero:\n\n", LIMIT);
zeroSum(0, 0);
}
}
|
Port the provided Tcl code into Python while preserving the original functionality. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| words = {
"alliance": -624, "archbishop": -925, "balm": 397,
"bonnet": 452, "brute": 870, "centipede": -658,
"cobol": 362, "covariate": 590, "departure": 952,
"deploy": 44, "diophantine": 645, "efferent": 54,
"elysee": -326, "eradicate": 376, "escritoire": 856,
"exorcism": -983, "fiat": 170, "filmy": -874,
"flatworm": 503, "gestapo": 915, "infra": -847,
"isis": -982, "lindholm": 999, "markham": 475,
"mincemeat": -880, "moresby": 756, "mycenae": 183,
"plugging": -266, "smokescreen": 423, "speakeasy": -745,
"vein": 813
}
neg = 0
pos = 0
for (w,v) in words.iteritems():
if v > 0: pos += v
else: neg += v
sums = [0] * (pos - neg + 1)
for (w,v) in words.iteritems():
s = sums[:]
if not s[v - neg]: s[v - neg] = (w,)
for (i, w2) in enumerate(sums):
if w2 and not s[i + v]:
s[i + v] = w2 + (w,)
sums = s
if s[-neg]:
for x in s[-neg]:
print(x, words[x])
break
|
Generate an equivalent Python version of this Tcl code. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| words = {
"alliance": -624, "archbishop": -925, "balm": 397,
"bonnet": 452, "brute": 870, "centipede": -658,
"cobol": 362, "covariate": 590, "departure": 952,
"deploy": 44, "diophantine": 645, "efferent": 54,
"elysee": -326, "eradicate": 376, "escritoire": 856,
"exorcism": -983, "fiat": 170, "filmy": -874,
"flatworm": 503, "gestapo": 915, "infra": -847,
"isis": -982, "lindholm": 999, "markham": 475,
"mincemeat": -880, "moresby": 756, "mycenae": 183,
"plugging": -266, "smokescreen": 423, "speakeasy": -745,
"vein": 813
}
neg = 0
pos = 0
for (w,v) in words.iteritems():
if v > 0: pos += v
else: neg += v
sums = [0] * (pos - neg + 1)
for (w,v) in words.iteritems():
s = sums[:]
if not s[v - neg]: s[v - neg] = (w,)
for (i, w2) in enumerate(sums):
if w2 and not s[i + v]:
s[i + v] = w2 + (w,)
sums = s
if s[-neg]:
for x in s[-neg]:
print(x, words[x])
break
|
Preserve the algorithm and functionality while converting the code from Tcl to Go. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| package main
import "fmt"
type ww struct {
word string
weight int
}
var input = []*ww{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
}
type sss struct {
subset []*ww
sum int
}
func main() {
ps := []sss{{nil, 0}}
for _, i := range input {
pl := len(ps)
for j := 0; j < pl; j++ {
subset := append([]*ww{i}, ps[j].subset...)
sum := i.weight + ps[j].sum
if sum == 0 {
fmt.Println("this subset sums to 0:")
for _, i := range subset {
fmt.Println(*i)
}
return
}
ps = append(ps, sss{subset, sum})
}
}
fmt.Println("no subset sums to 0")
}
|
Convert this Tcl block to Go, preserving its control flow and logic. | proc subsetsOfSize {set size} {
if {$size <= 0} {
return
} elseif {$size == 1} {
foreach elem $set {lappend result [list $elem]}
} else {
incr size [set i -1]
foreach elem $set {
foreach sub [subsetsOfSize [lreplace $set [incr i] $i] $size] {
lappend result [lappend sub $elem]
}
}
}
return $result
}
proc searchForSubset {wordweights {minsize 1}} {
set words [dict keys $wordweights]
for {set i $minsize} {$i < [llength $words]} {incr i} {
foreach subset [subsetsOfSize $words $i] {
set w 0
foreach elem $subset {incr w [dict get $wordweights $elem]}
if {!$w} {return $subset}
}
}
return -code error "no subset sums to zero"
}
| package main
import "fmt"
type ww struct {
word string
weight int
}
var input = []*ww{
{"alliance", -624},
{"archbishop", -915},
{"balm", 397},
{"bonnet", 452},
{"brute", 870},
{"centipede", -658},
{"cobol", 362},
{"covariate", 590},
{"departure", 952},
{"deploy", 44},
{"diophantine", 645},
{"efferent", 54},
{"elysee", -326},
{"eradicate", 376},
{"escritoire", 856},
{"exorcism", -983},
{"fiat", 170},
{"filmy", -874},
{"flatworm", 503},
{"gestapo", 915},
{"infra", -847},
{"isis", -982},
{"lindholm", 999},
{"markham", 475},
{"mincemeat", -880},
{"moresby", 756},
{"mycenae", 183},
{"plugging", -266},
{"smokescreen", 423},
{"speakeasy", -745},
{"vein", 813},
}
type sss struct {
subset []*ww
sum int
}
func main() {
ps := []sss{{nil, 0}}
for _, i := range input {
pl := len(ps)
for j := 0; j < pl; j++ {
subset := append([]*ww{i}, ps[j].subset...)
sum := i.weight + ps[j].sum
if sum == 0 {
fmt.Println("this subset sums to 0:")
for _, i := range subset {
fmt.Println(*i)
}
return
}
ps = append(ps, sss{subset, sum})
}
}
fmt.Println("no subset sums to 0")
}
|
Port the following code from Ada to C# with equivalent syntax and logic. | with Ada.Text_IO; use Ada.Text_IO;
procedure Man_Or_Boy is
function Zero return Integer is begin return 0; end Zero;
function One return Integer is begin return 1; end One;
function Neg return Integer is begin return -1; end Neg;
function A
( K : Integer;
X1, X2, X3, X4, X5 : access function return Integer
) return Integer is
M : Integer := K;
function B return Integer is
begin
M := M - 1;
return A (M, B'Access, X1, X2, X3, X4);
end B;
begin
if M <= 0 then
return X4.all + X5.all;
else
return B;
end if;
end A;
begin
Put_Line
( Integer'Image
( A
( 10,
One'Access,
Neg'Access,
Neg'Access,
One'Access,
Zero'Access
) ) );
end Man_Or_Boy;
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Produce a functionally identical C code for the snippet given in Ada. | with Ada.Text_IO; use Ada.Text_IO;
procedure Man_Or_Boy is
function Zero return Integer is begin return 0; end Zero;
function One return Integer is begin return 1; end One;
function Neg return Integer is begin return -1; end Neg;
function A
( K : Integer;
X1, X2, X3, X4, X5 : access function return Integer
) return Integer is
M : Integer := K;
function B return Integer is
begin
M := M - 1;
return A (M, B'Access, X1, X2, X3, X4);
end B;
begin
if M <= 0 then
return X4.all + X5.all;
else
return B;
end if;
end A;
begin
Put_Line
( Integer'Image
( A
( 10,
One'Access,
Neg'Access,
Neg'Access,
One'Access,
Zero'Access
) ) );
end Man_Or_Boy;
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Please provide an equivalent version of this Ada code in C++. | with Ada.Text_IO; use Ada.Text_IO;
procedure Man_Or_Boy is
function Zero return Integer is begin return 0; end Zero;
function One return Integer is begin return 1; end One;
function Neg return Integer is begin return -1; end Neg;
function A
( K : Integer;
X1, X2, X3, X4, X5 : access function return Integer
) return Integer is
M : Integer := K;
function B return Integer is
begin
M := M - 1;
return A (M, B'Access, X1, X2, X3, X4);
end B;
begin
if M <= 0 then
return X4.all + X5.all;
else
return B;
end if;
end A;
begin
Put_Line
( Integer'Image
( A
( 10,
One'Access,
Neg'Access,
Neg'Access,
One'Access,
Zero'Access
) ) );
end Man_Or_Boy;
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Change the programming language of this snippet from Ada to Go without modifying what it does. | with Ada.Text_IO; use Ada.Text_IO;
procedure Man_Or_Boy is
function Zero return Integer is begin return 0; end Zero;
function One return Integer is begin return 1; end One;
function Neg return Integer is begin return -1; end Neg;
function A
( K : Integer;
X1, X2, X3, X4, X5 : access function return Integer
) return Integer is
M : Integer := K;
function B return Integer is
begin
M := M - 1;
return A (M, B'Access, X1, X2, X3, X4);
end B;
begin
if M <= 0 then
return X4.all + X5.all;
else
return B;
end if;
end A;
begin
Put_Line
( Integer'Image
( A
( 10,
One'Access,
Neg'Access,
Neg'Access,
One'Access,
Zero'Access
) ) );
end Man_Or_Boy;
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Produce a language-to-language conversion: from Ada to Java, same semantics. | with Ada.Text_IO; use Ada.Text_IO;
procedure Man_Or_Boy is
function Zero return Integer is begin return 0; end Zero;
function One return Integer is begin return 1; end One;
function Neg return Integer is begin return -1; end Neg;
function A
( K : Integer;
X1, X2, X3, X4, X5 : access function return Integer
) return Integer is
M : Integer := K;
function B return Integer is
begin
M := M - 1;
return A (M, B'Access, X1, X2, X3, X4);
end B;
begin
if M <= 0 then
return X4.all + X5.all;
else
return B;
end if;
end A;
begin
Put_Line
( Integer'Image
( A
( 10,
One'Access,
Neg'Access,
Neg'Access,
One'Access,
Zero'Access
) ) );
end Man_Or_Boy;
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Write the same algorithm in Python as shown in this Ada implementation. | with Ada.Text_IO; use Ada.Text_IO;
procedure Man_Or_Boy is
function Zero return Integer is begin return 0; end Zero;
function One return Integer is begin return 1; end One;
function Neg return Integer is begin return -1; end Neg;
function A
( K : Integer;
X1, X2, X3, X4, X5 : access function return Integer
) return Integer is
M : Integer := K;
function B return Integer is
begin
M := M - 1;
return A (M, B'Access, X1, X2, X3, X4);
end B;
begin
if M <= 0 then
return X4.all + X5.all;
else
return B;
end if;
end A;
begin
Put_Line
( Integer'Image
( A
( 10,
One'Access,
Neg'Access,
Neg'Access,
One'Access,
Zero'Access
) ) );
end Man_Or_Boy;
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Write the same code in C as shown below in BBC_Basic. | HIMEM = PAGE + 200000000 :
FOR k% = 0 TO 20
PRINT FNA(k%, ^FN1(), ^FN_1(), ^FN_1(), ^FN1(), ^FN0())
NEXT
END
DEF FNA(k%, x1%, x2%, x3%, x4%, x5%)
IF k% <= 0 THEN = FN(x4%)(x4%) + FN(x5%)(x5%)
LOCAL b{}
DIM b{fn%, k%, x1%, x2%, x3%, x4%, x5%}
b.fn% = !^FNB()
b.k% = k%
b.x1% = x1%
b.x2% = x2%
b.x3% = x3%
b.x4% = x4%
b.x5% = x5%
DEF FNB(!(^b{}+4))
b.k% -= 1
= FNA(b.k%, b{}, b.x1%, b.x2%, b.x3%, b.x4%)
DEF FN0(d%) = 0
DEF FN1(d%) = 1
DEF FN_1(d%) = -1
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Produce a functionally identical C# code for the snippet given in BBC_Basic. | HIMEM = PAGE + 200000000 :
FOR k% = 0 TO 20
PRINT FNA(k%, ^FN1(), ^FN_1(), ^FN_1(), ^FN1(), ^FN0())
NEXT
END
DEF FNA(k%, x1%, x2%, x3%, x4%, x5%)
IF k% <= 0 THEN = FN(x4%)(x4%) + FN(x5%)(x5%)
LOCAL b{}
DIM b{fn%, k%, x1%, x2%, x3%, x4%, x5%}
b.fn% = !^FNB()
b.k% = k%
b.x1% = x1%
b.x2% = x2%
b.x3% = x3%
b.x4% = x4%
b.x5% = x5%
DEF FNB(!(^b{}+4))
b.k% -= 1
= FNA(b.k%, b{}, b.x1%, b.x2%, b.x3%, b.x4%)
DEF FN0(d%) = 0
DEF FN1(d%) = 1
DEF FN_1(d%) = -1
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Translate the given BBC_Basic code snippet into C++ without altering its behavior. | HIMEM = PAGE + 200000000 :
FOR k% = 0 TO 20
PRINT FNA(k%, ^FN1(), ^FN_1(), ^FN_1(), ^FN1(), ^FN0())
NEXT
END
DEF FNA(k%, x1%, x2%, x3%, x4%, x5%)
IF k% <= 0 THEN = FN(x4%)(x4%) + FN(x5%)(x5%)
LOCAL b{}
DIM b{fn%, k%, x1%, x2%, x3%, x4%, x5%}
b.fn% = !^FNB()
b.k% = k%
b.x1% = x1%
b.x2% = x2%
b.x3% = x3%
b.x4% = x4%
b.x5% = x5%
DEF FNB(!(^b{}+4))
b.k% -= 1
= FNA(b.k%, b{}, b.x1%, b.x2%, b.x3%, b.x4%)
DEF FN0(d%) = 0
DEF FN1(d%) = 1
DEF FN_1(d%) = -1
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Translate the given BBC_Basic code snippet into Java without altering its behavior. | HIMEM = PAGE + 200000000 :
FOR k% = 0 TO 20
PRINT FNA(k%, ^FN1(), ^FN_1(), ^FN_1(), ^FN1(), ^FN0())
NEXT
END
DEF FNA(k%, x1%, x2%, x3%, x4%, x5%)
IF k% <= 0 THEN = FN(x4%)(x4%) + FN(x5%)(x5%)
LOCAL b{}
DIM b{fn%, k%, x1%, x2%, x3%, x4%, x5%}
b.fn% = !^FNB()
b.k% = k%
b.x1% = x1%
b.x2% = x2%
b.x3% = x3%
b.x4% = x4%
b.x5% = x5%
DEF FNB(!(^b{}+4))
b.k% -= 1
= FNA(b.k%, b{}, b.x1%, b.x2%, b.x3%, b.x4%)
DEF FN0(d%) = 0
DEF FN1(d%) = 1
DEF FN_1(d%) = -1
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Rewrite the snippet below in Python so it works the same as the original BBC_Basic code. | HIMEM = PAGE + 200000000 :
FOR k% = 0 TO 20
PRINT FNA(k%, ^FN1(), ^FN_1(), ^FN_1(), ^FN1(), ^FN0())
NEXT
END
DEF FNA(k%, x1%, x2%, x3%, x4%, x5%)
IF k% <= 0 THEN = FN(x4%)(x4%) + FN(x5%)(x5%)
LOCAL b{}
DIM b{fn%, k%, x1%, x2%, x3%, x4%, x5%}
b.fn% = !^FNB()
b.k% = k%
b.x1% = x1%
b.x2% = x2%
b.x3% = x3%
b.x4% = x4%
b.x5% = x5%
DEF FNB(!(^b{}+4))
b.k% -= 1
= FNA(b.k%, b{}, b.x1%, b.x2%, b.x3%, b.x4%)
DEF FN0(d%) = 0
DEF FN1(d%) = 1
DEF FN_1(d%) = -1
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Translate the given BBC_Basic code snippet into Go without altering its behavior. | HIMEM = PAGE + 200000000 :
FOR k% = 0 TO 20
PRINT FNA(k%, ^FN1(), ^FN_1(), ^FN_1(), ^FN1(), ^FN0())
NEXT
END
DEF FNA(k%, x1%, x2%, x3%, x4%, x5%)
IF k% <= 0 THEN = FN(x4%)(x4%) + FN(x5%)(x5%)
LOCAL b{}
DIM b{fn%, k%, x1%, x2%, x3%, x4%, x5%}
b.fn% = !^FNB()
b.k% = k%
b.x1% = x1%
b.x2% = x2%
b.x3% = x3%
b.x4% = x4%
b.x5% = x5%
DEF FNB(!(^b{}+4))
b.k% -= 1
= FNA(b.k%, b{}, b.x1%, b.x2%, b.x3%, b.x4%)
DEF FN0(d%) = 0
DEF FN1(d%) = 1
DEF FN_1(d%) = -1
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Change the following Common_Lisp code into C without altering its purpose. | (declare a)
(defn man-or-boy
"Man or boy test for Clojure"
[k]
(let [k (atom k)]
(a k
(fn [] 1)
(fn [] -1)
(fn [] -1)
(fn [] 1)
(fn [] 0))))
(defn a
[k x1 x2 x3 x4 x5]
(let [k (atom @k)]
(letfn [(b []
(swap! k dec)
(a k b x1 x2 x3 x4))]
(if (<= @k 0)
(+ (x4) (x5))
(b)))))
(man-or-boy 10)
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | (declare a)
(defn man-or-boy
"Man or boy test for Clojure"
[k]
(let [k (atom k)]
(a k
(fn [] 1)
(fn [] -1)
(fn [] -1)
(fn [] 1)
(fn [] 0))))
(defn a
[k x1 x2 x3 x4 x5]
(let [k (atom @k)]
(letfn [(b []
(swap! k dec)
(a k b x1 x2 x3 x4))]
(if (<= @k 0)
(+ (x4) (x5))
(b)))))
(man-or-boy 10)
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Translate this program into C++ but keep the logic exactly as in Common_Lisp. | (declare a)
(defn man-or-boy
"Man or boy test for Clojure"
[k]
(let [k (atom k)]
(a k
(fn [] 1)
(fn [] -1)
(fn [] -1)
(fn [] 1)
(fn [] 0))))
(defn a
[k x1 x2 x3 x4 x5]
(let [k (atom @k)]
(letfn [(b []
(swap! k dec)
(a k b x1 x2 x3 x4))]
(if (<= @k 0)
(+ (x4) (x5))
(b)))))
(man-or-boy 10)
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Ensure the translated Java code behaves exactly like the original Common_Lisp snippet. | (declare a)
(defn man-or-boy
"Man or boy test for Clojure"
[k]
(let [k (atom k)]
(a k
(fn [] 1)
(fn [] -1)
(fn [] -1)
(fn [] 1)
(fn [] 0))))
(defn a
[k x1 x2 x3 x4 x5]
(let [k (atom @k)]
(letfn [(b []
(swap! k dec)
(a k b x1 x2 x3 x4))]
(if (<= @k 0)
(+ (x4) (x5))
(b)))))
(man-or-boy 10)
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Produce a language-to-language conversion: from Common_Lisp to Python, same semantics. | (declare a)
(defn man-or-boy
"Man or boy test for Clojure"
[k]
(let [k (atom k)]
(a k
(fn [] 1)
(fn [] -1)
(fn [] -1)
(fn [] 1)
(fn [] 0))))
(defn a
[k x1 x2 x3 x4 x5]
(let [k (atom @k)]
(letfn [(b []
(swap! k dec)
(a k b x1 x2 x3 x4))]
(if (<= @k 0)
(+ (x4) (x5))
(b)))))
(man-or-boy 10)
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Change the programming language of this snippet from Common_Lisp to Go without modifying what it does. | (declare a)
(defn man-or-boy
"Man or boy test for Clojure"
[k]
(let [k (atom k)]
(a k
(fn [] 1)
(fn [] -1)
(fn [] -1)
(fn [] 1)
(fn [] 0))))
(defn a
[k x1 x2 x3 x4 x5]
(let [k (atom @k)]
(letfn [(b []
(swap! k dec)
(a k b x1 x2 x3 x4))]
(if (<= @k 0)
(+ (x4) (x5))
(b)))))
(man-or-boy 10)
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Translate this program into C but keep the logic exactly as in D. | import core.stdc.stdio: printf;
int a(int k, const lazy int x1, const lazy int x2, const lazy int x3,
const lazy int x4, const lazy int x5) pure {
int b() {
k--;
return a(k, b(), x1, x2, x3, x4);
}
return k <= 0 ? x4 + x5 : b();
}
void main() {
printf("%d\n", a(10, 1, -1, -1, 1, 0));
}
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Translate this program into C# but keep the logic exactly as in D. | import core.stdc.stdio: printf;
int a(int k, const lazy int x1, const lazy int x2, const lazy int x3,
const lazy int x4, const lazy int x5) pure {
int b() {
k--;
return a(k, b(), x1, x2, x3, x4);
}
return k <= 0 ? x4 + x5 : b();
}
void main() {
printf("%d\n", a(10, 1, -1, -1, 1, 0));
}
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Write a version of this D function in C++ with identical behavior. | import core.stdc.stdio: printf;
int a(int k, const lazy int x1, const lazy int x2, const lazy int x3,
const lazy int x4, const lazy int x5) pure {
int b() {
k--;
return a(k, b(), x1, x2, x3, x4);
}
return k <= 0 ? x4 + x5 : b();
}
void main() {
printf("%d\n", a(10, 1, -1, -1, 1, 0));
}
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Convert this D block to Java, preserving its control flow and logic. | import core.stdc.stdio: printf;
int a(int k, const lazy int x1, const lazy int x2, const lazy int x3,
const lazy int x4, const lazy int x5) pure {
int b() {
k--;
return a(k, b(), x1, x2, x3, x4);
}
return k <= 0 ? x4 + x5 : b();
}
void main() {
printf("%d\n", a(10, 1, -1, -1, 1, 0));
}
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Port the provided D code into Python while preserving the original functionality. | import core.stdc.stdio: printf;
int a(int k, const lazy int x1, const lazy int x2, const lazy int x3,
const lazy int x4, const lazy int x5) pure {
int b() {
k--;
return a(k, b(), x1, x2, x3, x4);
}
return k <= 0 ? x4 + x5 : b();
}
void main() {
printf("%d\n", a(10, 1, -1, -1, 1, 0));
}
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Write a version of this D function in Go with identical behavior. | import core.stdc.stdio: printf;
int a(int k, const lazy int x1, const lazy int x2, const lazy int x3,
const lazy int x4, const lazy int x5) pure {
int b() {
k--;
return a(k, b(), x1, x2, x3, x4);
}
return k <= 0 ? x4 + x5 : b();
}
void main() {
printf("%d\n", a(10, 1, -1, -1, 1, 0));
}
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Change the following Delphi code into C without altering its purpose. | type
TFunc<T> = reference to function: T;
function C(x: Integer): TFunc<Integer>;
begin
Result := function: Integer
begin
Result := x;
end;
end;
function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer;
var
b: TFunc<Integer>;
begin
b := function: Integer
begin
Dec(k);
Result := A(k, b, x1, x2, x3, x4);
end;
if k <= 0 then
Result := x4 + x5
else
Result := b;
end;
begin
Writeln(A(10, C(1), C(-1), C(-1), C(1), C(0)));
end.
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Please provide an equivalent version of this Delphi code in C#. | type
TFunc<T> = reference to function: T;
function C(x: Integer): TFunc<Integer>;
begin
Result := function: Integer
begin
Result := x;
end;
end;
function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer;
var
b: TFunc<Integer>;
begin
b := function: Integer
begin
Dec(k);
Result := A(k, b, x1, x2, x3, x4);
end;
if k <= 0 then
Result := x4 + x5
else
Result := b;
end;
begin
Writeln(A(10, C(1), C(-1), C(-1), C(1), C(0)));
end.
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Convert the following code from Delphi to C++, ensuring the logic remains intact. | type
TFunc<T> = reference to function: T;
function C(x: Integer): TFunc<Integer>;
begin
Result := function: Integer
begin
Result := x;
end;
end;
function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer;
var
b: TFunc<Integer>;
begin
b := function: Integer
begin
Dec(k);
Result := A(k, b, x1, x2, x3, x4);
end;
if k <= 0 then
Result := x4 + x5
else
Result := b;
end;
begin
Writeln(A(10, C(1), C(-1), C(-1), C(1), C(0)));
end.
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Write a version of this Delphi function in Java with identical behavior. | type
TFunc<T> = reference to function: T;
function C(x: Integer): TFunc<Integer>;
begin
Result := function: Integer
begin
Result := x;
end;
end;
function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer;
var
b: TFunc<Integer>;
begin
b := function: Integer
begin
Dec(k);
Result := A(k, b, x1, x2, x3, x4);
end;
if k <= 0 then
Result := x4 + x5
else
Result := b;
end;
begin
Writeln(A(10, C(1), C(-1), C(-1), C(1), C(0)));
end.
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Keep all operations the same but rewrite the snippet in Python. | type
TFunc<T> = reference to function: T;
function C(x: Integer): TFunc<Integer>;
begin
Result := function: Integer
begin
Result := x;
end;
end;
function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer;
var
b: TFunc<Integer>;
begin
b := function: Integer
begin
Dec(k);
Result := A(k, b, x1, x2, x3, x4);
end;
if k <= 0 then
Result := x4 + x5
else
Result := b;
end;
begin
Writeln(A(10, C(1), C(-1), C(-1), C(1), C(0)));
end.
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Port the following code from Delphi to Go with equivalent syntax and logic. | type
TFunc<T> = reference to function: T;
function C(x: Integer): TFunc<Integer>;
begin
Result := function: Integer
begin
Result := x;
end;
end;
function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer;
var
b: TFunc<Integer>;
begin
b := function: Integer
begin
Dec(k);
Result := A(k, b, x1, x2, x3, x4);
end;
if k <= 0 then
Result := x4 + x5
else
Result := b;
end;
begin
Writeln(A(10, C(1), C(-1), C(-1), C(1), C(0)));
end.
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Keep all operations the same but rewrite the snippet in C. | [<EntryPoint>]
let main (args : string[]) =
let k = int(args.[0])
let l x = fun() -> x
let rec a k x1 x2 x3 x4 x5 =
if k <= 0 then
x4() + x5()
else
let k = ref k
let rec b() =
k := !k - 1
a !k b x1 x2 x3 x4
b()
a k (l 1) (l -1) (l -1) (l 1) (l 0)
|> printfn "%A"
0
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Produce a functionally identical C# code for the snippet given in F#. | [<EntryPoint>]
let main (args : string[]) =
let k = int(args.[0])
let l x = fun() -> x
let rec a k x1 x2 x3 x4 x5 =
if k <= 0 then
x4() + x5()
else
let k = ref k
let rec b() =
k := !k - 1
a !k b x1 x2 x3 x4
b()
a k (l 1) (l -1) (l -1) (l 1) (l 0)
|> printfn "%A"
0
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Can you help me rewrite this code in C++ instead of F#, keeping it the same logically? | [<EntryPoint>]
let main (args : string[]) =
let k = int(args.[0])
let l x = fun() -> x
let rec a k x1 x2 x3 x4 x5 =
if k <= 0 then
x4() + x5()
else
let k = ref k
let rec b() =
k := !k - 1
a !k b x1 x2 x3 x4
b()
a k (l 1) (l -1) (l -1) (l 1) (l 0)
|> printfn "%A"
0
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Generate an equivalent Java version of this F# code. | [<EntryPoint>]
let main (args : string[]) =
let k = int(args.[0])
let l x = fun() -> x
let rec a k x1 x2 x3 x4 x5 =
if k <= 0 then
x4() + x5()
else
let k = ref k
let rec b() =
k := !k - 1
a !k b x1 x2 x3 x4
b()
a k (l 1) (l -1) (l -1) (l 1) (l 0)
|> printfn "%A"
0
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Please provide an equivalent version of this F# code in Python. | [<EntryPoint>]
let main (args : string[]) =
let k = int(args.[0])
let l x = fun() -> x
let rec a k x1 x2 x3 x4 x5 =
if k <= 0 then
x4() + x5()
else
let k = ref k
let rec b() =
k := !k - 1
a !k b x1 x2 x3 x4
b()
a k (l 1) (l -1) (l -1) (l 1) (l 0)
|> printfn "%A"
0
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Produce a functionally identical Go code for the snippet given in F#. | [<EntryPoint>]
let main (args : string[]) =
let k = int(args.[0])
let l x = fun() -> x
let rec a k x1 x2 x3 x4 x5 =
if k <= 0 then
x4() + x5()
else
let k = ref k
let rec b() =
k := !k - 1
a !k b x1 x2 x3 x4
b()
a k (l 1) (l -1) (l -1) (l 1) (l 0)
|> printfn "%A"
0
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Produce a functionally identical C code for the snippet given in Forth. | : A {: w^ k x1 x2 x3 xt: x4 xt: x5 | w^ B :} recursive
k @ 0<= IF x4 x5 f+ ELSE
B k x1 x2 x3 action-of x4 [{: B k x1 x2 x3 x4 :}L
-1 k +!
k @ B @ x1 x2 x3 x4 A ;] dup B !
execute THEN ;
10 [: 1e ;] [: -1e ;] 2dup swap [: 0e ;] A f.
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Write the same code in C# as shown below in Forth. | : A {: w^ k x1 x2 x3 xt: x4 xt: x5 | w^ B :} recursive
k @ 0<= IF x4 x5 f+ ELSE
B k x1 x2 x3 action-of x4 [{: B k x1 x2 x3 x4 :}L
-1 k +!
k @ B @ x1 x2 x3 x4 A ;] dup B !
execute THEN ;
10 [: 1e ;] [: -1e ;] 2dup swap [: 0e ;] A f.
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Ensure the translated C++ code behaves exactly like the original Forth snippet. | : A {: w^ k x1 x2 x3 xt: x4 xt: x5 | w^ B :} recursive
k @ 0<= IF x4 x5 f+ ELSE
B k x1 x2 x3 action-of x4 [{: B k x1 x2 x3 x4 :}L
-1 k +!
k @ B @ x1 x2 x3 x4 A ;] dup B !
execute THEN ;
10 [: 1e ;] [: -1e ;] 2dup swap [: 0e ;] A f.
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Produce a functionally identical Java code for the snippet given in Forth. | : A {: w^ k x1 x2 x3 xt: x4 xt: x5 | w^ B :} recursive
k @ 0<= IF x4 x5 f+ ELSE
B k x1 x2 x3 action-of x4 [{: B k x1 x2 x3 x4 :}L
-1 k +!
k @ B @ x1 x2 x3 x4 A ;] dup B !
execute THEN ;
10 [: 1e ;] [: -1e ;] 2dup swap [: 0e ;] A f.
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Convert this Forth snippet to Python and keep its semantics consistent. | : A {: w^ k x1 x2 x3 xt: x4 xt: x5 | w^ B :} recursive
k @ 0<= IF x4 x5 f+ ELSE
B k x1 x2 x3 action-of x4 [{: B k x1 x2 x3 x4 :}L
-1 k +!
k @ B @ x1 x2 x3 x4 A ;] dup B !
execute THEN ;
10 [: 1e ;] [: -1e ;] 2dup swap [: 0e ;] A f.
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Produce a language-to-language conversion: from Forth to Go, same semantics. | : A {: w^ k x1 x2 x3 xt: x4 xt: x5 | w^ B :} recursive
k @ 0<= IF x4 x5 f+ ELSE
B k x1 x2 x3 action-of x4 [{: B k x1 x2 x3 x4 :}L
-1 k +!
k @ B @ x1 x2 x3 x4 A ;] dup B !
execute THEN ;
10 [: 1e ;] [: -1e ;] 2dup swap [: 0e ;] A f.
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Produce a language-to-language conversion: from Fortran to C#, same semantics. | module man_or_boy
implicit none
contains
recursive integer function A(k,x1,x2,x3,x4,x5) result(res)
integer, intent(in) :: k
interface
recursive integer function x1()
end function
recursive integer function x2()
end function
recursive integer function x3()
end function
recursive integer function x4()
end function
recursive integer function x5()
end function
end interface
integer :: m
if ( k <= 0 ) then
res = x4()+x5()
else
m = k
res = B()
end if
contains
recursive integer function B() result(res)
m = m-1
res = A(m,B,x1,x2,x3,x4)
end function B
end function A
recursive integer function one() result(res)
res = 1
end function
recursive integer function minus_one() result(res)
res = -1
end function
recursive integer function zero() result(res)
res = 0
end function
end module man_or_boy
program test
use man_or_boy
write (*,*) A(10,one,minus_one,minus_one,one,zero)
end program test
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Translate the given Fortran code snippet into C++ without altering its behavior. | module man_or_boy
implicit none
contains
recursive integer function A(k,x1,x2,x3,x4,x5) result(res)
integer, intent(in) :: k
interface
recursive integer function x1()
end function
recursive integer function x2()
end function
recursive integer function x3()
end function
recursive integer function x4()
end function
recursive integer function x5()
end function
end interface
integer :: m
if ( k <= 0 ) then
res = x4()+x5()
else
m = k
res = B()
end if
contains
recursive integer function B() result(res)
m = m-1
res = A(m,B,x1,x2,x3,x4)
end function B
end function A
recursive integer function one() result(res)
res = 1
end function
recursive integer function minus_one() result(res)
res = -1
end function
recursive integer function zero() result(res)
res = 0
end function
end module man_or_boy
program test
use man_or_boy
write (*,*) A(10,one,minus_one,minus_one,one,zero)
end program test
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Write the same algorithm in C as shown in this Fortran implementation. | module man_or_boy
implicit none
contains
recursive integer function A(k,x1,x2,x3,x4,x5) result(res)
integer, intent(in) :: k
interface
recursive integer function x1()
end function
recursive integer function x2()
end function
recursive integer function x3()
end function
recursive integer function x4()
end function
recursive integer function x5()
end function
end interface
integer :: m
if ( k <= 0 ) then
res = x4()+x5()
else
m = k
res = B()
end if
contains
recursive integer function B() result(res)
m = m-1
res = A(m,B,x1,x2,x3,x4)
end function B
end function A
recursive integer function one() result(res)
res = 1
end function
recursive integer function minus_one() result(res)
res = -1
end function
recursive integer function zero() result(res)
res = 0
end function
end module man_or_boy
program test
use man_or_boy
write (*,*) A(10,one,minus_one,minus_one,one,zero)
end program test
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Fortran version. | module man_or_boy
implicit none
contains
recursive integer function A(k,x1,x2,x3,x4,x5) result(res)
integer, intent(in) :: k
interface
recursive integer function x1()
end function
recursive integer function x2()
end function
recursive integer function x3()
end function
recursive integer function x4()
end function
recursive integer function x5()
end function
end interface
integer :: m
if ( k <= 0 ) then
res = x4()+x5()
else
m = k
res = B()
end if
contains
recursive integer function B() result(res)
m = m-1
res = A(m,B,x1,x2,x3,x4)
end function B
end function A
recursive integer function one() result(res)
res = 1
end function
recursive integer function minus_one() result(res)
res = -1
end function
recursive integer function zero() result(res)
res = 0
end function
end module man_or_boy
program test
use man_or_boy
write (*,*) A(10,one,minus_one,minus_one,one,zero)
end program test
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Can you help me rewrite this code in Python instead of Fortran, keeping it the same logically? | module man_or_boy
implicit none
contains
recursive integer function A(k,x1,x2,x3,x4,x5) result(res)
integer, intent(in) :: k
interface
recursive integer function x1()
end function
recursive integer function x2()
end function
recursive integer function x3()
end function
recursive integer function x4()
end function
recursive integer function x5()
end function
end interface
integer :: m
if ( k <= 0 ) then
res = x4()+x5()
else
m = k
res = B()
end if
contains
recursive integer function B() result(res)
m = m-1
res = A(m,B,x1,x2,x3,x4)
end function B
end function A
recursive integer function one() result(res)
res = 1
end function
recursive integer function minus_one() result(res)
res = -1
end function
recursive integer function zero() result(res)
res = 0
end function
end module man_or_boy
program test
use man_or_boy
write (*,*) A(10,one,minus_one,minus_one,one,zero)
end program test
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Change the programming language of this snippet from Fortran to PHP without modifying what it does. | module man_or_boy
implicit none
contains
recursive integer function A(k,x1,x2,x3,x4,x5) result(res)
integer, intent(in) :: k
interface
recursive integer function x1()
end function
recursive integer function x2()
end function
recursive integer function x3()
end function
recursive integer function x4()
end function
recursive integer function x5()
end function
end interface
integer :: m
if ( k <= 0 ) then
res = x4()+x5()
else
m = k
res = B()
end if
contains
recursive integer function B() result(res)
m = m-1
res = A(m,B,x1,x2,x3,x4)
end function B
end function A
recursive integer function one() result(res)
res = 1
end function
recursive integer function minus_one() result(res)
res = -1
end function
recursive integer function zero() result(res)
res = 0
end function
end module man_or_boy
program test
use man_or_boy
write (*,*) A(10,one,minus_one,minus_one,one,zero)
end program test
| <?php
function A($k,$x1,$x2,$x3,$x4,$x5) {
$b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {
return A(--$k,$b,$x1,$x2,$x3,$x4);
};
return $k <= 0 ? $x4() + $x5() : $b();
}
echo A(10, function () { return 1; },
function () { return -1; },
function () { return -1; },
function () { return 1; },
function () { return 0; }) . "\n";
?>
|
Produce a language-to-language conversion: from Groovy to C, same semantics. | def a; a = { k, x1, x2, x3, x4, x5 ->
def b; b = {
a (--k, b, x1, x2, x3, x4)
}
k <= 0 ? x4() + x5() : b()
}
def x = { n -> { it -> n } }
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Groovy. | def a; a = { k, x1, x2, x3, x4, x5 ->
def b; b = {
a (--k, b, x1, x2, x3, x4)
}
k <= 0 ? x4() + x5() : b()
}
def x = { n -> { it -> n } }
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Translate the given Groovy code snippet into C++ without altering its behavior. | def a; a = { k, x1, x2, x3, x4, x5 ->
def b; b = {
a (--k, b, x1, x2, x3, x4)
}
k <= 0 ? x4() + x5() : b()
}
def x = { n -> { it -> n } }
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Write the same algorithm in Java as shown in this Groovy implementation. | def a; a = { k, x1, x2, x3, x4, x5 ->
def b; b = {
a (--k, b, x1, x2, x3, x4)
}
k <= 0 ? x4() + x5() : b()
}
def x = { n -> { it -> n } }
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Change the programming language of this snippet from Groovy to Python without modifying what it does. | def a; a = { k, x1, x2, x3, x4, x5 ->
def b; b = {
a (--k, b, x1, x2, x3, x4)
}
k <= 0 ? x4() + x5() : b()
}
def x = { n -> { it -> n } }
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Transform the following Groovy implementation into Go, maintaining the same output and logic. | def a; a = { k, x1, x2, x3, x4, x5 ->
def b; b = {
a (--k, b, x1, x2, x3, x4)
}
k <= 0 ? x4() + x5() : b()
}
def x = { n -> { it -> n } }
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Translate this program into C but keep the logic exactly as in Haskell. | import Data.IORef (modifyIORef, newIORef, readIORef)
a
:: (Enum a, Num b, Num a, Ord a)
=> a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b
a k x1 x2 x3 x4 x5 = do
r <- newIORef k
let b = do
k <- pred ! r
a k b x1 x2 x3 x4
if k <= 0
then (+) <$> x4 <*> x5
else b
where
f !r = modifyIORef r f >> readIORef r
main :: IO ()
main = a 10 # 1 # (-1) # (-1) # 1 # 0 >>= print
where
( # ) f = f . return
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Translate this program into C# but keep the logic exactly as in Haskell. | import Data.IORef (modifyIORef, newIORef, readIORef)
a
:: (Enum a, Num b, Num a, Ord a)
=> a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b
a k x1 x2 x3 x4 x5 = do
r <- newIORef k
let b = do
k <- pred ! r
a k b x1 x2 x3 x4
if k <= 0
then (+) <$> x4 <*> x5
else b
where
f !r = modifyIORef r f >> readIORef r
main :: IO ()
main = a 10 # 1 # (-1) # (-1) # 1 # 0 >>= print
where
( # ) f = f . return
| using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
Translate this program into C++ but keep the logic exactly as in Haskell. | import Data.IORef (modifyIORef, newIORef, readIORef)
a
:: (Enum a, Num b, Num a, Ord a)
=> a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b
a k x1 x2 x3 x4 x5 = do
r <- newIORef k
let b = do
k <- pred ! r
a k b x1 x2 x3 x4
if k <= 0
then (+) <$> x4 <*> x5
else b
where
f !r = modifyIORef r f >> readIORef r
main :: IO ()
main = a 10 # 1 # (-1) # (-1) # 1 # 0 >>= print
where
( # ) f = f . return
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Convert this Haskell snippet to Java and keep its semantics consistent. | import Data.IORef (modifyIORef, newIORef, readIORef)
a
:: (Enum a, Num b, Num a, Ord a)
=> a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b
a k x1 x2 x3 x4 x5 = do
r <- newIORef k
let b = do
k <- pred ! r
a k b x1 x2 x3 x4
if k <= 0
then (+) <$> x4 <*> x5
else b
where
f !r = modifyIORef r f >> readIORef r
main :: IO ()
main = a 10 # 1 # (-1) # (-1) # 1 # 0 >>= print
where
( # ) f = f . return
| import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDouble() {
return A(--m, this, x1, x2, x3, x4);
}
};
return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
}
public static void main(String[] args) {
System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
}
}
|
Produce a language-to-language conversion: from Haskell to Python, same semantics. | import Data.IORef (modifyIORef, newIORef, readIORef)
a
:: (Enum a, Num b, Num a, Ord a)
=> a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b
a k x1 x2 x3 x4 x5 = do
r <- newIORef k
let b = do
k <- pred ! r
a k b x1 x2 x3 x4
if k <= 0
then (+) <$> x4 <*> x5
else b
where
f !r = modifyIORef r f >> readIORef r
main :: IO ()
main = a 10 # 1 # (-1) # (-1) # 1 # 0 >>= print
where
( # ) f = f . return
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Port the provided Haskell code into Go while preserving the original functionality. | import Data.IORef (modifyIORef, newIORef, readIORef)
a
:: (Enum a, Num b, Num a, Ord a)
=> a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b
a k x1 x2 x3 x4 x5 = do
r <- newIORef k
let b = do
k <- pred ! r
a k b x1 x2 x3 x4
if k <= 0
then (+) <$> x4 <*> x5
else b
where
f !r = modifyIORef r f >> readIORef r
main :: IO ()
main = a 10 # 1 # (-1) # (-1) # 1 # 0 >>= print
where
( # ) f = f . return
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.