Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the provided Julia code into C# while preserving the original functionality. | """ Rosetta code task rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity """
using Dates
using DataFrames
using HTTP
using JSON3
""" Get listing of all tasks and draft tasks with authors and dates created, with the counts as popularity """
function rosetta_code_language_example_counts(verbose = false)
URL = "https://rosettacode.org/w/api.php?"
LANGPARAMS = ["action" => "query", "format" => "json", "formatversion" => "2", "generator" => "categorymembers",
"gcmtitle" => "Category:Programming_Languages", "gcmlimit" => "500", "rawcontinue" => "", "prop" => "title"]
queryparams = copy(LANGPARAMS)
df = empty!(DataFrame([[""], [0]], ["ProgrammingLanguage", "ExampleCount"]))
while true
resp = HTTP.get(URL * join(map(p -> p[1] * (p[2] == "" ? "" : ("=" * p[2])), queryparams), "&"))
json = JSON3.read(String(resp.body))
pages = json.query.pages
reg = r"The following \d+ pages are in this category, out of ([\d\,]+) total"
for p in pages
lang = replace(p.title, "Category:" => "")
langpage = String(HTTP.get("https://rosettacode.org/w/index.php?curid=" * string(p.pageid)).body)
if !((m = match(reg, langpage)) isa Nothing)
push!(df, [lang, parse(Int, replace(m.captures[1], "," => ""))])
verbose && println("Language: $lang, count: ", m.captures[1])
end
end
!haskey(json, "query-continue") && break
queryparams = vcat(LANGPARAMS, "gcmcontinue" => json["query-continue"]["categorymembers"]["gcmcontinue"])
end
return sort!(df, :ExampleCount, rev = true)
end
println("Top 20 Programming Languages on Rosetta Code by Number of Examples, As of: ", now())
println(rosetta_code_language_example_counts()[begin:begin+19, :])
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Julia version. | """ Rosetta code task rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity """
using Dates
using DataFrames
using HTTP
using JSON3
""" Get listing of all tasks and draft tasks with authors and dates created, with the counts as popularity """
function rosetta_code_language_example_counts(verbose = false)
URL = "https://rosettacode.org/w/api.php?"
LANGPARAMS = ["action" => "query", "format" => "json", "formatversion" => "2", "generator" => "categorymembers",
"gcmtitle" => "Category:Programming_Languages", "gcmlimit" => "500", "rawcontinue" => "", "prop" => "title"]
queryparams = copy(LANGPARAMS)
df = empty!(DataFrame([[""], [0]], ["ProgrammingLanguage", "ExampleCount"]))
while true
resp = HTTP.get(URL * join(map(p -> p[1] * (p[2] == "" ? "" : ("=" * p[2])), queryparams), "&"))
json = JSON3.read(String(resp.body))
pages = json.query.pages
reg = r"The following \d+ pages are in this category, out of ([\d\,]+) total"
for p in pages
lang = replace(p.title, "Category:" => "")
langpage = String(HTTP.get("https://rosettacode.org/w/index.php?curid=" * string(p.pageid)).body)
if !((m = match(reg, langpage)) isa Nothing)
push!(df, [lang, parse(Int, replace(m.captures[1], "," => ""))])
verbose && println("Language: $lang, count: ", m.captures[1])
end
end
!haskey(json, "query-continue") && break
queryparams = vcat(LANGPARAMS, "gcmcontinue" => json["query-continue"]["categorymembers"]["gcmcontinue"])
end
return sort!(df, :ExampleCount, rev = true)
end
println("Top 20 Programming Languages on Rosetta Code by Number of Examples, As of: ", now())
println(rosetta_code_language_example_counts()[begin:begin+19, :])
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Ensure the translated Java code behaves exactly like the original Julia snippet. | """ Rosetta code task rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity """
using Dates
using DataFrames
using HTTP
using JSON3
""" Get listing of all tasks and draft tasks with authors and dates created, with the counts as popularity """
function rosetta_code_language_example_counts(verbose = false)
URL = "https://rosettacode.org/w/api.php?"
LANGPARAMS = ["action" => "query", "format" => "json", "formatversion" => "2", "generator" => "categorymembers",
"gcmtitle" => "Category:Programming_Languages", "gcmlimit" => "500", "rawcontinue" => "", "prop" => "title"]
queryparams = copy(LANGPARAMS)
df = empty!(DataFrame([[""], [0]], ["ProgrammingLanguage", "ExampleCount"]))
while true
resp = HTTP.get(URL * join(map(p -> p[1] * (p[2] == "" ? "" : ("=" * p[2])), queryparams), "&"))
json = JSON3.read(String(resp.body))
pages = json.query.pages
reg = r"The following \d+ pages are in this category, out of ([\d\,]+) total"
for p in pages
lang = replace(p.title, "Category:" => "")
langpage = String(HTTP.get("https://rosettacode.org/w/index.php?curid=" * string(p.pageid)).body)
if !((m = match(reg, langpage)) isa Nothing)
push!(df, [lang, parse(Int, replace(m.captures[1], "," => ""))])
verbose && println("Language: $lang, count: ", m.captures[1])
end
end
!haskey(json, "query-continue") && break
queryparams = vcat(LANGPARAMS, "gcmcontinue" => json["query-continue"]["categorymembers"]["gcmcontinue"])
end
return sort!(df, :ExampleCount, rev = true)
end
println("Top 20 Programming Languages on Rosetta Code by Number of Examples, As of: ", now())
println(rosetta_code_language_example_counts()[begin:begin+19, :])
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Julia version. | """ Rosetta code task rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity """
using Dates
using DataFrames
using HTTP
using JSON3
""" Get listing of all tasks and draft tasks with authors and dates created, with the counts as popularity """
function rosetta_code_language_example_counts(verbose = false)
URL = "https://rosettacode.org/w/api.php?"
LANGPARAMS = ["action" => "query", "format" => "json", "formatversion" => "2", "generator" => "categorymembers",
"gcmtitle" => "Category:Programming_Languages", "gcmlimit" => "500", "rawcontinue" => "", "prop" => "title"]
queryparams = copy(LANGPARAMS)
df = empty!(DataFrame([[""], [0]], ["ProgrammingLanguage", "ExampleCount"]))
while true
resp = HTTP.get(URL * join(map(p -> p[1] * (p[2] == "" ? "" : ("=" * p[2])), queryparams), "&"))
json = JSON3.read(String(resp.body))
pages = json.query.pages
reg = r"The following \d+ pages are in this category, out of ([\d\,]+) total"
for p in pages
lang = replace(p.title, "Category:" => "")
langpage = String(HTTP.get("https://rosettacode.org/w/index.php?curid=" * string(p.pageid)).body)
if !((m = match(reg, langpage)) isa Nothing)
push!(df, [lang, parse(Int, replace(m.captures[1], "," => ""))])
verbose && println("Language: $lang, count: ", m.captures[1])
end
end
!haskey(json, "query-continue") && break
queryparams = vcat(LANGPARAMS, "gcmcontinue" => json["query-continue"]["categorymembers"]["gcmcontinue"])
end
return sort!(df, :ExampleCount, rev = true)
end
println("Top 20 Programming Languages on Rosetta Code by Number of Examples, As of: ", now())
println(rosetta_code_language_example_counts()[begin:begin+19, :])
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Port the provided Julia code into VB while preserving the original functionality. | """ Rosetta code task rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity """
using Dates
using DataFrames
using HTTP
using JSON3
""" Get listing of all tasks and draft tasks with authors and dates created, with the counts as popularity """
function rosetta_code_language_example_counts(verbose = false)
URL = "https://rosettacode.org/w/api.php?"
LANGPARAMS = ["action" => "query", "format" => "json", "formatversion" => "2", "generator" => "categorymembers",
"gcmtitle" => "Category:Programming_Languages", "gcmlimit" => "500", "rawcontinue" => "", "prop" => "title"]
queryparams = copy(LANGPARAMS)
df = empty!(DataFrame([[""], [0]], ["ProgrammingLanguage", "ExampleCount"]))
while true
resp = HTTP.get(URL * join(map(p -> p[1] * (p[2] == "" ? "" : ("=" * p[2])), queryparams), "&"))
json = JSON3.read(String(resp.body))
pages = json.query.pages
reg = r"The following \d+ pages are in this category, out of ([\d\,]+) total"
for p in pages
lang = replace(p.title, "Category:" => "")
langpage = String(HTTP.get("https://rosettacode.org/w/index.php?curid=" * string(p.pageid)).body)
if !((m = match(reg, langpage)) isa Nothing)
push!(df, [lang, parse(Int, replace(m.captures[1], "," => ""))])
verbose && println("Language: $lang, count: ", m.captures[1])
end
end
!haskey(json, "query-continue") && break
queryparams = vcat(LANGPARAMS, "gcmcontinue" => json["query-continue"]["categorymembers"]["gcmcontinue"])
end
return sort!(df, :ExampleCount, rev = true)
end
println("Top 20 Programming Languages on Rosetta Code by Number of Examples, As of: ", now())
println(rosetta_code_language_example_counts()[begin:begin+19, :])
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Generate a Go translation of this Julia snippet without changing its computational steps. | """ Rosetta code task rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity """
using Dates
using DataFrames
using HTTP
using JSON3
""" Get listing of all tasks and draft tasks with authors and dates created, with the counts as popularity """
function rosetta_code_language_example_counts(verbose = false)
URL = "https://rosettacode.org/w/api.php?"
LANGPARAMS = ["action" => "query", "format" => "json", "formatversion" => "2", "generator" => "categorymembers",
"gcmtitle" => "Category:Programming_Languages", "gcmlimit" => "500", "rawcontinue" => "", "prop" => "title"]
queryparams = copy(LANGPARAMS)
df = empty!(DataFrame([[""], [0]], ["ProgrammingLanguage", "ExampleCount"]))
while true
resp = HTTP.get(URL * join(map(p -> p[1] * (p[2] == "" ? "" : ("=" * p[2])), queryparams), "&"))
json = JSON3.read(String(resp.body))
pages = json.query.pages
reg = r"The following \d+ pages are in this category, out of ([\d\,]+) total"
for p in pages
lang = replace(p.title, "Category:" => "")
langpage = String(HTTP.get("https://rosettacode.org/w/index.php?curid=" * string(p.pageid)).body)
if !((m = match(reg, langpage)) isa Nothing)
push!(df, [lang, parse(Int, replace(m.captures[1], "," => ""))])
verbose && println("Language: $lang, count: ", m.captures[1])
end
end
!haskey(json, "query-continue") && break
queryparams = vcat(LANGPARAMS, "gcmcontinue" => json["query-continue"]["categorymembers"]["gcmcontinue"])
end
return sort!(df, :ExampleCount, rev = true)
end
println("Top 20 Programming Languages on Rosetta Code by Number of Examples, As of: ", now())
println(rosetta_code_language_example_counts()[begin:begin+19, :])
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Generate an equivalent C version of this Mathematica code. | Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]];
Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}];
b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"],
"category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages;
For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], i]]
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Mathematica version. | Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]];
Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}];
b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"],
"category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages;
For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], i]]
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Write a version of this Mathematica function in C++ with identical behavior. | Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]];
Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}];
b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"],
"category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages;
For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], i]]
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Can you help me rewrite this code in Java instead of Mathematica, keeping it the same logically? | Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]];
Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}];
b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"],
"category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages;
For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], i]]
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]];
Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}];
b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"],
"category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages;
For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], i]]
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Convert this Mathematica block to VB, preserving its control flow and logic. | Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]];
Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}];
b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"],
"category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages;
For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], i]]
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Port the provided Mathematica code into Go while preserving the original functionality. | Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]];
Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}];
b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"],
"category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages;
For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], i]]
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Write a version of this Nim function in C with identical behavior. | import httpclient, json, re, strformat, strutils, algorithm
const
LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json"
CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
let regex = re"title=""Category:(.*?)"">.+?</a>.*\((.*) members\)"
type Rank = tuple[lang: string, count: int]
proc cmp(a, b: Rank): int =
result = cmp(b.count, a.count)
if result == 0: result = cmp(a.lang, b.lang)
proc add(langs: var seq[string]; fromJson: JsonNode) =
for entry in fromJson{"query", "categorymembers"}:
langs.add entry["title"].getStr.split("Category:")[1]
var client = newHttpClient()
var langs: seq[string]
var url = LangSite
while true:
let response = client.get(url)
if response.status != $Http200: break
let fromJson = response.body.parseJson()
langs.add fromJson
if "continue" notin fromJson: break
let cmcont = fromJson{"continue", "cmcontinue"}.getStr
let cont = fromJson{"continue", "continue"}.getStr
url = LangSite & fmt"&cmcontinue={cmcont}&continue={cont}"
var ranks: seq[Rank]
for line in client.getContent(CatSite).findAll(regex):
let lang = line.replacef(regex, "$1")
if lang in langs:
let count = parseInt(line.replacef(regex, "$2").replace(",", "").strip())
ranks.add (lang, count)
ranks.sort(cmp)
for i, rank in ranks:
echo &"{i + 1:3} {rank.count:4} - {rank.lang}"
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Change the programming language of this snippet from Nim to C# without modifying what it does. | import httpclient, json, re, strformat, strutils, algorithm
const
LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json"
CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
let regex = re"title=""Category:(.*?)"">.+?</a>.*\((.*) members\)"
type Rank = tuple[lang: string, count: int]
proc cmp(a, b: Rank): int =
result = cmp(b.count, a.count)
if result == 0: result = cmp(a.lang, b.lang)
proc add(langs: var seq[string]; fromJson: JsonNode) =
for entry in fromJson{"query", "categorymembers"}:
langs.add entry["title"].getStr.split("Category:")[1]
var client = newHttpClient()
var langs: seq[string]
var url = LangSite
while true:
let response = client.get(url)
if response.status != $Http200: break
let fromJson = response.body.parseJson()
langs.add fromJson
if "continue" notin fromJson: break
let cmcont = fromJson{"continue", "cmcontinue"}.getStr
let cont = fromJson{"continue", "continue"}.getStr
url = LangSite & fmt"&cmcontinue={cmcont}&continue={cont}"
var ranks: seq[Rank]
for line in client.getContent(CatSite).findAll(regex):
let lang = line.replacef(regex, "$1")
if lang in langs:
let count = parseInt(line.replacef(regex, "$2").replace(",", "").strip())
ranks.add (lang, count)
ranks.sort(cmp)
for i, rank in ranks:
echo &"{i + 1:3} {rank.count:4} - {rank.lang}"
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Generate an equivalent C++ version of this Nim code. | import httpclient, json, re, strformat, strutils, algorithm
const
LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json"
CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
let regex = re"title=""Category:(.*?)"">.+?</a>.*\((.*) members\)"
type Rank = tuple[lang: string, count: int]
proc cmp(a, b: Rank): int =
result = cmp(b.count, a.count)
if result == 0: result = cmp(a.lang, b.lang)
proc add(langs: var seq[string]; fromJson: JsonNode) =
for entry in fromJson{"query", "categorymembers"}:
langs.add entry["title"].getStr.split("Category:")[1]
var client = newHttpClient()
var langs: seq[string]
var url = LangSite
while true:
let response = client.get(url)
if response.status != $Http200: break
let fromJson = response.body.parseJson()
langs.add fromJson
if "continue" notin fromJson: break
let cmcont = fromJson{"continue", "cmcontinue"}.getStr
let cont = fromJson{"continue", "continue"}.getStr
url = LangSite & fmt"&cmcontinue={cmcont}&continue={cont}"
var ranks: seq[Rank]
for line in client.getContent(CatSite).findAll(regex):
let lang = line.replacef(regex, "$1")
if lang in langs:
let count = parseInt(line.replacef(regex, "$2").replace(",", "").strip())
ranks.add (lang, count)
ranks.sort(cmp)
for i, rank in ranks:
echo &"{i + 1:3} {rank.count:4} - {rank.lang}"
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Port the provided Nim code into Java while preserving the original functionality. | import httpclient, json, re, strformat, strutils, algorithm
const
LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json"
CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
let regex = re"title=""Category:(.*?)"">.+?</a>.*\((.*) members\)"
type Rank = tuple[lang: string, count: int]
proc cmp(a, b: Rank): int =
result = cmp(b.count, a.count)
if result == 0: result = cmp(a.lang, b.lang)
proc add(langs: var seq[string]; fromJson: JsonNode) =
for entry in fromJson{"query", "categorymembers"}:
langs.add entry["title"].getStr.split("Category:")[1]
var client = newHttpClient()
var langs: seq[string]
var url = LangSite
while true:
let response = client.get(url)
if response.status != $Http200: break
let fromJson = response.body.parseJson()
langs.add fromJson
if "continue" notin fromJson: break
let cmcont = fromJson{"continue", "cmcontinue"}.getStr
let cont = fromJson{"continue", "continue"}.getStr
url = LangSite & fmt"&cmcontinue={cmcont}&continue={cont}"
var ranks: seq[Rank]
for line in client.getContent(CatSite).findAll(regex):
let lang = line.replacef(regex, "$1")
if lang in langs:
let count = parseInt(line.replacef(regex, "$2").replace(",", "").strip())
ranks.add (lang, count)
ranks.sort(cmp)
for i, rank in ranks:
echo &"{i + 1:3} {rank.count:4} - {rank.lang}"
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Rewrite the snippet below in Python so it works the same as the original Nim code. | import httpclient, json, re, strformat, strutils, algorithm
const
LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json"
CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
let regex = re"title=""Category:(.*?)"">.+?</a>.*\((.*) members\)"
type Rank = tuple[lang: string, count: int]
proc cmp(a, b: Rank): int =
result = cmp(b.count, a.count)
if result == 0: result = cmp(a.lang, b.lang)
proc add(langs: var seq[string]; fromJson: JsonNode) =
for entry in fromJson{"query", "categorymembers"}:
langs.add entry["title"].getStr.split("Category:")[1]
var client = newHttpClient()
var langs: seq[string]
var url = LangSite
while true:
let response = client.get(url)
if response.status != $Http200: break
let fromJson = response.body.parseJson()
langs.add fromJson
if "continue" notin fromJson: break
let cmcont = fromJson{"continue", "cmcontinue"}.getStr
let cont = fromJson{"continue", "continue"}.getStr
url = LangSite & fmt"&cmcontinue={cmcont}&continue={cont}"
var ranks: seq[Rank]
for line in client.getContent(CatSite).findAll(regex):
let lang = line.replacef(regex, "$1")
if lang in langs:
let count = parseInt(line.replacef(regex, "$2").replace(",", "").strip())
ranks.add (lang, count)
ranks.sort(cmp)
for i, rank in ranks:
echo &"{i + 1:3} {rank.count:4} - {rank.lang}"
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Transform the following Nim implementation into VB, maintaining the same output and logic. | import httpclient, json, re, strformat, strutils, algorithm
const
LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json"
CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
let regex = re"title=""Category:(.*?)"">.+?</a>.*\((.*) members\)"
type Rank = tuple[lang: string, count: int]
proc cmp(a, b: Rank): int =
result = cmp(b.count, a.count)
if result == 0: result = cmp(a.lang, b.lang)
proc add(langs: var seq[string]; fromJson: JsonNode) =
for entry in fromJson{"query", "categorymembers"}:
langs.add entry["title"].getStr.split("Category:")[1]
var client = newHttpClient()
var langs: seq[string]
var url = LangSite
while true:
let response = client.get(url)
if response.status != $Http200: break
let fromJson = response.body.parseJson()
langs.add fromJson
if "continue" notin fromJson: break
let cmcont = fromJson{"continue", "cmcontinue"}.getStr
let cont = fromJson{"continue", "continue"}.getStr
url = LangSite & fmt"&cmcontinue={cmcont}&continue={cont}"
var ranks: seq[Rank]
for line in client.getContent(CatSite).findAll(regex):
let lang = line.replacef(regex, "$1")
if lang in langs:
let count = parseInt(line.replacef(regex, "$2").replace(",", "").strip())
ranks.add (lang, count)
ranks.sort(cmp)
for i, rank in ranks:
echo &"{i + 1:3} {rank.count:4} - {rank.lang}"
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Write the same code in Go as shown below in Nim. | import httpclient, json, re, strformat, strutils, algorithm
const
LangSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json"
CatSite = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"
let regex = re"title=""Category:(.*?)"">.+?</a>.*\((.*) members\)"
type Rank = tuple[lang: string, count: int]
proc cmp(a, b: Rank): int =
result = cmp(b.count, a.count)
if result == 0: result = cmp(a.lang, b.lang)
proc add(langs: var seq[string]; fromJson: JsonNode) =
for entry in fromJson{"query", "categorymembers"}:
langs.add entry["title"].getStr.split("Category:")[1]
var client = newHttpClient()
var langs: seq[string]
var url = LangSite
while true:
let response = client.get(url)
if response.status != $Http200: break
let fromJson = response.body.parseJson()
langs.add fromJson
if "continue" notin fromJson: break
let cmcont = fromJson{"continue", "cmcontinue"}.getStr
let cont = fromJson{"continue", "continue"}.getStr
url = LangSite & fmt"&cmcontinue={cmcont}&continue={cont}"
var ranks: seq[Rank]
for line in client.getContent(CatSite).findAll(regex):
let lang = line.replacef(regex, "$1")
if lang in langs:
let count = parseInt(line.replacef(regex, "$2").replace(",", "").strip())
ranks.add (lang, count)
ranks.sort(cmp)
for i, rank in ranks:
echo &"{i + 1:3} {rank.count:4} - {rank.lang}"
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Please provide an equivalent version of this Perl code in C. | use 5.010;
use MediaWiki::API;
my $api =
MediaWiki::API->new( { api_url => 'http://rosettacode.org/w/api.php' } );
my @languages;
my $gcmcontinue;
while (1) {
my $apih = $api->api(
{
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:Programming Languages',
gcmlimit => 250,
prop => 'categoryinfo',
gcmcontinue => $gcmcontinue
}
);
push @languages, values %{ $apih->{'query'}{'pages'} };
last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'};
}
for (@languages) {
$_->{'title'} =~ s/Category://;
$_->{'categoryinfo'}{'size'} //= 0;
}
my @sorted_languages =
reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} }
@languages;
binmode STDOUT, ':encoding(utf8)';
my $n = 1;
for (@sorted_languages) {
printf "%3d. %20s - %3d\n", $n++, $_->{'title'},
$_->{'categoryinfo'}{'size'};
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Write a version of this Perl function in C# with identical behavior. | use 5.010;
use MediaWiki::API;
my $api =
MediaWiki::API->new( { api_url => 'http://rosettacode.org/w/api.php' } );
my @languages;
my $gcmcontinue;
while (1) {
my $apih = $api->api(
{
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:Programming Languages',
gcmlimit => 250,
prop => 'categoryinfo',
gcmcontinue => $gcmcontinue
}
);
push @languages, values %{ $apih->{'query'}{'pages'} };
last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'};
}
for (@languages) {
$_->{'title'} =~ s/Category://;
$_->{'categoryinfo'}{'size'} //= 0;
}
my @sorted_languages =
reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} }
@languages;
binmode STDOUT, ':encoding(utf8)';
my $n = 1;
for (@sorted_languages) {
printf "%3d. %20s - %3d\n", $n++, $_->{'title'},
$_->{'categoryinfo'}{'size'};
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Generate a C++ translation of this Perl snippet without changing its computational steps. | use 5.010;
use MediaWiki::API;
my $api =
MediaWiki::API->new( { api_url => 'http://rosettacode.org/w/api.php' } );
my @languages;
my $gcmcontinue;
while (1) {
my $apih = $api->api(
{
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:Programming Languages',
gcmlimit => 250,
prop => 'categoryinfo',
gcmcontinue => $gcmcontinue
}
);
push @languages, values %{ $apih->{'query'}{'pages'} };
last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'};
}
for (@languages) {
$_->{'title'} =~ s/Category://;
$_->{'categoryinfo'}{'size'} //= 0;
}
my @sorted_languages =
reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} }
@languages;
binmode STDOUT, ':encoding(utf8)';
my $n = 1;
for (@sorted_languages) {
printf "%3d. %20s - %3d\n", $n++, $_->{'title'},
$_->{'categoryinfo'}{'size'};
}
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Port the provided Perl code into Java while preserving the original functionality. | use 5.010;
use MediaWiki::API;
my $api =
MediaWiki::API->new( { api_url => 'http://rosettacode.org/w/api.php' } );
my @languages;
my $gcmcontinue;
while (1) {
my $apih = $api->api(
{
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:Programming Languages',
gcmlimit => 250,
prop => 'categoryinfo',
gcmcontinue => $gcmcontinue
}
);
push @languages, values %{ $apih->{'query'}{'pages'} };
last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'};
}
for (@languages) {
$_->{'title'} =~ s/Category://;
$_->{'categoryinfo'}{'size'} //= 0;
}
my @sorted_languages =
reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} }
@languages;
binmode STDOUT, ':encoding(utf8)';
my $n = 1;
for (@sorted_languages) {
printf "%3d. %20s - %3d\n", $n++, $_->{'title'},
$_->{'categoryinfo'}{'size'};
}
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Port the following code from Perl to Python with equivalent syntax and logic. | use 5.010;
use MediaWiki::API;
my $api =
MediaWiki::API->new( { api_url => 'http://rosettacode.org/w/api.php' } );
my @languages;
my $gcmcontinue;
while (1) {
my $apih = $api->api(
{
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:Programming Languages',
gcmlimit => 250,
prop => 'categoryinfo',
gcmcontinue => $gcmcontinue
}
);
push @languages, values %{ $apih->{'query'}{'pages'} };
last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'};
}
for (@languages) {
$_->{'title'} =~ s/Category://;
$_->{'categoryinfo'}{'size'} //= 0;
}
my @sorted_languages =
reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} }
@languages;
binmode STDOUT, ':encoding(utf8)';
my $n = 1;
for (@sorted_languages) {
printf "%3d. %20s - %3d\n", $n++, $_->{'title'},
$_->{'categoryinfo'}{'size'};
}
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Rewrite the snippet below in VB so it works the same as the original Perl code. | use 5.010;
use MediaWiki::API;
my $api =
MediaWiki::API->new( { api_url => 'http://rosettacode.org/w/api.php' } );
my @languages;
my $gcmcontinue;
while (1) {
my $apih = $api->api(
{
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:Programming Languages',
gcmlimit => 250,
prop => 'categoryinfo',
gcmcontinue => $gcmcontinue
}
);
push @languages, values %{ $apih->{'query'}{'pages'} };
last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'};
}
for (@languages) {
$_->{'title'} =~ s/Category://;
$_->{'categoryinfo'}{'size'} //= 0;
}
my @sorted_languages =
reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} }
@languages;
binmode STDOUT, ':encoding(utf8)';
my $n = 1;
for (@sorted_languages) {
printf "%3d. %20s - %3d\n", $n++, $_->{'title'},
$_->{'categoryinfo'}{'size'};
}
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Ensure the translated Go code behaves exactly like the original Perl snippet. | use 5.010;
use MediaWiki::API;
my $api =
MediaWiki::API->new( { api_url => 'http://rosettacode.org/w/api.php' } );
my @languages;
my $gcmcontinue;
while (1) {
my $apih = $api->api(
{
action => 'query',
generator => 'categorymembers',
gcmtitle => 'Category:Programming Languages',
gcmlimit => 250,
prop => 'categoryinfo',
gcmcontinue => $gcmcontinue
}
);
push @languages, values %{ $apih->{'query'}{'pages'} };
last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'};
}
for (@languages) {
$_->{'title'} =~ s/Category://;
$_->{'categoryinfo'}{'size'} //= 0;
}
my @sorted_languages =
reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} }
@languages;
binmode STDOUT, ':encoding(utf8)';
my $n = 1;
for (@sorted_languages) {
printf "%3d. %20s - %3d\n", $n++, $_->{'title'},
$_->{'categoryinfo'}{'size'};
}
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Convert this PowerShell block to C, preserving its control flow and logic. | $get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json")
$get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$match1 = [regex]::matches($get1, "`"title`":`"Category:(.+?)`"")
$match2 = [regex]::matches($get2, "title=`"Category:([^`"]+?)`">[^<]+?</a>[^\(]*\((\d+) members\)")
$r = 1
$langs = $match1 | foreach { $_.Groups[1].Value.Replace("\","") }
$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {
if ($langs.Contains($_.Groups[1].Value))
{
[pscustomobject]@{
Rank = "$r"
Members = "$($_.Groups[2].Value)"
Language = "$($_.Groups[1].Value)"
}
$r++
}
}
1..30 | foreach{
[pscustomobject]@{
"Rank 1..30" = "$($_)"
"Members 1..30" = "$($res[$_-1].Members)"
"Language 1..30" = "$($res[$_-1].Language)"
"Rank 31..60" = "$($_+30)"
"Members 31..60" = "$($res[$_+30].Members)"
"Language 31..60" = "$($res[$_+30].Language)"
}
}| Format-Table -AutoSize
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Write the same code in C# as shown below in PowerShell. | $get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json")
$get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$match1 = [regex]::matches($get1, "`"title`":`"Category:(.+?)`"")
$match2 = [regex]::matches($get2, "title=`"Category:([^`"]+?)`">[^<]+?</a>[^\(]*\((\d+) members\)")
$r = 1
$langs = $match1 | foreach { $_.Groups[1].Value.Replace("\","") }
$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {
if ($langs.Contains($_.Groups[1].Value))
{
[pscustomobject]@{
Rank = "$r"
Members = "$($_.Groups[2].Value)"
Language = "$($_.Groups[1].Value)"
}
$r++
}
}
1..30 | foreach{
[pscustomobject]@{
"Rank 1..30" = "$($_)"
"Members 1..30" = "$($res[$_-1].Members)"
"Language 1..30" = "$($res[$_-1].Language)"
"Rank 31..60" = "$($_+30)"
"Members 31..60" = "$($res[$_+30].Members)"
"Language 31..60" = "$($res[$_+30].Language)"
}
}| Format-Table -AutoSize
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Write the same code in C++ as shown below in PowerShell. | $get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json")
$get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$match1 = [regex]::matches($get1, "`"title`":`"Category:(.+?)`"")
$match2 = [regex]::matches($get2, "title=`"Category:([^`"]+?)`">[^<]+?</a>[^\(]*\((\d+) members\)")
$r = 1
$langs = $match1 | foreach { $_.Groups[1].Value.Replace("\","") }
$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {
if ($langs.Contains($_.Groups[1].Value))
{
[pscustomobject]@{
Rank = "$r"
Members = "$($_.Groups[2].Value)"
Language = "$($_.Groups[1].Value)"
}
$r++
}
}
1..30 | foreach{
[pscustomobject]@{
"Rank 1..30" = "$($_)"
"Members 1..30" = "$($res[$_-1].Members)"
"Language 1..30" = "$($res[$_-1].Language)"
"Rank 31..60" = "$($_+30)"
"Members 31..60" = "$($res[$_+30].Members)"
"Language 31..60" = "$($res[$_+30].Language)"
}
}| Format-Table -AutoSize
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Produce a language-to-language conversion: from PowerShell to Java, same semantics. | $get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json")
$get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$match1 = [regex]::matches($get1, "`"title`":`"Category:(.+?)`"")
$match2 = [regex]::matches($get2, "title=`"Category:([^`"]+?)`">[^<]+?</a>[^\(]*\((\d+) members\)")
$r = 1
$langs = $match1 | foreach { $_.Groups[1].Value.Replace("\","") }
$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {
if ($langs.Contains($_.Groups[1].Value))
{
[pscustomobject]@{
Rank = "$r"
Members = "$($_.Groups[2].Value)"
Language = "$($_.Groups[1].Value)"
}
$r++
}
}
1..30 | foreach{
[pscustomobject]@{
"Rank 1..30" = "$($_)"
"Members 1..30" = "$($res[$_-1].Members)"
"Language 1..30" = "$($res[$_-1].Language)"
"Rank 31..60" = "$($_+30)"
"Members 31..60" = "$($res[$_+30].Members)"
"Language 31..60" = "$($res[$_+30].Language)"
}
}| Format-Table -AutoSize
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Write the same algorithm in Python as shown in this PowerShell implementation. | $get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json")
$get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$match1 = [regex]::matches($get1, "`"title`":`"Category:(.+?)`"")
$match2 = [regex]::matches($get2, "title=`"Category:([^`"]+?)`">[^<]+?</a>[^\(]*\((\d+) members\)")
$r = 1
$langs = $match1 | foreach { $_.Groups[1].Value.Replace("\","") }
$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {
if ($langs.Contains($_.Groups[1].Value))
{
[pscustomobject]@{
Rank = "$r"
Members = "$($_.Groups[2].Value)"
Language = "$($_.Groups[1].Value)"
}
$r++
}
}
1..30 | foreach{
[pscustomobject]@{
"Rank 1..30" = "$($_)"
"Members 1..30" = "$($res[$_-1].Members)"
"Language 1..30" = "$($res[$_-1].Language)"
"Rank 31..60" = "$($_+30)"
"Members 31..60" = "$($res[$_+30].Members)"
"Language 31..60" = "$($res[$_+30].Language)"
}
}| Format-Table -AutoSize
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Ensure the translated VB code behaves exactly like the original PowerShell snippet. | $get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json")
$get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$match1 = [regex]::matches($get1, "`"title`":`"Category:(.+?)`"")
$match2 = [regex]::matches($get2, "title=`"Category:([^`"]+?)`">[^<]+?</a>[^\(]*\((\d+) members\)")
$r = 1
$langs = $match1 | foreach { $_.Groups[1].Value.Replace("\","") }
$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {
if ($langs.Contains($_.Groups[1].Value))
{
[pscustomobject]@{
Rank = "$r"
Members = "$($_.Groups[2].Value)"
Language = "$($_.Groups[1].Value)"
}
$r++
}
}
1..30 | foreach{
[pscustomobject]@{
"Rank 1..30" = "$($_)"
"Members 1..30" = "$($res[$_-1].Members)"
"Language 1..30" = "$($res[$_-1].Language)"
"Rank 31..60" = "$($_+30)"
"Members 31..60" = "$($res[$_+30].Members)"
"Language 31..60" = "$($res[$_+30].Language)"
}
}| Format-Table -AutoSize
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Generate an equivalent Go version of this PowerShell code. | $get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json")
$get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$match1 = [regex]::matches($get1, "`"title`":`"Category:(.+?)`"")
$match2 = [regex]::matches($get2, "title=`"Category:([^`"]+?)`">[^<]+?</a>[^\(]*\((\d+) members\)")
$r = 1
$langs = $match1 | foreach { $_.Groups[1].Value.Replace("\","") }
$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {
if ($langs.Contains($_.Groups[1].Value))
{
[pscustomobject]@{
Rank = "$r"
Members = "$($_.Groups[2].Value)"
Language = "$($_.Groups[1].Value)"
}
$r++
}
}
1..30 | foreach{
[pscustomobject]@{
"Rank 1..30" = "$($_)"
"Members 1..30" = "$($res[$_-1].Members)"
"Language 1..30" = "$($res[$_-1].Language)"
"Rank 31..60" = "$($_+30)"
"Members 31..60" = "$($res[$_+30].Members)"
"Language 31..60" = "$($res[$_+30].Language)"
}
}| Format-Table -AutoSize
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Rewrite this program in C while keeping its functionality equivalent to the Racket version. | #lang racket
(require racket/hash
net/url
json)
(define limit 15)
(define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1"))
(define category "Category:Programming Languages")
(define entries "entries")
(define api-url (string->url "http://rosettacode.org/mw/api.php"))
(define (make-complete-url gcmcontinue)
(struct-copy url api-url
[query `([format . "json"]
[action . "query"]
[generator . "categorymembers"]
[gcmtitle . ,category]
[gcmlimit . "200"]
[gcmcontinue . ,gcmcontinue]
[continue . ""]
[prop . "categoryinfo"])]))
(define @ hash-ref)
(define table (make-hash))
(let loop ([gcmcontinue ""])
(define resp (read-json (get-pure-port (make-complete-url gcmcontinue))))
(hash-union! table
(for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))])
(values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0))))
(cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))
(for/fold ([prev #f] [rank #f] #:result (void))
([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)])
(match-define (cons cat size) item)
(define this-rank (if (equal? prev size) rank (add1 i)))
(printf "Rank: ~a ~a ~a\n"
(~a this-rank #:align 'right #:min-width 2)
(~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14)
(replacer cat))
(values size this-rank))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Racket. | #lang racket
(require racket/hash
net/url
json)
(define limit 15)
(define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1"))
(define category "Category:Programming Languages")
(define entries "entries")
(define api-url (string->url "http://rosettacode.org/mw/api.php"))
(define (make-complete-url gcmcontinue)
(struct-copy url api-url
[query `([format . "json"]
[action . "query"]
[generator . "categorymembers"]
[gcmtitle . ,category]
[gcmlimit . "200"]
[gcmcontinue . ,gcmcontinue]
[continue . ""]
[prop . "categoryinfo"])]))
(define @ hash-ref)
(define table (make-hash))
(let loop ([gcmcontinue ""])
(define resp (read-json (get-pure-port (make-complete-url gcmcontinue))))
(hash-union! table
(for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))])
(values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0))))
(cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))
(for/fold ([prev #f] [rank #f] #:result (void))
([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)])
(match-define (cons cat size) item)
(define this-rank (if (equal? prev size) rank (add1 i)))
(printf "Rank: ~a ~a ~a\n"
(~a this-rank #:align 'right #:min-width 2)
(~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14)
(replacer cat))
(values size this-rank))
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Racket version. | #lang racket
(require racket/hash
net/url
json)
(define limit 15)
(define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1"))
(define category "Category:Programming Languages")
(define entries "entries")
(define api-url (string->url "http://rosettacode.org/mw/api.php"))
(define (make-complete-url gcmcontinue)
(struct-copy url api-url
[query `([format . "json"]
[action . "query"]
[generator . "categorymembers"]
[gcmtitle . ,category]
[gcmlimit . "200"]
[gcmcontinue . ,gcmcontinue]
[continue . ""]
[prop . "categoryinfo"])]))
(define @ hash-ref)
(define table (make-hash))
(let loop ([gcmcontinue ""])
(define resp (read-json (get-pure-port (make-complete-url gcmcontinue))))
(hash-union! table
(for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))])
(values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0))))
(cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))
(for/fold ([prev #f] [rank #f] #:result (void))
([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)])
(match-define (cons cat size) item)
(define this-rank (if (equal? prev size) rank (add1 i)))
(printf "Rank: ~a ~a ~a\n"
(~a this-rank #:align 'right #:min-width 2)
(~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14)
(replacer cat))
(values size this-rank))
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Change the programming language of this snippet from Racket to Java without modifying what it does. | #lang racket
(require racket/hash
net/url
json)
(define limit 15)
(define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1"))
(define category "Category:Programming Languages")
(define entries "entries")
(define api-url (string->url "http://rosettacode.org/mw/api.php"))
(define (make-complete-url gcmcontinue)
(struct-copy url api-url
[query `([format . "json"]
[action . "query"]
[generator . "categorymembers"]
[gcmtitle . ,category]
[gcmlimit . "200"]
[gcmcontinue . ,gcmcontinue]
[continue . ""]
[prop . "categoryinfo"])]))
(define @ hash-ref)
(define table (make-hash))
(let loop ([gcmcontinue ""])
(define resp (read-json (get-pure-port (make-complete-url gcmcontinue))))
(hash-union! table
(for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))])
(values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0))))
(cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))
(for/fold ([prev #f] [rank #f] #:result (void))
([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)])
(match-define (cons cat size) item)
(define this-rank (if (equal? prev size) rank (add1 i)))
(printf "Rank: ~a ~a ~a\n"
(~a this-rank #:align 'right #:min-width 2)
(~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14)
(replacer cat))
(values size this-rank))
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Produce a functionally identical Python code for the snippet given in Racket. | #lang racket
(require racket/hash
net/url
json)
(define limit 15)
(define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1"))
(define category "Category:Programming Languages")
(define entries "entries")
(define api-url (string->url "http://rosettacode.org/mw/api.php"))
(define (make-complete-url gcmcontinue)
(struct-copy url api-url
[query `([format . "json"]
[action . "query"]
[generator . "categorymembers"]
[gcmtitle . ,category]
[gcmlimit . "200"]
[gcmcontinue . ,gcmcontinue]
[continue . ""]
[prop . "categoryinfo"])]))
(define @ hash-ref)
(define table (make-hash))
(let loop ([gcmcontinue ""])
(define resp (read-json (get-pure-port (make-complete-url gcmcontinue))))
(hash-union! table
(for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))])
(values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0))))
(cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))
(for/fold ([prev #f] [rank #f] #:result (void))
([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)])
(match-define (cons cat size) item)
(define this-rank (if (equal? prev size) rank (add1 i)))
(printf "Rank: ~a ~a ~a\n"
(~a this-rank #:align 'right #:min-width 2)
(~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14)
(replacer cat))
(values size this-rank))
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Keep all operations the same but rewrite the snippet in VB. | #lang racket
(require racket/hash
net/url
json)
(define limit 15)
(define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1"))
(define category "Category:Programming Languages")
(define entries "entries")
(define api-url (string->url "http://rosettacode.org/mw/api.php"))
(define (make-complete-url gcmcontinue)
(struct-copy url api-url
[query `([format . "json"]
[action . "query"]
[generator . "categorymembers"]
[gcmtitle . ,category]
[gcmlimit . "200"]
[gcmcontinue . ,gcmcontinue]
[continue . ""]
[prop . "categoryinfo"])]))
(define @ hash-ref)
(define table (make-hash))
(let loop ([gcmcontinue ""])
(define resp (read-json (get-pure-port (make-complete-url gcmcontinue))))
(hash-union! table
(for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))])
(values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0))))
(cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))
(for/fold ([prev #f] [rank #f] #:result (void))
([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)])
(match-define (cons cat size) item)
(define this-rank (if (equal? prev size) rank (add1 i)))
(printf "Rank: ~a ~a ~a\n"
(~a this-rank #:align 'right #:min-width 2)
(~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14)
(replacer cat))
(values size this-rank))
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Write the same code in Go as shown below in Racket. | #lang racket
(require racket/hash
net/url
json)
(define limit 15)
(define (replacer cat) (regexp-replace #rx"^Category:(.*?)$" cat "\\1"))
(define category "Category:Programming Languages")
(define entries "entries")
(define api-url (string->url "http://rosettacode.org/mw/api.php"))
(define (make-complete-url gcmcontinue)
(struct-copy url api-url
[query `([format . "json"]
[action . "query"]
[generator . "categorymembers"]
[gcmtitle . ,category]
[gcmlimit . "200"]
[gcmcontinue . ,gcmcontinue]
[continue . ""]
[prop . "categoryinfo"])]))
(define @ hash-ref)
(define table (make-hash))
(let loop ([gcmcontinue ""])
(define resp (read-json (get-pure-port (make-complete-url gcmcontinue))))
(hash-union! table
(for/hash ([(k v) (in-hash (@ (@ resp 'query) 'pages))])
(values (@ v 'title #f) (@ (@ v 'categoryinfo (hash)) 'size 0))))
(cond [(@ resp 'continue #f) => (λ (c) (loop (@ c 'gcmcontinue)))]))
(for/fold ([prev #f] [rank #f] #:result (void))
([item (in-list (sort (hash->list table) > #:key cdr))] [i (in-range limit)])
(match-define (cons cat size) item)
(define this-rank (if (equal? prev size) rank (add1 i)))
(printf "Rank: ~a ~a ~a\n"
(~a this-rank #:align 'right #:min-width 2)
(~a (format "(~a ~a)" size entries) #:align 'right #:min-width 14)
(replacer cat))
(values size this-rank))
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Keep all operations the same but rewrite the snippet in C. |
* Create a list of Rosetta Code languages showing the number of tasks
* This program's logic is basically that of the REXX program
* rearranged to my taste and utilizing the array class of ooRexx
* which offers a neat way of sorting as desired, see :CLASS mycmp below
* For the input to this program open these links:
* http://rosettacode.org/wiki/Category:Programming_Languages
* http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000
* and save the pages as LAN.txt and CAT.txt, respectively
* Output: RC_POP.txt list of languages sorted by popularity
* If test=1, additionally:
* RC_LNG.txt list of languages alphabetically sorted
* RC_TRN.txt list language name translations (debug)
*--------------------------------------------------------------------*/
test=1
name.='??'
l.=0
safe=''
x00='00'x
linfid='RC_LAN.txt'
linfid='LAN.txt'
cinfid='CAT.txt'
oid='RC_POP.txt'; 'erase' oid
If test Then Do
tid='RC.TRN.txt'; 'erase' tid
tia='RC_LNG.txt'; 'erase' tia
End
Call init
call read_lang
Call read_cat
Call ot words(lang_list) 'possible languages'
Call ot words(lang_listr) 'relevant languages'
llrn=words(lang_listr)
If test Then
Call no_member
a=.array~new
cnt.=0
Do i=1 By 1 While lang_listr<>''
Parse Var lang_listr ddu0 lang_listr
ddu=translate(ddu0,' ',x00)
a[i]=right(mem.ddu,3) name.ddu
z=mem.ddu
cnt.z=cnt.z+1
End
n=i-1
a~sortWith(.mycmp~new)
* and now create the output
*--------------------------------------------------------------------*/
Call o ' '
Call o center('timestamp: ' date() time('Civil'),79,'-')
Call o ' '
Call o right(lrecs,9) 'records read from file: ' linfid
Call o right(crecs,9) 'records read from file: ' cinfid
Call o right(llrn,9) 'relevant languages'
Call o ' '
rank=0
rank.=0
Do i=1 To n
rank=rank+1
Parse Value a[i] With o . 6 lang
ol=' rank: 'right(rank,3)' '||,
'('right(o,3) 'entries) 'lang
If cnt.o>1 Then Do
If rank.o=0 Then
rank.o=rank
ol=overlay(right(rank.o,3),ol,17)
ol=overlay('[tied]',ol,22)
End
Call o ol
End
Call o ' '
Call o center('+ end of list +',72)
Say 'Output in' oid
If test Then Do
b=.array~new
cnt.=0
Do i=1 By 1 While lang_list<>''
Parse Var lang_list ddu0 lang_list
ddu=translate(ddu0,' ',x00)
b[i]=right(mem.ddu,3) name.ddu
End
n=i-1
b~sortWith(.alpha~new)
Call oa n 'languages'
Do i=1 To n
Call oa b[i]
End
Say 'Sorted list of languages in' tia
End
Exit
o:
Return lineout(oid,arg(1))
ot:
If test Then Call lineout tid,arg(1)
Return
oa:
If test Then Call lineout tia,arg(1)
Return
read_lang:
* Read the language page to determine the list of possible languages
* Output: l.lang>0 for all languages found
* name.lang original name of uppercased language name
* lang_list list of uppercased language names
* lrecs number of records read from language file
*--------------------------------------------------------------------*/
l.=0
name.='??'
lang_list=''
Do lrecs=0 While lines(linfid)\==0
l=linein(linfid)
l=translate(l,' ','9'x)
dd=space(l)
ddu=translate(dd)
If pos('AUTOMATED ADMINISTRATION',ddu)>0 Then
Iterate
If pos('RETRIEVED FROM',ddu)\==0 Then
Leave
If dd=='' Then
Iterate
If left(dd,1)\=='*' Then
Iterate
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
Parse Var dd '*' dd "<"
ddu=strip(translate(dd))
If name.ddu='??' Then
name.ddu=dd
l.ddu=l.ddu+1
ddu_=translate(ddu,x00,' ')
If wordpos(ddu_,lang_list)=0 Then
lang_list=lang_list ddu_
End
Return
read_cat:
* Read the category page to get language names and number of members
* Output: mem.ddu number of members for (uppercase) Language ddu
* lang_listr the list of relevant languages
*--------------------------------------------------------------------*/
mem.=0
lang_listr=''
Do crecs=0 While lines(cinfid)\==0
l=get_cat(cinfid)
l=translate(l,' ','9'x)
dd=space(l)
If dd=='' Then
Iterate
ddu=translate(dd)
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
du=translate(dd)
If pos('RETRIEVED FROM',du)\==0 Then
Leave
Parse Var dd dd '<' "(" mems .
dd=space(substr(dd,3))
_=translate(dd)
If \l._ Then
Iterate
if pos(',', mems)\==0 then
mems=changestr(",", mems, '')
If\datatype(mems,'W') Then
Iterate
ddu=space(translate(dd))
mem.ddu=mem.ddu+mems
Call memory ddu
End
Return
get_cat:
* get a (logical) line from the category file
* These two lines
* * Lotus 123 Macro Scripting
* </wiki/Category:Lotus_123_Macro_Scripting>�‎ (3 members)
* are returned as one line:
*-> * Lotus 123 Macro Scripting </wiki/Cate ... (3 members)
* we need language name and number of members in one line
*--------------------------------------------------------------------*/
Parse Arg fid
If safe<>'' Then
ol=safe
Else Do
If lines(fid)=0 Then
Return ''
ol=linein(fid)
safe=''
End
If left(ol,3)=' *' Then Do
Do Until left(r,3)==' *' | lines(fid)=0
r=linein(fid)
If left(r,3)==' *' Then Do
safe=r
Return ol
End
Else
ol=ol r
End
End
Return ol
memory:
ddu0=translate(ddu,x00,' ')
If wordpos(ddu0,lang_listr)=0 Then
lang_listr=lang_listr ddu0
Return
fix_lang: Procedure Expose old. new.
Parse Arg s
Do k=1 While old.k\==''
If pos(old.k,s)\==0 Then
s=changestr(old.k,s,new.k)
End
Return s
init:
old.=''
old.1='UC++'
new.1="µC++"
old.2='МК-61/52'
new.2='MK-61/52'
old.3='Déjà Vu'
new.3='Déjà Vu'
old.4='Caché'
new.4='Caché'
old.5='ΜC++'
new.5="MC++"
Call ot 'Language replacements:'
Do ii=1 To 5
Call ot ' ' left(old.ii,10) left(c2x(old.ii),20) '->' new.ii
End
Call ot ' '
Return
no_member: Procedure Expose lang_list lang_listr tid x00 test
* show languages found in language file that are not referred to
* in the category file
*--------------------------------------------------------------------*/
ll =wordsort(lang_list )
llr=wordsort(lang_listr)
Parse Var ll l1 ll
Parse Var llr l2 llr
nn.=0
Do Forever
Select
When l1=l2 Then Do
If l1='' Then
Leave
Parse Var ll l1 ll
Parse Var llr l2 llr
End
When l1<l2 Then Do
z=nn.0+1
nn.z=' 'translate(l1,' ',x00)
nn.0=z
Parse Var ll l1 ll
End
Otherwise Do
Call ot '?? 'translate(l2,' ',x00)
Say 'In category file but not in language file:'
Say '?? 'translate(l2,' ',x00)
Say 'Hit enter to proceed'
Pull .
Parse Var llr l2 llr
End
End
End
Call ot nn.0 'Languages without members:'
Do ii=1 To nn.0
Call ot nn.ii
End
Return
::CLASS mycmp MIXINCLASS Comparator
::METHOD compare
* smaller number is considered higher
* numbers equal: higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
Select
When na<<nb THEN res=1
When na==nb Then Do
If ta<<tb Then res=-1
Else res=1
End
Otherwise res=-1
End
Return res
::CLASS alpha MIXINCLASS Comparator
::METHOD compare
* higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
If ta<<tb Then res=-1
Else res=1
Return res
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. |
* Create a list of Rosetta Code languages showing the number of tasks
* This program's logic is basically that of the REXX program
* rearranged to my taste and utilizing the array class of ooRexx
* which offers a neat way of sorting as desired, see :CLASS mycmp below
* For the input to this program open these links:
* http://rosettacode.org/wiki/Category:Programming_Languages
* http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000
* and save the pages as LAN.txt and CAT.txt, respectively
* Output: RC_POP.txt list of languages sorted by popularity
* If test=1, additionally:
* RC_LNG.txt list of languages alphabetically sorted
* RC_TRN.txt list language name translations (debug)
*--------------------------------------------------------------------*/
test=1
name.='??'
l.=0
safe=''
x00='00'x
linfid='RC_LAN.txt'
linfid='LAN.txt'
cinfid='CAT.txt'
oid='RC_POP.txt'; 'erase' oid
If test Then Do
tid='RC.TRN.txt'; 'erase' tid
tia='RC_LNG.txt'; 'erase' tia
End
Call init
call read_lang
Call read_cat
Call ot words(lang_list) 'possible languages'
Call ot words(lang_listr) 'relevant languages'
llrn=words(lang_listr)
If test Then
Call no_member
a=.array~new
cnt.=0
Do i=1 By 1 While lang_listr<>''
Parse Var lang_listr ddu0 lang_listr
ddu=translate(ddu0,' ',x00)
a[i]=right(mem.ddu,3) name.ddu
z=mem.ddu
cnt.z=cnt.z+1
End
n=i-1
a~sortWith(.mycmp~new)
* and now create the output
*--------------------------------------------------------------------*/
Call o ' '
Call o center('timestamp: ' date() time('Civil'),79,'-')
Call o ' '
Call o right(lrecs,9) 'records read from file: ' linfid
Call o right(crecs,9) 'records read from file: ' cinfid
Call o right(llrn,9) 'relevant languages'
Call o ' '
rank=0
rank.=0
Do i=1 To n
rank=rank+1
Parse Value a[i] With o . 6 lang
ol=' rank: 'right(rank,3)' '||,
'('right(o,3) 'entries) 'lang
If cnt.o>1 Then Do
If rank.o=0 Then
rank.o=rank
ol=overlay(right(rank.o,3),ol,17)
ol=overlay('[tied]',ol,22)
End
Call o ol
End
Call o ' '
Call o center('+ end of list +',72)
Say 'Output in' oid
If test Then Do
b=.array~new
cnt.=0
Do i=1 By 1 While lang_list<>''
Parse Var lang_list ddu0 lang_list
ddu=translate(ddu0,' ',x00)
b[i]=right(mem.ddu,3) name.ddu
End
n=i-1
b~sortWith(.alpha~new)
Call oa n 'languages'
Do i=1 To n
Call oa b[i]
End
Say 'Sorted list of languages in' tia
End
Exit
o:
Return lineout(oid,arg(1))
ot:
If test Then Call lineout tid,arg(1)
Return
oa:
If test Then Call lineout tia,arg(1)
Return
read_lang:
* Read the language page to determine the list of possible languages
* Output: l.lang>0 for all languages found
* name.lang original name of uppercased language name
* lang_list list of uppercased language names
* lrecs number of records read from language file
*--------------------------------------------------------------------*/
l.=0
name.='??'
lang_list=''
Do lrecs=0 While lines(linfid)\==0
l=linein(linfid)
l=translate(l,' ','9'x)
dd=space(l)
ddu=translate(dd)
If pos('AUTOMATED ADMINISTRATION',ddu)>0 Then
Iterate
If pos('RETRIEVED FROM',ddu)\==0 Then
Leave
If dd=='' Then
Iterate
If left(dd,1)\=='*' Then
Iterate
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
Parse Var dd '*' dd "<"
ddu=strip(translate(dd))
If name.ddu='??' Then
name.ddu=dd
l.ddu=l.ddu+1
ddu_=translate(ddu,x00,' ')
If wordpos(ddu_,lang_list)=0 Then
lang_list=lang_list ddu_
End
Return
read_cat:
* Read the category page to get language names and number of members
* Output: mem.ddu number of members for (uppercase) Language ddu
* lang_listr the list of relevant languages
*--------------------------------------------------------------------*/
mem.=0
lang_listr=''
Do crecs=0 While lines(cinfid)\==0
l=get_cat(cinfid)
l=translate(l,' ','9'x)
dd=space(l)
If dd=='' Then
Iterate
ddu=translate(dd)
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
du=translate(dd)
If pos('RETRIEVED FROM',du)\==0 Then
Leave
Parse Var dd dd '<' "(" mems .
dd=space(substr(dd,3))
_=translate(dd)
If \l._ Then
Iterate
if pos(',', mems)\==0 then
mems=changestr(",", mems, '')
If\datatype(mems,'W') Then
Iterate
ddu=space(translate(dd))
mem.ddu=mem.ddu+mems
Call memory ddu
End
Return
get_cat:
* get a (logical) line from the category file
* These two lines
* * Lotus 123 Macro Scripting
* </wiki/Category:Lotus_123_Macro_Scripting>�‎ (3 members)
* are returned as one line:
*-> * Lotus 123 Macro Scripting </wiki/Cate ... (3 members)
* we need language name and number of members in one line
*--------------------------------------------------------------------*/
Parse Arg fid
If safe<>'' Then
ol=safe
Else Do
If lines(fid)=0 Then
Return ''
ol=linein(fid)
safe=''
End
If left(ol,3)=' *' Then Do
Do Until left(r,3)==' *' | lines(fid)=0
r=linein(fid)
If left(r,3)==' *' Then Do
safe=r
Return ol
End
Else
ol=ol r
End
End
Return ol
memory:
ddu0=translate(ddu,x00,' ')
If wordpos(ddu0,lang_listr)=0 Then
lang_listr=lang_listr ddu0
Return
fix_lang: Procedure Expose old. new.
Parse Arg s
Do k=1 While old.k\==''
If pos(old.k,s)\==0 Then
s=changestr(old.k,s,new.k)
End
Return s
init:
old.=''
old.1='UC++'
new.1="µC++"
old.2='МК-61/52'
new.2='MK-61/52'
old.3='Déjà Vu'
new.3='Déjà Vu'
old.4='Caché'
new.4='Caché'
old.5='ΜC++'
new.5="MC++"
Call ot 'Language replacements:'
Do ii=1 To 5
Call ot ' ' left(old.ii,10) left(c2x(old.ii),20) '->' new.ii
End
Call ot ' '
Return
no_member: Procedure Expose lang_list lang_listr tid x00 test
* show languages found in language file that are not referred to
* in the category file
*--------------------------------------------------------------------*/
ll =wordsort(lang_list )
llr=wordsort(lang_listr)
Parse Var ll l1 ll
Parse Var llr l2 llr
nn.=0
Do Forever
Select
When l1=l2 Then Do
If l1='' Then
Leave
Parse Var ll l1 ll
Parse Var llr l2 llr
End
When l1<l2 Then Do
z=nn.0+1
nn.z=' 'translate(l1,' ',x00)
nn.0=z
Parse Var ll l1 ll
End
Otherwise Do
Call ot '?? 'translate(l2,' ',x00)
Say 'In category file but not in language file:'
Say '?? 'translate(l2,' ',x00)
Say 'Hit enter to proceed'
Pull .
Parse Var llr l2 llr
End
End
End
Call ot nn.0 'Languages without members:'
Do ii=1 To nn.0
Call ot nn.ii
End
Return
::CLASS mycmp MIXINCLASS Comparator
::METHOD compare
* smaller number is considered higher
* numbers equal: higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
Select
When na<<nb THEN res=1
When na==nb Then Do
If ta<<tb Then res=-1
Else res=1
End
Otherwise res=-1
End
Return res
::CLASS alpha MIXINCLASS Comparator
::METHOD compare
* higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
If ta<<tb Then res=-1
Else res=1
Return res
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Generate an equivalent C++ version of this REXX code. |
* Create a list of Rosetta Code languages showing the number of tasks
* This program's logic is basically that of the REXX program
* rearranged to my taste and utilizing the array class of ooRexx
* which offers a neat way of sorting as desired, see :CLASS mycmp below
* For the input to this program open these links:
* http://rosettacode.org/wiki/Category:Programming_Languages
* http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000
* and save the pages as LAN.txt and CAT.txt, respectively
* Output: RC_POP.txt list of languages sorted by popularity
* If test=1, additionally:
* RC_LNG.txt list of languages alphabetically sorted
* RC_TRN.txt list language name translations (debug)
*--------------------------------------------------------------------*/
test=1
name.='??'
l.=0
safe=''
x00='00'x
linfid='RC_LAN.txt'
linfid='LAN.txt'
cinfid='CAT.txt'
oid='RC_POP.txt'; 'erase' oid
If test Then Do
tid='RC.TRN.txt'; 'erase' tid
tia='RC_LNG.txt'; 'erase' tia
End
Call init
call read_lang
Call read_cat
Call ot words(lang_list) 'possible languages'
Call ot words(lang_listr) 'relevant languages'
llrn=words(lang_listr)
If test Then
Call no_member
a=.array~new
cnt.=0
Do i=1 By 1 While lang_listr<>''
Parse Var lang_listr ddu0 lang_listr
ddu=translate(ddu0,' ',x00)
a[i]=right(mem.ddu,3) name.ddu
z=mem.ddu
cnt.z=cnt.z+1
End
n=i-1
a~sortWith(.mycmp~new)
* and now create the output
*--------------------------------------------------------------------*/
Call o ' '
Call o center('timestamp: ' date() time('Civil'),79,'-')
Call o ' '
Call o right(lrecs,9) 'records read from file: ' linfid
Call o right(crecs,9) 'records read from file: ' cinfid
Call o right(llrn,9) 'relevant languages'
Call o ' '
rank=0
rank.=0
Do i=1 To n
rank=rank+1
Parse Value a[i] With o . 6 lang
ol=' rank: 'right(rank,3)' '||,
'('right(o,3) 'entries) 'lang
If cnt.o>1 Then Do
If rank.o=0 Then
rank.o=rank
ol=overlay(right(rank.o,3),ol,17)
ol=overlay('[tied]',ol,22)
End
Call o ol
End
Call o ' '
Call o center('+ end of list +',72)
Say 'Output in' oid
If test Then Do
b=.array~new
cnt.=0
Do i=1 By 1 While lang_list<>''
Parse Var lang_list ddu0 lang_list
ddu=translate(ddu0,' ',x00)
b[i]=right(mem.ddu,3) name.ddu
End
n=i-1
b~sortWith(.alpha~new)
Call oa n 'languages'
Do i=1 To n
Call oa b[i]
End
Say 'Sorted list of languages in' tia
End
Exit
o:
Return lineout(oid,arg(1))
ot:
If test Then Call lineout tid,arg(1)
Return
oa:
If test Then Call lineout tia,arg(1)
Return
read_lang:
* Read the language page to determine the list of possible languages
* Output: l.lang>0 for all languages found
* name.lang original name of uppercased language name
* lang_list list of uppercased language names
* lrecs number of records read from language file
*--------------------------------------------------------------------*/
l.=0
name.='??'
lang_list=''
Do lrecs=0 While lines(linfid)\==0
l=linein(linfid)
l=translate(l,' ','9'x)
dd=space(l)
ddu=translate(dd)
If pos('AUTOMATED ADMINISTRATION',ddu)>0 Then
Iterate
If pos('RETRIEVED FROM',ddu)\==0 Then
Leave
If dd=='' Then
Iterate
If left(dd,1)\=='*' Then
Iterate
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
Parse Var dd '*' dd "<"
ddu=strip(translate(dd))
If name.ddu='??' Then
name.ddu=dd
l.ddu=l.ddu+1
ddu_=translate(ddu,x00,' ')
If wordpos(ddu_,lang_list)=0 Then
lang_list=lang_list ddu_
End
Return
read_cat:
* Read the category page to get language names and number of members
* Output: mem.ddu number of members for (uppercase) Language ddu
* lang_listr the list of relevant languages
*--------------------------------------------------------------------*/
mem.=0
lang_listr=''
Do crecs=0 While lines(cinfid)\==0
l=get_cat(cinfid)
l=translate(l,' ','9'x)
dd=space(l)
If dd=='' Then
Iterate
ddu=translate(dd)
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
du=translate(dd)
If pos('RETRIEVED FROM',du)\==0 Then
Leave
Parse Var dd dd '<' "(" mems .
dd=space(substr(dd,3))
_=translate(dd)
If \l._ Then
Iterate
if pos(',', mems)\==0 then
mems=changestr(",", mems, '')
If\datatype(mems,'W') Then
Iterate
ddu=space(translate(dd))
mem.ddu=mem.ddu+mems
Call memory ddu
End
Return
get_cat:
* get a (logical) line from the category file
* These two lines
* * Lotus 123 Macro Scripting
* </wiki/Category:Lotus_123_Macro_Scripting>�‎ (3 members)
* are returned as one line:
*-> * Lotus 123 Macro Scripting </wiki/Cate ... (3 members)
* we need language name and number of members in one line
*--------------------------------------------------------------------*/
Parse Arg fid
If safe<>'' Then
ol=safe
Else Do
If lines(fid)=0 Then
Return ''
ol=linein(fid)
safe=''
End
If left(ol,3)=' *' Then Do
Do Until left(r,3)==' *' | lines(fid)=0
r=linein(fid)
If left(r,3)==' *' Then Do
safe=r
Return ol
End
Else
ol=ol r
End
End
Return ol
memory:
ddu0=translate(ddu,x00,' ')
If wordpos(ddu0,lang_listr)=0 Then
lang_listr=lang_listr ddu0
Return
fix_lang: Procedure Expose old. new.
Parse Arg s
Do k=1 While old.k\==''
If pos(old.k,s)\==0 Then
s=changestr(old.k,s,new.k)
End
Return s
init:
old.=''
old.1='UC++'
new.1="µC++"
old.2='МК-61/52'
new.2='MK-61/52'
old.3='Déjà Vu'
new.3='Déjà Vu'
old.4='Caché'
new.4='Caché'
old.5='ΜC++'
new.5="MC++"
Call ot 'Language replacements:'
Do ii=1 To 5
Call ot ' ' left(old.ii,10) left(c2x(old.ii),20) '->' new.ii
End
Call ot ' '
Return
no_member: Procedure Expose lang_list lang_listr tid x00 test
* show languages found in language file that are not referred to
* in the category file
*--------------------------------------------------------------------*/
ll =wordsort(lang_list )
llr=wordsort(lang_listr)
Parse Var ll l1 ll
Parse Var llr l2 llr
nn.=0
Do Forever
Select
When l1=l2 Then Do
If l1='' Then
Leave
Parse Var ll l1 ll
Parse Var llr l2 llr
End
When l1<l2 Then Do
z=nn.0+1
nn.z=' 'translate(l1,' ',x00)
nn.0=z
Parse Var ll l1 ll
End
Otherwise Do
Call ot '?? 'translate(l2,' ',x00)
Say 'In category file but not in language file:'
Say '?? 'translate(l2,' ',x00)
Say 'Hit enter to proceed'
Pull .
Parse Var llr l2 llr
End
End
End
Call ot nn.0 'Languages without members:'
Do ii=1 To nn.0
Call ot nn.ii
End
Return
::CLASS mycmp MIXINCLASS Comparator
::METHOD compare
* smaller number is considered higher
* numbers equal: higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
Select
When na<<nb THEN res=1
When na==nb Then Do
If ta<<tb Then res=-1
Else res=1
End
Otherwise res=-1
End
Return res
::CLASS alpha MIXINCLASS Comparator
::METHOD compare
* higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
If ta<<tb Then res=-1
Else res=1
Return res
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Convert the following code from REXX to Java, ensuring the logic remains intact. |
* Create a list of Rosetta Code languages showing the number of tasks
* This program's logic is basically that of the REXX program
* rearranged to my taste and utilizing the array class of ooRexx
* which offers a neat way of sorting as desired, see :CLASS mycmp below
* For the input to this program open these links:
* http://rosettacode.org/wiki/Category:Programming_Languages
* http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000
* and save the pages as LAN.txt and CAT.txt, respectively
* Output: RC_POP.txt list of languages sorted by popularity
* If test=1, additionally:
* RC_LNG.txt list of languages alphabetically sorted
* RC_TRN.txt list language name translations (debug)
*--------------------------------------------------------------------*/
test=1
name.='??'
l.=0
safe=''
x00='00'x
linfid='RC_LAN.txt'
linfid='LAN.txt'
cinfid='CAT.txt'
oid='RC_POP.txt'; 'erase' oid
If test Then Do
tid='RC.TRN.txt'; 'erase' tid
tia='RC_LNG.txt'; 'erase' tia
End
Call init
call read_lang
Call read_cat
Call ot words(lang_list) 'possible languages'
Call ot words(lang_listr) 'relevant languages'
llrn=words(lang_listr)
If test Then
Call no_member
a=.array~new
cnt.=0
Do i=1 By 1 While lang_listr<>''
Parse Var lang_listr ddu0 lang_listr
ddu=translate(ddu0,' ',x00)
a[i]=right(mem.ddu,3) name.ddu
z=mem.ddu
cnt.z=cnt.z+1
End
n=i-1
a~sortWith(.mycmp~new)
* and now create the output
*--------------------------------------------------------------------*/
Call o ' '
Call o center('timestamp: ' date() time('Civil'),79,'-')
Call o ' '
Call o right(lrecs,9) 'records read from file: ' linfid
Call o right(crecs,9) 'records read from file: ' cinfid
Call o right(llrn,9) 'relevant languages'
Call o ' '
rank=0
rank.=0
Do i=1 To n
rank=rank+1
Parse Value a[i] With o . 6 lang
ol=' rank: 'right(rank,3)' '||,
'('right(o,3) 'entries) 'lang
If cnt.o>1 Then Do
If rank.o=0 Then
rank.o=rank
ol=overlay(right(rank.o,3),ol,17)
ol=overlay('[tied]',ol,22)
End
Call o ol
End
Call o ' '
Call o center('+ end of list +',72)
Say 'Output in' oid
If test Then Do
b=.array~new
cnt.=0
Do i=1 By 1 While lang_list<>''
Parse Var lang_list ddu0 lang_list
ddu=translate(ddu0,' ',x00)
b[i]=right(mem.ddu,3) name.ddu
End
n=i-1
b~sortWith(.alpha~new)
Call oa n 'languages'
Do i=1 To n
Call oa b[i]
End
Say 'Sorted list of languages in' tia
End
Exit
o:
Return lineout(oid,arg(1))
ot:
If test Then Call lineout tid,arg(1)
Return
oa:
If test Then Call lineout tia,arg(1)
Return
read_lang:
* Read the language page to determine the list of possible languages
* Output: l.lang>0 for all languages found
* name.lang original name of uppercased language name
* lang_list list of uppercased language names
* lrecs number of records read from language file
*--------------------------------------------------------------------*/
l.=0
name.='??'
lang_list=''
Do lrecs=0 While lines(linfid)\==0
l=linein(linfid)
l=translate(l,' ','9'x)
dd=space(l)
ddu=translate(dd)
If pos('AUTOMATED ADMINISTRATION',ddu)>0 Then
Iterate
If pos('RETRIEVED FROM',ddu)\==0 Then
Leave
If dd=='' Then
Iterate
If left(dd,1)\=='*' Then
Iterate
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
Parse Var dd '*' dd "<"
ddu=strip(translate(dd))
If name.ddu='??' Then
name.ddu=dd
l.ddu=l.ddu+1
ddu_=translate(ddu,x00,' ')
If wordpos(ddu_,lang_list)=0 Then
lang_list=lang_list ddu_
End
Return
read_cat:
* Read the category page to get language names and number of members
* Output: mem.ddu number of members for (uppercase) Language ddu
* lang_listr the list of relevant languages
*--------------------------------------------------------------------*/
mem.=0
lang_listr=''
Do crecs=0 While lines(cinfid)\==0
l=get_cat(cinfid)
l=translate(l,' ','9'x)
dd=space(l)
If dd=='' Then
Iterate
ddu=translate(dd)
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
du=translate(dd)
If pos('RETRIEVED FROM',du)\==0 Then
Leave
Parse Var dd dd '<' "(" mems .
dd=space(substr(dd,3))
_=translate(dd)
If \l._ Then
Iterate
if pos(',', mems)\==0 then
mems=changestr(",", mems, '')
If\datatype(mems,'W') Then
Iterate
ddu=space(translate(dd))
mem.ddu=mem.ddu+mems
Call memory ddu
End
Return
get_cat:
* get a (logical) line from the category file
* These two lines
* * Lotus 123 Macro Scripting
* </wiki/Category:Lotus_123_Macro_Scripting>�‎ (3 members)
* are returned as one line:
*-> * Lotus 123 Macro Scripting </wiki/Cate ... (3 members)
* we need language name and number of members in one line
*--------------------------------------------------------------------*/
Parse Arg fid
If safe<>'' Then
ol=safe
Else Do
If lines(fid)=0 Then
Return ''
ol=linein(fid)
safe=''
End
If left(ol,3)=' *' Then Do
Do Until left(r,3)==' *' | lines(fid)=0
r=linein(fid)
If left(r,3)==' *' Then Do
safe=r
Return ol
End
Else
ol=ol r
End
End
Return ol
memory:
ddu0=translate(ddu,x00,' ')
If wordpos(ddu0,lang_listr)=0 Then
lang_listr=lang_listr ddu0
Return
fix_lang: Procedure Expose old. new.
Parse Arg s
Do k=1 While old.k\==''
If pos(old.k,s)\==0 Then
s=changestr(old.k,s,new.k)
End
Return s
init:
old.=''
old.1='UC++'
new.1="µC++"
old.2='МК-61/52'
new.2='MK-61/52'
old.3='Déjà Vu'
new.3='Déjà Vu'
old.4='Caché'
new.4='Caché'
old.5='ΜC++'
new.5="MC++"
Call ot 'Language replacements:'
Do ii=1 To 5
Call ot ' ' left(old.ii,10) left(c2x(old.ii),20) '->' new.ii
End
Call ot ' '
Return
no_member: Procedure Expose lang_list lang_listr tid x00 test
* show languages found in language file that are not referred to
* in the category file
*--------------------------------------------------------------------*/
ll =wordsort(lang_list )
llr=wordsort(lang_listr)
Parse Var ll l1 ll
Parse Var llr l2 llr
nn.=0
Do Forever
Select
When l1=l2 Then Do
If l1='' Then
Leave
Parse Var ll l1 ll
Parse Var llr l2 llr
End
When l1<l2 Then Do
z=nn.0+1
nn.z=' 'translate(l1,' ',x00)
nn.0=z
Parse Var ll l1 ll
End
Otherwise Do
Call ot '?? 'translate(l2,' ',x00)
Say 'In category file but not in language file:'
Say '?? 'translate(l2,' ',x00)
Say 'Hit enter to proceed'
Pull .
Parse Var llr l2 llr
End
End
End
Call ot nn.0 'Languages without members:'
Do ii=1 To nn.0
Call ot nn.ii
End
Return
::CLASS mycmp MIXINCLASS Comparator
::METHOD compare
* smaller number is considered higher
* numbers equal: higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
Select
When na<<nb THEN res=1
When na==nb Then Do
If ta<<tb Then res=-1
Else res=1
End
Otherwise res=-1
End
Return res
::CLASS alpha MIXINCLASS Comparator
::METHOD compare
* higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
If ta<<tb Then res=-1
Else res=1
Return res
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. |
* Create a list of Rosetta Code languages showing the number of tasks
* This program's logic is basically that of the REXX program
* rearranged to my taste and utilizing the array class of ooRexx
* which offers a neat way of sorting as desired, see :CLASS mycmp below
* For the input to this program open these links:
* http://rosettacode.org/wiki/Category:Programming_Languages
* http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000
* and save the pages as LAN.txt and CAT.txt, respectively
* Output: RC_POP.txt list of languages sorted by popularity
* If test=1, additionally:
* RC_LNG.txt list of languages alphabetically sorted
* RC_TRN.txt list language name translations (debug)
*--------------------------------------------------------------------*/
test=1
name.='??'
l.=0
safe=''
x00='00'x
linfid='RC_LAN.txt'
linfid='LAN.txt'
cinfid='CAT.txt'
oid='RC_POP.txt'; 'erase' oid
If test Then Do
tid='RC.TRN.txt'; 'erase' tid
tia='RC_LNG.txt'; 'erase' tia
End
Call init
call read_lang
Call read_cat
Call ot words(lang_list) 'possible languages'
Call ot words(lang_listr) 'relevant languages'
llrn=words(lang_listr)
If test Then
Call no_member
a=.array~new
cnt.=0
Do i=1 By 1 While lang_listr<>''
Parse Var lang_listr ddu0 lang_listr
ddu=translate(ddu0,' ',x00)
a[i]=right(mem.ddu,3) name.ddu
z=mem.ddu
cnt.z=cnt.z+1
End
n=i-1
a~sortWith(.mycmp~new)
* and now create the output
*--------------------------------------------------------------------*/
Call o ' '
Call o center('timestamp: ' date() time('Civil'),79,'-')
Call o ' '
Call o right(lrecs,9) 'records read from file: ' linfid
Call o right(crecs,9) 'records read from file: ' cinfid
Call o right(llrn,9) 'relevant languages'
Call o ' '
rank=0
rank.=0
Do i=1 To n
rank=rank+1
Parse Value a[i] With o . 6 lang
ol=' rank: 'right(rank,3)' '||,
'('right(o,3) 'entries) 'lang
If cnt.o>1 Then Do
If rank.o=0 Then
rank.o=rank
ol=overlay(right(rank.o,3),ol,17)
ol=overlay('[tied]',ol,22)
End
Call o ol
End
Call o ' '
Call o center('+ end of list +',72)
Say 'Output in' oid
If test Then Do
b=.array~new
cnt.=0
Do i=1 By 1 While lang_list<>''
Parse Var lang_list ddu0 lang_list
ddu=translate(ddu0,' ',x00)
b[i]=right(mem.ddu,3) name.ddu
End
n=i-1
b~sortWith(.alpha~new)
Call oa n 'languages'
Do i=1 To n
Call oa b[i]
End
Say 'Sorted list of languages in' tia
End
Exit
o:
Return lineout(oid,arg(1))
ot:
If test Then Call lineout tid,arg(1)
Return
oa:
If test Then Call lineout tia,arg(1)
Return
read_lang:
* Read the language page to determine the list of possible languages
* Output: l.lang>0 for all languages found
* name.lang original name of uppercased language name
* lang_list list of uppercased language names
* lrecs number of records read from language file
*--------------------------------------------------------------------*/
l.=0
name.='??'
lang_list=''
Do lrecs=0 While lines(linfid)\==0
l=linein(linfid)
l=translate(l,' ','9'x)
dd=space(l)
ddu=translate(dd)
If pos('AUTOMATED ADMINISTRATION',ddu)>0 Then
Iterate
If pos('RETRIEVED FROM',ddu)\==0 Then
Leave
If dd=='' Then
Iterate
If left(dd,1)\=='*' Then
Iterate
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
Parse Var dd '*' dd "<"
ddu=strip(translate(dd))
If name.ddu='??' Then
name.ddu=dd
l.ddu=l.ddu+1
ddu_=translate(ddu,x00,' ')
If wordpos(ddu_,lang_list)=0 Then
lang_list=lang_list ddu_
End
Return
read_cat:
* Read the category page to get language names and number of members
* Output: mem.ddu number of members for (uppercase) Language ddu
* lang_listr the list of relevant languages
*--------------------------------------------------------------------*/
mem.=0
lang_listr=''
Do crecs=0 While lines(cinfid)\==0
l=get_cat(cinfid)
l=translate(l,' ','9'x)
dd=space(l)
If dd=='' Then
Iterate
ddu=translate(dd)
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
du=translate(dd)
If pos('RETRIEVED FROM',du)\==0 Then
Leave
Parse Var dd dd '<' "(" mems .
dd=space(substr(dd,3))
_=translate(dd)
If \l._ Then
Iterate
if pos(',', mems)\==0 then
mems=changestr(",", mems, '')
If\datatype(mems,'W') Then
Iterate
ddu=space(translate(dd))
mem.ddu=mem.ddu+mems
Call memory ddu
End
Return
get_cat:
* get a (logical) line from the category file
* These two lines
* * Lotus 123 Macro Scripting
* </wiki/Category:Lotus_123_Macro_Scripting>�‎ (3 members)
* are returned as one line:
*-> * Lotus 123 Macro Scripting </wiki/Cate ... (3 members)
* we need language name and number of members in one line
*--------------------------------------------------------------------*/
Parse Arg fid
If safe<>'' Then
ol=safe
Else Do
If lines(fid)=0 Then
Return ''
ol=linein(fid)
safe=''
End
If left(ol,3)=' *' Then Do
Do Until left(r,3)==' *' | lines(fid)=0
r=linein(fid)
If left(r,3)==' *' Then Do
safe=r
Return ol
End
Else
ol=ol r
End
End
Return ol
memory:
ddu0=translate(ddu,x00,' ')
If wordpos(ddu0,lang_listr)=0 Then
lang_listr=lang_listr ddu0
Return
fix_lang: Procedure Expose old. new.
Parse Arg s
Do k=1 While old.k\==''
If pos(old.k,s)\==0 Then
s=changestr(old.k,s,new.k)
End
Return s
init:
old.=''
old.1='UC++'
new.1="µC++"
old.2='МК-61/52'
new.2='MK-61/52'
old.3='Déjà Vu'
new.3='Déjà Vu'
old.4='Caché'
new.4='Caché'
old.5='ΜC++'
new.5="MC++"
Call ot 'Language replacements:'
Do ii=1 To 5
Call ot ' ' left(old.ii,10) left(c2x(old.ii),20) '->' new.ii
End
Call ot ' '
Return
no_member: Procedure Expose lang_list lang_listr tid x00 test
* show languages found in language file that are not referred to
* in the category file
*--------------------------------------------------------------------*/
ll =wordsort(lang_list )
llr=wordsort(lang_listr)
Parse Var ll l1 ll
Parse Var llr l2 llr
nn.=0
Do Forever
Select
When l1=l2 Then Do
If l1='' Then
Leave
Parse Var ll l1 ll
Parse Var llr l2 llr
End
When l1<l2 Then Do
z=nn.0+1
nn.z=' 'translate(l1,' ',x00)
nn.0=z
Parse Var ll l1 ll
End
Otherwise Do
Call ot '?? 'translate(l2,' ',x00)
Say 'In category file but not in language file:'
Say '?? 'translate(l2,' ',x00)
Say 'Hit enter to proceed'
Pull .
Parse Var llr l2 llr
End
End
End
Call ot nn.0 'Languages without members:'
Do ii=1 To nn.0
Call ot nn.ii
End
Return
::CLASS mycmp MIXINCLASS Comparator
::METHOD compare
* smaller number is considered higher
* numbers equal: higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
Select
When na<<nb THEN res=1
When na==nb Then Do
If ta<<tb Then res=-1
Else res=1
End
Otherwise res=-1
End
Return res
::CLASS alpha MIXINCLASS Comparator
::METHOD compare
* higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
If ta<<tb Then res=-1
Else res=1
Return res
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Translate this program into VB but keep the logic exactly as in REXX. |
* Create a list of Rosetta Code languages showing the number of tasks
* This program's logic is basically that of the REXX program
* rearranged to my taste and utilizing the array class of ooRexx
* which offers a neat way of sorting as desired, see :CLASS mycmp below
* For the input to this program open these links:
* http://rosettacode.org/wiki/Category:Programming_Languages
* http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000
* and save the pages as LAN.txt and CAT.txt, respectively
* Output: RC_POP.txt list of languages sorted by popularity
* If test=1, additionally:
* RC_LNG.txt list of languages alphabetically sorted
* RC_TRN.txt list language name translations (debug)
*--------------------------------------------------------------------*/
test=1
name.='??'
l.=0
safe=''
x00='00'x
linfid='RC_LAN.txt'
linfid='LAN.txt'
cinfid='CAT.txt'
oid='RC_POP.txt'; 'erase' oid
If test Then Do
tid='RC.TRN.txt'; 'erase' tid
tia='RC_LNG.txt'; 'erase' tia
End
Call init
call read_lang
Call read_cat
Call ot words(lang_list) 'possible languages'
Call ot words(lang_listr) 'relevant languages'
llrn=words(lang_listr)
If test Then
Call no_member
a=.array~new
cnt.=0
Do i=1 By 1 While lang_listr<>''
Parse Var lang_listr ddu0 lang_listr
ddu=translate(ddu0,' ',x00)
a[i]=right(mem.ddu,3) name.ddu
z=mem.ddu
cnt.z=cnt.z+1
End
n=i-1
a~sortWith(.mycmp~new)
* and now create the output
*--------------------------------------------------------------------*/
Call o ' '
Call o center('timestamp: ' date() time('Civil'),79,'-')
Call o ' '
Call o right(lrecs,9) 'records read from file: ' linfid
Call o right(crecs,9) 'records read from file: ' cinfid
Call o right(llrn,9) 'relevant languages'
Call o ' '
rank=0
rank.=0
Do i=1 To n
rank=rank+1
Parse Value a[i] With o . 6 lang
ol=' rank: 'right(rank,3)' '||,
'('right(o,3) 'entries) 'lang
If cnt.o>1 Then Do
If rank.o=0 Then
rank.o=rank
ol=overlay(right(rank.o,3),ol,17)
ol=overlay('[tied]',ol,22)
End
Call o ol
End
Call o ' '
Call o center('+ end of list +',72)
Say 'Output in' oid
If test Then Do
b=.array~new
cnt.=0
Do i=1 By 1 While lang_list<>''
Parse Var lang_list ddu0 lang_list
ddu=translate(ddu0,' ',x00)
b[i]=right(mem.ddu,3) name.ddu
End
n=i-1
b~sortWith(.alpha~new)
Call oa n 'languages'
Do i=1 To n
Call oa b[i]
End
Say 'Sorted list of languages in' tia
End
Exit
o:
Return lineout(oid,arg(1))
ot:
If test Then Call lineout tid,arg(1)
Return
oa:
If test Then Call lineout tia,arg(1)
Return
read_lang:
* Read the language page to determine the list of possible languages
* Output: l.lang>0 for all languages found
* name.lang original name of uppercased language name
* lang_list list of uppercased language names
* lrecs number of records read from language file
*--------------------------------------------------------------------*/
l.=0
name.='??'
lang_list=''
Do lrecs=0 While lines(linfid)\==0
l=linein(linfid)
l=translate(l,' ','9'x)
dd=space(l)
ddu=translate(dd)
If pos('AUTOMATED ADMINISTRATION',ddu)>0 Then
Iterate
If pos('RETRIEVED FROM',ddu)\==0 Then
Leave
If dd=='' Then
Iterate
If left(dd,1)\=='*' Then
Iterate
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
Parse Var dd '*' dd "<"
ddu=strip(translate(dd))
If name.ddu='??' Then
name.ddu=dd
l.ddu=l.ddu+1
ddu_=translate(ddu,x00,' ')
If wordpos(ddu_,lang_list)=0 Then
lang_list=lang_list ddu_
End
Return
read_cat:
* Read the category page to get language names and number of members
* Output: mem.ddu number of members for (uppercase) Language ddu
* lang_listr the list of relevant languages
*--------------------------------------------------------------------*/
mem.=0
lang_listr=''
Do crecs=0 While lines(cinfid)\==0
l=get_cat(cinfid)
l=translate(l,' ','9'x)
dd=space(l)
If dd=='' Then
Iterate
ddu=translate(dd)
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
du=translate(dd)
If pos('RETRIEVED FROM',du)\==0 Then
Leave
Parse Var dd dd '<' "(" mems .
dd=space(substr(dd,3))
_=translate(dd)
If \l._ Then
Iterate
if pos(',', mems)\==0 then
mems=changestr(",", mems, '')
If\datatype(mems,'W') Then
Iterate
ddu=space(translate(dd))
mem.ddu=mem.ddu+mems
Call memory ddu
End
Return
get_cat:
* get a (logical) line from the category file
* These two lines
* * Lotus 123 Macro Scripting
* </wiki/Category:Lotus_123_Macro_Scripting>�‎ (3 members)
* are returned as one line:
*-> * Lotus 123 Macro Scripting </wiki/Cate ... (3 members)
* we need language name and number of members in one line
*--------------------------------------------------------------------*/
Parse Arg fid
If safe<>'' Then
ol=safe
Else Do
If lines(fid)=0 Then
Return ''
ol=linein(fid)
safe=''
End
If left(ol,3)=' *' Then Do
Do Until left(r,3)==' *' | lines(fid)=0
r=linein(fid)
If left(r,3)==' *' Then Do
safe=r
Return ol
End
Else
ol=ol r
End
End
Return ol
memory:
ddu0=translate(ddu,x00,' ')
If wordpos(ddu0,lang_listr)=0 Then
lang_listr=lang_listr ddu0
Return
fix_lang: Procedure Expose old. new.
Parse Arg s
Do k=1 While old.k\==''
If pos(old.k,s)\==0 Then
s=changestr(old.k,s,new.k)
End
Return s
init:
old.=''
old.1='UC++'
new.1="µC++"
old.2='МК-61/52'
new.2='MK-61/52'
old.3='Déjà Vu'
new.3='Déjà Vu'
old.4='Caché'
new.4='Caché'
old.5='ΜC++'
new.5="MC++"
Call ot 'Language replacements:'
Do ii=1 To 5
Call ot ' ' left(old.ii,10) left(c2x(old.ii),20) '->' new.ii
End
Call ot ' '
Return
no_member: Procedure Expose lang_list lang_listr tid x00 test
* show languages found in language file that are not referred to
* in the category file
*--------------------------------------------------------------------*/
ll =wordsort(lang_list )
llr=wordsort(lang_listr)
Parse Var ll l1 ll
Parse Var llr l2 llr
nn.=0
Do Forever
Select
When l1=l2 Then Do
If l1='' Then
Leave
Parse Var ll l1 ll
Parse Var llr l2 llr
End
When l1<l2 Then Do
z=nn.0+1
nn.z=' 'translate(l1,' ',x00)
nn.0=z
Parse Var ll l1 ll
End
Otherwise Do
Call ot '?? 'translate(l2,' ',x00)
Say 'In category file but not in language file:'
Say '?? 'translate(l2,' ',x00)
Say 'Hit enter to proceed'
Pull .
Parse Var llr l2 llr
End
End
End
Call ot nn.0 'Languages without members:'
Do ii=1 To nn.0
Call ot nn.ii
End
Return
::CLASS mycmp MIXINCLASS Comparator
::METHOD compare
* smaller number is considered higher
* numbers equal: higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
Select
When na<<nb THEN res=1
When na==nb Then Do
If ta<<tb Then res=-1
Else res=1
End
Otherwise res=-1
End
Return res
::CLASS alpha MIXINCLASS Comparator
::METHOD compare
* higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
If ta<<tb Then res=-1
Else res=1
Return res
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Write a version of this REXX function in Go with identical behavior. |
* Create a list of Rosetta Code languages showing the number of tasks
* This program's logic is basically that of the REXX program
* rearranged to my taste and utilizing the array class of ooRexx
* which offers a neat way of sorting as desired, see :CLASS mycmp below
* For the input to this program open these links:
* http://rosettacode.org/wiki/Category:Programming_Languages
* http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000
* and save the pages as LAN.txt and CAT.txt, respectively
* Output: RC_POP.txt list of languages sorted by popularity
* If test=1, additionally:
* RC_LNG.txt list of languages alphabetically sorted
* RC_TRN.txt list language name translations (debug)
*--------------------------------------------------------------------*/
test=1
name.='??'
l.=0
safe=''
x00='00'x
linfid='RC_LAN.txt'
linfid='LAN.txt'
cinfid='CAT.txt'
oid='RC_POP.txt'; 'erase' oid
If test Then Do
tid='RC.TRN.txt'; 'erase' tid
tia='RC_LNG.txt'; 'erase' tia
End
Call init
call read_lang
Call read_cat
Call ot words(lang_list) 'possible languages'
Call ot words(lang_listr) 'relevant languages'
llrn=words(lang_listr)
If test Then
Call no_member
a=.array~new
cnt.=0
Do i=1 By 1 While lang_listr<>''
Parse Var lang_listr ddu0 lang_listr
ddu=translate(ddu0,' ',x00)
a[i]=right(mem.ddu,3) name.ddu
z=mem.ddu
cnt.z=cnt.z+1
End
n=i-1
a~sortWith(.mycmp~new)
* and now create the output
*--------------------------------------------------------------------*/
Call o ' '
Call o center('timestamp: ' date() time('Civil'),79,'-')
Call o ' '
Call o right(lrecs,9) 'records read from file: ' linfid
Call o right(crecs,9) 'records read from file: ' cinfid
Call o right(llrn,9) 'relevant languages'
Call o ' '
rank=0
rank.=0
Do i=1 To n
rank=rank+1
Parse Value a[i] With o . 6 lang
ol=' rank: 'right(rank,3)' '||,
'('right(o,3) 'entries) 'lang
If cnt.o>1 Then Do
If rank.o=0 Then
rank.o=rank
ol=overlay(right(rank.o,3),ol,17)
ol=overlay('[tied]',ol,22)
End
Call o ol
End
Call o ' '
Call o center('+ end of list +',72)
Say 'Output in' oid
If test Then Do
b=.array~new
cnt.=0
Do i=1 By 1 While lang_list<>''
Parse Var lang_list ddu0 lang_list
ddu=translate(ddu0,' ',x00)
b[i]=right(mem.ddu,3) name.ddu
End
n=i-1
b~sortWith(.alpha~new)
Call oa n 'languages'
Do i=1 To n
Call oa b[i]
End
Say 'Sorted list of languages in' tia
End
Exit
o:
Return lineout(oid,arg(1))
ot:
If test Then Call lineout tid,arg(1)
Return
oa:
If test Then Call lineout tia,arg(1)
Return
read_lang:
* Read the language page to determine the list of possible languages
* Output: l.lang>0 for all languages found
* name.lang original name of uppercased language name
* lang_list list of uppercased language names
* lrecs number of records read from language file
*--------------------------------------------------------------------*/
l.=0
name.='??'
lang_list=''
Do lrecs=0 While lines(linfid)\==0
l=linein(linfid)
l=translate(l,' ','9'x)
dd=space(l)
ddu=translate(dd)
If pos('AUTOMATED ADMINISTRATION',ddu)>0 Then
Iterate
If pos('RETRIEVED FROM',ddu)\==0 Then
Leave
If dd=='' Then
Iterate
If left(dd,1)\=='*' Then
Iterate
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
Parse Var dd '*' dd "<"
ddu=strip(translate(dd))
If name.ddu='??' Then
name.ddu=dd
l.ddu=l.ddu+1
ddu_=translate(ddu,x00,' ')
If wordpos(ddu_,lang_list)=0 Then
lang_list=lang_list ddu_
End
Return
read_cat:
* Read the category page to get language names and number of members
* Output: mem.ddu number of members for (uppercase) Language ddu
* lang_listr the list of relevant languages
*--------------------------------------------------------------------*/
mem.=0
lang_listr=''
Do crecs=0 While lines(cinfid)\==0
l=get_cat(cinfid)
l=translate(l,' ','9'x)
dd=space(l)
If dd=='' Then
Iterate
ddu=translate(dd)
ddo=fix_lang(dd)
If ddo<>dd Then Do
Call ot ' ' dd
Call ot '>' ddo
dd=ddo
End
du=translate(dd)
If pos('RETRIEVED FROM',du)\==0 Then
Leave
Parse Var dd dd '<' "(" mems .
dd=space(substr(dd,3))
_=translate(dd)
If \l._ Then
Iterate
if pos(',', mems)\==0 then
mems=changestr(",", mems, '')
If\datatype(mems,'W') Then
Iterate
ddu=space(translate(dd))
mem.ddu=mem.ddu+mems
Call memory ddu
End
Return
get_cat:
* get a (logical) line from the category file
* These two lines
* * Lotus 123 Macro Scripting
* </wiki/Category:Lotus_123_Macro_Scripting>�‎ (3 members)
* are returned as one line:
*-> * Lotus 123 Macro Scripting </wiki/Cate ... (3 members)
* we need language name and number of members in one line
*--------------------------------------------------------------------*/
Parse Arg fid
If safe<>'' Then
ol=safe
Else Do
If lines(fid)=0 Then
Return ''
ol=linein(fid)
safe=''
End
If left(ol,3)=' *' Then Do
Do Until left(r,3)==' *' | lines(fid)=0
r=linein(fid)
If left(r,3)==' *' Then Do
safe=r
Return ol
End
Else
ol=ol r
End
End
Return ol
memory:
ddu0=translate(ddu,x00,' ')
If wordpos(ddu0,lang_listr)=0 Then
lang_listr=lang_listr ddu0
Return
fix_lang: Procedure Expose old. new.
Parse Arg s
Do k=1 While old.k\==''
If pos(old.k,s)\==0 Then
s=changestr(old.k,s,new.k)
End
Return s
init:
old.=''
old.1='UC++'
new.1="µC++"
old.2='МК-61/52'
new.2='MK-61/52'
old.3='Déjà Vu'
new.3='Déjà Vu'
old.4='Caché'
new.4='Caché'
old.5='ΜC++'
new.5="MC++"
Call ot 'Language replacements:'
Do ii=1 To 5
Call ot ' ' left(old.ii,10) left(c2x(old.ii),20) '->' new.ii
End
Call ot ' '
Return
no_member: Procedure Expose lang_list lang_listr tid x00 test
* show languages found in language file that are not referred to
* in the category file
*--------------------------------------------------------------------*/
ll =wordsort(lang_list )
llr=wordsort(lang_listr)
Parse Var ll l1 ll
Parse Var llr l2 llr
nn.=0
Do Forever
Select
When l1=l2 Then Do
If l1='' Then
Leave
Parse Var ll l1 ll
Parse Var llr l2 llr
End
When l1<l2 Then Do
z=nn.0+1
nn.z=' 'translate(l1,' ',x00)
nn.0=z
Parse Var ll l1 ll
End
Otherwise Do
Call ot '?? 'translate(l2,' ',x00)
Say 'In category file but not in language file:'
Say '?? 'translate(l2,' ',x00)
Say 'Hit enter to proceed'
Pull .
Parse Var llr l2 llr
End
End
End
Call ot nn.0 'Languages without members:'
Do ii=1 To nn.0
Call ot nn.ii
End
Return
::CLASS mycmp MIXINCLASS Comparator
::METHOD compare
* smaller number is considered higher
* numbers equal: higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
Select
When na<<nb THEN res=1
When na==nb Then Do
If ta<<tb Then res=-1
Else res=1
End
Otherwise res=-1
End
Return res
::CLASS alpha MIXINCLASS Comparator
::METHOD compare
* higher language considered higher
* otherwise return lower
**********************************************************************/
Parse Upper Arg a,b
Parse Var a na +4 ta
Parse Var b nb +4 tb
If ta<<tb Then res=-1
Else res=1
Return res
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Port the provided Ruby code into C while preserving the original functionality. | require 'rosettacode'
langs = []
RosettaCode.category_members("Programming Languages") {|lang| langs << lang}
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
"action" => "query",
"prop" => "categoryinfo",
"format" => "xml",
"titles" => sublist.join("|"),
})
doc = REXML::Document.new open(url)
REXML::XPath.each(doc, "//page") do |page|
lang = page.attribute("title").value
info = REXML::XPath.first(page, "categoryinfo")
langcount[lang] = info.nil? ? 0 : info.attribute("pages").value.to_i
end
end
puts Time.now
puts "There are
puts "the top 25:"
langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i|
puts "
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Write a version of this Ruby function in C# with identical behavior. | require 'rosettacode'
langs = []
RosettaCode.category_members("Programming Languages") {|lang| langs << lang}
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
"action" => "query",
"prop" => "categoryinfo",
"format" => "xml",
"titles" => sublist.join("|"),
})
doc = REXML::Document.new open(url)
REXML::XPath.each(doc, "//page") do |page|
lang = page.attribute("title").value
info = REXML::XPath.first(page, "categoryinfo")
langcount[lang] = info.nil? ? 0 : info.attribute("pages").value.to_i
end
end
puts Time.now
puts "There are
puts "the top 25:"
langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i|
puts "
end
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | require 'rosettacode'
langs = []
RosettaCode.category_members("Programming Languages") {|lang| langs << lang}
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
"action" => "query",
"prop" => "categoryinfo",
"format" => "xml",
"titles" => sublist.join("|"),
})
doc = REXML::Document.new open(url)
REXML::XPath.each(doc, "//page") do |page|
lang = page.attribute("title").value
info = REXML::XPath.first(page, "categoryinfo")
langcount[lang] = info.nil? ? 0 : info.attribute("pages").value.to_i
end
end
puts Time.now
puts "There are
puts "the top 25:"
langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i|
puts "
end
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Can you help me rewrite this code in Python instead of Ruby, keeping it the same logically? | require 'rosettacode'
langs = []
RosettaCode.category_members("Programming Languages") {|lang| langs << lang}
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
"action" => "query",
"prop" => "categoryinfo",
"format" => "xml",
"titles" => sublist.join("|"),
})
doc = REXML::Document.new open(url)
REXML::XPath.each(doc, "//page") do |page|
lang = page.attribute("title").value
info = REXML::XPath.first(page, "categoryinfo")
langcount[lang] = info.nil? ? 0 : info.attribute("pages").value.to_i
end
end
puts Time.now
puts "There are
puts "the top 25:"
langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i|
puts "
end
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Translate this program into VB but keep the logic exactly as in Ruby. | require 'rosettacode'
langs = []
RosettaCode.category_members("Programming Languages") {|lang| langs << lang}
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
"action" => "query",
"prop" => "categoryinfo",
"format" => "xml",
"titles" => sublist.join("|"),
})
doc = REXML::Document.new open(url)
REXML::XPath.each(doc, "//page") do |page|
lang = page.attribute("title").value
info = REXML::XPath.first(page, "categoryinfo")
langcount[lang] = info.nil? ? 0 : info.attribute("pages").value.to_i
end
end
puts Time.now
puts "There are
puts "the top 25:"
langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i|
puts "
end
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Change the following Ruby code into Go without altering its purpose. | require 'rosettacode'
langs = []
RosettaCode.category_members("Programming Languages") {|lang| langs << lang}
langcount = {}
langs.each_slice(20) do |sublist|
url = RosettaCode.get_api_url({
"action" => "query",
"prop" => "categoryinfo",
"format" => "xml",
"titles" => sublist.join("|"),
})
doc = REXML::Document.new open(url)
REXML::XPath.each(doc, "//page") do |page|
lang = page.attribute("title").value
info = REXML::XPath.first(page, "categoryinfo")
langcount[lang] = info.nil? ? 0 : info.attribute("pages").value.to_i
end
end
puts Time.now
puts "There are
puts "the top 25:"
langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i|
puts "
end
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Rewrite the snippet below in C so it works the same as the original Scala code. | import java.net.URL
import java.io.*
object Popularity {
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
try {
val rc = URL(path).openConnection()
rc.setRequestProperty("User-Agent", "")
val bfr = BufferedReader(InputStreamReader(rc.inputStream))
try {
gcm = ""
var languageName = "?"
var line: String? = bfr.readLine()
while (line != null) {
line = line.trim { it <= ' ' }
if (line.startsWith("[title]")) {
languageName = line[':']
} else if (line.startsWith("[pages]")) {
val pageCount = line['>']
if (pageCount != "Array") {
languages += pageCount.toInt().toChar() + languageName
languageName = "?"
}
} else if (line.startsWith("[gcmcontinue]"))
gcm = line['>']
line = bfr.readLine()
}
} finally {
bfr.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
} while (gcm != "")
return languages.sortedWith(LanguageComparator)
}
internal object LanguageComparator : java.util.Comparator<String> {
override fun compare(a: String, b: String): Int {
var r = b.first() - a.first()
return if (r == 0) a.compareTo(b) else r
}
}
private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }
private val url = "http:
"&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
"&gcmlimit=500"
}
fun main(args: Array<String>) {
var lastTie = -1
var lastCount = -1
Popularity.ofLanguages().forEachIndexed { i, lang ->
val count = lang.first().toInt()
if (count == lastCount)
println("%12s%s".format("", lang.substring(1)))
else {
println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
lastTie = i
lastCount = count
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | import java.net.URL
import java.io.*
object Popularity {
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
try {
val rc = URL(path).openConnection()
rc.setRequestProperty("User-Agent", "")
val bfr = BufferedReader(InputStreamReader(rc.inputStream))
try {
gcm = ""
var languageName = "?"
var line: String? = bfr.readLine()
while (line != null) {
line = line.trim { it <= ' ' }
if (line.startsWith("[title]")) {
languageName = line[':']
} else if (line.startsWith("[pages]")) {
val pageCount = line['>']
if (pageCount != "Array") {
languages += pageCount.toInt().toChar() + languageName
languageName = "?"
}
} else if (line.startsWith("[gcmcontinue]"))
gcm = line['>']
line = bfr.readLine()
}
} finally {
bfr.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
} while (gcm != "")
return languages.sortedWith(LanguageComparator)
}
internal object LanguageComparator : java.util.Comparator<String> {
override fun compare(a: String, b: String): Int {
var r = b.first() - a.first()
return if (r == 0) a.compareTo(b) else r
}
}
private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }
private val url = "http:
"&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
"&gcmlimit=500"
}
fun main(args: Array<String>) {
var lastTie = -1
var lastCount = -1
Popularity.ofLanguages().forEachIndexed { i, lang ->
val count = lang.first().toInt()
if (count == lastCount)
println("%12s%s".format("", lang.substring(1)))
else {
println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
lastTie = i
lastCount = count
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Translate this program into C++ but keep the logic exactly as in Scala. | import java.net.URL
import java.io.*
object Popularity {
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
try {
val rc = URL(path).openConnection()
rc.setRequestProperty("User-Agent", "")
val bfr = BufferedReader(InputStreamReader(rc.inputStream))
try {
gcm = ""
var languageName = "?"
var line: String? = bfr.readLine()
while (line != null) {
line = line.trim { it <= ' ' }
if (line.startsWith("[title]")) {
languageName = line[':']
} else if (line.startsWith("[pages]")) {
val pageCount = line['>']
if (pageCount != "Array") {
languages += pageCount.toInt().toChar() + languageName
languageName = "?"
}
} else if (line.startsWith("[gcmcontinue]"))
gcm = line['>']
line = bfr.readLine()
}
} finally {
bfr.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
} while (gcm != "")
return languages.sortedWith(LanguageComparator)
}
internal object LanguageComparator : java.util.Comparator<String> {
override fun compare(a: String, b: String): Int {
var r = b.first() - a.first()
return if (r == 0) a.compareTo(b) else r
}
}
private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }
private val url = "http:
"&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
"&gcmlimit=500"
}
fun main(args: Array<String>) {
var lastTie = -1
var lastCount = -1
Popularity.ofLanguages().forEachIndexed { i, lang ->
val count = lang.first().toInt()
if (count == lastCount)
println("%12s%s".format("", lang.substring(1)))
else {
println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
lastTie = i
lastCount = count
}
}
}
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Convert the following code from Scala to Java, ensuring the logic remains intact. | import java.net.URL
import java.io.*
object Popularity {
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
try {
val rc = URL(path).openConnection()
rc.setRequestProperty("User-Agent", "")
val bfr = BufferedReader(InputStreamReader(rc.inputStream))
try {
gcm = ""
var languageName = "?"
var line: String? = bfr.readLine()
while (line != null) {
line = line.trim { it <= ' ' }
if (line.startsWith("[title]")) {
languageName = line[':']
} else if (line.startsWith("[pages]")) {
val pageCount = line['>']
if (pageCount != "Array") {
languages += pageCount.toInt().toChar() + languageName
languageName = "?"
}
} else if (line.startsWith("[gcmcontinue]"))
gcm = line['>']
line = bfr.readLine()
}
} finally {
bfr.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
} while (gcm != "")
return languages.sortedWith(LanguageComparator)
}
internal object LanguageComparator : java.util.Comparator<String> {
override fun compare(a: String, b: String): Int {
var r = b.first() - a.first()
return if (r == 0) a.compareTo(b) else r
}
}
private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }
private val url = "http:
"&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
"&gcmlimit=500"
}
fun main(args: Array<String>) {
var lastTie = -1
var lastCount = -1
Popularity.ofLanguages().forEachIndexed { i, lang ->
val count = lang.first().toInt()
if (count == lastCount)
println("%12s%s".format("", lang.substring(1)))
else {
println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
lastTie = i
lastCount = count
}
}
}
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Rewrite the snippet below in Python so it works the same as the original Scala code. | import java.net.URL
import java.io.*
object Popularity {
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
try {
val rc = URL(path).openConnection()
rc.setRequestProperty("User-Agent", "")
val bfr = BufferedReader(InputStreamReader(rc.inputStream))
try {
gcm = ""
var languageName = "?"
var line: String? = bfr.readLine()
while (line != null) {
line = line.trim { it <= ' ' }
if (line.startsWith("[title]")) {
languageName = line[':']
} else if (line.startsWith("[pages]")) {
val pageCount = line['>']
if (pageCount != "Array") {
languages += pageCount.toInt().toChar() + languageName
languageName = "?"
}
} else if (line.startsWith("[gcmcontinue]"))
gcm = line['>']
line = bfr.readLine()
}
} finally {
bfr.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
} while (gcm != "")
return languages.sortedWith(LanguageComparator)
}
internal object LanguageComparator : java.util.Comparator<String> {
override fun compare(a: String, b: String): Int {
var r = b.first() - a.first()
return if (r == 0) a.compareTo(b) else r
}
}
private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }
private val url = "http:
"&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
"&gcmlimit=500"
}
fun main(args: Array<String>) {
var lastTie = -1
var lastCount = -1
Popularity.ofLanguages().forEachIndexed { i, lang ->
val count = lang.first().toInt()
if (count == lastCount)
println("%12s%s".format("", lang.substring(1)))
else {
println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
lastTie = i
lastCount = count
}
}
}
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Write the same code in VB as shown below in Scala. | import java.net.URL
import java.io.*
object Popularity {
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
try {
val rc = URL(path).openConnection()
rc.setRequestProperty("User-Agent", "")
val bfr = BufferedReader(InputStreamReader(rc.inputStream))
try {
gcm = ""
var languageName = "?"
var line: String? = bfr.readLine()
while (line != null) {
line = line.trim { it <= ' ' }
if (line.startsWith("[title]")) {
languageName = line[':']
} else if (line.startsWith("[pages]")) {
val pageCount = line['>']
if (pageCount != "Array") {
languages += pageCount.toInt().toChar() + languageName
languageName = "?"
}
} else if (line.startsWith("[gcmcontinue]"))
gcm = line['>']
line = bfr.readLine()
}
} finally {
bfr.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
} while (gcm != "")
return languages.sortedWith(LanguageComparator)
}
internal object LanguageComparator : java.util.Comparator<String> {
override fun compare(a: String, b: String): Int {
var r = b.first() - a.first()
return if (r == 0) a.compareTo(b) else r
}
}
private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }
private val url = "http:
"&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
"&gcmlimit=500"
}
fun main(args: Array<String>) {
var lastTie = -1
var lastCount = -1
Popularity.ofLanguages().forEachIndexed { i, lang ->
val count = lang.first().toInt()
if (count == lastCount)
println("%12s%s".format("", lang.substring(1)))
else {
println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
lastTie = i
lastCount = count
}
}
}
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Port the following code from Scala to Go with equivalent syntax and logic. | import java.net.URL
import java.io.*
object Popularity {
fun ofLanguages(): List<String> {
val languages = mutableListOf<String>()
var gcm = ""
do {
val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
try {
val rc = URL(path).openConnection()
rc.setRequestProperty("User-Agent", "")
val bfr = BufferedReader(InputStreamReader(rc.inputStream))
try {
gcm = ""
var languageName = "?"
var line: String? = bfr.readLine()
while (line != null) {
line = line.trim { it <= ' ' }
if (line.startsWith("[title]")) {
languageName = line[':']
} else if (line.startsWith("[pages]")) {
val pageCount = line['>']
if (pageCount != "Array") {
languages += pageCount.toInt().toChar() + languageName
languageName = "?"
}
} else if (line.startsWith("[gcmcontinue]"))
gcm = line['>']
line = bfr.readLine()
}
} finally {
bfr.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
} while (gcm != "")
return languages.sortedWith(LanguageComparator)
}
internal object LanguageComparator : java.util.Comparator<String> {
override fun compare(a: String, b: String): Int {
var r = b.first() - a.first()
return if (r == 0) a.compareTo(b) else r
}
}
private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }
private val url = "http:
"&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
"&gcmlimit=500"
}
fun main(args: Array<String>) {
var lastTie = -1
var lastCount = -1
Popularity.ofLanguages().forEachIndexed { i, lang ->
val count = lang.first().toInt()
if (count == lastCount)
println("%12s%s".format("", lang.substring(1)))
else {
println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
lastTie = i
lastCount = count
}
}
}
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Translate the given Tcl code snippet into C without altering its behavior. | package require Tcl 8.5
package require http
set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=8000]
array set ignore {
"Basic language learning" 1
"Encyclopedia" 1
"Implementations" 1
"Language Implementations" 1
"Language users" 1
"Maintenance/OmitCategoriesCreated" 1
"Programming Languages" 1
"Programming Tasks" 1
"RCTemplates" 1
"Solutions by Library" 1
"Solutions by Programming Language" 1
"Solutions by Programming Task" 1
"Unimplemented tasks by language" 1
"WikiStubs" 1
"Examples needing attention" 1
"Impl needed" 1
}
proc filterLang {n} {
return [expr {[string first "User" $n] > 0}]
}
foreach line [split [http::data $response] \n] {
if {[regexp {title..Category:([^"]+).* \((\d+) members\)} $line -> lang num]} {
if {![info exists ignore($lang)] && ![filterLang $lang]} {
lappend langs [list $num $lang]
}
}
}
foreach entry [lsort -integer -index 0 -decreasing $langs] {
lassign $entry num lang
puts [format "%d. %d - %s" [incr i] $num $lang]
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * lang_url = "http:
"list=categorymembers&cmtitle=Category:Programming_Languages&"
"cmlimit=500&format=json";
const char * cat_url = "http:
#define BLOCK 1024
char *get_page(const char *url)
{
char cmd[1024];
char *ptr, *buf;
int bytes_read = 1, len = 0;
sprintf(cmd, "wget -q \"%s\" -O -", url);
FILE *fp = popen(cmd, "r");
if (!fp) return 0;
for (ptr = buf = 0; bytes_read > 0; ) {
buf = realloc(buf, 1 + (len += BLOCK));
if (!ptr) ptr = buf;
bytes_read = fread(ptr, 1, BLOCK, fp);
if (bytes_read <= 0) break;
ptr += bytes_read;
}
*++ptr = '\0';
return buf;
}
char ** get_langs(char *buf, int *l)
{
char **arr = 0;
for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
*buf != '"' || (*buf++ = 0);
buf++);
return arr;
}
typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
char str[1024], *found;
cnt_t *list = 0;
int i, llen = 0;
for (i = 0; i < len; i++) {
sprintf(str, "/wiki/Category:%s", langs[i]);
if (!(found = strstr(buf, str))) continue;
buf = found + strlen(str);
if (!(found = strstr(buf, "</a> ("))) continue;
list = realloc(list, sizeof(cnt_t) * ++llen);
list[llen - 1].name = langs[i];
list[llen - 1].count = strtol(found + 6, 0, 10);
}
*ret_len = llen;
return list;
}
int _scmp(const void *a, const void *b)
{
int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
return x < y ? -1 : x > y;
}
int main()
{
int len, clen;
char ** langs = get_langs(get_page(lang_url), &len);
cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
qsort(cats, clen, sizeof(cnt_t), _scmp);
while (--clen >= 0)
printf("%4d %s\n", cats[clen].count, cats[clen].name);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Tcl to C#. | package require Tcl 8.5
package require http
set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=8000]
array set ignore {
"Basic language learning" 1
"Encyclopedia" 1
"Implementations" 1
"Language Implementations" 1
"Language users" 1
"Maintenance/OmitCategoriesCreated" 1
"Programming Languages" 1
"Programming Tasks" 1
"RCTemplates" 1
"Solutions by Library" 1
"Solutions by Programming Language" 1
"Solutions by Programming Task" 1
"Unimplemented tasks by language" 1
"WikiStubs" 1
"Examples needing attention" 1
"Impl needed" 1
}
proc filterLang {n} {
return [expr {[string first "User" $n] > 0}]
}
foreach line [split [http::data $response] \n] {
if {[regexp {title..Category:([^"]+).* \((\d+) members\)} $line -> lang num]} {
if {![info exists ignore($lang)] && ![filterLang $lang]} {
lappend langs [list $num $lang]
}
}
}
foreach entry [lsort -integer -index 0 -decreasing $langs] {
lassign $entry num lang
puts [format "%d. %d - %s" [incr i] $num $lang]
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string get1 = new WebClient().DownloadString("http:
string get2 = new WebClient().DownloadString("http:
ArrayList langs = new ArrayList();
Dictionary<string, int> qtdmbr = new Dictionary<string, int>();
MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);
foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);
foreach (Match match in match2)
{
if (langs.Contains(match.Groups[1].Value))
{
qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
}
}
string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();
int count = 1;
foreach (string i in test)
{
Console.WriteLine("{0,3}. {1}", count, i);
count++;
}
}
}
|
Preserve the algorithm and functionality while converting the code from Tcl to C++. | package require Tcl 8.5
package require http
set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=8000]
array set ignore {
"Basic language learning" 1
"Encyclopedia" 1
"Implementations" 1
"Language Implementations" 1
"Language users" 1
"Maintenance/OmitCategoriesCreated" 1
"Programming Languages" 1
"Programming Tasks" 1
"RCTemplates" 1
"Solutions by Library" 1
"Solutions by Programming Language" 1
"Solutions by Programming Task" 1
"Unimplemented tasks by language" 1
"WikiStubs" 1
"Examples needing attention" 1
"Impl needed" 1
}
proc filterLang {n} {
return [expr {[string first "User" $n] > 0}]
}
foreach line [split [http::data $response] \n] {
if {[regexp {title..Category:([^"]+).* \((\d+) members\)} $line -> lang num]} {
if {![info exists ignore($lang)] && ![filterLang $lang]} {
lappend langs [list $num $lang]
}
}
}
foreach entry [lsort -integer -index 0 -decreasing $langs] {
lassign $entry num lang
puts [format "%d. %d - %s" [incr i] $num $lang]
}
| #include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
struct Sort {
bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
const {
return a.second > b.second ;
}
} ;
int main( ) {
try {
boost::asio::io_service io_service ;
boost::asio::ip::tcp::resolver resolver ( io_service ) ;
boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
boost::asio::ip::tcp::resolver::iterator end ;
boost::asio::ip::tcp::socket socket( io_service ) ;
boost::system::error_code error = boost::asio::error::host_not_found ;
while ( error && endpoint_iterator != end ) {
socket.close( ) ;
socket.connect( *endpoint_iterator++ , error ) ;
}
if ( error )
throw boost::system::system_error ( error ) ;
boost::asio::streambuf request ;
std::ostream request_stream( &request ) ;
request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
request_stream << "Accept: */*\r\n" ;
request_stream << "Connection: close\r\n\r\n" ;
boost::asio::write( socket , request ) ;
boost::asio::streambuf response ;
std::istream response_stream ( &response ) ;
boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ;
std::ostringstream line ;
std::vector<std::pair<std::string , int> > languages ;
boost::smatch matches ;
while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
line << &response ;
if ( boost::regex_search( line.str( ) , matches , e ) ) {
std::string lang( matches[2].first , matches[2].second ) ;
int zahl = atoi ( lang.c_str( ) ) ;
languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
}
line.str( "") ;
}
if ( error != boost::asio::error::eof )
throw boost::system::system_error( error ) ;
std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
int n = 1 ;
for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
spi != languages.end( ) ; ++spi ) {
std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
spi->second << " - " << spi->first << '\n' ;
n++ ;
}
} catch ( std::exception &ex ) {
std::cout << "Exception: " << ex.what( ) << '\n' ;
}
return 0 ;
}
|
Change the programming language of this snippet from Tcl to Java without modifying what it does. | package require Tcl 8.5
package require http
set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=8000]
array set ignore {
"Basic language learning" 1
"Encyclopedia" 1
"Implementations" 1
"Language Implementations" 1
"Language users" 1
"Maintenance/OmitCategoriesCreated" 1
"Programming Languages" 1
"Programming Tasks" 1
"RCTemplates" 1
"Solutions by Library" 1
"Solutions by Programming Language" 1
"Solutions by Programming Task" 1
"Unimplemented tasks by language" 1
"WikiStubs" 1
"Examples needing attention" 1
"Impl needed" 1
}
proc filterLang {n} {
return [expr {[string first "User" $n] > 0}]
}
foreach line [split [http::data $response] \n] {
if {[regexp {title..Category:([^"]+).* \((\d+) members\)} $line -> lang num]} {
if {![info exists ignore($lang)] && ![filterLang $lang]} {
lappend langs [list $num $lang]
}
}
}
foreach entry [lsort -integer -index 0 -decreasing $langs] {
lassign $entry num lang
puts [format "%d. %d - %s" [incr i] $num $lang]
}
| import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.*;
public class GetRCLanguages
{
private static class LanguageComparator implements Comparator<String>
{
public int compare( String a, String b )
{
int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
if( result == 0 )
{
result = a.compareTo( b );
}
return result;
}
}
private static String after( String text, int marker )
{
String result = "";
int pos = text.indexOf( marker );
if( pos >= 0 )
{
result = text.substring( pos + 1 );
}
return result;
}
public static void parseContent( String path
, String[] gcmcontinue
, ArrayList<String> languageList
)
{
try
{
URL url = new URL( path );
URLConnection rc = url.openConnection();
rc.setRequestProperty( "User-Agent", "" );
BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );
gcmcontinue[0] = "";
String languageName = "?";
String line = bfr.readLine();
while( line != null )
{
line = line.trim();
if ( line.startsWith( "[title]" ) )
{
languageName = after( line, ':' ).trim();
}
else if( line.startsWith( "[pages]" ) )
{
String pageCount = after( line, '>' ).trim();
if( pageCount.compareTo( "Array" ) != 0 )
{
languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
languageName = "?";
}
}
else if( line.startsWith( "[gcmcontinue]" ) )
{
gcmcontinue[0] = after( line, '>' ).trim();
}
line = bfr.readLine();
}
bfr.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
ArrayList<String> languageList = new ArrayList<String>( 1000 );
String[] gcmcontinue = new String[1];
gcmcontinue[0] = "";
do
{
String path = ( "http:
+ "&generator=categorymembers"
+ "&gcmtitle=Category:Programming%20Languages"
+ "&gcmlimit=500"
+ ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
+ "&prop=categoryinfo"
+ "&format=txt"
);
parseContent( path, gcmcontinue, languageList );
}
while( gcmcontinue[0].compareTo( "" ) != 0 );
String[] languages = languageList.toArray(new String[]{});
Arrays.sort( languages, new LanguageComparator() );
int lastTie = -1;
int lastCount = -1;
for( int lPos = 0; lPos < languages.length; lPos ++ )
{
int count = (int) ( languages[ lPos ].charAt( 0 ) );
System.out.format( "%4d: %4d: %s\n"
, 1 + ( count == lastCount ? lastTie : lPos )
, count
, languages[ lPos ].substring( 1 )
);
if( count != lastCount )
{
lastTie = lPos;
lastCount = count;
}
}
}
}
|
Convert this Tcl block to Python, preserving its control flow and logic. | package require Tcl 8.5
package require http
set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=8000]
array set ignore {
"Basic language learning" 1
"Encyclopedia" 1
"Implementations" 1
"Language Implementations" 1
"Language users" 1
"Maintenance/OmitCategoriesCreated" 1
"Programming Languages" 1
"Programming Tasks" 1
"RCTemplates" 1
"Solutions by Library" 1
"Solutions by Programming Language" 1
"Solutions by Programming Task" 1
"Unimplemented tasks by language" 1
"WikiStubs" 1
"Examples needing attention" 1
"Impl needed" 1
}
proc filterLang {n} {
return [expr {[string first "User" $n] > 0}]
}
foreach line [split [http::data $response] \n] {
if {[regexp {title..Category:([^"]+).* \((\d+) members\)} $line -> lang num]} {
if {![info exists ignore($lang)] && ![filterLang $lang]} {
lappend langs [list $num $lang]
}
}
}
foreach entry [lsort -integer -index 0 -decreasing $langs] {
lassign $entry num lang
puts [format "%d. %d - %s" [incr i] $num $lang]
}
| import requests
import re
response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3]
response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)
members = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response)
for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]):
if language in languages:
print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
|
Generate a VB translation of this Tcl snippet without changing its computational steps. | package require Tcl 8.5
package require http
set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=8000]
array set ignore {
"Basic language learning" 1
"Encyclopedia" 1
"Implementations" 1
"Language Implementations" 1
"Language users" 1
"Maintenance/OmitCategoriesCreated" 1
"Programming Languages" 1
"Programming Tasks" 1
"RCTemplates" 1
"Solutions by Library" 1
"Solutions by Programming Language" 1
"Solutions by Programming Task" 1
"Unimplemented tasks by language" 1
"WikiStubs" 1
"Examples needing attention" 1
"Impl needed" 1
}
proc filterLang {n} {
return [expr {[string first "User" $n] > 0}]
}
foreach line [split [http::data $response] \n] {
if {[regexp {title..Category:([^"]+).* \((\d+) members\)} $line -> lang num]} {
if {![info exists ignore($lang)] && ![filterLang $lang]} {
lappend langs [list $num $lang]
}
}
}
foreach entry [lsort -integer -index 0 -decreasing $langs] {
lassign $entry num lang
puts [format "%d. %d - %s" [incr i] $num $lang]
}
|
URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue"
URL2 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue="
Function ScrapeGoat(link)
On Error Resume Next
ScrapeGoat = ""
Err.Clear
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", link, False
objHttp.Send
If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText
Set objHttp = Nothing
End Function
Set HTML = CreateObject("HtmlFile")
Set HTMLWindow = HTML.ParentWindow
On Error Resume Next
isComplete = 0
cntLoop = 0
Set outputData = CreateObject("Scripting.Dictionary")
Do
If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)
If Len(strData) = 0 Then
Set HTML = Nothing
WScript.StdErr.WriteLine "Processing of data stopped because API query failed."
WScript.Quit(1)
End If
HTMLWindow.ExecScript "var json = " & strData, "JavaScript"
Set ObjJS = HTMLWindow.json
Err.Clear
batchCompl = ObjJS.BatchComplete
If Err.Number = 438 Then
gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue
Else
isComplete = 1
End If
HTMLWindow.ExecScript "var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}" & _
"var nums=langs.length;", "JavaScript"
Set arrLangs = HTMLWindow.langs
arrLength = HTMLWindow.nums
For i = 0 to arrLength - 1
BuffStr = "ObjJS.Query.Pages.[" & Eval("arrLangs.[" & i & "]") & "]"
EachStr = Eval(BuffStr & ".title")
Err.Clear
CntLang = Eval(BuffStr & ".CategoryInfo.Pages")
If InStr(EachStr, "Category:") = 1 And Err.Number = 0 Then
outputData.Add Replace(EachStr, "Category:", "", 1, 1), CntLang
End If
Next
cntLoop = cntLoop + 1
Loop While isComplete = 0
arrRelease = Array()
ReDim arrRelease(UBound(outputData.Keys), 1)
outKeys = outputData.Keys
outItem = outputData.Items
For i = 0 To UBound(outKeys)
arrRelease(i, 0) = outKeys(i)
arrRelease(i, 1) = outItem(i)
Next
For i = 0 to UBound(arrRelease, 1)
For j = 0 to UBound(arrRelease, 1) - 1
If arrRelease(j, 1) < arrRelease(j + 1, 1) Then
temp1 = arrRelease(j + 1, 0)
temp2 = arrRelease(j + 1, 1)
arrRelease(j + 1, 0) = arrRelease(j, 0)
arrRelease(j + 1, 1) = arrRelease(j, 1)
arrRelease(j, 0) = temp1
arrRelease(j, 1) = temp2
End If
Next
Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txtOut = objFSO.CreateTextFile(".\OutVBRC.txt", True, True)
txtOut.WriteLine "As of " & Now & ", RC has " & UBound(arrRelease) + 1 & " languages."
txtOut.WriteLine ""
For i = 0 to UBound(arrRelease)
txtOut.WriteLine arrRelease(i, 1) & " Examples - " & arrRelease(i, 0)
Next
Set HTML = Nothing
Set objFSO = Nothing
WScript.Quit(0)
|
Convert this Tcl snippet to Go and keep its semantics consistent. | package require Tcl 8.5
package require http
set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=8000]
array set ignore {
"Basic language learning" 1
"Encyclopedia" 1
"Implementations" 1
"Language Implementations" 1
"Language users" 1
"Maintenance/OmitCategoriesCreated" 1
"Programming Languages" 1
"Programming Tasks" 1
"RCTemplates" 1
"Solutions by Library" 1
"Solutions by Programming Language" 1
"Solutions by Programming Task" 1
"Unimplemented tasks by language" 1
"WikiStubs" 1
"Examples needing attention" 1
"Impl needed" 1
}
proc filterLang {n} {
return [expr {[string first "User" $n] > 0}]
}
foreach line [split [http::data $response] \n] {
if {[regexp {title..Category:([^"]+).* \((\d+) members\)} $line -> lang num]} {
if {![info exists ignore($lang)] && ![filterLang $lang]} {
lappend langs [list $num $lang]
}
}
}
foreach entry [lsort -integer -index 0 -decreasing $langs] {
lassign $entry num lang
puts [format "%d. %d - %s" [incr i] $num $lang]
}
| package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=500"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
log.Fatal(err)
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
type pop struct {
string
int
}
type popList []pop
func (pl popList) Len() int { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
switch d := pl[i].int - pl[j].int; {
case d > 0:
return true
case d < 0:
return false
}
return pl[i].string < pl[j].string
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) {
if strings.HasPrefix(cm, "Category:") {
cm = cm[9:]
}
langMap[cm] = true
}
languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
continueAt := req(languageQuery, storeLang)
for continueAt != "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
s := make(popList, 0, len(langMap))
resp, err := http.Get("http:
"?title=Special:Categories&limit=5000")
if err != nil {
log.Fatal(err)
}
page, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
for _, sm := range rx.FindAllSubmatch(page, -1) {
ls := string(sm[1])
if langMap[ls] {
if n, err := strconv.Atoi(string(sm[2])); err == nil {
s = append(s, pop{ls, n})
}
}
}
sort.Sort(s)
lastCnt, lastIdx := -1, 1
for i, lang := range s {
if lang.int != lastCnt {
lastCnt = lang.int
lastIdx = i + 1
}
fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | package Preferences
is
type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon);
subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last;
type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan);
subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_X'Last;
type Extended_Rank is range 0 .. 10;
subtype Rank is Extended_Rank range 1 .. Extended_Rank'Last;
type His_Rank is array (Rank) of Girl;
type He_Prefers is array (Guy) of His_Rank;
Guys_Like : constant He_Prefers := He_Prefers'(
abe => His_Rank'(abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay),
bob => His_Rank'(cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay),
col => His_Rank'(hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan),
dan => His_Rank'(ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi),
ed => His_Rank'(jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay),
fred => His_Rank'(bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay),
gav => His_Rank'(gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay),
hal => His_Rank'(abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee),
ian => His_Rank'(hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve),
jon => His_Rank'(abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope));
type Her_Rank is array(Rank) of Guy;
type She_Prefers is array (Girl) of Her_Rank;
Girls_Like : constant She_Prefers := She_Prefers'(
abi => Her_Rank'(bob, fred, jon, gav, ian, abe, dan, ed, col, hal),
bea => Her_Rank'(bob, abe, col, fred, gav, dan, ian, ed, jon, hal),
cath => Her_Rank'(fred, bob, ed, gav, hal, col, ian, abe, dan, jon),
dee => Her_Rank'(fred, jon, col, abe, ian, hal, gav, dan, bob, ed),
eve => Her_Rank'(jon, hal, fred, dan, abe, gav, col, ed, ian, bob),
fay => Her_Rank'(bob, abe, ed, ian, jon, dan, fred, gav, col, hal),
gay => Her_Rank'(jon, gav, hal, fred, bob, abe, col, ed, dan, ian),
hope => Her_Rank'(gav, jon, bob, abe, ian, dan, hal, ed, col, fred),
ivy => Her_Rank'(ian, col, hal, gav, fred, bob, abe, ed, jon, dan),
jan => Her_Rank'(ed, hal, gav, abe, bob, jon, col, ian, fred, dan));
end Preferences;
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Write the same code in C as shown below in Ada. | package Preferences
is
type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon);
subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last;
type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan);
subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_X'Last;
type Extended_Rank is range 0 .. 10;
subtype Rank is Extended_Rank range 1 .. Extended_Rank'Last;
type His_Rank is array (Rank) of Girl;
type He_Prefers is array (Guy) of His_Rank;
Guys_Like : constant He_Prefers := He_Prefers'(
abe => His_Rank'(abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay),
bob => His_Rank'(cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay),
col => His_Rank'(hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan),
dan => His_Rank'(ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi),
ed => His_Rank'(jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay),
fred => His_Rank'(bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay),
gav => His_Rank'(gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay),
hal => His_Rank'(abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee),
ian => His_Rank'(hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve),
jon => His_Rank'(abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope));
type Her_Rank is array(Rank) of Guy;
type She_Prefers is array (Girl) of Her_Rank;
Girls_Like : constant She_Prefers := She_Prefers'(
abi => Her_Rank'(bob, fred, jon, gav, ian, abe, dan, ed, col, hal),
bea => Her_Rank'(bob, abe, col, fred, gav, dan, ian, ed, jon, hal),
cath => Her_Rank'(fred, bob, ed, gav, hal, col, ian, abe, dan, jon),
dee => Her_Rank'(fred, jon, col, abe, ian, hal, gav, dan, bob, ed),
eve => Her_Rank'(jon, hal, fred, dan, abe, gav, col, ed, ian, bob),
fay => Her_Rank'(bob, abe, ed, ian, jon, dan, fred, gav, col, hal),
gay => Her_Rank'(jon, gav, hal, fred, bob, abe, col, ed, dan, ian),
hope => Her_Rank'(gav, jon, bob, abe, ian, dan, hal, ed, col, fred),
ivy => Her_Rank'(ian, col, hal, gav, fred, bob, abe, ed, jon, dan),
jan => Her_Rank'(ed, hal, gav, abe, bob, jon, col, ian, fred, dan));
end Preferences;
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },
{ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay },
{ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan },
{ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi },
{ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay },
{ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay },
{ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay },
{ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee },
{ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve },
{ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope },
{ bob, fred, jon, gav, ian, abe, dan, ed, col, hal },
{ bob, abe, col, fred, gav, dan, ian, ed, jon, hal },
{ fred, bob, ed, gav, hal, col, ian, abe, dan, jon },
{ fred, jon, col, abe, ian, hal, gav, dan, bob, ed },
{ jon, hal, fred, dan, abe, gav, col, ed, ian, bob },
{ bob, abe, ed, ian, jon, dan, fred, gav, col, hal },
{ jon, gav, hal, fred, bob, abe, col, ed, dan, ian },
{ gav, jon, bob, abe, ian, dan, hal, ed, col, fred },
{ ian, col, hal, gav, fred, bob, abe, ed, jon, dan },
{ ed, hal, gav, abe, bob, jon, col, ian, fred, dan },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | package Preferences
is
type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon);
subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last;
type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan);
subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_X'Last;
type Extended_Rank is range 0 .. 10;
subtype Rank is Extended_Rank range 1 .. Extended_Rank'Last;
type His_Rank is array (Rank) of Girl;
type He_Prefers is array (Guy) of His_Rank;
Guys_Like : constant He_Prefers := He_Prefers'(
abe => His_Rank'(abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay),
bob => His_Rank'(cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay),
col => His_Rank'(hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan),
dan => His_Rank'(ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi),
ed => His_Rank'(jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay),
fred => His_Rank'(bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay),
gav => His_Rank'(gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay),
hal => His_Rank'(abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee),
ian => His_Rank'(hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve),
jon => His_Rank'(abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope));
type Her_Rank is array(Rank) of Guy;
type She_Prefers is array (Girl) of Her_Rank;
Girls_Like : constant She_Prefers := She_Prefers'(
abi => Her_Rank'(bob, fred, jon, gav, ian, abe, dan, ed, col, hal),
bea => Her_Rank'(bob, abe, col, fred, gav, dan, ian, ed, jon, hal),
cath => Her_Rank'(fred, bob, ed, gav, hal, col, ian, abe, dan, jon),
dee => Her_Rank'(fred, jon, col, abe, ian, hal, gav, dan, bob, ed),
eve => Her_Rank'(jon, hal, fred, dan, abe, gav, col, ed, ian, bob),
fay => Her_Rank'(bob, abe, ed, ian, jon, dan, fred, gav, col, hal),
gay => Her_Rank'(jon, gav, hal, fred, bob, abe, col, ed, dan, ian),
hope => Her_Rank'(gav, jon, bob, abe, ian, dan, hal, ed, col, fred),
ivy => Her_Rank'(ian, col, hal, gav, fred, bob, abe, ed, jon, dan),
jan => Her_Rank'(ed, hal, gav, abe, bob, jon, col, ian, fred, dan));
end Preferences;
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay" },
{ "bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay" },
{ "col", "hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan" },
{ "dan", "ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi" },
{ "ed", "jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay" },
{ "fred", "bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay" },
{ "gav", "gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay" },
{ "hal", "abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee" },
{ "ian", "hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve" },
{ "jon", "abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope" }
};
const char *women_data[][11] = {
{ "abi", "bob","fred","jon","gav","ian","abe","dan","ed","col","hal" },
{ "bea", "bob","abe","col","fred","gav","dan","ian","ed","jon","hal" },
{ "cath", "fred","bob","ed","gav","hal","col","ian","abe","dan","jon" },
{ "dee", "fred","jon","col","abe","ian","hal","gav","dan","bob","ed" },
{ "eve", "jon","hal","fred","dan","abe","gav","col","ed","ian","bob" },
{ "fay", "bob","abe","ed","ian","jon","dan","fred","gav","col","hal" },
{ "gay", "jon","gav","hal","fred","bob","abe","col","ed","dan","ian" },
{ "hope", "gav","jon","bob","abe","ian","dan","hal","ed","col","fred" },
{ "ivy", "ian","col","hal","gav","fred","bob","abe","ed","jon","dan" },
{ "jan", "ed","hal","gav","abe","bob","jon","col","ian","fred","dan" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Convert the following code from Ada to Go, ensuring the logic remains intact. | package Preferences
is
type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon);
subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last;
type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan);
subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_X'Last;
type Extended_Rank is range 0 .. 10;
subtype Rank is Extended_Rank range 1 .. Extended_Rank'Last;
type His_Rank is array (Rank) of Girl;
type He_Prefers is array (Guy) of His_Rank;
Guys_Like : constant He_Prefers := He_Prefers'(
abe => His_Rank'(abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay),
bob => His_Rank'(cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay),
col => His_Rank'(hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan),
dan => His_Rank'(ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi),
ed => His_Rank'(jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay),
fred => His_Rank'(bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay),
gav => His_Rank'(gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay),
hal => His_Rank'(abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee),
ian => His_Rank'(hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve),
jon => His_Rank'(abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope));
type Her_Rank is array(Rank) of Guy;
type She_Prefers is array (Girl) of Her_Rank;
Girls_Like : constant She_Prefers := She_Prefers'(
abi => Her_Rank'(bob, fred, jon, gav, ian, abe, dan, ed, col, hal),
bea => Her_Rank'(bob, abe, col, fred, gav, dan, ian, ed, jon, hal),
cath => Her_Rank'(fred, bob, ed, gav, hal, col, ian, abe, dan, jon),
dee => Her_Rank'(fred, jon, col, abe, ian, hal, gav, dan, bob, ed),
eve => Her_Rank'(jon, hal, fred, dan, abe, gav, col, ed, ian, bob),
fay => Her_Rank'(bob, abe, ed, ian, jon, dan, fred, gav, col, hal),
gay => Her_Rank'(jon, gav, hal, fred, bob, abe, col, ed, dan, ian),
hope => Her_Rank'(gav, jon, bob, abe, ian, dan, hal, ed, col, fred),
ivy => Her_Rank'(ian, col, hal, gav, fred, bob, abe, ed, jon, dan),
jan => Her_Rank'(ed, hal, gav, abe, bob, jon, col, ian, fred, dan));
end Preferences;
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Produce a functionally identical Java code for the snippet given in Ada. | package Preferences
is
type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon);
subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last;
type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan);
subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_X'Last;
type Extended_Rank is range 0 .. 10;
subtype Rank is Extended_Rank range 1 .. Extended_Rank'Last;
type His_Rank is array (Rank) of Girl;
type He_Prefers is array (Guy) of His_Rank;
Guys_Like : constant He_Prefers := He_Prefers'(
abe => His_Rank'(abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay),
bob => His_Rank'(cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay),
col => His_Rank'(hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan),
dan => His_Rank'(ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi),
ed => His_Rank'(jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay),
fred => His_Rank'(bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay),
gav => His_Rank'(gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay),
hal => His_Rank'(abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee),
ian => His_Rank'(hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve),
jon => His_Rank'(abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope));
type Her_Rank is array(Rank) of Guy;
type She_Prefers is array (Girl) of Her_Rank;
Girls_Like : constant She_Prefers := She_Prefers'(
abi => Her_Rank'(bob, fred, jon, gav, ian, abe, dan, ed, col, hal),
bea => Her_Rank'(bob, abe, col, fred, gav, dan, ian, ed, jon, hal),
cath => Her_Rank'(fred, bob, ed, gav, hal, col, ian, abe, dan, jon),
dee => Her_Rank'(fred, jon, col, abe, ian, hal, gav, dan, bob, ed),
eve => Her_Rank'(jon, hal, fred, dan, abe, gav, col, ed, ian, bob),
fay => Her_Rank'(bob, abe, ed, ian, jon, dan, fred, gav, col, hal),
gay => Her_Rank'(jon, gav, hal, fred, bob, abe, col, ed, dan, ian),
hope => Her_Rank'(gav, jon, bob, abe, ian, dan, hal, ed, col, fred),
ivy => Her_Rank'(ian, col, hal, gav, fred, bob, abe, ed, jon, dan),
jan => Her_Rank'(ed, hal, gav, abe, bob, jon, col, ian, fred, dan));
end Preferences;
| import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"});
static Map<String, List<String>> guyPrefers =
new HashMap<String, List<String>>(){{
put("abe",
Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay",
"bea", "hope", "gay"));
put("bob",
Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea",
"jan", "ivy", "gay"));
put("col",
Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy",
"gay", "cath", "jan"));
put("dan",
Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan",
"bea", "cath", "abi"));
put("ed",
Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi",
"ivy", "hope", "gay"));
put("fred",
Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath",
"jan", "hope", "fay"));
put("gav",
Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee",
"hope", "jan", "fay"));
put("hal",
Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan",
"bea", "gay", "dee"));
put("ian",
Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay",
"ivy", "jan", "eve"));
put("jon",
Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee",
"cath", "ivy", "hope"));
}};
static Map<String, List<String>> girlPrefers =
new HashMap<String, List<String>>(){{
put("abi",
Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan",
"ed", "col", "hal"));
put("bea",
Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian",
"ed", "jon", "hal"));
put("cath",
Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"));
put("dee",
Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav",
"dan", "bob", "ed"));
put("eve",
Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col",
"ed", "ian", "bob"));
put("fay",
Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred",
"gav", "col", "hal"));
put("gay",
Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col",
"ed", "dan", "ian"));
put("hope",
Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal",
"ed", "col", "fred"));
put("ivy",
Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe",
"ed", "jon", "dan"));
put("jan",
Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col",
"ian", "fred", "dan"));
}};
public static void main(String[] args){
Map<String, String> matches = match(guys, guyPrefers, girlPrefers);
for(Map.Entry<String, String> couple:matches.entrySet()){
System.out.println(
couple.getKey() + " is engaged to " + couple.getValue());
}
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
String tmp = matches.get(girls.get(0));
matches.put(girls.get(0), matches.get(girls.get(1)));
matches.put(girls.get(1), tmp);
System.out.println(
girls.get(0) +" and " + girls.get(1) + " have switched partners");
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
}
private static Map<String, String> match(List<String> guys,
Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers){
Map<String, String> engagedTo = new TreeMap<String, String>();
List<String> freeGuys = new LinkedList<String>();
freeGuys.addAll(guys);
while(!freeGuys.isEmpty()){
String thisGuy = freeGuys.remove(0);
List<String> thisGuyPrefers = guyPrefers.get(thisGuy);
for(String girl:thisGuyPrefers){
if(engagedTo.get(girl) == null){
engagedTo.put(girl, thisGuy);
break;
}else{
String otherGuy = engagedTo.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(thisGuy) <
thisGirlPrefers.indexOf(otherGuy)){
engagedTo.put(girl, thisGuy);
freeGuys.add(otherGuy);
break;
}
}
}
}
return engagedTo;
}
private static boolean checkMatches(List<String> guys, List<String> girls,
Map<String, String> matches, Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers) {
if(!matches.keySet().containsAll(girls)){
return false;
}
if(!matches.values().containsAll(guys)){
return false;
}
Map<String, String> invertedMatches = new TreeMap<String, String>();
for(Map.Entry<String, String> couple:matches.entrySet()){
invertedMatches.put(couple.getValue(), couple.getKey());
}
for(Map.Entry<String, String> couple:matches.entrySet()){
List<String> shePrefers = girlPrefers.get(couple.getKey());
List<String> sheLikesBetter = new LinkedList<String>();
sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));
List<String> hePrefers = guyPrefers.get(couple.getValue());
List<String> heLikesBetter = new LinkedList<String>();
heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));
for(String guy : sheLikesBetter){
String guysFinace = invertedMatches.get(guy);
List<String> thisGuyPrefers = guyPrefers.get(guy);
if(thisGuyPrefers.indexOf(guysFinace) >
thisGuyPrefers.indexOf(couple.getKey())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getKey(), guy, couple.getValue(),
guy, couple.getKey());
return false;
}
}
for(String girl : heLikesBetter){
String girlsFinace = matches.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(girlsFinace) >
thisGirlPrefers.indexOf(couple.getValue())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getValue(), girl, couple.getKey(),
girl, couple.getValue());
return false;
}
}
}
return true;
}
}
|
Produce a language-to-language conversion: from Ada to Python, same semantics. | package Preferences
is
type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon);
subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last;
type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan);
subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_X'Last;
type Extended_Rank is range 0 .. 10;
subtype Rank is Extended_Rank range 1 .. Extended_Rank'Last;
type His_Rank is array (Rank) of Girl;
type He_Prefers is array (Guy) of His_Rank;
Guys_Like : constant He_Prefers := He_Prefers'(
abe => His_Rank'(abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay),
bob => His_Rank'(cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay),
col => His_Rank'(hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan),
dan => His_Rank'(ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi),
ed => His_Rank'(jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay),
fred => His_Rank'(bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay),
gav => His_Rank'(gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay),
hal => His_Rank'(abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee),
ian => His_Rank'(hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve),
jon => His_Rank'(abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope));
type Her_Rank is array(Rank) of Guy;
type She_Prefers is array (Girl) of Her_Rank;
Girls_Like : constant She_Prefers := She_Prefers'(
abi => Her_Rank'(bob, fred, jon, gav, ian, abe, dan, ed, col, hal),
bea => Her_Rank'(bob, abe, col, fred, gav, dan, ian, ed, jon, hal),
cath => Her_Rank'(fred, bob, ed, gav, hal, col, ian, abe, dan, jon),
dee => Her_Rank'(fred, jon, col, abe, ian, hal, gav, dan, bob, ed),
eve => Her_Rank'(jon, hal, fred, dan, abe, gav, col, ed, ian, bob),
fay => Her_Rank'(bob, abe, ed, ian, jon, dan, fred, gav, col, hal),
gay => Her_Rank'(jon, gav, hal, fred, bob, abe, col, ed, dan, ian),
hope => Her_Rank'(gav, jon, bob, abe, ian, dan, hal, ed, col, fred),
ivy => Her_Rank'(ian, col, hal, gav, fred, bob, abe, ed, jon, dan),
jan => Her_Rank'(ed, hal, gav, abe, bob, jon, col, ian, fred, dan));
end Preferences;
| import copy
guyprefers = {
'abe': ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'],
'bob': ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'],
'col': ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'],
'dan': ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'],
'ed': ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'],
'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'],
'gav': ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'],
'hal': ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'],
'ian': ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'],
'jon': ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']}
galprefers = {
'abi': ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'],
'bea': ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'],
'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'],
'dee': ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'],
'eve': ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'],
'fay': ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'],
'gay': ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'],
'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'],
'ivy': ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'],
'jan': ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Write a version of this Ada function in VB with identical behavior. | package Preferences
is
type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon);
subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last;
type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan);
subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_X'Last;
type Extended_Rank is range 0 .. 10;
subtype Rank is Extended_Rank range 1 .. Extended_Rank'Last;
type His_Rank is array (Rank) of Girl;
type He_Prefers is array (Guy) of His_Rank;
Guys_Like : constant He_Prefers := He_Prefers'(
abe => His_Rank'(abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay),
bob => His_Rank'(cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay),
col => His_Rank'(hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan),
dan => His_Rank'(ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi),
ed => His_Rank'(jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay),
fred => His_Rank'(bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay),
gav => His_Rank'(gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay),
hal => His_Rank'(abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee),
ian => His_Rank'(hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve),
jon => His_Rank'(abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope));
type Her_Rank is array(Rank) of Guy;
type She_Prefers is array (Girl) of Her_Rank;
Girls_Like : constant She_Prefers := She_Prefers'(
abi => Her_Rank'(bob, fred, jon, gav, ian, abe, dan, ed, col, hal),
bea => Her_Rank'(bob, abe, col, fred, gav, dan, ian, ed, jon, hal),
cath => Her_Rank'(fred, bob, ed, gav, hal, col, ian, abe, dan, jon),
dee => Her_Rank'(fred, jon, col, abe, ian, hal, gav, dan, bob, ed),
eve => Her_Rank'(jon, hal, fred, dan, abe, gav, col, ed, ian, bob),
fay => Her_Rank'(bob, abe, ed, ian, jon, dan, fred, gav, col, hal),
gay => Her_Rank'(jon, gav, hal, fred, bob, abe, col, ed, dan, ian),
hope => Her_Rank'(gav, jon, bob, abe, ian, dan, hal, ed, col, fred),
ivy => Her_Rank'(ian, col, hal, gav, fred, bob, abe, ed, jon, dan),
jan => Her_Rank'(ed, hal, gav, abe, bob, jon, col, ian, fred, dan));
end Preferences;
| Sub M_snb()
c00 = "_abe abi eve cath ivy jan dee fay bea hope gay " & _
"_bob cath hope abi dee eve fay bea jan ivy gay " & _
"_col hope eve abi dee bea fay ivy gay cath jan " & _
"_dan ivy fay dee gay hope eve jan bea cath abi " & _
"_ed jan dee bea cath fay eve abi ivy hope gay " & _
"_fred bea abi dee gay eve ivy cath jan hope fay " & _
"_gav gay eve ivy bea cath abi dee hope jan fay " & _
"_hal abi eve hope fay ivy cath jan bea gay dee " & _
"_ian hope cath dee gay bea abi fay ivy jan eve " & _
"_jon abi fay jan gay eve bea dee cath ivy hope " & _
"_abi bob fred jon gav ian abe dan ed col hal " & _
"_bea bob abe col fred gav dan ian ed jon hal " & _
"_cath fred bob ed gav hal col ian abe dan jon " & _
"_dee fred jon col abe ian hal gav dan bob ed " & _
"_eve jon hal fred dan abe gav col ed ian bob " & _
"_fay bob abe ed ian jon dan fred gav col hal " & _
"_gay jon gav hal fred bob abe col ed dan ian " & _
"_hope gav jon bob abe ian dan hal ed col fred " & _
"_ivy ian col hal gav fred bob abe ed jon dan " & _
"_jan ed hal gav abe bob jon col ian fred dan "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Preserve the algorithm and functionality while converting the code from AutoHotKey to C. |
abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]
bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]
col := ["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"]
dan := ["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"]
ed := ["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"]
fred := ["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"]
gav := ["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"]
hal := ["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"]
ian := ["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"]
jon := ["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]
abi := ["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"]
bea := ["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"]
cath := ["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"]
dee := ["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"]
eve := ["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"]
fay := ["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"]
gay := ["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"]
hope := ["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"]
ivy := ["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"]
jan := ["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]
males := ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
females := ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
engagements := Object()
freemales := males.Clone()
,s := "Engagements:`n"
For i, male in freemales
{
j:=1
While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female]))
j++
If (engagements[female] != "")
freemales.insert(engagements[female])
,s .= female . " dumped " . engagements[female] . "`n"
engagements[female] := male
,s .= female . " accepted " . male . "`n"
}
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
s .= "`nWhat if cath and ivy swap?`n"
engagements["cath"]:="abe", engagements["ivy"]:="bob"
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
Msgbox % clipboard := s
Return
Index(obj, value) {
For key, val in obj
If (val = value)
Return, key, ErrorLevel := 0
Return, False, Errorlevel := 1
}
Stable(engagements, females) {
For female, male in engagements
{
For j, female2 in females
{
If (index(%male%, female) > index(%male%, female2)
and index(%female2%, male2:=engagements[female2]) > index(%female2%, male))
s .= male . " is engaged to " . female . " but would prefer " . female2
. " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n"
}
}
If s
Return "`nThese couples are not stable.`n" . s
Else
Return "`nThese couples are stable.`n"
}
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },
{ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay },
{ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan },
{ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi },
{ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay },
{ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay },
{ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay },
{ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee },
{ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve },
{ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope },
{ bob, fred, jon, gav, ian, abe, dan, ed, col, hal },
{ bob, abe, col, fred, gav, dan, ian, ed, jon, hal },
{ fred, bob, ed, gav, hal, col, ian, abe, dan, jon },
{ fred, jon, col, abe, ian, hal, gav, dan, bob, ed },
{ jon, hal, fred, dan, abe, gav, col, ed, ian, bob },
{ bob, abe, ed, ian, jon, dan, fred, gav, col, hal },
{ jon, gav, hal, fred, bob, abe, col, ed, dan, ian },
{ gav, jon, bob, abe, ian, dan, hal, ed, col, fred },
{ ian, col, hal, gav, fred, bob, abe, ed, jon, dan },
{ ed, hal, gav, abe, bob, jon, col, ian, fred, dan },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Produce a functionally identical C# code for the snippet given in AutoHotKey. |
abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]
bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]
col := ["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"]
dan := ["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"]
ed := ["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"]
fred := ["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"]
gav := ["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"]
hal := ["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"]
ian := ["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"]
jon := ["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]
abi := ["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"]
bea := ["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"]
cath := ["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"]
dee := ["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"]
eve := ["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"]
fay := ["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"]
gay := ["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"]
hope := ["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"]
ivy := ["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"]
jan := ["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]
males := ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
females := ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
engagements := Object()
freemales := males.Clone()
,s := "Engagements:`n"
For i, male in freemales
{
j:=1
While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female]))
j++
If (engagements[female] != "")
freemales.insert(engagements[female])
,s .= female . " dumped " . engagements[female] . "`n"
engagements[female] := male
,s .= female . " accepted " . male . "`n"
}
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
s .= "`nWhat if cath and ivy swap?`n"
engagements["cath"]:="abe", engagements["ivy"]:="bob"
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
Msgbox % clipboard := s
Return
Index(obj, value) {
For key, val in obj
If (val = value)
Return, key, ErrorLevel := 0
Return, False, Errorlevel := 1
}
Stable(engagements, females) {
For female, male in engagements
{
For j, female2 in females
{
If (index(%male%, female) > index(%male%, female2)
and index(%female2%, male2:=engagements[female2]) > index(%female2%, male))
s .= male . " is engaged to " . female . " but would prefer " . female2
. " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n"
}
}
If s
Return "`nThese couples are not stable.`n" . s
Else
Return "`nThese couples are stable.`n"
}
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Generate a C++ translation of this AutoHotKey snippet without changing its computational steps. |
abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]
bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]
col := ["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"]
dan := ["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"]
ed := ["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"]
fred := ["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"]
gav := ["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"]
hal := ["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"]
ian := ["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"]
jon := ["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]
abi := ["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"]
bea := ["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"]
cath := ["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"]
dee := ["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"]
eve := ["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"]
fay := ["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"]
gay := ["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"]
hope := ["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"]
ivy := ["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"]
jan := ["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]
males := ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
females := ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
engagements := Object()
freemales := males.Clone()
,s := "Engagements:`n"
For i, male in freemales
{
j:=1
While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female]))
j++
If (engagements[female] != "")
freemales.insert(engagements[female])
,s .= female . " dumped " . engagements[female] . "`n"
engagements[female] := male
,s .= female . " accepted " . male . "`n"
}
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
s .= "`nWhat if cath and ivy swap?`n"
engagements["cath"]:="abe", engagements["ivy"]:="bob"
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
Msgbox % clipboard := s
Return
Index(obj, value) {
For key, val in obj
If (val = value)
Return, key, ErrorLevel := 0
Return, False, Errorlevel := 1
}
Stable(engagements, females) {
For female, male in engagements
{
For j, female2 in females
{
If (index(%male%, female) > index(%male%, female2)
and index(%female2%, male2:=engagements[female2]) > index(%female2%, male))
s .= male . " is engaged to " . female . " but would prefer " . female2
. " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n"
}
}
If s
Return "`nThese couples are not stable.`n" . s
Else
Return "`nThese couples are stable.`n"
}
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay" },
{ "bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay" },
{ "col", "hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan" },
{ "dan", "ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi" },
{ "ed", "jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay" },
{ "fred", "bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay" },
{ "gav", "gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay" },
{ "hal", "abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee" },
{ "ian", "hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve" },
{ "jon", "abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope" }
};
const char *women_data[][11] = {
{ "abi", "bob","fred","jon","gav","ian","abe","dan","ed","col","hal" },
{ "bea", "bob","abe","col","fred","gav","dan","ian","ed","jon","hal" },
{ "cath", "fred","bob","ed","gav","hal","col","ian","abe","dan","jon" },
{ "dee", "fred","jon","col","abe","ian","hal","gav","dan","bob","ed" },
{ "eve", "jon","hal","fred","dan","abe","gav","col","ed","ian","bob" },
{ "fay", "bob","abe","ed","ian","jon","dan","fred","gav","col","hal" },
{ "gay", "jon","gav","hal","fred","bob","abe","col","ed","dan","ian" },
{ "hope", "gav","jon","bob","abe","ian","dan","hal","ed","col","fred" },
{ "ivy", "ian","col","hal","gav","fred","bob","abe","ed","jon","dan" },
{ "jan", "ed","hal","gav","abe","bob","jon","col","ian","fred","dan" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Transform the following AutoHotKey implementation into Python, maintaining the same output and logic. |
abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]
bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]
col := ["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"]
dan := ["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"]
ed := ["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"]
fred := ["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"]
gav := ["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"]
hal := ["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"]
ian := ["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"]
jon := ["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]
abi := ["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"]
bea := ["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"]
cath := ["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"]
dee := ["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"]
eve := ["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"]
fay := ["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"]
gay := ["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"]
hope := ["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"]
ivy := ["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"]
jan := ["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]
males := ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
females := ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
engagements := Object()
freemales := males.Clone()
,s := "Engagements:`n"
For i, male in freemales
{
j:=1
While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female]))
j++
If (engagements[female] != "")
freemales.insert(engagements[female])
,s .= female . " dumped " . engagements[female] . "`n"
engagements[female] := male
,s .= female . " accepted " . male . "`n"
}
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
s .= "`nWhat if cath and ivy swap?`n"
engagements["cath"]:="abe", engagements["ivy"]:="bob"
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
Msgbox % clipboard := s
Return
Index(obj, value) {
For key, val in obj
If (val = value)
Return, key, ErrorLevel := 0
Return, False, Errorlevel := 1
}
Stable(engagements, females) {
For female, male in engagements
{
For j, female2 in females
{
If (index(%male%, female) > index(%male%, female2)
and index(%female2%, male2:=engagements[female2]) > index(%female2%, male))
s .= male . " is engaged to " . female . " but would prefer " . female2
. " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n"
}
}
If s
Return "`nThese couples are not stable.`n" . s
Else
Return "`nThese couples are stable.`n"
}
| import copy
guyprefers = {
'abe': ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'],
'bob': ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'],
'col': ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'],
'dan': ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'],
'ed': ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'],
'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'],
'gav': ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'],
'hal': ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'],
'ian': ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'],
'jon': ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']}
galprefers = {
'abi': ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'],
'bea': ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'],
'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'],
'dee': ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'],
'eve': ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'],
'fay': ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'],
'gay': ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'],
'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'],
'ivy': ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'],
'jan': ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Change the programming language of this snippet from AutoHotKey to VB without modifying what it does. |
abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]
bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]
col := ["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"]
dan := ["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"]
ed := ["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"]
fred := ["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"]
gav := ["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"]
hal := ["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"]
ian := ["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"]
jon := ["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]
abi := ["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"]
bea := ["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"]
cath := ["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"]
dee := ["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"]
eve := ["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"]
fay := ["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"]
gay := ["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"]
hope := ["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"]
ivy := ["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"]
jan := ["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]
males := ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
females := ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
engagements := Object()
freemales := males.Clone()
,s := "Engagements:`n"
For i, male in freemales
{
j:=1
While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female]))
j++
If (engagements[female] != "")
freemales.insert(engagements[female])
,s .= female . " dumped " . engagements[female] . "`n"
engagements[female] := male
,s .= female . " accepted " . male . "`n"
}
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
s .= "`nWhat if cath and ivy swap?`n"
engagements["cath"]:="abe", engagements["ivy"]:="bob"
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
Msgbox % clipboard := s
Return
Index(obj, value) {
For key, val in obj
If (val = value)
Return, key, ErrorLevel := 0
Return, False, Errorlevel := 1
}
Stable(engagements, females) {
For female, male in engagements
{
For j, female2 in females
{
If (index(%male%, female) > index(%male%, female2)
and index(%female2%, male2:=engagements[female2]) > index(%female2%, male))
s .= male . " is engaged to " . female . " but would prefer " . female2
. " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n"
}
}
If s
Return "`nThese couples are not stable.`n" . s
Else
Return "`nThese couples are stable.`n"
}
| Sub M_snb()
c00 = "_abe abi eve cath ivy jan dee fay bea hope gay " & _
"_bob cath hope abi dee eve fay bea jan ivy gay " & _
"_col hope eve abi dee bea fay ivy gay cath jan " & _
"_dan ivy fay dee gay hope eve jan bea cath abi " & _
"_ed jan dee bea cath fay eve abi ivy hope gay " & _
"_fred bea abi dee gay eve ivy cath jan hope fay " & _
"_gav gay eve ivy bea cath abi dee hope jan fay " & _
"_hal abi eve hope fay ivy cath jan bea gay dee " & _
"_ian hope cath dee gay bea abi fay ivy jan eve " & _
"_jon abi fay jan gay eve bea dee cath ivy hope " & _
"_abi bob fred jon gav ian abe dan ed col hal " & _
"_bea bob abe col fred gav dan ian ed jon hal " & _
"_cath fred bob ed gav hal col ian abe dan jon " & _
"_dee fred jon col abe ian hal gav dan bob ed " & _
"_eve jon hal fred dan abe gav col ed ian bob " & _
"_fay bob abe ed ian jon dan fred gav col hal " & _
"_gay jon gav hal fred bob abe col ed dan ian " & _
"_hope gav jon bob abe ian dan hal ed col fred " & _
"_ivy ian col hal gav fred bob abe ed jon dan " & _
"_jan ed hal gav abe bob jon col ian fred dan "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Rewrite this program in Go while keeping its functionality equivalent to the AutoHotKey version. |
abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]
bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]
col := ["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"]
dan := ["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"]
ed := ["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"]
fred := ["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"]
gav := ["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"]
hal := ["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"]
ian := ["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"]
jon := ["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]
abi := ["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"]
bea := ["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"]
cath := ["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"]
dee := ["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"]
eve := ["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"]
fay := ["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"]
gay := ["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"]
hope := ["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"]
ivy := ["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"]
jan := ["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]
males := ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
females := ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
engagements := Object()
freemales := males.Clone()
,s := "Engagements:`n"
For i, male in freemales
{
j:=1
While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female]))
j++
If (engagements[female] != "")
freemales.insert(engagements[female])
,s .= female . " dumped " . engagements[female] . "`n"
engagements[female] := male
,s .= female . " accepted " . male . "`n"
}
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
s .= "`nWhat if cath and ivy swap?`n"
engagements["cath"]:="abe", engagements["ivy"]:="bob"
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
Msgbox % clipboard := s
Return
Index(obj, value) {
For key, val in obj
If (val = value)
Return, key, ErrorLevel := 0
Return, False, Errorlevel := 1
}
Stable(engagements, females) {
For female, male in engagements
{
For j, female2 in females
{
If (index(%male%, female) > index(%male%, female2)
and index(%female2%, male2:=engagements[female2]) > index(%female2%, male))
s .= male . " is engaged to " . female . " but would prefer " . female2
. " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n"
}
}
If s
Return "`nThese couples are not stable.`n" . s
Else
Return "`nThese couples are stable.`n"
}
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Translate the given BBC_Basic code snippet into C without altering its behavior. | N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon"
wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan"
mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\
\ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH"
wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\
\ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD"
REPEAT
FOR m% = 1 TO N
REPEAT
IF mpartner%(m%) EXIT REPEAT
FOR i% = 1 TO N
w% = ASCMID$(mpref$(m%),i%) - 64
IF proposed&(m%,w%) = 0 EXIT FOR
NEXT i%
IF i% > N EXIT REPEAT
proposed&(m%,w%) = 1
IF wpartner%(w%) = 0 THEN
mpartner%(m%) = w% :
wpartner%(w%) = m%
ELSE
o% = wpartner%(w%)
IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN
mpartner%(o%) = 0 :
mpartner%(m%) = w% :
wpartner%(w%) = m%
ENDIF
ENDIF
UNTIL TRUE
NEXT m%
UNTIL SUM(mpartner%()) = (N*(N+1))/2
FOR m% = 1 TO N
PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%))
NEXT
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
a% = RND(N)
REPEAT b% = RND(N) : UNTIL b%<>a%
PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:"
SWAP mpartner%(a%), mpartner%(b%)
PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%))
PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%))
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
END
DEF FNstable
LOCAL m%, w%, o%, p%
FOR m% = 1 TO N
w% = mpartner%(m%)
FOR o% = 1 TO N
p% = wpartner%(o%)
IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \
\ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \
\ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN
= FALSE
ENDIF
NEXT o%
NEXT m%
= TRUE
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },
{ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay },
{ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan },
{ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi },
{ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay },
{ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay },
{ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay },
{ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee },
{ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve },
{ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope },
{ bob, fred, jon, gav, ian, abe, dan, ed, col, hal },
{ bob, abe, col, fred, gav, dan, ian, ed, jon, hal },
{ fred, bob, ed, gav, hal, col, ian, abe, dan, jon },
{ fred, jon, col, abe, ian, hal, gav, dan, bob, ed },
{ jon, hal, fred, dan, abe, gav, col, ed, ian, bob },
{ bob, abe, ed, ian, jon, dan, fred, gav, col, hal },
{ jon, gav, hal, fred, bob, abe, col, ed, dan, ian },
{ gav, jon, bob, abe, ian, dan, hal, ed, col, fred },
{ ian, col, hal, gav, fred, bob, abe, ed, jon, dan },
{ ed, hal, gav, abe, bob, jon, col, ian, fred, dan },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Produce a functionally identical C# code for the snippet given in BBC_Basic. | N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon"
wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan"
mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\
\ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH"
wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\
\ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD"
REPEAT
FOR m% = 1 TO N
REPEAT
IF mpartner%(m%) EXIT REPEAT
FOR i% = 1 TO N
w% = ASCMID$(mpref$(m%),i%) - 64
IF proposed&(m%,w%) = 0 EXIT FOR
NEXT i%
IF i% > N EXIT REPEAT
proposed&(m%,w%) = 1
IF wpartner%(w%) = 0 THEN
mpartner%(m%) = w% :
wpartner%(w%) = m%
ELSE
o% = wpartner%(w%)
IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN
mpartner%(o%) = 0 :
mpartner%(m%) = w% :
wpartner%(w%) = m%
ENDIF
ENDIF
UNTIL TRUE
NEXT m%
UNTIL SUM(mpartner%()) = (N*(N+1))/2
FOR m% = 1 TO N
PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%))
NEXT
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
a% = RND(N)
REPEAT b% = RND(N) : UNTIL b%<>a%
PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:"
SWAP mpartner%(a%), mpartner%(b%)
PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%))
PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%))
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
END
DEF FNstable
LOCAL m%, w%, o%, p%
FOR m% = 1 TO N
w% = mpartner%(m%)
FOR o% = 1 TO N
p% = wpartner%(o%)
IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \
\ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \
\ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN
= FALSE
ENDIF
NEXT o%
NEXT m%
= TRUE
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Rewrite the snippet below in C++ so it works the same as the original BBC_Basic code. | N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon"
wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan"
mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\
\ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH"
wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\
\ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD"
REPEAT
FOR m% = 1 TO N
REPEAT
IF mpartner%(m%) EXIT REPEAT
FOR i% = 1 TO N
w% = ASCMID$(mpref$(m%),i%) - 64
IF proposed&(m%,w%) = 0 EXIT FOR
NEXT i%
IF i% > N EXIT REPEAT
proposed&(m%,w%) = 1
IF wpartner%(w%) = 0 THEN
mpartner%(m%) = w% :
wpartner%(w%) = m%
ELSE
o% = wpartner%(w%)
IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN
mpartner%(o%) = 0 :
mpartner%(m%) = w% :
wpartner%(w%) = m%
ENDIF
ENDIF
UNTIL TRUE
NEXT m%
UNTIL SUM(mpartner%()) = (N*(N+1))/2
FOR m% = 1 TO N
PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%))
NEXT
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
a% = RND(N)
REPEAT b% = RND(N) : UNTIL b%<>a%
PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:"
SWAP mpartner%(a%), mpartner%(b%)
PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%))
PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%))
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
END
DEF FNstable
LOCAL m%, w%, o%, p%
FOR m% = 1 TO N
w% = mpartner%(m%)
FOR o% = 1 TO N
p% = wpartner%(o%)
IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \
\ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \
\ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN
= FALSE
ENDIF
NEXT o%
NEXT m%
= TRUE
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay" },
{ "bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay" },
{ "col", "hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan" },
{ "dan", "ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi" },
{ "ed", "jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay" },
{ "fred", "bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay" },
{ "gav", "gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay" },
{ "hal", "abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee" },
{ "ian", "hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve" },
{ "jon", "abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope" }
};
const char *women_data[][11] = {
{ "abi", "bob","fred","jon","gav","ian","abe","dan","ed","col","hal" },
{ "bea", "bob","abe","col","fred","gav","dan","ian","ed","jon","hal" },
{ "cath", "fred","bob","ed","gav","hal","col","ian","abe","dan","jon" },
{ "dee", "fred","jon","col","abe","ian","hal","gav","dan","bob","ed" },
{ "eve", "jon","hal","fred","dan","abe","gav","col","ed","ian","bob" },
{ "fay", "bob","abe","ed","ian","jon","dan","fred","gav","col","hal" },
{ "gay", "jon","gav","hal","fred","bob","abe","col","ed","dan","ian" },
{ "hope", "gav","jon","bob","abe","ian","dan","hal","ed","col","fred" },
{ "ivy", "ian","col","hal","gav","fred","bob","abe","ed","jon","dan" },
{ "jan", "ed","hal","gav","abe","bob","jon","col","ian","fred","dan" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Port the provided BBC_Basic code into Java while preserving the original functionality. | N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon"
wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan"
mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\
\ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH"
wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\
\ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD"
REPEAT
FOR m% = 1 TO N
REPEAT
IF mpartner%(m%) EXIT REPEAT
FOR i% = 1 TO N
w% = ASCMID$(mpref$(m%),i%) - 64
IF proposed&(m%,w%) = 0 EXIT FOR
NEXT i%
IF i% > N EXIT REPEAT
proposed&(m%,w%) = 1
IF wpartner%(w%) = 0 THEN
mpartner%(m%) = w% :
wpartner%(w%) = m%
ELSE
o% = wpartner%(w%)
IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN
mpartner%(o%) = 0 :
mpartner%(m%) = w% :
wpartner%(w%) = m%
ENDIF
ENDIF
UNTIL TRUE
NEXT m%
UNTIL SUM(mpartner%()) = (N*(N+1))/2
FOR m% = 1 TO N
PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%))
NEXT
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
a% = RND(N)
REPEAT b% = RND(N) : UNTIL b%<>a%
PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:"
SWAP mpartner%(a%), mpartner%(b%)
PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%))
PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%))
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
END
DEF FNstable
LOCAL m%, w%, o%, p%
FOR m% = 1 TO N
w% = mpartner%(m%)
FOR o% = 1 TO N
p% = wpartner%(o%)
IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \
\ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \
\ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN
= FALSE
ENDIF
NEXT o%
NEXT m%
= TRUE
| import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"});
static Map<String, List<String>> guyPrefers =
new HashMap<String, List<String>>(){{
put("abe",
Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay",
"bea", "hope", "gay"));
put("bob",
Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea",
"jan", "ivy", "gay"));
put("col",
Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy",
"gay", "cath", "jan"));
put("dan",
Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan",
"bea", "cath", "abi"));
put("ed",
Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi",
"ivy", "hope", "gay"));
put("fred",
Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath",
"jan", "hope", "fay"));
put("gav",
Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee",
"hope", "jan", "fay"));
put("hal",
Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan",
"bea", "gay", "dee"));
put("ian",
Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay",
"ivy", "jan", "eve"));
put("jon",
Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee",
"cath", "ivy", "hope"));
}};
static Map<String, List<String>> girlPrefers =
new HashMap<String, List<String>>(){{
put("abi",
Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan",
"ed", "col", "hal"));
put("bea",
Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian",
"ed", "jon", "hal"));
put("cath",
Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"));
put("dee",
Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav",
"dan", "bob", "ed"));
put("eve",
Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col",
"ed", "ian", "bob"));
put("fay",
Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred",
"gav", "col", "hal"));
put("gay",
Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col",
"ed", "dan", "ian"));
put("hope",
Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal",
"ed", "col", "fred"));
put("ivy",
Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe",
"ed", "jon", "dan"));
put("jan",
Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col",
"ian", "fred", "dan"));
}};
public static void main(String[] args){
Map<String, String> matches = match(guys, guyPrefers, girlPrefers);
for(Map.Entry<String, String> couple:matches.entrySet()){
System.out.println(
couple.getKey() + " is engaged to " + couple.getValue());
}
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
String tmp = matches.get(girls.get(0));
matches.put(girls.get(0), matches.get(girls.get(1)));
matches.put(girls.get(1), tmp);
System.out.println(
girls.get(0) +" and " + girls.get(1) + " have switched partners");
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
}
private static Map<String, String> match(List<String> guys,
Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers){
Map<String, String> engagedTo = new TreeMap<String, String>();
List<String> freeGuys = new LinkedList<String>();
freeGuys.addAll(guys);
while(!freeGuys.isEmpty()){
String thisGuy = freeGuys.remove(0);
List<String> thisGuyPrefers = guyPrefers.get(thisGuy);
for(String girl:thisGuyPrefers){
if(engagedTo.get(girl) == null){
engagedTo.put(girl, thisGuy);
break;
}else{
String otherGuy = engagedTo.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(thisGuy) <
thisGirlPrefers.indexOf(otherGuy)){
engagedTo.put(girl, thisGuy);
freeGuys.add(otherGuy);
break;
}
}
}
}
return engagedTo;
}
private static boolean checkMatches(List<String> guys, List<String> girls,
Map<String, String> matches, Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers) {
if(!matches.keySet().containsAll(girls)){
return false;
}
if(!matches.values().containsAll(guys)){
return false;
}
Map<String, String> invertedMatches = new TreeMap<String, String>();
for(Map.Entry<String, String> couple:matches.entrySet()){
invertedMatches.put(couple.getValue(), couple.getKey());
}
for(Map.Entry<String, String> couple:matches.entrySet()){
List<String> shePrefers = girlPrefers.get(couple.getKey());
List<String> sheLikesBetter = new LinkedList<String>();
sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));
List<String> hePrefers = guyPrefers.get(couple.getValue());
List<String> heLikesBetter = new LinkedList<String>();
heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));
for(String guy : sheLikesBetter){
String guysFinace = invertedMatches.get(guy);
List<String> thisGuyPrefers = guyPrefers.get(guy);
if(thisGuyPrefers.indexOf(guysFinace) >
thisGuyPrefers.indexOf(couple.getKey())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getKey(), guy, couple.getValue(),
guy, couple.getKey());
return false;
}
}
for(String girl : heLikesBetter){
String girlsFinace = matches.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(girlsFinace) >
thisGirlPrefers.indexOf(couple.getValue())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getValue(), girl, couple.getKey(),
girl, couple.getValue());
return false;
}
}
}
return true;
}
}
|
Convert this BBC_Basic block to Python, preserving its control flow and logic. | N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon"
wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan"
mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\
\ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH"
wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\
\ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD"
REPEAT
FOR m% = 1 TO N
REPEAT
IF mpartner%(m%) EXIT REPEAT
FOR i% = 1 TO N
w% = ASCMID$(mpref$(m%),i%) - 64
IF proposed&(m%,w%) = 0 EXIT FOR
NEXT i%
IF i% > N EXIT REPEAT
proposed&(m%,w%) = 1
IF wpartner%(w%) = 0 THEN
mpartner%(m%) = w% :
wpartner%(w%) = m%
ELSE
o% = wpartner%(w%)
IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN
mpartner%(o%) = 0 :
mpartner%(m%) = w% :
wpartner%(w%) = m%
ENDIF
ENDIF
UNTIL TRUE
NEXT m%
UNTIL SUM(mpartner%()) = (N*(N+1))/2
FOR m% = 1 TO N
PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%))
NEXT
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
a% = RND(N)
REPEAT b% = RND(N) : UNTIL b%<>a%
PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:"
SWAP mpartner%(a%), mpartner%(b%)
PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%))
PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%))
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
END
DEF FNstable
LOCAL m%, w%, o%, p%
FOR m% = 1 TO N
w% = mpartner%(m%)
FOR o% = 1 TO N
p% = wpartner%(o%)
IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \
\ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \
\ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN
= FALSE
ENDIF
NEXT o%
NEXT m%
= TRUE
| import copy
guyprefers = {
'abe': ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'],
'bob': ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'],
'col': ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'],
'dan': ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'],
'ed': ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'],
'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'],
'gav': ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'],
'hal': ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'],
'ian': ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'],
'jon': ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']}
galprefers = {
'abi': ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'],
'bea': ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'],
'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'],
'dee': ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'],
'eve': ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'],
'fay': ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'],
'gay': ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'],
'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'],
'ivy': ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'],
'jan': ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Port the following code from BBC_Basic to VB with equivalent syntax and logic. | N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon"
wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan"
mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\
\ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH"
wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\
\ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD"
REPEAT
FOR m% = 1 TO N
REPEAT
IF mpartner%(m%) EXIT REPEAT
FOR i% = 1 TO N
w% = ASCMID$(mpref$(m%),i%) - 64
IF proposed&(m%,w%) = 0 EXIT FOR
NEXT i%
IF i% > N EXIT REPEAT
proposed&(m%,w%) = 1
IF wpartner%(w%) = 0 THEN
mpartner%(m%) = w% :
wpartner%(w%) = m%
ELSE
o% = wpartner%(w%)
IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN
mpartner%(o%) = 0 :
mpartner%(m%) = w% :
wpartner%(w%) = m%
ENDIF
ENDIF
UNTIL TRUE
NEXT m%
UNTIL SUM(mpartner%()) = (N*(N+1))/2
FOR m% = 1 TO N
PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%))
NEXT
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
a% = RND(N)
REPEAT b% = RND(N) : UNTIL b%<>a%
PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:"
SWAP mpartner%(a%), mpartner%(b%)
PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%))
PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%))
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
END
DEF FNstable
LOCAL m%, w%, o%, p%
FOR m% = 1 TO N
w% = mpartner%(m%)
FOR o% = 1 TO N
p% = wpartner%(o%)
IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \
\ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \
\ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN
= FALSE
ENDIF
NEXT o%
NEXT m%
= TRUE
| Sub M_snb()
c00 = "_abe abi eve cath ivy jan dee fay bea hope gay " & _
"_bob cath hope abi dee eve fay bea jan ivy gay " & _
"_col hope eve abi dee bea fay ivy gay cath jan " & _
"_dan ivy fay dee gay hope eve jan bea cath abi " & _
"_ed jan dee bea cath fay eve abi ivy hope gay " & _
"_fred bea abi dee gay eve ivy cath jan hope fay " & _
"_gav gay eve ivy bea cath abi dee hope jan fay " & _
"_hal abi eve hope fay ivy cath jan bea gay dee " & _
"_ian hope cath dee gay bea abi fay ivy jan eve " & _
"_jon abi fay jan gay eve bea dee cath ivy hope " & _
"_abi bob fred jon gav ian abe dan ed col hal " & _
"_bea bob abe col fred gav dan ian ed jon hal " & _
"_cath fred bob ed gav hal col ian abe dan jon " & _
"_dee fred jon col abe ian hal gav dan bob ed " & _
"_eve jon hal fred dan abe gav col ed ian bob " & _
"_fay bob abe ed ian jon dan fred gav col hal " & _
"_gay jon gav hal fred bob abe col ed dan ian " & _
"_hope gav jon bob abe ian dan hal ed col fred " & _
"_ivy ian col hal gav fred bob abe ed jon dan " & _
"_jan ed hal gav abe bob jon col ian fred dan "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Write the same algorithm in Go as shown in this BBC_Basic implementation. | N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon"
wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan"
mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\
\ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH"
wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\
\ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD"
REPEAT
FOR m% = 1 TO N
REPEAT
IF mpartner%(m%) EXIT REPEAT
FOR i% = 1 TO N
w% = ASCMID$(mpref$(m%),i%) - 64
IF proposed&(m%,w%) = 0 EXIT FOR
NEXT i%
IF i% > N EXIT REPEAT
proposed&(m%,w%) = 1
IF wpartner%(w%) = 0 THEN
mpartner%(m%) = w% :
wpartner%(w%) = m%
ELSE
o% = wpartner%(w%)
IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN
mpartner%(o%) = 0 :
mpartner%(m%) = w% :
wpartner%(w%) = m%
ENDIF
ENDIF
UNTIL TRUE
NEXT m%
UNTIL SUM(mpartner%()) = (N*(N+1))/2
FOR m% = 1 TO N
PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%))
NEXT
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
a% = RND(N)
REPEAT b% = RND(N) : UNTIL b%<>a%
PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:"
SWAP mpartner%(a%), mpartner%(b%)
PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%))
PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%))
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
END
DEF FNstable
LOCAL m%, w%, o%, p%
FOR m% = 1 TO N
w% = mpartner%(m%)
FOR o% = 1 TO N
p% = wpartner%(o%)
IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \
\ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \
\ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN
= FALSE
ENDIF
NEXT o%
NEXT m%
= TRUE
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Ensure the translated C code behaves exactly like the original D snippet. | import std.stdio, std.array, std.algorithm, std.string;
string[string] matchmaker(string[][string] guyPrefers,
string[][string] girlPrefers) {
string[string] engagedTo;
string[] freeGuys = guyPrefers.keys;
while (freeGuys.length) {
const string thisGuy = freeGuys[0];
freeGuys.popFront();
const auto thisGuyPrefers = guyPrefers[thisGuy];
foreach (girl; thisGuyPrefers) {
if (girl !in engagedTo) {
engagedTo[girl] = thisGuy;
break;
} else {
string otherGuy = engagedTo[girl];
string[] thisGirlPrefers = girlPrefers[girl];
if (thisGirlPrefers.countUntil(thisGuy) <
thisGirlPrefers.countUntil(otherGuy)) {
engagedTo[girl] = thisGuy;
freeGuys ~= otherGuy;
break;
}
}
}
}
return engagedTo;
}
bool check(bool doPrint=false)(string[string] engagedTo,
string[][string] guyPrefers,
string[][string] galPrefers) @safe {
enum MSG = "%s likes %s better than %s and %s " ~
"likes %s better than their current partner";
string[string] inverseEngaged;
foreach (k, v; engagedTo)
inverseEngaged[v] = k;
foreach (she, he; engagedTo) {
auto sheLikes = galPrefers[she];
auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];
auto heLikes = guyPrefers[he];
auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];
foreach (guy; sheLikesBetter) {
auto guysGirl = inverseEngaged[guy];
auto guyLikes = guyPrefers[guy];
if (guyLikes.countUntil(guysGirl) >
guyLikes.countUntil(she)) {
static if (doPrint)
writefln(MSG, she, guy, he, guy, she);
return false;
}
}
foreach (gal; heLikesBetter) {
auto girlsGuy = engagedTo[gal];
auto galLikes = galPrefers[gal];
if (galLikes.countUntil(girlsGuy) >
galLikes.countUntil(he)) {
static if (doPrint)
writefln(MSG, he, gal, she, gal, he);
return false;
}
}
}
return true;
}
void main() {
auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay
bob cath hope abi dee eve fay bea jan ivy gay
col hope eve abi dee bea fay ivy gay cath jan
dan ivy fay dee gay hope eve jan bea cath abi
ed jan dee bea cath fay eve abi ivy hope gay
fred bea abi dee gay eve ivy cath jan hope fay
gav gay eve ivy bea cath abi dee hope jan fay
hal abi eve hope fay ivy cath jan bea gay dee
ian hope cath dee gay bea abi fay ivy jan eve
jon abi fay jan gay eve bea dee cath ivy hope";
auto galData = "abi bob fred jon gav ian abe dan ed col hal
bea bob abe col fred gav dan ian ed jon hal
cath fred bob ed gav hal col ian abe dan jon
dee fred jon col abe ian hal gav dan bob ed
eve jon hal fred dan abe gav col ed ian bob
fay bob abe ed ian jon dan fred gav col hal
gay jon gav hal fred bob abe col ed dan ian
hope gav jon bob abe ian dan hal ed col fred
ivy ian col hal gav fred bob abe ed jon dan
jan ed hal gav abe bob jon col ian fred dan";
string[][string] guyPrefers, galPrefers;
foreach (line; guyData.splitLines())
guyPrefers[split(line)[0]] = split(line)[1..$];
foreach (line; galData.splitLines())
galPrefers[split(line)[0]] = split(line)[1..$];
writeln("Engagements:");
auto engagedTo = matchmaker(guyPrefers, galPrefers);
writeln("\nCouples:");
string[] parts;
foreach (k; engagedTo.keys.sort())
writefln("%s is engagedTo to %s", k, engagedTo[k]);
writeln();
bool c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
writeln("\n\nSwapping two fiances to introduce an error");
auto gals = galPrefers.keys.sort();
swap(engagedTo[gals[0]], engagedTo[gals[1]]);
foreach (gal; gals[0 .. 2])
writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]);
writeln();
c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
}
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },
{ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay },
{ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan },
{ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi },
{ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay },
{ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay },
{ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay },
{ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee },
{ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve },
{ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope },
{ bob, fred, jon, gav, ian, abe, dan, ed, col, hal },
{ bob, abe, col, fred, gav, dan, ian, ed, jon, hal },
{ fred, bob, ed, gav, hal, col, ian, abe, dan, jon },
{ fred, jon, col, abe, ian, hal, gav, dan, bob, ed },
{ jon, hal, fred, dan, abe, gav, col, ed, ian, bob },
{ bob, abe, ed, ian, jon, dan, fred, gav, col, hal },
{ jon, gav, hal, fred, bob, abe, col, ed, dan, ian },
{ gav, jon, bob, abe, ian, dan, hal, ed, col, fred },
{ ian, col, hal, gav, fred, bob, abe, ed, jon, dan },
{ ed, hal, gav, abe, bob, jon, col, ian, fred, dan },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | import std.stdio, std.array, std.algorithm, std.string;
string[string] matchmaker(string[][string] guyPrefers,
string[][string] girlPrefers) {
string[string] engagedTo;
string[] freeGuys = guyPrefers.keys;
while (freeGuys.length) {
const string thisGuy = freeGuys[0];
freeGuys.popFront();
const auto thisGuyPrefers = guyPrefers[thisGuy];
foreach (girl; thisGuyPrefers) {
if (girl !in engagedTo) {
engagedTo[girl] = thisGuy;
break;
} else {
string otherGuy = engagedTo[girl];
string[] thisGirlPrefers = girlPrefers[girl];
if (thisGirlPrefers.countUntil(thisGuy) <
thisGirlPrefers.countUntil(otherGuy)) {
engagedTo[girl] = thisGuy;
freeGuys ~= otherGuy;
break;
}
}
}
}
return engagedTo;
}
bool check(bool doPrint=false)(string[string] engagedTo,
string[][string] guyPrefers,
string[][string] galPrefers) @safe {
enum MSG = "%s likes %s better than %s and %s " ~
"likes %s better than their current partner";
string[string] inverseEngaged;
foreach (k, v; engagedTo)
inverseEngaged[v] = k;
foreach (she, he; engagedTo) {
auto sheLikes = galPrefers[she];
auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];
auto heLikes = guyPrefers[he];
auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];
foreach (guy; sheLikesBetter) {
auto guysGirl = inverseEngaged[guy];
auto guyLikes = guyPrefers[guy];
if (guyLikes.countUntil(guysGirl) >
guyLikes.countUntil(she)) {
static if (doPrint)
writefln(MSG, she, guy, he, guy, she);
return false;
}
}
foreach (gal; heLikesBetter) {
auto girlsGuy = engagedTo[gal];
auto galLikes = galPrefers[gal];
if (galLikes.countUntil(girlsGuy) >
galLikes.countUntil(he)) {
static if (doPrint)
writefln(MSG, he, gal, she, gal, he);
return false;
}
}
}
return true;
}
void main() {
auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay
bob cath hope abi dee eve fay bea jan ivy gay
col hope eve abi dee bea fay ivy gay cath jan
dan ivy fay dee gay hope eve jan bea cath abi
ed jan dee bea cath fay eve abi ivy hope gay
fred bea abi dee gay eve ivy cath jan hope fay
gav gay eve ivy bea cath abi dee hope jan fay
hal abi eve hope fay ivy cath jan bea gay dee
ian hope cath dee gay bea abi fay ivy jan eve
jon abi fay jan gay eve bea dee cath ivy hope";
auto galData = "abi bob fred jon gav ian abe dan ed col hal
bea bob abe col fred gav dan ian ed jon hal
cath fred bob ed gav hal col ian abe dan jon
dee fred jon col abe ian hal gav dan bob ed
eve jon hal fred dan abe gav col ed ian bob
fay bob abe ed ian jon dan fred gav col hal
gay jon gav hal fred bob abe col ed dan ian
hope gav jon bob abe ian dan hal ed col fred
ivy ian col hal gav fred bob abe ed jon dan
jan ed hal gav abe bob jon col ian fred dan";
string[][string] guyPrefers, galPrefers;
foreach (line; guyData.splitLines())
guyPrefers[split(line)[0]] = split(line)[1..$];
foreach (line; galData.splitLines())
galPrefers[split(line)[0]] = split(line)[1..$];
writeln("Engagements:");
auto engagedTo = matchmaker(guyPrefers, galPrefers);
writeln("\nCouples:");
string[] parts;
foreach (k; engagedTo.keys.sort())
writefln("%s is engagedTo to %s", k, engagedTo[k]);
writeln();
bool c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
writeln("\n\nSwapping two fiances to introduce an error");
auto gals = galPrefers.keys.sort();
swap(engagedTo[gals[0]], engagedTo[gals[1]]);
foreach (gal; gals[0 .. 2])
writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]);
writeln();
c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
}
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Produce a language-to-language conversion: from D to C++, same semantics. | import std.stdio, std.array, std.algorithm, std.string;
string[string] matchmaker(string[][string] guyPrefers,
string[][string] girlPrefers) {
string[string] engagedTo;
string[] freeGuys = guyPrefers.keys;
while (freeGuys.length) {
const string thisGuy = freeGuys[0];
freeGuys.popFront();
const auto thisGuyPrefers = guyPrefers[thisGuy];
foreach (girl; thisGuyPrefers) {
if (girl !in engagedTo) {
engagedTo[girl] = thisGuy;
break;
} else {
string otherGuy = engagedTo[girl];
string[] thisGirlPrefers = girlPrefers[girl];
if (thisGirlPrefers.countUntil(thisGuy) <
thisGirlPrefers.countUntil(otherGuy)) {
engagedTo[girl] = thisGuy;
freeGuys ~= otherGuy;
break;
}
}
}
}
return engagedTo;
}
bool check(bool doPrint=false)(string[string] engagedTo,
string[][string] guyPrefers,
string[][string] galPrefers) @safe {
enum MSG = "%s likes %s better than %s and %s " ~
"likes %s better than their current partner";
string[string] inverseEngaged;
foreach (k, v; engagedTo)
inverseEngaged[v] = k;
foreach (she, he; engagedTo) {
auto sheLikes = galPrefers[she];
auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];
auto heLikes = guyPrefers[he];
auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];
foreach (guy; sheLikesBetter) {
auto guysGirl = inverseEngaged[guy];
auto guyLikes = guyPrefers[guy];
if (guyLikes.countUntil(guysGirl) >
guyLikes.countUntil(she)) {
static if (doPrint)
writefln(MSG, she, guy, he, guy, she);
return false;
}
}
foreach (gal; heLikesBetter) {
auto girlsGuy = engagedTo[gal];
auto galLikes = galPrefers[gal];
if (galLikes.countUntil(girlsGuy) >
galLikes.countUntil(he)) {
static if (doPrint)
writefln(MSG, he, gal, she, gal, he);
return false;
}
}
}
return true;
}
void main() {
auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay
bob cath hope abi dee eve fay bea jan ivy gay
col hope eve abi dee bea fay ivy gay cath jan
dan ivy fay dee gay hope eve jan bea cath abi
ed jan dee bea cath fay eve abi ivy hope gay
fred bea abi dee gay eve ivy cath jan hope fay
gav gay eve ivy bea cath abi dee hope jan fay
hal abi eve hope fay ivy cath jan bea gay dee
ian hope cath dee gay bea abi fay ivy jan eve
jon abi fay jan gay eve bea dee cath ivy hope";
auto galData = "abi bob fred jon gav ian abe dan ed col hal
bea bob abe col fred gav dan ian ed jon hal
cath fred bob ed gav hal col ian abe dan jon
dee fred jon col abe ian hal gav dan bob ed
eve jon hal fred dan abe gav col ed ian bob
fay bob abe ed ian jon dan fred gav col hal
gay jon gav hal fred bob abe col ed dan ian
hope gav jon bob abe ian dan hal ed col fred
ivy ian col hal gav fred bob abe ed jon dan
jan ed hal gav abe bob jon col ian fred dan";
string[][string] guyPrefers, galPrefers;
foreach (line; guyData.splitLines())
guyPrefers[split(line)[0]] = split(line)[1..$];
foreach (line; galData.splitLines())
galPrefers[split(line)[0]] = split(line)[1..$];
writeln("Engagements:");
auto engagedTo = matchmaker(guyPrefers, galPrefers);
writeln("\nCouples:");
string[] parts;
foreach (k; engagedTo.keys.sort())
writefln("%s is engagedTo to %s", k, engagedTo[k]);
writeln();
bool c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
writeln("\n\nSwapping two fiances to introduce an error");
auto gals = galPrefers.keys.sort();
swap(engagedTo[gals[0]], engagedTo[gals[1]]);
foreach (gal; gals[0 .. 2])
writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]);
writeln();
c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
}
| #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay" },
{ "bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay" },
{ "col", "hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan" },
{ "dan", "ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi" },
{ "ed", "jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay" },
{ "fred", "bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay" },
{ "gav", "gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay" },
{ "hal", "abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee" },
{ "ian", "hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve" },
{ "jon", "abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope" }
};
const char *women_data[][11] = {
{ "abi", "bob","fred","jon","gav","ian","abe","dan","ed","col","hal" },
{ "bea", "bob","abe","col","fred","gav","dan","ian","ed","jon","hal" },
{ "cath", "fred","bob","ed","gav","hal","col","ian","abe","dan","jon" },
{ "dee", "fred","jon","col","abe","ian","hal","gav","dan","bob","ed" },
{ "eve", "jon","hal","fred","dan","abe","gav","col","ed","ian","bob" },
{ "fay", "bob","abe","ed","ian","jon","dan","fred","gav","col","hal" },
{ "gay", "jon","gav","hal","fred","bob","abe","col","ed","dan","ian" },
{ "hope", "gav","jon","bob","abe","ian","dan","hal","ed","col","fred" },
{ "ivy", "ian","col","hal","gav","fred","bob","abe","ed","jon","dan" },
{ "jan", "ed","hal","gav","abe","bob","jon","col","ian","fred","dan" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false;
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride)
break;
if (prefers(preflist, *it, bride) &&
prefers(women_pref.at(*it), groom, engaged.at(*it)))
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
for (int i = 0; i < 10; ++i)
{
for (int j = 1; j < 11; ++j)
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged;
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end())
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor;
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom);
engaged[bride] = suitor;
break;
}
}
bachelors.pop();
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
}
|
Port the following code from D to Python with equivalent syntax and logic. | import std.stdio, std.array, std.algorithm, std.string;
string[string] matchmaker(string[][string] guyPrefers,
string[][string] girlPrefers) {
string[string] engagedTo;
string[] freeGuys = guyPrefers.keys;
while (freeGuys.length) {
const string thisGuy = freeGuys[0];
freeGuys.popFront();
const auto thisGuyPrefers = guyPrefers[thisGuy];
foreach (girl; thisGuyPrefers) {
if (girl !in engagedTo) {
engagedTo[girl] = thisGuy;
break;
} else {
string otherGuy = engagedTo[girl];
string[] thisGirlPrefers = girlPrefers[girl];
if (thisGirlPrefers.countUntil(thisGuy) <
thisGirlPrefers.countUntil(otherGuy)) {
engagedTo[girl] = thisGuy;
freeGuys ~= otherGuy;
break;
}
}
}
}
return engagedTo;
}
bool check(bool doPrint=false)(string[string] engagedTo,
string[][string] guyPrefers,
string[][string] galPrefers) @safe {
enum MSG = "%s likes %s better than %s and %s " ~
"likes %s better than their current partner";
string[string] inverseEngaged;
foreach (k, v; engagedTo)
inverseEngaged[v] = k;
foreach (she, he; engagedTo) {
auto sheLikes = galPrefers[she];
auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];
auto heLikes = guyPrefers[he];
auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];
foreach (guy; sheLikesBetter) {
auto guysGirl = inverseEngaged[guy];
auto guyLikes = guyPrefers[guy];
if (guyLikes.countUntil(guysGirl) >
guyLikes.countUntil(she)) {
static if (doPrint)
writefln(MSG, she, guy, he, guy, she);
return false;
}
}
foreach (gal; heLikesBetter) {
auto girlsGuy = engagedTo[gal];
auto galLikes = galPrefers[gal];
if (galLikes.countUntil(girlsGuy) >
galLikes.countUntil(he)) {
static if (doPrint)
writefln(MSG, he, gal, she, gal, he);
return false;
}
}
}
return true;
}
void main() {
auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay
bob cath hope abi dee eve fay bea jan ivy gay
col hope eve abi dee bea fay ivy gay cath jan
dan ivy fay dee gay hope eve jan bea cath abi
ed jan dee bea cath fay eve abi ivy hope gay
fred bea abi dee gay eve ivy cath jan hope fay
gav gay eve ivy bea cath abi dee hope jan fay
hal abi eve hope fay ivy cath jan bea gay dee
ian hope cath dee gay bea abi fay ivy jan eve
jon abi fay jan gay eve bea dee cath ivy hope";
auto galData = "abi bob fred jon gav ian abe dan ed col hal
bea bob abe col fred gav dan ian ed jon hal
cath fred bob ed gav hal col ian abe dan jon
dee fred jon col abe ian hal gav dan bob ed
eve jon hal fred dan abe gav col ed ian bob
fay bob abe ed ian jon dan fred gav col hal
gay jon gav hal fred bob abe col ed dan ian
hope gav jon bob abe ian dan hal ed col fred
ivy ian col hal gav fred bob abe ed jon dan
jan ed hal gav abe bob jon col ian fred dan";
string[][string] guyPrefers, galPrefers;
foreach (line; guyData.splitLines())
guyPrefers[split(line)[0]] = split(line)[1..$];
foreach (line; galData.splitLines())
galPrefers[split(line)[0]] = split(line)[1..$];
writeln("Engagements:");
auto engagedTo = matchmaker(guyPrefers, galPrefers);
writeln("\nCouples:");
string[] parts;
foreach (k; engagedTo.keys.sort())
writefln("%s is engagedTo to %s", k, engagedTo[k]);
writeln();
bool c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
writeln("\n\nSwapping two fiances to introduce an error");
auto gals = galPrefers.keys.sort();
swap(engagedTo[gals[0]], engagedTo[gals[1]]);
foreach (gal; gals[0 .. 2])
writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]);
writeln();
c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
}
| import copy
guyprefers = {
'abe': ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'],
'bob': ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'],
'col': ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'],
'dan': ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'],
'ed': ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'],
'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'],
'gav': ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'],
'hal': ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'],
'ian': ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'],
'jon': ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']}
galprefers = {
'abi': ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'],
'bea': ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'],
'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'],
'dee': ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'],
'eve': ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'],
'fay': ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'],
'gay': ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'],
'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'],
'ivy': ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'],
'jan': ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Convert the following code from D to VB, ensuring the logic remains intact. | import std.stdio, std.array, std.algorithm, std.string;
string[string] matchmaker(string[][string] guyPrefers,
string[][string] girlPrefers) {
string[string] engagedTo;
string[] freeGuys = guyPrefers.keys;
while (freeGuys.length) {
const string thisGuy = freeGuys[0];
freeGuys.popFront();
const auto thisGuyPrefers = guyPrefers[thisGuy];
foreach (girl; thisGuyPrefers) {
if (girl !in engagedTo) {
engagedTo[girl] = thisGuy;
break;
} else {
string otherGuy = engagedTo[girl];
string[] thisGirlPrefers = girlPrefers[girl];
if (thisGirlPrefers.countUntil(thisGuy) <
thisGirlPrefers.countUntil(otherGuy)) {
engagedTo[girl] = thisGuy;
freeGuys ~= otherGuy;
break;
}
}
}
}
return engagedTo;
}
bool check(bool doPrint=false)(string[string] engagedTo,
string[][string] guyPrefers,
string[][string] galPrefers) @safe {
enum MSG = "%s likes %s better than %s and %s " ~
"likes %s better than their current partner";
string[string] inverseEngaged;
foreach (k, v; engagedTo)
inverseEngaged[v] = k;
foreach (she, he; engagedTo) {
auto sheLikes = galPrefers[she];
auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];
auto heLikes = guyPrefers[he];
auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];
foreach (guy; sheLikesBetter) {
auto guysGirl = inverseEngaged[guy];
auto guyLikes = guyPrefers[guy];
if (guyLikes.countUntil(guysGirl) >
guyLikes.countUntil(she)) {
static if (doPrint)
writefln(MSG, she, guy, he, guy, she);
return false;
}
}
foreach (gal; heLikesBetter) {
auto girlsGuy = engagedTo[gal];
auto galLikes = galPrefers[gal];
if (galLikes.countUntil(girlsGuy) >
galLikes.countUntil(he)) {
static if (doPrint)
writefln(MSG, he, gal, she, gal, he);
return false;
}
}
}
return true;
}
void main() {
auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay
bob cath hope abi dee eve fay bea jan ivy gay
col hope eve abi dee bea fay ivy gay cath jan
dan ivy fay dee gay hope eve jan bea cath abi
ed jan dee bea cath fay eve abi ivy hope gay
fred bea abi dee gay eve ivy cath jan hope fay
gav gay eve ivy bea cath abi dee hope jan fay
hal abi eve hope fay ivy cath jan bea gay dee
ian hope cath dee gay bea abi fay ivy jan eve
jon abi fay jan gay eve bea dee cath ivy hope";
auto galData = "abi bob fred jon gav ian abe dan ed col hal
bea bob abe col fred gav dan ian ed jon hal
cath fred bob ed gav hal col ian abe dan jon
dee fred jon col abe ian hal gav dan bob ed
eve jon hal fred dan abe gav col ed ian bob
fay bob abe ed ian jon dan fred gav col hal
gay jon gav hal fred bob abe col ed dan ian
hope gav jon bob abe ian dan hal ed col fred
ivy ian col hal gav fred bob abe ed jon dan
jan ed hal gav abe bob jon col ian fred dan";
string[][string] guyPrefers, galPrefers;
foreach (line; guyData.splitLines())
guyPrefers[split(line)[0]] = split(line)[1..$];
foreach (line; galData.splitLines())
galPrefers[split(line)[0]] = split(line)[1..$];
writeln("Engagements:");
auto engagedTo = matchmaker(guyPrefers, galPrefers);
writeln("\nCouples:");
string[] parts;
foreach (k; engagedTo.keys.sort())
writefln("%s is engagedTo to %s", k, engagedTo[k]);
writeln();
bool c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
writeln("\n\nSwapping two fiances to introduce an error");
auto gals = galPrefers.keys.sort();
swap(engagedTo[gals[0]], engagedTo[gals[1]]);
foreach (gal; gals[0 .. 2])
writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]);
writeln();
c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
}
| Sub M_snb()
c00 = "_abe abi eve cath ivy jan dee fay bea hope gay " & _
"_bob cath hope abi dee eve fay bea jan ivy gay " & _
"_col hope eve abi dee bea fay ivy gay cath jan " & _
"_dan ivy fay dee gay hope eve jan bea cath abi " & _
"_ed jan dee bea cath fay eve abi ivy hope gay " & _
"_fred bea abi dee gay eve ivy cath jan hope fay " & _
"_gav gay eve ivy bea cath abi dee hope jan fay " & _
"_hal abi eve hope fay ivy cath jan bea gay dee " & _
"_ian hope cath dee gay bea abi fay ivy jan eve " & _
"_jon abi fay jan gay eve bea dee cath ivy hope " & _
"_abi bob fred jon gav ian abe dan ed col hal " & _
"_bea bob abe col fred gav dan ian ed jon hal " & _
"_cath fred bob ed gav hal col ian abe dan jon " & _
"_dee fred jon col abe ian hal gav dan bob ed " & _
"_eve jon hal fred dan abe gav col ed ian bob " & _
"_fay bob abe ed ian jon dan fred gav col hal " & _
"_gay jon gav hal fred bob abe col ed dan ian " & _
"_hope gav jon bob abe ian dan hal ed col fred " & _
"_ivy ian col hal gav fred bob abe ed jon dan " & _
"_jan ed hal gav abe bob jon col ian fred dan "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Generate a Go translation of this D snippet without changing its computational steps. | import std.stdio, std.array, std.algorithm, std.string;
string[string] matchmaker(string[][string] guyPrefers,
string[][string] girlPrefers) {
string[string] engagedTo;
string[] freeGuys = guyPrefers.keys;
while (freeGuys.length) {
const string thisGuy = freeGuys[0];
freeGuys.popFront();
const auto thisGuyPrefers = guyPrefers[thisGuy];
foreach (girl; thisGuyPrefers) {
if (girl !in engagedTo) {
engagedTo[girl] = thisGuy;
break;
} else {
string otherGuy = engagedTo[girl];
string[] thisGirlPrefers = girlPrefers[girl];
if (thisGirlPrefers.countUntil(thisGuy) <
thisGirlPrefers.countUntil(otherGuy)) {
engagedTo[girl] = thisGuy;
freeGuys ~= otherGuy;
break;
}
}
}
}
return engagedTo;
}
bool check(bool doPrint=false)(string[string] engagedTo,
string[][string] guyPrefers,
string[][string] galPrefers) @safe {
enum MSG = "%s likes %s better than %s and %s " ~
"likes %s better than their current partner";
string[string] inverseEngaged;
foreach (k, v; engagedTo)
inverseEngaged[v] = k;
foreach (she, he; engagedTo) {
auto sheLikes = galPrefers[she];
auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];
auto heLikes = guyPrefers[he];
auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];
foreach (guy; sheLikesBetter) {
auto guysGirl = inverseEngaged[guy];
auto guyLikes = guyPrefers[guy];
if (guyLikes.countUntil(guysGirl) >
guyLikes.countUntil(she)) {
static if (doPrint)
writefln(MSG, she, guy, he, guy, she);
return false;
}
}
foreach (gal; heLikesBetter) {
auto girlsGuy = engagedTo[gal];
auto galLikes = galPrefers[gal];
if (galLikes.countUntil(girlsGuy) >
galLikes.countUntil(he)) {
static if (doPrint)
writefln(MSG, he, gal, she, gal, he);
return false;
}
}
}
return true;
}
void main() {
auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay
bob cath hope abi dee eve fay bea jan ivy gay
col hope eve abi dee bea fay ivy gay cath jan
dan ivy fay dee gay hope eve jan bea cath abi
ed jan dee bea cath fay eve abi ivy hope gay
fred bea abi dee gay eve ivy cath jan hope fay
gav gay eve ivy bea cath abi dee hope jan fay
hal abi eve hope fay ivy cath jan bea gay dee
ian hope cath dee gay bea abi fay ivy jan eve
jon abi fay jan gay eve bea dee cath ivy hope";
auto galData = "abi bob fred jon gav ian abe dan ed col hal
bea bob abe col fred gav dan ian ed jon hal
cath fred bob ed gav hal col ian abe dan jon
dee fred jon col abe ian hal gav dan bob ed
eve jon hal fred dan abe gav col ed ian bob
fay bob abe ed ian jon dan fred gav col hal
gay jon gav hal fred bob abe col ed dan ian
hope gav jon bob abe ian dan hal ed col fred
ivy ian col hal gav fred bob abe ed jon dan
jan ed hal gav abe bob jon col ian fred dan";
string[][string] guyPrefers, galPrefers;
foreach (line; guyData.splitLines())
guyPrefers[split(line)[0]] = split(line)[1..$];
foreach (line; galData.splitLines())
galPrefers[split(line)[0]] = split(line)[1..$];
writeln("Engagements:");
auto engagedTo = matchmaker(guyPrefers, galPrefers);
writeln("\nCouples:");
string[] parts;
foreach (k; engagedTo.keys.sort())
writefln("%s is engagedTo to %s", k, engagedTo[k]);
writeln();
bool c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
writeln("\n\nSwapping two fiances to introduce an error");
auto gals = galPrefers.keys.sort();
swap(engagedTo[gals[0]], engagedTo[gals[1]]);
foreach (gal; gals[0 .. 2])
writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]);
writeln();
c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
}
| package main
import "fmt"
type proposers map[string][]string
var mPref = proposers{
"abe": []string{
"abi", "eve", "cath", "ivy", "jan",
"dee", "fay", "bea", "hope", "gay"},
"bob": []string{
"cath", "hope", "abi", "dee", "eve",
"fay", "bea", "jan", "ivy", "gay"},
"col": []string{
"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"},
"dan": []string{
"ivy", "fay", "dee", "gay", "hope",
"eve", "jan", "bea", "cath", "abi"},
"ed": []string{
"jan", "dee", "bea", "cath", "fay",
"eve", "abi", "ivy", "hope", "gay"},
"fred": []string{
"bea", "abi", "dee", "gay", "eve",
"ivy", "cath", "jan", "hope", "fay"},
"gav": []string{
"gay", "eve", "ivy", "bea", "cath",
"abi", "dee", "hope", "jan", "fay"},
"hal": []string{
"abi", "eve", "hope", "fay", "ivy",
"cath", "jan", "bea", "gay", "dee"},
"ian": []string{
"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"},
"jon": []string{
"abi", "fay", "jan", "gay", "eve",
"bea", "dee", "cath", "ivy", "hope"},
}
type recipients map[string]map[string]int
var wPref = recipients{
"abi": map[string]int{
"bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5,
"abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10},
"bea": map[string]int{
"bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5,
"dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10},
"cath": map[string]int{
"fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5,
"col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10},
"dee": map[string]int{
"fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5,
"hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10},
"eve": map[string]int{
"jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5,
"gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10},
"fay": map[string]int{
"bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5,
"dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10},
"gay": map[string]int{
"jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5,
"abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10},
"hope": map[string]int{
"gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5,
"dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10},
"ivy": map[string]int{
"ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5,
"bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10},
"jan": map[string]int{
"ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5,
"jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10},
}
func main() {
ps := pair(mPref, wPref)
fmt.Println("\nresult:")
if !validateStable(ps, mPref, wPref) {
return
}
for {
i := 0
var w2, m2 [2]string
for w, m := range ps {
w2[i] = w
m2[i] = m
if i == 1 {
break
}
i++
}
fmt.Println("\nexchanging partners of", m2[0], "and", m2[1])
ps[w2[0]] = m2[1]
ps[w2[1]] = m2[0]
if !validateStable(ps, mPref, wPref) {
return
}
}
}
type parings map[string]string
func pair(pPref proposers, rPref recipients) parings {
pFree := proposers{}
for k, v := range pPref {
pFree[k] = append([]string{}, v...)
}
rFree := recipients{}
for k, v := range rPref {
rFree[k] = v
}
type save struct {
proposer string
pPref []string
rPref map[string]int
}
proposals := map[string]save{}
for len(pFree) > 0 {
var proposer string
var ppref []string
for proposer, ppref = range pFree {
break
}
if len(ppref) == 0 {
continue
}
recipient := ppref[0]
ppref = ppref[1:]
var rpref map[string]int
var ok bool
if rpref, ok = rFree[recipient]; ok {
} else {
s := proposals[recipient]
if s.rPref[proposer] < s.rPref[s.proposer] {
fmt.Println("engagement broken:", recipient, s.proposer)
pFree[s.proposer] = s.pPref
rpref = s.rPref
} else {
pFree[proposer] = ppref
continue
}
}
fmt.Println("engagement:", recipient, proposer)
proposals[recipient] = save{proposer, ppref, rpref}
delete(pFree, proposer)
delete(rFree, recipient)
}
ps := parings{}
for recipient, s := range proposals {
ps[recipient] = s.proposer
}
return ps
}
func validateStable(ps parings, pPref proposers, rPref recipients) bool {
for r, p := range ps {
fmt.Println(r, p)
}
for r, p := range ps {
for _, rp := range pPref[p] {
if rp == r {
break
}
rprefs := rPref[rp]
if rprefs[p] < rprefs[ps[rp]] {
fmt.Println("unstable.")
fmt.Printf("%s and %s would prefer each other over"+
" their current pairings.\n", p, rp)
return false
}
}
}
fmt.Println("stable.")
return true
}
|
Rewrite the snippet below in C so it works the same as the original F# code. | let menPrefs =
Map.ofList
["abe", ["abi";"eve";"cath";"ivy";"jan";"dee";"fay";"bea";"hope";"gay"];
"bob", ["cath";"hope";"abi";"dee";"eve";"fay";"bea";"jan";"ivy";"gay"];
"col", ["hope";"eve";"abi";"dee";"bea";"fay";"ivy";"gay";"cath";"jan"];
"dan", ["ivy";"fay";"dee";"gay";"hope";"eve";"jan";"bea";"cath";"abi"];
"ed", ["jan";"dee";"bea";"cath";"fay";"eve";"abi";"ivy";"hope";"gay"];
"fred", ["bea";"abi";"dee";"gay";"eve";"ivy";"cath";"jan";"hope";"fay"];
"gav", ["gay";"eve";"ivy";"bea";"cath";"abi";"dee";"hope";"jan";"fay"];
"hal", ["abi";"eve";"hope";"fay";"ivy";"cath";"jan";"bea";"gay";"dee"];
"ian", ["hope";"cath";"dee";"gay";"bea";"abi";"fay";"ivy";"jan";"eve"];
"jon", ["abi";"fay";"jan";"gay";"eve";"bea";"dee";"cath";"ivy";"hope"];
]
let womenPrefs =
Map.ofList
["abi", ["bob";"fred";"jon";"gav";"ian";"abe";"dan";"ed";"col";"hal"];
"bea", ["bob";"abe";"col";"fred";"gav";"dan";"ian";"ed";"jon";"hal"];
"cath", ["fred";"bob";"ed";"gav";"hal";"col";"ian";"abe";"dan";"jon"];
"dee", ["fred";"jon";"col";"abe";"ian";"hal";"gav";"dan";"bob";"ed"];
"eve", ["jon";"hal";"fred";"dan";"abe";"gav";"col";"ed";"ian";"bob"];
"fay", ["bob";"abe";"ed";"ian";"jon";"dan";"fred";"gav";"col";"hal"];
"gay", ["jon";"gav";"hal";"fred";"bob";"abe";"col";"ed";"dan";"ian"];
"hope", ["gav";"jon";"bob";"abe";"ian";"dan";"hal";"ed";"col";"fred"];
"ivy", ["ian";"col";"hal";"gav";"fred";"bob";"abe";"ed";"jon";"dan"];
"jan", ["ed";"hal";"gav";"abe";"bob";"jon";"col";"ian";"fred";"dan"];
]
let men = menPrefs |> Map.toList |> List.map fst |> List.sort
let women = womenPrefs |> Map.toList |> List.map fst |> List.sort
type Configuration =
{
proposed: Map<string,string list>;
wifeOf: Map<string, string>;
husbandOf: Map<string, string>;
}
let isFreeMan config man = config.wifeOf.TryFind man = None
let isFreeWoman config woman = config.husbandOf.TryFind woman = None
let hasProposedTo config man woman =
defaultArg (config.proposed.TryFind(man)) []
|> List.exists ((=) woman)
let negate f = fun x -> not (f x)
let notProposedBy config man women = List.filter (negate (hasProposedTo config man)) women
let prefers (prefs:Map<string,string list>) w m1 m2 =
let order = prefs.[w]
let m1i = List.findIndex ((=) m1) order
let m2i = List.findIndex ((=) m2) order
m1i < m2i
let womanPrefers = prefers womenPrefs
let manPrefers = prefers menPrefs
let preferredWomen config m =
let w = config.wifeOf.[m]
women
|> List.filter (fun w' -> manPrefers m w' w)
let prefersAWomanWhoAlsoPrefersHim config m =
preferredWomen config m
|> List.exists (fun w -> womanPrefers w m config.husbandOf.[w])
let isStable config =
not (List.exists (prefersAWomanWhoAlsoPrefersHim config) men)
let engage config man woman =
{ config with wifeOf = config.wifeOf.Add(man, woman);
husbandOf = config.husbandOf.Add(woman, man) }
let breakOff config man =
let woman = config.wifeOf.[man]
{ config with wifeOf = config.wifeOf.Remove(man);
husbandOf = config.husbandOf.Remove(woman) }
let propose config m w =
let proposedByM = defaultArg (config.proposed.TryFind m) []
let proposed' = config.proposed.Add(m, w::proposedByM)
let config = { config with proposed = proposed'}
if isFreeWoman config w then engage config m w
else
let m' = config.husbandOf.[w]
if womanPrefers w m m' then
let config = breakOff config m'
engage config m w
else
config
let step config : Configuration option =
let freeMen = men |> List.filter (isFreeMan config)
let menWhoCanPropose =
freeMen |>
List.filter (fun man -> (notProposedBy config man women) <> [] )
match menWhoCanPropose with
| [] -> None
| m::_ -> let unproposedByM = menPrefs.[m] |> notProposedBy config m
let w = List.head unproposedByM
Some( propose config m w )
let rec loop config =
match step config with
| None -> config
| Some config' -> loop config'
let solution = loop { proposed = Map.empty<string, string list>;
wifeOf = Map.empty<string, string>;
husbandOf = Map.empty<string, string> }
for woman, man in Map.toList solution.husbandOf do
printfn "%s is engaged to %s" woman man
printfn "Solution is stable: %A" (isStable solution)
let perturbed =
let gal0 = women.[0]
let gal1 = women.[1]
let guy0 = solution.husbandOf.[gal0]
let guy1 = solution.husbandOf.[gal1]
{ solution with wifeOf = solution.wifeOf.Add( guy0, gal1 ).Add( guy1, gal0 );
husbandOf = solution.husbandOf.Add( gal0, guy1 ).Add( gal1, guy0 ) }
printfn "Perturbed is stable: %A" (isStable perturbed)
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },
{ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay },
{ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan },
{ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi },
{ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay },
{ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay },
{ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay },
{ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee },
{ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve },
{ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope },
{ bob, fred, jon, gav, ian, abe, dan, ed, col, hal },
{ bob, abe, col, fred, gav, dan, ian, ed, jon, hal },
{ fred, bob, ed, gav, hal, col, ian, abe, dan, jon },
{ fred, jon, col, abe, ian, hal, gav, dan, bob, ed },
{ jon, hal, fred, dan, abe, gav, col, ed, ian, bob },
{ bob, abe, ed, ian, jon, dan, fred, gav, col, hal },
{ jon, gav, hal, fred, bob, abe, col, ed, dan, ian },
{ gav, jon, bob, abe, ian, dan, hal, ed, col, fred },
{ ian, col, hal, gav, fred, bob, abe, ed, jon, dan },
{ ed, hal, gav, abe, bob, jon, col, ian, fred, dan },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Please provide an equivalent version of this F# code in C#. | let menPrefs =
Map.ofList
["abe", ["abi";"eve";"cath";"ivy";"jan";"dee";"fay";"bea";"hope";"gay"];
"bob", ["cath";"hope";"abi";"dee";"eve";"fay";"bea";"jan";"ivy";"gay"];
"col", ["hope";"eve";"abi";"dee";"bea";"fay";"ivy";"gay";"cath";"jan"];
"dan", ["ivy";"fay";"dee";"gay";"hope";"eve";"jan";"bea";"cath";"abi"];
"ed", ["jan";"dee";"bea";"cath";"fay";"eve";"abi";"ivy";"hope";"gay"];
"fred", ["bea";"abi";"dee";"gay";"eve";"ivy";"cath";"jan";"hope";"fay"];
"gav", ["gay";"eve";"ivy";"bea";"cath";"abi";"dee";"hope";"jan";"fay"];
"hal", ["abi";"eve";"hope";"fay";"ivy";"cath";"jan";"bea";"gay";"dee"];
"ian", ["hope";"cath";"dee";"gay";"bea";"abi";"fay";"ivy";"jan";"eve"];
"jon", ["abi";"fay";"jan";"gay";"eve";"bea";"dee";"cath";"ivy";"hope"];
]
let womenPrefs =
Map.ofList
["abi", ["bob";"fred";"jon";"gav";"ian";"abe";"dan";"ed";"col";"hal"];
"bea", ["bob";"abe";"col";"fred";"gav";"dan";"ian";"ed";"jon";"hal"];
"cath", ["fred";"bob";"ed";"gav";"hal";"col";"ian";"abe";"dan";"jon"];
"dee", ["fred";"jon";"col";"abe";"ian";"hal";"gav";"dan";"bob";"ed"];
"eve", ["jon";"hal";"fred";"dan";"abe";"gav";"col";"ed";"ian";"bob"];
"fay", ["bob";"abe";"ed";"ian";"jon";"dan";"fred";"gav";"col";"hal"];
"gay", ["jon";"gav";"hal";"fred";"bob";"abe";"col";"ed";"dan";"ian"];
"hope", ["gav";"jon";"bob";"abe";"ian";"dan";"hal";"ed";"col";"fred"];
"ivy", ["ian";"col";"hal";"gav";"fred";"bob";"abe";"ed";"jon";"dan"];
"jan", ["ed";"hal";"gav";"abe";"bob";"jon";"col";"ian";"fred";"dan"];
]
let men = menPrefs |> Map.toList |> List.map fst |> List.sort
let women = womenPrefs |> Map.toList |> List.map fst |> List.sort
type Configuration =
{
proposed: Map<string,string list>;
wifeOf: Map<string, string>;
husbandOf: Map<string, string>;
}
let isFreeMan config man = config.wifeOf.TryFind man = None
let isFreeWoman config woman = config.husbandOf.TryFind woman = None
let hasProposedTo config man woman =
defaultArg (config.proposed.TryFind(man)) []
|> List.exists ((=) woman)
let negate f = fun x -> not (f x)
let notProposedBy config man women = List.filter (negate (hasProposedTo config man)) women
let prefers (prefs:Map<string,string list>) w m1 m2 =
let order = prefs.[w]
let m1i = List.findIndex ((=) m1) order
let m2i = List.findIndex ((=) m2) order
m1i < m2i
let womanPrefers = prefers womenPrefs
let manPrefers = prefers menPrefs
let preferredWomen config m =
let w = config.wifeOf.[m]
women
|> List.filter (fun w' -> manPrefers m w' w)
let prefersAWomanWhoAlsoPrefersHim config m =
preferredWomen config m
|> List.exists (fun w -> womanPrefers w m config.husbandOf.[w])
let isStable config =
not (List.exists (prefersAWomanWhoAlsoPrefersHim config) men)
let engage config man woman =
{ config with wifeOf = config.wifeOf.Add(man, woman);
husbandOf = config.husbandOf.Add(woman, man) }
let breakOff config man =
let woman = config.wifeOf.[man]
{ config with wifeOf = config.wifeOf.Remove(man);
husbandOf = config.husbandOf.Remove(woman) }
let propose config m w =
let proposedByM = defaultArg (config.proposed.TryFind m) []
let proposed' = config.proposed.Add(m, w::proposedByM)
let config = { config with proposed = proposed'}
if isFreeWoman config w then engage config m w
else
let m' = config.husbandOf.[w]
if womanPrefers w m m' then
let config = breakOff config m'
engage config m w
else
config
let step config : Configuration option =
let freeMen = men |> List.filter (isFreeMan config)
let menWhoCanPropose =
freeMen |>
List.filter (fun man -> (notProposedBy config man women) <> [] )
match menWhoCanPropose with
| [] -> None
| m::_ -> let unproposedByM = menPrefs.[m] |> notProposedBy config m
let w = List.head unproposedByM
Some( propose config m w )
let rec loop config =
match step config with
| None -> config
| Some config' -> loop config'
let solution = loop { proposed = Map.empty<string, string list>;
wifeOf = Map.empty<string, string>;
husbandOf = Map.empty<string, string> }
for woman, man in Map.toList solution.husbandOf do
printfn "%s is engaged to %s" woman man
printfn "Solution is stable: %A" (isStable solution)
let perturbed =
let gal0 = women.[0]
let gal1 = women.[1]
let guy0 = solution.husbandOf.[gal0]
let guy1 = solution.husbandOf.[gal1]
{ solution with wifeOf = solution.wifeOf.Add( guy0, gal1 ).Add( guy1, gal0 );
husbandOf = solution.husbandOf.Add( gal0, guy1 ).Add( gal1, guy0 ) }
printfn "Perturbed is stable: %A" (isStable perturbed)
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Change the following F# code into Python without altering its purpose. | let menPrefs =
Map.ofList
["abe", ["abi";"eve";"cath";"ivy";"jan";"dee";"fay";"bea";"hope";"gay"];
"bob", ["cath";"hope";"abi";"dee";"eve";"fay";"bea";"jan";"ivy";"gay"];
"col", ["hope";"eve";"abi";"dee";"bea";"fay";"ivy";"gay";"cath";"jan"];
"dan", ["ivy";"fay";"dee";"gay";"hope";"eve";"jan";"bea";"cath";"abi"];
"ed", ["jan";"dee";"bea";"cath";"fay";"eve";"abi";"ivy";"hope";"gay"];
"fred", ["bea";"abi";"dee";"gay";"eve";"ivy";"cath";"jan";"hope";"fay"];
"gav", ["gay";"eve";"ivy";"bea";"cath";"abi";"dee";"hope";"jan";"fay"];
"hal", ["abi";"eve";"hope";"fay";"ivy";"cath";"jan";"bea";"gay";"dee"];
"ian", ["hope";"cath";"dee";"gay";"bea";"abi";"fay";"ivy";"jan";"eve"];
"jon", ["abi";"fay";"jan";"gay";"eve";"bea";"dee";"cath";"ivy";"hope"];
]
let womenPrefs =
Map.ofList
["abi", ["bob";"fred";"jon";"gav";"ian";"abe";"dan";"ed";"col";"hal"];
"bea", ["bob";"abe";"col";"fred";"gav";"dan";"ian";"ed";"jon";"hal"];
"cath", ["fred";"bob";"ed";"gav";"hal";"col";"ian";"abe";"dan";"jon"];
"dee", ["fred";"jon";"col";"abe";"ian";"hal";"gav";"dan";"bob";"ed"];
"eve", ["jon";"hal";"fred";"dan";"abe";"gav";"col";"ed";"ian";"bob"];
"fay", ["bob";"abe";"ed";"ian";"jon";"dan";"fred";"gav";"col";"hal"];
"gay", ["jon";"gav";"hal";"fred";"bob";"abe";"col";"ed";"dan";"ian"];
"hope", ["gav";"jon";"bob";"abe";"ian";"dan";"hal";"ed";"col";"fred"];
"ivy", ["ian";"col";"hal";"gav";"fred";"bob";"abe";"ed";"jon";"dan"];
"jan", ["ed";"hal";"gav";"abe";"bob";"jon";"col";"ian";"fred";"dan"];
]
let men = menPrefs |> Map.toList |> List.map fst |> List.sort
let women = womenPrefs |> Map.toList |> List.map fst |> List.sort
type Configuration =
{
proposed: Map<string,string list>;
wifeOf: Map<string, string>;
husbandOf: Map<string, string>;
}
let isFreeMan config man = config.wifeOf.TryFind man = None
let isFreeWoman config woman = config.husbandOf.TryFind woman = None
let hasProposedTo config man woman =
defaultArg (config.proposed.TryFind(man)) []
|> List.exists ((=) woman)
let negate f = fun x -> not (f x)
let notProposedBy config man women = List.filter (negate (hasProposedTo config man)) women
let prefers (prefs:Map<string,string list>) w m1 m2 =
let order = prefs.[w]
let m1i = List.findIndex ((=) m1) order
let m2i = List.findIndex ((=) m2) order
m1i < m2i
let womanPrefers = prefers womenPrefs
let manPrefers = prefers menPrefs
let preferredWomen config m =
let w = config.wifeOf.[m]
women
|> List.filter (fun w' -> manPrefers m w' w)
let prefersAWomanWhoAlsoPrefersHim config m =
preferredWomen config m
|> List.exists (fun w -> womanPrefers w m config.husbandOf.[w])
let isStable config =
not (List.exists (prefersAWomanWhoAlsoPrefersHim config) men)
let engage config man woman =
{ config with wifeOf = config.wifeOf.Add(man, woman);
husbandOf = config.husbandOf.Add(woman, man) }
let breakOff config man =
let woman = config.wifeOf.[man]
{ config with wifeOf = config.wifeOf.Remove(man);
husbandOf = config.husbandOf.Remove(woman) }
let propose config m w =
let proposedByM = defaultArg (config.proposed.TryFind m) []
let proposed' = config.proposed.Add(m, w::proposedByM)
let config = { config with proposed = proposed'}
if isFreeWoman config w then engage config m w
else
let m' = config.husbandOf.[w]
if womanPrefers w m m' then
let config = breakOff config m'
engage config m w
else
config
let step config : Configuration option =
let freeMen = men |> List.filter (isFreeMan config)
let menWhoCanPropose =
freeMen |>
List.filter (fun man -> (notProposedBy config man women) <> [] )
match menWhoCanPropose with
| [] -> None
| m::_ -> let unproposedByM = menPrefs.[m] |> notProposedBy config m
let w = List.head unproposedByM
Some( propose config m w )
let rec loop config =
match step config with
| None -> config
| Some config' -> loop config'
let solution = loop { proposed = Map.empty<string, string list>;
wifeOf = Map.empty<string, string>;
husbandOf = Map.empty<string, string> }
for woman, man in Map.toList solution.husbandOf do
printfn "%s is engaged to %s" woman man
printfn "Solution is stable: %A" (isStable solution)
let perturbed =
let gal0 = women.[0]
let gal1 = women.[1]
let guy0 = solution.husbandOf.[gal0]
let guy1 = solution.husbandOf.[gal1]
{ solution with wifeOf = solution.wifeOf.Add( guy0, gal1 ).Add( guy1, gal0 );
husbandOf = solution.husbandOf.Add( gal0, guy1 ).Add( gal1, guy0 ) }
printfn "Perturbed is stable: %A" (isStable perturbed)
| import copy
guyprefers = {
'abe': ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'],
'bob': ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'],
'col': ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'],
'dan': ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'],
'ed': ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'],
'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'],
'gav': ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'],
'hal': ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'],
'ian': ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'],
'jon': ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']}
galprefers = {
'abi': ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'],
'bea': ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'],
'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'],
'dee': ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'],
'eve': ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'],
'fay': ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'],
'gay': ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'],
'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'],
'ivy': ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'],
'jan': ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']}
guys = sorted(guyprefers.keys())
gals = sorted(galprefers.keys())
def check(engaged):
inverseengaged = dict((v,k) for k,v in engaged.items())
for she, he in engaged.items():
shelikes = galprefers[she]
shelikesbetter = shelikes[:shelikes.index(he)]
helikes = guyprefers[he]
helikesbetter = helikes[:helikes.index(she)]
for guy in shelikesbetter:
guysgirl = inverseengaged[guy]
guylikes = guyprefers[guy]
if guylikes.index(guysgirl) > guylikes.index(she):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (she, guy, he, guysgirl))
return False
for gal in helikesbetter:
girlsguy = engaged[gal]
gallikes = galprefers[gal]
if gallikes.index(girlsguy) > gallikes.index(he):
print("%s and %s like each other better than "
"their present partners: %s and %s, respectively"
% (he, gal, she, girlsguy))
return False
return True
def matchmaker():
guysfree = guys[:]
engaged = {}
guyprefers2 = copy.deepcopy(guyprefers)
galprefers2 = copy.deepcopy(galprefers)
while guysfree:
guy = guysfree.pop(0)
guyslist = guyprefers2[guy]
gal = guyslist.pop(0)
fiance = engaged.get(gal)
if not fiance:
engaged[gal] = guy
print(" %s and %s" % (guy, gal))
else:
galslist = galprefers2[gal]
if galslist.index(fiance) > galslist.index(guy):
engaged[gal] = guy
print(" %s dumped %s for %s" % (gal, fiance, guy))
if guyprefers2[fiance]:
guysfree.append(fiance)
else:
if guyslist:
guysfree.append(guy)
return engaged
print('\nEngagements:')
engaged = matchmaker()
print('\nCouples:')
print(' ' + ',\n '.join('%s is engaged to %s' % couple
for couple in sorted(engaged.items())))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
print('\n\nSwapping two fiances to introduce an error')
engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]
for gal in gals[:2]:
print(' %s is now engaged to %s' % (gal, engaged[gal]))
print()
print('Engagement stability check PASSED'
if check(engaged) else 'Engagement stability check FAILED')
|
Port the following code from F# to VB with equivalent syntax and logic. | let menPrefs =
Map.ofList
["abe", ["abi";"eve";"cath";"ivy";"jan";"dee";"fay";"bea";"hope";"gay"];
"bob", ["cath";"hope";"abi";"dee";"eve";"fay";"bea";"jan";"ivy";"gay"];
"col", ["hope";"eve";"abi";"dee";"bea";"fay";"ivy";"gay";"cath";"jan"];
"dan", ["ivy";"fay";"dee";"gay";"hope";"eve";"jan";"bea";"cath";"abi"];
"ed", ["jan";"dee";"bea";"cath";"fay";"eve";"abi";"ivy";"hope";"gay"];
"fred", ["bea";"abi";"dee";"gay";"eve";"ivy";"cath";"jan";"hope";"fay"];
"gav", ["gay";"eve";"ivy";"bea";"cath";"abi";"dee";"hope";"jan";"fay"];
"hal", ["abi";"eve";"hope";"fay";"ivy";"cath";"jan";"bea";"gay";"dee"];
"ian", ["hope";"cath";"dee";"gay";"bea";"abi";"fay";"ivy";"jan";"eve"];
"jon", ["abi";"fay";"jan";"gay";"eve";"bea";"dee";"cath";"ivy";"hope"];
]
let womenPrefs =
Map.ofList
["abi", ["bob";"fred";"jon";"gav";"ian";"abe";"dan";"ed";"col";"hal"];
"bea", ["bob";"abe";"col";"fred";"gav";"dan";"ian";"ed";"jon";"hal"];
"cath", ["fred";"bob";"ed";"gav";"hal";"col";"ian";"abe";"dan";"jon"];
"dee", ["fred";"jon";"col";"abe";"ian";"hal";"gav";"dan";"bob";"ed"];
"eve", ["jon";"hal";"fred";"dan";"abe";"gav";"col";"ed";"ian";"bob"];
"fay", ["bob";"abe";"ed";"ian";"jon";"dan";"fred";"gav";"col";"hal"];
"gay", ["jon";"gav";"hal";"fred";"bob";"abe";"col";"ed";"dan";"ian"];
"hope", ["gav";"jon";"bob";"abe";"ian";"dan";"hal";"ed";"col";"fred"];
"ivy", ["ian";"col";"hal";"gav";"fred";"bob";"abe";"ed";"jon";"dan"];
"jan", ["ed";"hal";"gav";"abe";"bob";"jon";"col";"ian";"fred";"dan"];
]
let men = menPrefs |> Map.toList |> List.map fst |> List.sort
let women = womenPrefs |> Map.toList |> List.map fst |> List.sort
type Configuration =
{
proposed: Map<string,string list>;
wifeOf: Map<string, string>;
husbandOf: Map<string, string>;
}
let isFreeMan config man = config.wifeOf.TryFind man = None
let isFreeWoman config woman = config.husbandOf.TryFind woman = None
let hasProposedTo config man woman =
defaultArg (config.proposed.TryFind(man)) []
|> List.exists ((=) woman)
let negate f = fun x -> not (f x)
let notProposedBy config man women = List.filter (negate (hasProposedTo config man)) women
let prefers (prefs:Map<string,string list>) w m1 m2 =
let order = prefs.[w]
let m1i = List.findIndex ((=) m1) order
let m2i = List.findIndex ((=) m2) order
m1i < m2i
let womanPrefers = prefers womenPrefs
let manPrefers = prefers menPrefs
let preferredWomen config m =
let w = config.wifeOf.[m]
women
|> List.filter (fun w' -> manPrefers m w' w)
let prefersAWomanWhoAlsoPrefersHim config m =
preferredWomen config m
|> List.exists (fun w -> womanPrefers w m config.husbandOf.[w])
let isStable config =
not (List.exists (prefersAWomanWhoAlsoPrefersHim config) men)
let engage config man woman =
{ config with wifeOf = config.wifeOf.Add(man, woman);
husbandOf = config.husbandOf.Add(woman, man) }
let breakOff config man =
let woman = config.wifeOf.[man]
{ config with wifeOf = config.wifeOf.Remove(man);
husbandOf = config.husbandOf.Remove(woman) }
let propose config m w =
let proposedByM = defaultArg (config.proposed.TryFind m) []
let proposed' = config.proposed.Add(m, w::proposedByM)
let config = { config with proposed = proposed'}
if isFreeWoman config w then engage config m w
else
let m' = config.husbandOf.[w]
if womanPrefers w m m' then
let config = breakOff config m'
engage config m w
else
config
let step config : Configuration option =
let freeMen = men |> List.filter (isFreeMan config)
let menWhoCanPropose =
freeMen |>
List.filter (fun man -> (notProposedBy config man women) <> [] )
match menWhoCanPropose with
| [] -> None
| m::_ -> let unproposedByM = menPrefs.[m] |> notProposedBy config m
let w = List.head unproposedByM
Some( propose config m w )
let rec loop config =
match step config with
| None -> config
| Some config' -> loop config'
let solution = loop { proposed = Map.empty<string, string list>;
wifeOf = Map.empty<string, string>;
husbandOf = Map.empty<string, string> }
for woman, man in Map.toList solution.husbandOf do
printfn "%s is engaged to %s" woman man
printfn "Solution is stable: %A" (isStable solution)
let perturbed =
let gal0 = women.[0]
let gal1 = women.[1]
let guy0 = solution.husbandOf.[gal0]
let guy1 = solution.husbandOf.[gal1]
{ solution with wifeOf = solution.wifeOf.Add( guy0, gal1 ).Add( guy1, gal0 );
husbandOf = solution.husbandOf.Add( gal0, guy1 ).Add( gal1, guy0 ) }
printfn "Perturbed is stable: %A" (isStable perturbed)
| Sub M_snb()
c00 = "_abe abi eve cath ivy jan dee fay bea hope gay " & _
"_bob cath hope abi dee eve fay bea jan ivy gay " & _
"_col hope eve abi dee bea fay ivy gay cath jan " & _
"_dan ivy fay dee gay hope eve jan bea cath abi " & _
"_ed jan dee bea cath fay eve abi ivy hope gay " & _
"_fred bea abi dee gay eve ivy cath jan hope fay " & _
"_gav gay eve ivy bea cath abi dee hope jan fay " & _
"_hal abi eve hope fay ivy cath jan bea gay dee " & _
"_ian hope cath dee gay bea abi fay ivy jan eve " & _
"_jon abi fay jan gay eve bea dee cath ivy hope " & _
"_abi bob fred jon gav ian abe dan ed col hal " & _
"_bea bob abe col fred gav dan ian ed jon hal " & _
"_cath fred bob ed gav hal col ian abe dan jon " & _
"_dee fred jon col abe ian hal gav dan bob ed " & _
"_eve jon hal fred dan abe gav col ed ian bob " & _
"_fay bob abe ed ian jon dan fred gav col hal " & _
"_gay jon gav hal fred bob abe col ed dan ian " & _
"_hope gav jon bob abe ian dan hal ed col fred " & _
"_ivy ian col hal gav fred bob abe ed jon dan " & _
"_jan ed hal gav abe bob jon col ian fred dan "
sn = Filter(Filter(Split(c00), "_"), "-", 0)
Do
c01 = Mid(c00, InStr(c00, sn(0) & " "))
st = Split(Left(c01, InStr(Mid(c01, 2), "_")))
For j = 1 To UBound(st) - 1
If InStr(c00, "_" & st(j) & " ") > 0 Then
c00 = Replace(Replace(c00, sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
Else
c02 = Filter(Split(c00, "_"), st(j) & ".")(0)
c03 = Split(Split(c02)(0), ".")(1)
If InStr(c02, " " & Mid(sn(0), 2) & " ") < InStr(c02, " " & c03 & " ") Then
c00 = Replace(Replace(Replace(c00, c03 & "-" & st(j), c03), sn(0), sn(0) & "-" & st(j)), "_" & st(j), "_" & st(j) & "." & Mid(sn(0), 2))
Exit For
End If
End If
Next
sn = Filter(Filter(Filter(Split(c00), "_"), "-", 0), ".", 0)
Loop Until UBound(sn) = -1
MsgBox Replace(Join(Filter(Split(c00), "-"), vbLf), "_", "")
End Sub
|
Rewrite this program in C while keeping its functionality equivalent to the Groovy version. | import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys -= thisGuy
List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }
for(Woman girl in guyChoices) {
if(! engagedTo[girl]) {
engagedTo[girl] = thisGuy
break
} else {
Man thatGuy = engagedTo[girl]
if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {
engagedTo[girl] = thisGuy
freeGuys << thatGuy
break
}
}
}
}
engagedTo
}
| #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },
{ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay },
{ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan },
{ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi },
{ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay },
{ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay },
{ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay },
{ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee },
{ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve },
{ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope },
{ bob, fred, jon, gav, ian, abe, dan, ed, col, hal },
{ bob, abe, col, fred, gav, dan, ian, ed, jon, hal },
{ fred, bob, ed, gav, hal, col, ian, abe, dan, jon },
{ fred, jon, col, abe, ian, hal, gav, dan, bob, ed },
{ jon, hal, fred, dan, abe, gav, col, ed, ian, bob },
{ bob, abe, ed, ian, jon, dan, fred, gav, col, hal },
{ jon, gav, hal, fred, bob, abe, col, ed, dan, ian },
{ gav, jon, bob, abe, ian, dan, hal, ed, col, fred },
{ ian, col, hal, gav, fred, bob, abe, ed, jon, dan },
{ ed, hal, gav, abe, bob, jon, col, ian, fred, dan },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n"
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Groovy to C#. | import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys -= thisGuy
List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }
for(Woman girl in guyChoices) {
if(! engagedTo[girl]) {
engagedTo[girl] = thisGuy
break
} else {
Man thatGuy = engagedTo[girl]
if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {
engagedTo[girl] = thisGuy
freeGuys << thatGuy
break
}
}
}
}
engagedTo
}
| using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.