Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same code in C as shown below in Icon. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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;
}
|
Write the same algorithm in C# as shown in this Icon implementation. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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#. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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);
}
}
}
|
Port the provided Icon code into C++ while preserving the original functionality. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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;
}
|
Write a version of this Icon function in C++ with identical behavior. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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;
}
|
Transform the following Icon implementation into Java, maintaining the same output and logic. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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);
}
}
|
Rewrite the snippet below in Java so it works the same as the original Icon code. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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);
}
}
|
Port the following code from Icon to Python with equivalent syntax and logic. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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
|
Rewrite the snippet below in Python so it works the same as the original Icon code. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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
|
Generate an equivalent Go version of this Icon code. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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")
}
|
Please provide an equivalent version of this Icon code in Go. | link printf,lists
procedure main()
BruteZeroSubset(string2table(
"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/"))
end
procedure BruteZeroSubset(words)
every n := 1 to *words do {
every t := tcomb(words,n) do {
every (sum := 0) +:= words[!t]
if sum = 0 then {
printf("A zero-sum subset of length %d : %s\n",n,list2string(sort(t)))
break next
}
}
printf("No zero-sum subsets of length %d\n",n)
}
end
procedure tcomb(T, i)
local K
every put(K := [],key(T))
every suspend lcomb(K,i)
end
procedure list2string(L)
every (s := "[ ") ||:= !L || " "
return s || "]"
end
procedure string2table(s,d)
T := table()
/d := "/"
s ? until pos(0) do
T[1(tab(find(d)),=d)] := numeric(1(tab(find(d)),=d))
return T
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")
}
|
Produce a functionally identical C code for the snippet given in J. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| #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 J to C without modifying what it does. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| #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 J to C# with equivalent syntax and logic. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| 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);
}
}
}
|
Produce a functionally identical C# code for the snippet given in J. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| 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);
}
}
}
|
Convert the following code from J to C++, ensuring the logic remains intact. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| #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;
}
|
Change the programming language of this snippet from J to C++ without modifying what it does. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| #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;
}
|
Write a version of this J function in Java with identical behavior. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| 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 this J block to Java, preserving its control flow and logic. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| 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 Python version of this J code. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| 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 code in Python as shown below in J. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| 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
|
Rewrite the snippet below in Go so it works the same as the original J code. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| 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")
}
|
Generate an equivalent Go version of this J code. | text=:0 :0
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=:{.@;:;._2 text
numbs=:+/|:0&".;._2 text
| 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 this program into C but keep the logic exactly as in Julia. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| #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 Julia block to C, preserving its control flow and logic. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| #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 Julia block to C#, preserving its control flow and logic. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| 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);
}
}
}
|
Convert this Julia block to C#, preserving its control flow and logic. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| 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);
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| #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 Julia to C++ with equivalent syntax and logic. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| #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;
}
|
Change the programming language of this snippet from Julia to Java without modifying what it does. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| 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);
}
}
|
Produce a functionally identical Java code for the snippet given in Julia. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| 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);
}
}
|
Ensure the translated Python code behaves exactly like the original Julia snippet. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| 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 a version of this Julia function in Python with identical behavior. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| 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 Go as shown in this Julia implementation. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| 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 the following code from Julia to Go, ensuring the logic remains intact. | using Combinatorics
const pairs = [
"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]
const weights = [v for (k, v) in pairs]
const weightkeyed = Dict(Pair(v, k) for (k, v) in pairs)
function zerosums()
total = 0
for i in 1:length(weights)
print("\nFor length $i: ")
sets = [a for a in combinations(weights, i) if sum(a) == 0]
if (n = length(sets)) == 0
print("None")
else
total += n
print("$n sets, example: ", map(x -> weightkeyed[x], rand(sets)))
end
end
println("\n\nGrand total sets: $total")
end
zerosums()
| 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 Mathematica to C without modifying what it does. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| #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 Mathematica. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| #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;
}
|
Transform the following Mathematica implementation into C#, maintaining the same output and logic. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| 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);
}
}
}
|
Can you help me rewrite this code in C# instead of Mathematica, keeping it the same logically? | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| 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);
}
}
}
|
Change the following Mathematica code into C++ without altering its purpose. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| #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 Mathematica snippet to C++ and keep its semantics consistent. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| #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;
}
|
Produce a language-to-language conversion: from Mathematica to Java, same semantics. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| 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 Mathematica code in Java. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| 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 Mathematica snippet without changing its computational steps. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| 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 code in Python as shown below in Mathematica. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| 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
|
Rewrite this program in Go while keeping its functionality equivalent to the Mathematica version. | a = {{"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}};
result = Rest@Select[ Subsets[a, 7], (Total[#[[;; , 2]]] == 0) &];
Map[ (Print["A zero-sum subset of length ", Length[#], " : ", #[[;; , 1]]])& , result ]
| 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")
}
|
Write the same code in C as shown below in Nim. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| #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;
}
|
Produce a functionally identical C code for the snippet given in Nim. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| #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;
}
|
Write the same algorithm in C# as shown in this Nim implementation. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| 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);
}
}
}
|
Change the following Nim code into C# without altering its purpose. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| 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);
}
}
}
|
Write the same code in C++ as shown below in Nim. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| #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 Nim snippet to C++ and keep its semantics consistent. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| #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;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| 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);
}
}
|
Change the following Nim code into Java without altering its purpose. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| 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 this Nim snippet to Python and keep its semantics consistent. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| 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 Nim implementation into Go, maintaining the same output and logic. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| 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 Nim to Go without modifying what it does. | import sequtils, strformat, strutils
import itertools
const Words = {"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}
var words: seq[string]
var values: seq[int]
for (word, value) in Words:
words.add word
values.add value
for lg in 1..words.len:
block checkCombs:
for comb in combinations(words.len, lg):
var sum = 0
for idx in comb: sum += values[idx]
if sum == 0:
echo &"For length {lg}, found for example: ", comb.mapIt(words[it]).join(" ")
break checkCombs
echo &"For length {lg}, no set found."
| 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 this program in C while keeping its functionality equivalent to the OCaml version. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| #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;
}
|
Rewrite this program in C while keeping its functionality equivalent to the OCaml version. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| #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;
}
|
Produce a functionally identical C# code for the snippet given in OCaml. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| 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);
}
}
}
|
Produce a language-to-language conversion: from OCaml to C#, same semantics. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| 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 OCaml code. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| #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 OCaml code into C++ while preserving the original functionality. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| #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 the given OCaml code snippet into Java without altering its behavior. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| 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 Java as shown in this OCaml implementation. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| 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);
}
}
|
Keep all operations the same but rewrite the snippet in Python. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| 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 code in Python as shown below in OCaml. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| 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 OCaml code into Go while preserving the original functionality. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| 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")
}
|
Maintain the same structure and functionality when rewriting this code in Go. | let d =
[ "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; ]
let sum = List.fold_left (fun sum (_,w) -> sum + w) 0
let p = function [] -> false | lst -> (sum lst) = 0
let take lst set =
let x = List.nth set (Random.int (List.length set)) in
(x::lst, List.filter (fun y -> y <> x) set)
let swap (a, b) = (b, a)
let pop lst set = swap (take set lst)
let () =
Random.self_init ();
let rec aux lst set =
let f =
match lst, set with
| [], _ -> take
| _, [] -> pop
| _ -> if Random.bool () then take else pop
in
let lst, set = f lst set in
if p lst then lst
else aux lst set
in
let res = aux [] d in
List.iter (fun (n,w) -> Printf.printf " %4d\t%s\n" w n) res
| 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 Perl to C with equivalent syntax and logic. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| #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 the following code from Perl to C, ensuring the logic remains intact. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| #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 an equivalent C# version of this Perl code. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| 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);
}
}
}
|
Produce a language-to-language conversion: from Perl to C++, same semantics. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| #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 Perl code into C++ while preserving the original functionality. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| #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 Perl snippet to Java and keep its semantics consistent. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| 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 Perl code in Java. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| 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 Perl implementation. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| 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
|
Maintain the same structure and functionality when rewriting this code in Python. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| 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
|
Maintain the same structure and functionality when rewriting this code in Go. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| 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 Perl to Go with equivalent syntax and logic. | use ntheory qw/:all/;
my %pairs = (
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 );
my @names = sort keys(%pairs);
my @weights = @pairs{@names};
foreach my $n (1 .. @names) {
forcomb {
lastfor, print "Length $n: @names[@_]\n" if vecsum(@weights[@_]) == 0;
} @names, $n;
}
| 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")
}
|
Write a version of this Racket function in C with identical behavior. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| #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;
}
|
Ensure the translated C code behaves exactly like the original Racket snippet. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| #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;
}
|
Ensure the translated C# code behaves exactly like the original Racket snippet. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| 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 a C# translation of this Racket snippet without changing its computational steps. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| 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);
}
}
}
|
Port the provided Racket code into C++ while preserving the original functionality. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| #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 Racket to C++ with equivalent syntax and logic. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| #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;
}
|
Transform the following Racket implementation into Java, maintaining the same output and logic. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| 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 Racket to Java, ensuring the logic remains intact. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| 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 Racket code in Python. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| 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
|
Rewrite the snippet below in Python so it works the same as the original Racket code. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| 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 this Racket block to Go, preserving its control flow and logic. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| 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")
}
|
Please provide an equivalent version of this Racket code in Go. | #lang racket
(define words
'([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]))
(define (nsubsets l n)
(cond [(zero? n) '(())] [(null? l) '()]
[else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))])
(cons (car l) l2))
(nsubsets (cdr l) n))]))
(for*/first ([i (sub1 (length words))] [s (nsubsets words (add1 i))]
#:when (zero? (apply + (map cadr s))))
(map car s))
(define (zero-subsets l)
(define (loop l len n r sum)
(cond [(zero? n) (when (zero? sum) (displayln (reverse r)))]
[(and (pair? l) (<= sum (* 1000 n)))
(when (< n len) (loop (cdr l) (sub1 len) n r sum))
(loop (cdr l) (sub1 len) (sub1 n) (cons (caar l) r)
(+ (cadar l) sum))]))
(define len (length l))
(for ([i (sub1 len)]) (loop l len (add1 i) '() 0)))
(zero-subsets words)
| 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")
}
|
Write a version of this REXX function in C with identical 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
| #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 an equivalent C version of this REXX code. |
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
| #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 the given REXX code snippet into C# 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
| 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#. |
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
| 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);
}
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the REXX version. |
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
| #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 REXX snippet without changing its computational steps. |
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
| #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;
}
|
Rewrite the snippet below in Java so it works the same as the original REXX code. |
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
| 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 following code from REXX to Java with equivalent syntax 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
| 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);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.