Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same algorithm in C++ as shown in this Tcl implementation.
package require sha1 puts [sha1::sha1 "Rosetta Code"]
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Generate an equivalent C++ version of this Tcl code.
package require sha1 puts [sha1::sha1 "Rosetta Code"]
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Transform the following Tcl implementation into Python, maintaining the same output and logic.
package require sha1 puts [sha1::sha1 "Rosetta Code"]
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Change the programming language of this snippet from Tcl to Python without modifying what it does.
package require sha1 puts [sha1::sha1 "Rosetta Code"]
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Write the same algorithm in Go as shown in this Tcl implementation.
package require sha1 puts [sha1::sha1 "Rosetta Code"]
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
Ensure the translated Go code behaves exactly like the original Tcl snippet.
package require sha1 puts [sha1::sha1 "Rosetta Code"]
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
Rewrite the snippet below in PHP so it works the same as the original Rust code.
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Change the following Rust code into PHP without altering its purpose.
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Maintain the same structure and functionality when rewriting this code in PHP.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Produce a language-to-language conversion: from Ada to PHP, same semantics.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert the following code from Arturo to PHP, ensuring the logic remains intact.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Please provide an equivalent version of this Arturo code in PHP.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Keep all operations the same but rewrite the snippet in PHP.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Please provide an equivalent version of this AutoHotKey code in PHP.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert this BBC_Basic snippet to PHP and keep its semantics consistent.
PRINT FNsha1("Rosetta Code") END DEF FNsha1(message$) LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i% CALG_SHA1 = &8004 CRYPT_VERIFYCONTEXT = &F0000000 HP_HASHVAL = 2 PROV_RSA_FULL = 1 buflen% = 64 DIM buffer% LOCAL buflen%-1 SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Keep all operations the same but rewrite the snippet in PHP.
PRINT FNsha1("Rosetta Code") END DEF FNsha1(message$) LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i% CALG_SHA1 = &8004 CRYPT_VERIFYCONTEXT = &F0000000 HP_HASHVAL = 2 PROV_RSA_FULL = 1 buflen% = 64 DIM buffer% LOCAL buflen%-1 SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert this Common_Lisp snippet to PHP and keep its semantics consistent.
(defun sha1-hash (data) (let ((sha1 (ironclad:make-digest 'ironclad:sha1)) (bin-data (ironclad:ascii-string-to-byte-array data))) (ironclad:update-digest sha1 bin-data) (ironclad:byte-array-to-hex-string (ironclad:produce-digest sha1))))
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Generate an equivalent PHP version of this Common_Lisp code.
(defun sha1-hash (data) (let ((sha1 (ironclad:make-digest 'ironclad:sha1)) (bin-data (ironclad:ascii-string-to-byte-array data))) (ironclad:update-digest sha1 bin-data) (ironclad:byte-array-to-hex-string (ironclad:produce-digest sha1))))
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Port the provided D code into PHP while preserving the original functionality.
void main() { import std.stdio, std.digest.sha; writefln("%-(%02x%)", "Ars longa, vita brevis".sha1Of); }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert this D snippet to PHP and keep its semantics consistent.
void main() { import std.stdio, std.digest.sha; writefln("%-(%02x%)", "Ars longa, vita brevis".sha1Of); }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Change the following Delphi code into PHP without altering its purpose.
program Sha_1; uses System.SysUtils, DCPsha1; function SHA1(const Str: string): string; var HashDigest: array of byte; d: Byte; begin Result := ''; with TDCP_sha1.Create(nil) do begin Init; UpdateStr(Str); SetLength(HashDigest, GetHashSize div 8); final(HashDigest[0]); for d in HashDigest do Result := Result + d.ToHexString(2); Free; end; end; begin Writeln(SHA1('Rosetta Code')); readln; end.
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Please provide an equivalent version of this Delphi code in PHP.
program Sha_1; uses System.SysUtils, DCPsha1; function SHA1(const Str: string): string; var HashDigest: array of byte; d: Byte; begin Result := ''; with TDCP_sha1.Create(nil) do begin Init; UpdateStr(Str); SetLength(HashDigest, GetHashSize div 8); final(HashDigest[0]); for d in HashDigest do Result := Result + d.ToHexString(2); Free; end; end; begin Writeln(SHA1('Rosetta Code')); readln; end.
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Change the programming language of this snippet from Elixir to PHP without modifying what it does.
iex(1)> :crypto.hash(:sha, "A string") <<110, 185, 174, 8, 151, 66, 9, 104, 174, 225, 10, 43, 9, 92, 82, 190, 197, 150, 224, 92>>
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert the following code from Elixir to PHP, ensuring the logic remains intact.
iex(1)> :crypto.hash(:sha, "A string") <<110, 185, 174, 8, 151, 66, 9, 104, 174, 225, 10, 43, 9, 92, 82, 190, 197, 150, 224, 92>>
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Translate this program into PHP but keep the logic exactly as in F#.
let n = System.Security.Cryptography.SHA1.Create() Array.iter (printf "%x ") (n.ComputeHash "Rosetta Code"B)
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Change the programming language of this snippet from F# to PHP without modifying what it does.
let n = System.Security.Cryptography.SHA1.Create() Array.iter (printf "%x ") (n.ComputeHash "Rosetta Code"B)
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Please provide an equivalent version of this Fortran code in PHP.
module sha1_mod use kernel32 use advapi32 implicit none integer, parameter :: SHA1LEN = 20 contains subroutine sha1hash(name, hash, dwStatus, filesize) implicit none character(*) :: name integer, parameter :: BUFLEN = 32768 integer(HANDLE) :: hFile, hProv, hHash integer(DWORD) :: dwStatus, nRead integer(BOOL) :: status integer(BYTE) :: buffer(BUFLEN) integer(BYTE) :: hash(SHA1LEN) integer(UINT64) :: filesize dwStatus = 0 filesize = 0 hFile = CreateFile(trim(name) // char(0), GENERIC_READ, FILE_SHARE_READ, NULL, & OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL) if (hFile == INVALID_HANDLE_VALUE) then dwStatus = GetLastError() print *, "CreateFile failed." return end if if (CryptAcquireContext(hProv, NULL, NULL, PROV_RSA_FULL, & CRYPT_VERIFYCONTEXT) == FALSE) then dwStatus = GetLastError() print *, "CryptAcquireContext failed." goto 3 end if if (CryptCreateHash(hProv, CALG_SHA1, 0_ULONG_PTR, 0_DWORD, hHash) == FALSE) then dwStatus = GetLastError() print *, "CryptCreateHash failed." go to 2 end if do status = ReadFile(hFile, loc(buffer), BUFLEN, nRead, NULL) if (status == FALSE .or. nRead == 0) exit filesize = filesize + nRead if (CryptHashData(hHash, buffer, nRead, 0) == FALSE) then dwStatus = GetLastError() print *, "CryptHashData failed." go to 1 end if end do if (status == FALSE) then dwStatus = GetLastError() print *, "ReadFile failed." go to 1 end if nRead = SHA1LEN if (CryptGetHashParam(hHash, HP_HASHVAL, hash, nRead, 0) == FALSE) then dwStatus = GetLastError() print *, "CryptGetHashParam failed.", status, nRead, dwStatus end if 1 status = CryptDestroyHash(hHash) 2 status = CryptReleaseContext(hProv, 0) 3 status = CloseHandle(hFile) end subroutine end module program sha1 use sha1_mod implicit none integer :: n, m, i, j character(:), allocatable :: name integer(DWORD) :: dwStatus integer(BYTE) :: hash(SHA1LEN) integer(UINT64) :: filesize n = command_argument_count() do i = 1, n call get_command_argument(i, length=m) allocate(character(m) :: name) call get_command_argument(i, name) call sha1hash(name, hash, dwStatus, filesize) if (dwStatus == 0) then do j = 1, SHA1LEN write(*, "(Z2.2)", advance="NO") hash(j) end do write(*, "(' ',A,' (',G0,' bytes)')") name, filesize end if deallocate(name) end do end program
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Port the following code from Fortran to PHP with equivalent syntax and logic.
module sha1_mod use kernel32 use advapi32 implicit none integer, parameter :: SHA1LEN = 20 contains subroutine sha1hash(name, hash, dwStatus, filesize) implicit none character(*) :: name integer, parameter :: BUFLEN = 32768 integer(HANDLE) :: hFile, hProv, hHash integer(DWORD) :: dwStatus, nRead integer(BOOL) :: status integer(BYTE) :: buffer(BUFLEN) integer(BYTE) :: hash(SHA1LEN) integer(UINT64) :: filesize dwStatus = 0 filesize = 0 hFile = CreateFile(trim(name) // char(0), GENERIC_READ, FILE_SHARE_READ, NULL, & OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL) if (hFile == INVALID_HANDLE_VALUE) then dwStatus = GetLastError() print *, "CreateFile failed." return end if if (CryptAcquireContext(hProv, NULL, NULL, PROV_RSA_FULL, & CRYPT_VERIFYCONTEXT) == FALSE) then dwStatus = GetLastError() print *, "CryptAcquireContext failed." goto 3 end if if (CryptCreateHash(hProv, CALG_SHA1, 0_ULONG_PTR, 0_DWORD, hHash) == FALSE) then dwStatus = GetLastError() print *, "CryptCreateHash failed." go to 2 end if do status = ReadFile(hFile, loc(buffer), BUFLEN, nRead, NULL) if (status == FALSE .or. nRead == 0) exit filesize = filesize + nRead if (CryptHashData(hHash, buffer, nRead, 0) == FALSE) then dwStatus = GetLastError() print *, "CryptHashData failed." go to 1 end if end do if (status == FALSE) then dwStatus = GetLastError() print *, "ReadFile failed." go to 1 end if nRead = SHA1LEN if (CryptGetHashParam(hHash, HP_HASHVAL, hash, nRead, 0) == FALSE) then dwStatus = GetLastError() print *, "CryptGetHashParam failed.", status, nRead, dwStatus end if 1 status = CryptDestroyHash(hHash) 2 status = CryptReleaseContext(hProv, 0) 3 status = CloseHandle(hFile) end subroutine end module program sha1 use sha1_mod implicit none integer :: n, m, i, j character(:), allocatable :: name integer(DWORD) :: dwStatus integer(BYTE) :: hash(SHA1LEN) integer(UINT64) :: filesize n = command_argument_count() do i = 1, n call get_command_argument(i, length=m) allocate(character(m) :: name) call get_command_argument(i, name) call sha1hash(name, hash, dwStatus, filesize) if (dwStatus == 0) then do j = 1, SHA1LEN write(*, "(Z2.2)", advance="NO") hash(j) end do write(*, "(' ',A,' (',G0,' bytes)')") name, filesize end if deallocate(name) end do end program
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert this Haskell snippet to PHP and keep its semantics consistent.
module Digestor where import Data.Digest.Pure.SHA import qualified Data.ByteString.Lazy as B convertString :: String -> B.ByteString convertString phrase = B.pack $ map ( fromIntegral . fromEnum ) phrase convertToSHA1 :: String -> String convertToSHA1 word = showDigest $ sha1 $ convertString word main = do putStr "Rosetta Code SHA1-codiert: " putStrLn $ convertToSHA1 "Rosetta Code"
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Write the same algorithm in PHP as shown in this Haskell implementation.
module Digestor where import Data.Digest.Pure.SHA import qualified Data.ByteString.Lazy as B convertString :: String -> B.ByteString convertString phrase = B.pack $ map ( fromIntegral . fromEnum ) phrase convertToSHA1 :: String -> String convertToSHA1 word = showDigest $ sha1 $ convertString word main = do putStr "Rosetta Code SHA1-codiert: " putStrLn $ convertToSHA1 "Rosetta Code"
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Change the following J code into PHP without altering its purpose.
require '~addons/ide/qt/qt.ijs' getsha1=: 'sha1'&gethash_jqtide_ getsha1 'Rosetta Code' 48c98f7e5a6e736d790ab740dfc3f51a61abe2b5
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Port the following code from J to PHP with equivalent syntax and logic.
require '~addons/ide/qt/qt.ijs' getsha1=: 'sha1'&gethash_jqtide_ getsha1 'Rosetta Code' 48c98f7e5a6e736d790ab740dfc3f51a61abe2b5
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Preserve the algorithm and functionality while converting the code from Julia to PHP.
using Nettle testdict = Dict("abc" => "a9993e364706816aba3e25717850c26c9cd0d89d", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" => "84983e441c3bd26ebaae4aa1f95129e5e54670f1", "a" ^ 1_000_000 => "34aa973cd4c4daa4f61eeb2bdbad27316534016f",) for (text, expect) in testdict digest = hexdigest("sha1", text) if length(text) > 50 text = text[1:50] * "..." end println(" end
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert the following code from Julia to PHP, ensuring the logic remains intact.
using Nettle testdict = Dict("abc" => "a9993e364706816aba3e25717850c26c9cd0d89d", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" => "84983e441c3bd26ebaae4aa1f95129e5e54670f1", "a" ^ 1_000_000 => "34aa973cd4c4daa4f61eeb2bdbad27316534016f",) for (text, expect) in testdict digest = hexdigest("sha1", text) if length(text) > 50 text = text[1:50] * "..." end println(" end
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Port the provided Lua code into PHP while preserving the original functionality.
#!/usr/bin/lua local sha1 = require "sha1" for i, str in ipairs{"Rosetta code", "Rosetta Code"} do print(string.format("SHA-1(%q) = %s", str, sha1(str))) end
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Write a version of this Lua function in PHP with identical behavior.
#!/usr/bin/lua local sha1 = require "sha1" for i, str in ipairs{"Rosetta code", "Rosetta Code"} do print(string.format("SHA-1(%q) = %s", str, sha1(str))) end
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Port the provided Nim code into PHP while preserving the original functionality.
import std/sha1 echo secureHash("Rosetta Code")
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Please provide an equivalent version of this Nim code in PHP.
import std/sha1 echo secureHash("Rosetta Code")
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Write the same algorithm in PHP as shown in this OCaml implementation.
$ ocaml -I +sha sha1.cma Objective Caml version 3.12.1 # Sha1.to_hex (Sha1.string "Rosetta Code") ;; - : string = "48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Rewrite the snippet below in PHP so it works the same as the original OCaml code.
$ ocaml -I +sha sha1.cma Objective Caml version 3.12.1 # Sha1.to_hex (Sha1.string "Rosetta Code") ;; - : string = "48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Maintain the same structure and functionality when rewriting this code in PHP.
program RosettaSha1; uses sha1; var d: TSHA1Digest; begin d:=SHA1String('Rosetta Code'); WriteLn(SHA1Print(d)); end.
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert the following code from Pascal to PHP, ensuring the logic remains intact.
program RosettaSha1; uses sha1; var d: TSHA1Digest; begin d:=SHA1String('Rosetta Code'); WriteLn(SHA1Print(d)); end.
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Maintain the same structure and functionality when rewriting this code in PHP.
use Digest::SHA qw(sha1_hex); print sha1_hex('Rosetta Code'), "\n";
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Perl version.
use Digest::SHA qw(sha1_hex); print sha1_hex('Rosetta Code'), "\n";
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Write a version of this PowerShell function in PHP with identical behavior.
Function Calculate-SHA1( $String ){ $Enc = [system.Text.Encoding]::UTF8 $Data = $enc.GetBytes($String) $Sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider $Result = $sha.ComputeHash($Data) [System.Convert]::ToBase64String($Result) }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert the following code from PowerShell to PHP, ensuring the logic remains intact.
Function Calculate-SHA1( $String ){ $Enc = [system.Text.Encoding]::UTF8 $Data = $enc.GetBytes($String) $Sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider $Result = $sha.ComputeHash($Data) [System.Convert]::ToBase64String($Result) }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Write the same code in PHP as shown below in Racket.
#lang racket (require file/sha1) (sha1 (open-input-string "Rosetta Code"))
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Ensure the translated PHP code behaves exactly like the original Racket snippet.
#lang racket (require file/sha1) (sha1 (open-input-string "Rosetta Code"))
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Write a version of this REXX function in PHP with identical behavior.
options replace format comments java crossref savelog symbols binary import java.security.MessageDigest SHA1('Rosetta Code', '48c98f7e5a6e736d790ab740dfc3f51a61abe2b5') return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method SHA1(messageText, verifyCheck) public static algorithm = 'SHA-1' digestSum = getDigest(messageText, algorithm) say '<Message>'messageText'</Message>' say Rexx('<'algorithm'>').right(12) || digestSum'</'algorithm'>' say Rexx('<Verify>').right(12) || verifyCheck'</Verify>' if digestSum == verifyCheck then say algorithm 'Confirmed' else say algorithm 'Failed' return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx algorithm = algorithm.upper encoding = encoding.upper message = String(messageText) messageBytes = byte[] digestBytes = byte[] digestSum = Rexx '' do messageBytes = message.getBytes(encoding) md = MessageDigest.getInstance(algorithm) md.update(messageBytes) digestBytes = md.digest loop b_ = 0 to digestBytes.length - 1 bb = Rexx(digestBytes[b_]).d2x(2) if lowercase then digestSum = digestSum || bb.lower else digestSum = digestSum || bb.upper end b_ catch ex = Exception ex.printStackTrace end return digestSum
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Keep all operations the same but rewrite the snippet in PHP.
options replace format comments java crossref savelog symbols binary import java.security.MessageDigest SHA1('Rosetta Code', '48c98f7e5a6e736d790ab740dfc3f51a61abe2b5') return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method SHA1(messageText, verifyCheck) public static algorithm = 'SHA-1' digestSum = getDigest(messageText, algorithm) say '<Message>'messageText'</Message>' say Rexx('<'algorithm'>').right(12) || digestSum'</'algorithm'>' say Rexx('<Verify>').right(12) || verifyCheck'</Verify>' if digestSum == verifyCheck then say algorithm 'Confirmed' else say algorithm 'Failed' return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx algorithm = algorithm.upper encoding = encoding.upper message = String(messageText) messageBytes = byte[] digestBytes = byte[] digestSum = Rexx '' do messageBytes = message.getBytes(encoding) md = MessageDigest.getInstance(algorithm) md.update(messageBytes) digestBytes = md.digest loop b_ = 0 to digestBytes.length - 1 bb = Rexx(digestBytes[b_]).d2x(2) if lowercase then digestSum = digestSum || bb.lower else digestSum = digestSum || bb.upper end b_ catch ex = Exception ex.printStackTrace end return digestSum
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Produce a functionally identical PHP code for the snippet given in Ruby.
require "openssl" puts OpenSSL::Digest.new("sha1").update("Rosetta Code")
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Generate an equivalent PHP version of this Ruby code.
require "openssl" puts OpenSSL::Digest.new("sha1").update("Rosetta Code")
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Produce a language-to-language conversion: from Scala to PHP, same semantics.
import java.security.MessageDigest fun main(args: Array<String>) { val text = "Rosetta Code" val bytes = text.toByteArray() val md = MessageDigest.getInstance("SHA-1") val digest = md.digest(bytes) for (byte in digest) print("%02x".format(byte)) println() }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Generate a PHP translation of this Scala snippet without changing its computational steps.
import java.security.MessageDigest fun main(args: Array<String>) { val text = "Rosetta Code" val bytes = text.toByteArray() val md = MessageDigest.getInstance("SHA-1") val digest = md.digest(bytes) for (byte in digest) print("%02x".format(byte)) println() }
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Maintain the same structure and functionality when rewriting this code in PHP.
package require sha1 puts [sha1::sha1 "Rosetta Code"]
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Port the provided Tcl code into PHP while preserving the original functionality.
package require sha1 puts [sha1::sha1 "Rosetta Code"]
<?php $string = 'Rosetta Code'; echo sha1( $string ), "\n"; ?>
Convert this C snippet to Rust and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
Write a version of this C++ function in Rust with identical behavior.
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
Translate this program into Rust but keep the logic exactly as in C++.
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
Write the same algorithm in Rust as shown in this C# implementation.
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
Change the programming language of this snippet from C# to Rust without modifying what it does.
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
Rewrite this program in Rust while keeping its functionality equivalent to the Go version.
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
Maintain the same structure and functionality when rewriting this code in Rust.
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
Rewrite the snippet below in Python so it works the same as the original Rust code.
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Port the provided Rust code into Python while preserving the original functionality.
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Write the same algorithm in Rust as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
use sha1::Sha1; fn main() { let mut hash_msg = Sha1::new(); hash_msg.update(b"Rosetta Code"); println!("{}", hash_msg.digest().to_string()); }
Write a version of this Ada function in C# with identical behavior.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
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 Ada code.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
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 Ada, keeping it the same logically?
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
#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 Ada.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
#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 provided Ada code into C++ while preserving the original functionality.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
#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 functionally identical C++ code for the snippet given in Ada.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
#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 Go.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
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 Ada to Go without modifying what it does.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
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") }
Keep all operations the same but rewrite the snippet in Java.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
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 code in Java as shown below in Ada.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
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); } }
Transform the following Ada implementation into Python, maintaining the same output and logic.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
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
Ensure the translated Python code behaves exactly like the original Ada snippet.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure SubsetSum is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; type Point is record str : Unbounded_String; num : Integer; end record; type Points is array (Natural range <>) of Point; type Indices is array (Natural range <>) of Natural; procedure Print (data : Points; list : Indices; len : Positive) is begin Put (len'Img & ":"); for i in 0..len-1 loop Put (" "& To_String(data(list(i)).str)); end loop; New_Line; end Print; function Check (data : Points; list : Indices; len : Positive) return Boolean is sum : Integer := 0; begin for i in 0..len-1 loop sum := sum + data(list(i)).num; end loop; return sum = 0; end Check; procedure Next (list : in out Indices; n, r : Positive ) is begin for i in reverse 0..r-1 loop if list(i)/=i+n-r then list(i):=list(i)+1; for j in i+1..r-1 loop list(j):=list(j-1)+1; end loop; exit; end if; end loop; end Next; data : constant Points := ((+"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)); list, last : Indices (data'Range); begin for len in 2..data'Length loop for i in 0..len-1 loop list(i):=i; end loop; loop if Check(data, list, len) then Print(data, list, len); exit; end if; last := list; Next(list, data'Length, len); exit when last=list; end loop; end loop; end SubsetSum;
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 D implementation into C, maintaining the same output and logic.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
#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; }
Keep all operations the same but rewrite the snippet in C.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
#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 D block to C#, preserving its control flow and logic.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
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 D snippet to C# and keep its semantics consistent.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
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); } } }
Please provide an equivalent version of this D code in C++.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
#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; }
Please provide an equivalent version of this D code in C++.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
#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 D code snippet into Java without altering its behavior.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
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 D block to Python, preserving its control flow and logic.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
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
Produce a language-to-language conversion: from D to Python, same semantics.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
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 D block to Go, preserving its control flow and logic.
void main() { import std.stdio, std.algorithm, std.typecons, combinations3; alias P = tuple; immutable items = [ P("alliance", -624), P("archbishop", -915), P("balm", 397), P("bonnet", 452), P("brute", 870), P("centipede", -658), P("cobol", 362), P("covariate", 590), P("departure", 952), P("deploy", 44), P("diophantine", 645), P("efferent", 54), P("elysee", -326), P("eradicate", 376), P("escritoire", 856), P("exorcism", -983), P("fiat", 170), P("filmy", -874), P("flatworm", 503), P("gestapo", 915), P("infra", -847), P("isis", -982), P("lindholm", 999), P("markham", 475), P("mincemeat", -880), P("moresby", 756), P("mycenae", 183), P("plugging", -266), P("smokescreen", 423), P("speakeasy", -745), P("vein", 813)]; foreach (immutable n; 1 .. items.length) foreach (const comb; items.combinations(n)) if (comb.map!q{ a[1] }.sum == 0) return writefln("A subset of length %d: %-(%s, %)", n, comb.map!q{ a[0] }); "No solution found.".writeln; }
package main import "fmt" type ww struct { word string weight int } var input = []*ww{ {"alliance", -624}, {"archbishop", -915}, {"balm", 397}, {"bonnet", 452}, {"brute", 870}, {"centipede", -658}, {"cobol", 362}, {"covariate", 590}, {"departure", 952}, {"deploy", 44}, {"diophantine", 645}, {"efferent", 54}, {"elysee", -326}, {"eradicate", 376}, {"escritoire", 856}, {"exorcism", -983}, {"fiat", 170}, {"filmy", -874}, {"flatworm", 503}, {"gestapo", 915}, {"infra", -847}, {"isis", -982}, {"lindholm", 999}, {"markham", 475}, {"mincemeat", -880}, {"moresby", 756}, {"mycenae", 183}, {"plugging", -266}, {"smokescreen", 423}, {"speakeasy", -745}, {"vein", 813}, } type sss struct { subset []*ww sum int } func main() { ps := []sss{{nil, 0}} for _, i := range input { pl := len(ps) for j := 0; j < pl; j++ { subset := append([]*ww{i}, ps[j].subset...) sum := i.weight + ps[j].sum if sum == 0 { fmt.Println("this subset sums to 0:") for _, i := range subset { fmt.Println(*i) } return } ps = append(ps, sss{subset, sum}) } } fmt.Println("no subset sums to 0") }
Convert this Haskell block to C, preserving its control flow and logic.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
#include <stdio.h> #include <stdlib.h> typedef struct { char *word; int weight; } item_t; item_t items[] = { {"alliance", -624}, {"archbishop", -915}, {"balm", 397}, {"bonnet", 452}, {"brute", 870}, {"centipede", -658}, {"cobol", 362}, {"covariate", 590}, {"departure", 952}, {"deploy", 44}, {"diophantine", 645}, {"efferent", 54}, {"elysee", -326}, {"eradicate", 376}, {"escritoire", 856}, {"exorcism", -983}, {"fiat", 170}, {"filmy", -874}, {"flatworm", 503}, {"gestapo", 915}, {"infra", -847}, {"isis", -982}, {"lindholm", 999}, {"markham", 475}, {"mincemeat", -880}, {"moresby", 756}, {"mycenae", 183}, {"plugging", -266}, {"smokescreen", 423}, {"speakeasy", -745}, {"vein", 813}, }; int n = sizeof (items) / sizeof (item_t); int *set; void subsum (int i, int weight) { int j; if (i && !weight) { for (j = 0; j < i; j++) { item_t item = items[set[j]]; printf("%s%s", j ? " " : "", items[set[j]].word); } printf("\n"); } for (j = i ? set[i - 1] + 1: 0; j < n; j++) { set[i] = j; subsum(i + 1, weight + items[j].weight); } } int main () { set = malloc(n * sizeof (int)); subsum(0, 0); return 0; }
Generate a C translation of this Haskell snippet without changing its computational steps.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
#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 Haskell.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
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 the snippet below in C++ so it works the same as the original Haskell code.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
#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 Haskell code snippet into C++ without altering its behavior.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
#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 Haskell code into Java while preserving the original functionality.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
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); } }
Can you help me rewrite this code in Java instead of Haskell, keeping it the same logically?
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
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); } }
Transform the following Haskell implementation into Python, maintaining the same output and logic.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
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.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
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 Haskell snippet to Go and keep its semantics consistent.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
package main import "fmt" type ww struct { word string weight int } var input = []*ww{ {"alliance", -624}, {"archbishop", -915}, {"balm", 397}, {"bonnet", 452}, {"brute", 870}, {"centipede", -658}, {"cobol", 362}, {"covariate", 590}, {"departure", 952}, {"deploy", 44}, {"diophantine", 645}, {"efferent", 54}, {"elysee", -326}, {"eradicate", 376}, {"escritoire", 856}, {"exorcism", -983}, {"fiat", 170}, {"filmy", -874}, {"flatworm", 503}, {"gestapo", 915}, {"infra", -847}, {"isis", -982}, {"lindholm", 999}, {"markham", 475}, {"mincemeat", -880}, {"moresby", 756}, {"mycenae", 183}, {"plugging", -266}, {"smokescreen", 423}, {"speakeasy", -745}, {"vein", 813}, } type sss struct { subset []*ww sum int } func main() { ps := []sss{{nil, 0}} for _, i := range input { pl := len(ps) for j := 0; j < pl; j++ { subset := append([]*ww{i}, ps[j].subset...) sum := i.weight + ps[j].sum if sum == 0 { fmt.Println("this subset sums to 0:") for _, i := range subset { fmt.Println(*i) } return } ps = append(ps, sss{subset, sum}) } } fmt.Println("no subset sums to 0") }
Translate the given Haskell code snippet into Go without altering its behavior.
combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations _ [] = [] combinations k (x:xs) = map (x:) (combinations (k - 1) xs) ++ combinations k xs data W = W { word :: String, weight :: Int } solver :: [W] -> [[W]] solver it = [comb | n <- [1 .. length it], comb <- combinations n it, sum (map weight comb) == 0] items = [W "alliance" (-624), W "archbishop" (-915), W "balm" 397, W "bonnet" 452, W "brute" 870, W "centipede" (-658), W "cobol" 362, W "covariate" 590, W "departure" 952, W "deploy" 44, W "diophantine" 645, W "efferent" 54, W "elysee" (-326), W "eradicate" 376, W "escritoire" 856, W "exorcism" (-983), W "fiat" 170, W "filmy" (-874), W "flatworm" 503, W "gestapo" 915, W "infra" (-847), W "isis" (-982), W "lindholm" 999, W "markham" 475, W "mincemeat" (-880), W "moresby" 756, W "mycenae" 183, W "plugging" (-266), W "smokescreen" 423, W "speakeasy" (-745), W "vein" 813] main = print $ map word $ head $ solver items
package main import "fmt" type ww struct { word string weight int } var input = []*ww{ {"alliance", -624}, {"archbishop", -915}, {"balm", 397}, {"bonnet", 452}, {"brute", 870}, {"centipede", -658}, {"cobol", 362}, {"covariate", 590}, {"departure", 952}, {"deploy", 44}, {"diophantine", 645}, {"efferent", 54}, {"elysee", -326}, {"eradicate", 376}, {"escritoire", 856}, {"exorcism", -983}, {"fiat", 170}, {"filmy", -874}, {"flatworm", 503}, {"gestapo", 915}, {"infra", -847}, {"isis", -982}, {"lindholm", 999}, {"markham", 475}, {"mincemeat", -880}, {"moresby", 756}, {"mycenae", 183}, {"plugging", -266}, {"smokescreen", 423}, {"speakeasy", -745}, {"vein", 813}, } type sss struct { subset []*ww sum int } func main() { ps := []sss{{nil, 0}} for _, i := range input { pl := len(ps) for j := 0; j < pl; j++ { subset := append([]*ww{i}, ps[j].subset...) sum := i.weight + ps[j].sum if sum == 0 { fmt.Println("this subset sums to 0:") for _, i := range subset { fmt.Println(*i) } return } ps = append(ps, sss{subset, sum}) } } fmt.Println("no subset sums to 0") }
Convert this Icon block to C, preserving its control flow 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
#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; }